From a4f27b7354a6595b8df30533c14a8477502daf5a Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sat, 31 Oct 2026 17:06:03 +0000 Subject: [PATCH] docs: consolidate Chapter 3 pixelization and MGE teaching --- README.md | 12 +- llms-full.txt | 18 +- llms.txt | 4 +- notebooks/chapter_3_pixelizations/README.md | 26 +- .../tutorial_1_pixelizations.ipynb | 358 ++++--- ... tutorial_2_bayesian_regularization.ipynb} | 730 +++++++++---- .../tutorial_2_mappers.ipynb | 395 ------- .../tutorial_3_inversions.ipynb | 443 -------- .../tutorial_3_model_fit.ipynb | 334 ++++++ .../tutorial_5_bayesian_formalism.ipynb | 984 ------------------ .../tutorial_6_model_fit.ipynb | 410 -------- scripts/chapter_3_pixelizations/README.md | 26 +- scripts/chapter_3_pixelizations/introduction | 30 +- .../tutorial_1_pixelizations.py | 281 +++-- .../tutorial_2_bayesian_regularization.py | 577 ++++++++++ .../tutorial_2_mappers.py | 197 ---- .../tutorial_3_inversions.py | 233 ----- .../tutorial_3_model_fit.py | 212 ++++ .../tutorial_4_bayesian_regularization.py | 304 ------ .../tutorial_5_bayesian_formalism.py | 620 ----------- .../tutorial_6_model_fit.py | 256 ----- workspace_index.json | 124 +-- 22 files changed, 2112 insertions(+), 4462 deletions(-) rename notebooks/chapter_3_pixelizations/{tutorial_4_bayesian_regularization.ipynb => tutorial_2_bayesian_regularization.ipynb} (57%) delete mode 100644 notebooks/chapter_3_pixelizations/tutorial_2_mappers.ipynb delete mode 100644 notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb create mode 100644 notebooks/chapter_3_pixelizations/tutorial_3_model_fit.ipynb delete mode 100644 notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb delete mode 100644 notebooks/chapter_3_pixelizations/tutorial_6_model_fit.ipynb create mode 100644 scripts/chapter_3_pixelizations/tutorial_2_bayesian_regularization.py delete mode 100644 scripts/chapter_3_pixelizations/tutorial_2_mappers.py delete mode 100644 scripts/chapter_3_pixelizations/tutorial_3_inversions.py create mode 100644 scripts/chapter_3_pixelizations/tutorial_3_model_fit.py delete mode 100644 scripts/chapter_3_pixelizations/tutorial_4_bayesian_regularization.py delete mode 100644 scripts/chapter_3_pixelizations/tutorial_5_bayesian_formalism.py delete mode 100644 scripts/chapter_3_pixelizations/tutorial_6_model_fit.py diff --git a/README.md b/README.md index cc24518..583af4f 100644 --- a/README.md +++ b/README.md @@ -96,13 +96,11 @@ for the chapter 1 tutorials listed with a `markdown` link below; every other tut - Tutorial 8: Need for Speed — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_8_need_for_speed.ipynb)) - Tutorial 9: Search Chaining — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_9_search_chaining.ipynb)) - Tutorial 10: Prior Passing — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_10_prior_passing.ipynb)) -- **[Chapter 3: Pixelizations](scripts/chapter_3_pixelizations/README.md)** — Pixelized galaxy reconstructions, inversions, regularization, and the Bayesian formalism. - - Tutorial 1: Pixelizations — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb)) - - Tutorial 2: Mappers — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_3_pixelizations/tutorial_2_mappers.ipynb)) - - Tutorial 3: Inversions — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb)) - - Tutorial 4: Bayesian Regularization — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb)) - - Tutorial 5: Bayesian Formalism — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb)) - - Tutorial 6: Model Fit — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_3_pixelizations/tutorial_6_model_fit.ipynb)) +- **[Chapter 3: Pixelizations](scripts/chapter_3_pixelizations/README.md)** — Indexed mappings, inversions, regularization and MGE search chaining. + - Tutorial 1: Pixelizations — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb)) + - Tutorial 2: Bayesian Regularization — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_2_bayesian_regularization.ipynb)) + - Tutorial 3: Model Fit — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_model_fit.ipynb)) + - **[Chapter 4: Scaling Up Galaxies](scripts/chapter_4_scaling_up_galaxies/README.md)** — Extra galaxies, blended multi-galaxy systems, and cluster fields. - Tutorial 1: Extra Galaxies — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_4_scaling_up_galaxies/tutorial_1_extra_galaxies.ipynb)) - Tutorial 2: Multi Galaxy — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy.ipynb)) diff --git a/llms-full.txt b/llms-full.txt index be234c0..efd7ad6 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -46,18 +46,12 @@ AUTO-GENERATED by PyAutoHands — do not edit by hand; regenerate with generate. ## chapter_3_pixelizations -- [Tutorial 1: Pixelizations](scripts/chapter_3_pixelizations/tutorial_1_pixelizations.py): In the previous chapters, we used light profiles to model the light of a galaxy, where the light profile was an analytic description of how the luminosity varies as a function of radius. - - Contents: Initial Setup, Mesh, Wrap Up -- [Tutorial 2: Mappers](scripts/chapter_3_pixelizations/tutorial_2_mappers.py): In the previous tutorial, we used a pixelization to create a `Mapper`. However, it was not clear what a `Mapper` does, why it was called a mapper and whether it was mapping anything at all! - - Contents: Initial Setup, Dataset Auto-Simulation, Mappers, Mask, Wrap Up -- [Tutorial 3: Inversions](scripts/chapter_3_pixelizations/tutorial_3_inversions.py): In the previous two tutorials, we introduced: - - Contents: Initial Setup, Dataset Auto-Simulation, Pixelization, Positive Only Solver, Detailed Explanation, Wrap Up -- [Tutorial 4: Bayesian Regularization](scripts/chapter_3_pixelizations/tutorial_4_bayesian_regularization.py): So far, we have: - - Contents: Initial Setup, Dataset Auto-Simulation, Convenience Function, Pixelization, Regularization, Bayesian Evidence, Non-Linear and Linear, Detailed Description, Wrap Up -- [Tutorial 5: Bayesian Formalism](scripts/chapter_3_pixelizations/tutorial_5_bayesian_formalism.py): In tutorials 1 to 4, we built an intuition for how pixelized galaxy reconstruction works: pixelizations place a pixel-grid over the galaxy's image, mappers pair pixelization pixels with image-pixels, inversions solve for the pixel fluxes that best fit the data, and regularization smooths the solution within a Bayesian framework. - - Contents: Initial Setup, Dataset Auto-Simulation, Mask, Over Sampling, Mesh Shape, Galaxy, Image Grid, Mesh Pixel Centres, Interpolation, Mapper, Mapping Matrix, Blurred Mapping Matrix, Data Vector (D), Curvature Matrix (F), Unregularized Solve, Regularization Matrix (H), Galaxy Reconstruction (s), Image Reconstruction, Likelihood Function, Chi Squared, Regularization Term, Complexity Terms, Noise Normalization Term, Log Evidence, Fit, Wrap Up -- [Tutorial 6: Model Fit](scripts/chapter_3_pixelizations/tutorial_6_model_fit.py): In the previous tutorials we used an inversion to reconstruct a complex galaxy. However, from the perspective of a scientific analysis, it is not clear how useful this was. When we fit a galaxy with light profiles, we learn about its brightness (`intensity`), size (`effective_radius`), compactness (`sersic_index`), etc. - - Contents: Initial Setup, Dataset Auto-Simulation, Model + Search + Analysis + Model-Fit (Search 1), Mesh Shape, Model + Search + Analysis + Model-Fit (Search 2), Model + Search (Search 3), Wrap Up +- [Tutorial 1: Pixelizations, Mappers and Inversions](scripts/chapter_3_pixelizations/tutorial_1_pixelizations.py): Look at a resolved galaxy image. Its broad light distribution may follow a smooth bulge and disc, while smaller regions contain bright star-forming knots, off-centre clumps or irregular extensions. A model can capture the overall galaxy yet leave these features clearly visible in the residual image. + - Contents: The image and its coordinates, A brightness mesh, Following the mappings, An inversion, A model image, Using FitImaging +- [Tutorial 2: Bayesian Regularization](scripts/chapter_3_pixelizations/tutorial_2_bayesian_regularization.py): (no summary in script docstring) + - Contents: Interpolation and our starting reconstruction., Reducing and increasing regularization., Bayesian evidence and a coefficient experiment., Inspecting the preferred reconstruction., Linear brightnesses and non-linear model choices., Comparing mesh resolutions. +- [Tutorial 3: Model Fit](scripts/chapter_3_pixelizations/tutorial_3_model_fit.py): A pixelization can describe a galaxy without assigning an analytic centre and shape to every visible feature. However, analytic profiles remain useful when we want to describe its smooth components. In this tutorial we combine an MGE with a pixelization and use search chaining to put the smooth light model in place first. + - Contents: Dataset, Search 1, Search 2, Search 3, Interpretation ## chapter_4_scaling_up_galaxies diff --git a/llms.txt b/llms.txt index 536f0ee..b702b74 100644 --- a/llms.txt +++ b/llms.txt @@ -26,7 +26,7 @@ real analysis?" below). - **Chapter 1 — Introduction** → [scripts/chapter_1_introduction/](scripts/chapter_1_introduction/): Galaxies from first principles: grids & galaxies, light profiles, simulating data, and fitting data. The conceptual foundation. - **Chapter 2 — Modeling** → [scripts/chapter_2_modeling/](scripts/chapter_2_modeling/): Fitting a galaxy model to data with a non-linear search — parameter spaces, priors, dealing with failure, linear light profiles, masking, and reading results. -- **Chapter 3 — Pixelizations** → [scripts/chapter_3_pixelizations/](scripts/chapter_3_pixelizations/): Reconstructing irregular galaxy structure on a pixel-grid instead of with light profiles — mappers, inversions, Bayesian regularization, the Bayesian formalism. +- **Chapter 3 — Pixelizations** → [scripts/chapter_3_pixelizations/](scripts/chapter_3_pixelizations/): Reconstructing galaxy structure on a mesh — indexed mappings, inversions, Bayesian regularization and combined MGE/pixelization search chaining. - **Chapter 4 — Scaling Up Galaxies** → [scripts/chapter_4_scaling_up_galaxies/](scripts/chapter_4_scaling_up_galaxies/): Beyond a single galaxy — extra galaxies, blended multi-galaxy systems, and cluster fields. ## I want to understand… @@ -38,7 +38,7 @@ real analysis?" below). - **My fit found a wrong (local-maxima) solution — what do I do?** → [scripts/chapter_2_modeling/tutorial_4_dealing_with_failure.py](scripts/chapter_2_modeling/tutorial_4_dealing_with_failure.py): Prior tuning, reducing complexity, and looking harder. - **What are linear light profiles / MGE?** → [scripts/chapter_2_modeling/tutorial_5_linear_profiles.py](scripts/chapter_2_modeling/tutorial_5_linear_profiles.py): Solving intensities linearly; the Multi-Gaussian Expansion basis. - **How do I model an image with two galaxies?** → [scripts/chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy.py](scripts/chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy.py): Joint fitting of blended galaxies and their degeneracies. -- **How do I reconstruct irregular structure on a pixel grid?** → [scripts/chapter_3_pixelizations/tutorial_1_pixelizations.py](scripts/chapter_3_pixelizations/tutorial_1_pixelizations.py) through [tutorial_4_bayesian_regularization.py](scripts/chapter_3_pixelizations/tutorial_4_bayesian_regularization.py). +- **How do I reconstruct irregular structure on a pixel grid?** → [scripts/chapter_3_pixelizations/tutorial_1_pixelizations.py](scripts/chapter_3_pixelizations/tutorial_1_pixelizations.py) through [tutorial_3_model_fit.py](scripts/chapter_3_pixelizations/tutorial_3_model_fit.py). ## Ready for real analysis? diff --git a/notebooks/chapter_3_pixelizations/README.md b/notebooks/chapter_3_pixelizations/README.md index 8e4fd2c..d45eaf7 100644 --- a/notebooks/chapter_3_pixelizations/README.md +++ b/notebooks/chapter_3_pixelizations/README.md @@ -1,17 +1,25 @@ -In chapter 3, we use **Pixelizations** to reconstruct the light of complex galaxies on pixelized grids. +Look at a resolved galaxy image. Its broad light distribution may follow a smooth bulge and disc, while smaller regions contain bright star-forming knots, off-centre clumps or irregular extensions. A model can capture the overall galaxy yet leave these features clearly visible in the residual image. -**Colab** links to every tutorial are included. +In Chapter 2, we introduced linear light profiles and multi-Gaussian expansions (MGEs). Combining Gaussians of different widths gives us a more flexible radial brightness distribution than a single Sérsic profile. Gaussian groups with different ellipticities and orientations can also describe changes in flattening and isophotal twists. Fixed widths and linearly solved intensities provide this flexibility without introducing a large number of non-linear parameters. -# Files +Our worked example nevertheless imposed a particular geometry: the Gaussians within each galaxy’s group shared a common centre and elliptical shape. Adding more Gaussians improves our control over the brightness distribution around that centre, but does not create independently positioned knots or several components with distinct centres. + +We could introduce offset Gaussian groups. The limitation is not that MGEs cannot represent multiple centres, but that increasingly complicated galaxies require us to choose and fit an increasingly elaborate arrangement of components. + +Suppose the MGE reproduces the smooth galaxy light but leaves compact, structured residuals. These may indicate that the model needs more freedom to describe local features. They are not automatically evidence for additional galaxy components: an inaccurate PSF, background estimate, contaminating object or other data-treatment error can also leave structured residuals. -- [Tutorial 1: Pixelizations](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb) — Creating a pixel-grid to reconstruct a galaxy's light. +In this chapter, we introduce pixelized reconstruction as another way to describe the galaxy’s light. We infer brightness values across a mesh without assigning a separate analytic centre and shape to every feature. The predicted image includes telescope blurring, so the reconstruction is an inferred description of the galaxy rather than simply a copy of the observed pixels. -- [Tutorial 2: Mappers](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_3_pixelizations/tutorial_2_mappers.ipynb) — How a pixelization maps its pixels to image-pixels. +This builds on the linear profiles of Chapter 2. Instead of solving for Gaussian intensities, we solve for the mesh brightness values. Their extra freedom can describe irregular structure, but can also fit noise. Regularization supplies a prior that controls variations between neighbouring brightness values. -- [Tutorial 3: Inversions](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb) — Inverting the mappings to reconstruct the galaxy's light. +The reconstruction still depends on modelling choices, including the mesh, its resolution, regularization and the treatment of the data. We will learn to inspect how those choices affect both the reconstructed galaxy and the image residuals. + +MGE and other analytic profiles remain useful for describing and measuring smooth galaxy components. Pixelizations complement them when more complicated structure needs to be represented, including in models that combine analytic components with a pixelized reconstruction. + +# Files -- [Tutorial 4: Bayesian Regularization](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb) — Smoothing the reconstruction within a Bayesian framework. +- [Tutorial 1: Pixelizations](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb) — Meshes, indexed mappings, inversions and telescope blurring. -- [Tutorial 5: Bayesian Formalism](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb) — The linear algebra and Bayesian evidence equations behind pixelized galaxy reconstruction. +- [Tutorial 2: Bayesian Regularization](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_2_bayesian_regularization.ipynb) — Interpolation, smoothness priors, evidence and resolution experiments. -- [Tutorial 6: Model Fit](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_3_pixelizations/tutorial_6_model_fit.ipynb) — An example modeling pipeline which uses an inversion. +- [Tutorial 3: Model Fit](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_model_fit.ipynb) — An MGE fit followed by a combined MGE and pixelized model. diff --git a/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb b/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb index 1bf0a4d..d51bd13 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb @@ -4,20 +4,39 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Tutorial 1: Pixelizations\n", - "=========================\n", + "Tutorial 1: Pixelizations, Mappers and Inversions\n", + "=================================================\n", "\n", - "In the previous chapters, we used light profiles to model the light of a galaxy, where the light profile was an\n", - "analytic description of how the luminosity varies as a function of radius.\n", + "Look at a resolved galaxy image. Its broad light distribution may follow a smooth bulge and disc, while smaller regions contain bright star-forming knots, off-centre clumps or irregular extensions. A model can capture the overall galaxy yet leave these features clearly visible in the residual image.\n", "\n", - "In this chapter, we are instead going to reconstruct the galaxy's light on a pixel-grid, and in this tutorial we will\n", - "learn how to create a pixelization in **PyAutoGalaxy**.\n", + "In Chapter 2, we introduced linear light profiles and multi-Gaussian expansions (MGEs). Combining Gaussians of different widths gives us a more flexible radial brightness distribution than a single S\u00e9rsic profile. Gaussian groups with different ellipticities and orientations can also describe changes in flattening and isophotal twists. Fixed widths and linearly solved intensities provide this flexibility without introducing a large number of non-linear parameters.\n", + "\n", + "Our worked example nevertheless imposed a particular geometry: the Gaussians within each galaxy\u2019s group shared a common centre and elliptical shape. Adding more Gaussians improves our control over the brightness distribution around that centre, but does not create independently positioned knots or several components with distinct centres.\n", + "\n", + "We could introduce offset Gaussian groups. The limitation is not that MGEs cannot represent multiple centres, but that increasingly complicated galaxies require us to choose and fit an increasingly elaborate arrangement of components.\n", + "\n", + "Suppose the MGE reproduces the smooth galaxy light but leaves compact, structured residuals. These may indicate that the model needs more freedom to describe local features. They are not automatically evidence for additional galaxy components: an inaccurate PSF, background estimate, contaminating object or other data-treatment error can also leave structured residuals.\n", + "\n", + "In this chapter, we introduce pixelized reconstruction as another way to describe the galaxy\u2019s light. We infer brightness values across a mesh without assigning a separate analytic centre and shape to every feature. The predicted image includes telescope blurring, so the reconstruction is an inferred description of the galaxy rather than simply a copy of the observed pixels.\n", + "\n", + "This builds on the linear profiles of Chapter 2. Instead of solving for Gaussian intensities, we solve for the mesh brightness values. Their extra freedom can describe irregular structure, but can also fit noise. Regularization supplies a prior that controls variations between neighbouring brightness values.\n", + "\n", + "The reconstruction still depends on modelling choices, including the mesh, its resolution, regularization and the treatment of the data. We will learn to inspect how those choices affect both the reconstructed galaxy and the image residuals.\n", + "\n", + "MGE and other analytic profiles remain useful for describing and measuring smooth galaxy components. Pixelizations complement them when more complicated structure needs to be represented, including in models that combine analytic components with a pixelized reconstruction.\n", + "\n", + "We will build the connection between image coordinates, mesh indexes, reconstructed brightnesses and the model\n", + "image. Our worked dataset is deliberately a simple smooth bulge and disc: it makes these ingredients easy to see\n", + "before applying them to more complicated galaxy structure.\n", "\n", "__Contents__\n", "\n", - "- **Initial Setup:** Create a grid for illustration.\n", - "- **Mesh:** Set up a rectangular mesh for the pixelization.\n", - "- **Wrap Up:** Summary of pixelization concepts." + "- **The image and its coordinates:** Load and mask the data.\n", + "- **A brightness mesh:** Distinguish image indexes from mesh indexes.\n", + "- **Following the mappings:** Highlight which image pixels receive each mesh contribution.\n", + "- **An inversion:** Infer brightnesses, accounting for noise and telescope blurring.\n", + "- **A model image:** Inspect the reconstruction and residuals separately.\n", + "- **Using FitImaging:** Put these ingredients into a galaxy model." ] }, { @@ -58,34 +77,48 @@ "_setup_colab.setup(\"howtogalaxy\")" ] }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autogalaxy import setup_notebook; setup_notebook()\n", - "\n", - "import autogalaxy as ag\n", - "import autogalaxy.plot as aplt\n", - "from autoarray.inversion.plot.mapper_plots import plot_mapper" - ], - "outputs": [], - "execution_count": null - }, { "cell_type": "markdown", "metadata": {}, "source": [ - "__Initial Setup__\n", + "__The image and its coordinates__\n", "\n", - "Lets setup a grid. " + "The simulator supplies a S\u00e9rsic bulge and exponential disc. The circular mask selects the image pixels used in the\n", + "fit. We use one sample per image pixel for the indexed illustrations; accurate scientific modelling should also\n", + "check image integration. Each unmasked pixel has a position and a flattened index. These indexes describe the data,\n", + "not the separate mesh we are about to construct." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "grid = ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.05)" + "from pathlib import Path\n", + "import subprocess\n", + "import sys\n", + "import numpy as np\n", + "import autogalaxy as ag\n", + "import autogalaxy.plot as aplt\n", + "import autoarray.plot as aaplt\n", + "\n", + "dataset_path = Path(\"dataset\") / \"imaging\" / \"simple\"\n", + "if ag.util.dataset.should_simulate(str(dataset_path)):\n", + " subprocess.run([sys.executable, \"scripts/simulators/simple.py\"], check=True)\n", + "dataset = ag.Imaging.from_fits(\n", + " data_path=dataset_path / \"data.fits\",\n", + " noise_map_path=dataset_path / \"noise_map.fits\",\n", + " psf_path=dataset_path / \"psf.fits\",\n", + " pixel_scales=0.1,\n", + ")\n", + "mask = ag.Mask2D.circular(\n", + " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.0\n", + ")\n", + "dataset = dataset.apply_mask(mask=mask)\n", + "dataset = dataset.apply_over_sampling(over_sample_size_pixelization=1)\n", + "# Keep the smoke-test mesh smaller than its deliberately capped image.\n", + "mesh_pixels = min(25, min(dataset.shape_native) // 2)\n", + "mesh_shape = (mesh_pixels, mesh_pixels)\n", + "aplt.subplot_imaging_dataset(dataset=dataset)" ], "outputs": [], "execution_count": null @@ -94,82 +127,54 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Mesh__\n", + "__A brightness mesh__\n", "\n", - "Next, lets set up a `Mesh` using the `mesh` module. The mesh represents the pixel-grid used by the pixelization\n", - "to reconstruct the galaxy.\n", + "Our rectangular mesh covers the observed galaxy. There is no ray tracing: image coordinates and reconstructed\n", + "coordinates refer to the same sky. The shared mapper API nevertheless calls its reconstruction coordinates\n", + "`source_plane_data_grid` and `source_plane_mesh_grid`.\n", "\n", - "There are multiple `Mesh`'s available in **PyAutoGalaxy**. For now, we'll keep it simple and use a rectangular\n", - "grid, whose `shape` defines its $(y,x)$ dimensions. We will make it the same shape as the 2D grid.\n", + "`RectangularUniform` places brightness values at regularly spaced points. An image coordinate usually falls between\n", + "four mesh points, so bilinear interpolation combines their values with position-dependent weights. An image pixel\n", + "falling inside a rectangular cell does not simply take all its brightness from one mesh point.\n", "\n", - "The `RectangularBilinearAdaptDensity` mesh adapts its pixels to the density of the masked image-plane\n", - "grid via the ray-guided transformed uniform (RTU) grid formulation of Enzi et al. (2026)\n", - "(https://arxiv.org/abs/2606.30620), which should be cited in published work using this mesh.\n", - "Note that whereas that paper pairs the RTU grid with a Gaussian-process prior, **PyAutoGalaxy**\n", - "instead uses its own regularization schemes, introduced later in this chapter." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mesh = ag.mesh.RectangularBilinearAdaptDensity(shape=(100, 100))" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now pass the mesh to a `Pixelization`." + "Let's select small groups of image pixels near two different positions. Coordinate-based selection keeps this\n", + "illustration meaningful even when a quick smoke run uses a smaller dataset." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "pixelization = ag.Pixelization(mesh=mesh)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "By itself, a pixelization does not tell us much. It has no grid of $(y,x)$ coordinates, no image, and no information\n", - "about the galaxy we are fitting. \n", "\n", - "This information comes when we use the pixelization to create a `Mapper`, which we perform below using the grid\n", - "that we created above." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ + "image_grid = dataset.grids.pixelization\n", + "image_coordinates = np.asarray(image_grid)\n", + "indexes = [\n", + " np.argsort(np.sum((image_coordinates - position) ** 2, axis=1))[:5].tolist()\n", + " for position in [(0.0, 0.5), (0.0, -0.5)]\n", + "]\n", + "aaplt.plot_grid(\n", + " grid=image_grid, indexes=indexes, title=\"Selected Image-Pixel Coordinates\"\n", + ")\n", + "mesh = ag.mesh.RectangularUniform(shape=mesh_shape)\n", "interpolator = mesh.interpolator_from(\n", - " source_plane_data_grid=grid, source_plane_mesh_grid=None\n", + " source_plane_data_grid=image_grid, source_plane_mesh_grid=None\n", ")\n", - "\n", - "mapper = ag.Mapper(interpolator=interpolator)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This `Mapper` is a `RectangularMapper` -- every `Mesh` and `Pixelization` generates its own mapper." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(type(mapper))" + "mapper = ag.Mapper(\n", + " interpolator=interpolator, regularization=ag.reg.Constant(coefficient=1.0)\n", + ")\n", + "image_index = indexes[0][0]\n", + "weights = np.asarray(mapper.mapping_matrix[image_index])\n", + "mesh_indexes = np.flatnonzero(np.abs(weights) > 1.0e-12)\n", + "aaplt.plot_grid(\n", + " grid=mapper.source_plane_mesh_grid,\n", + " indexes=[mesh_indexes.tolist()],\n", + " title=f\"Mesh Points Contributing to Image Pixel {image_index}\",\n", + ")\n", + "print(\"Image position:\", image_coordinates[image_index])\n", + "for mesh_index in mesh_indexes:\n", + " print(\n", + " f\"Mesh index {mesh_index}: position={np.asarray(mapper.source_plane_mesh_grid[mesh_index])}, weight={weights[mesh_index]:.4f}\"\n", + " )" ], "outputs": [], "execution_count": null @@ -178,16 +183,49 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "By plotting our mapper, we now see our `Pixelization`. Its a fairly boring grid of rectangular pixels." + "__Following the mappings__\n", + "\n", + "An image-pixel index and mesh index refer to different things. The mapper stores the relationship between them.\n", + "We can follow it in the opposite direction: select mesh points and find the image pixels receiving a contribution.\n", + "\n", + "Matching colours identify the selected mesh groups and their associated image regions. These are interpolation\n", + "contributions, rather than a strict claim that every image coordinate lies inside a coloured cell. Nearby mesh\n", + "values can contribute to the same image pixel; that overlap is part of interpolation.\n", + "\n", + "First inspect one mesh point near the centre, then compare a pair of nearby points with an offset point. Try moving\n", + "the offset position and watch which image pixels change colour." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "plot_mapper(\n", + "\n", + "mesh_coordinates = np.asarray(mapper.source_plane_mesh_grid)\n", + "central_index = int(np.argmin(np.sum(mesh_coordinates**2, axis=1)))\n", + "pix_indexes = [[central_index]]\n", + "mappings = mapper.mappings_from(pix_indexes=pix_indexes)\n", + "aaplt.subplot_image_and_mapper(\n", " mapper=mapper,\n", - " title=\"Fairly Boring Grid2D of RectangularBilinearAdaptDensity Pixels\",\n", + " image=dataset.data,\n", + " regions=mappings,\n", + " region_labels=[str(central_index)],\n", + " mesh_grid=mapper.source_plane_mesh_grid,\n", + ")\n", + "nearby_indexes = np.argsort(\n", + " np.sum((mesh_coordinates - mesh_coordinates[central_index]) ** 2, axis=1)\n", + ")[:2].tolist()\n", + "offset_index = int(\n", + " np.argmin(np.sum((mesh_coordinates - np.array([0.3, 0.3])) ** 2, axis=1))\n", + ")\n", + "pix_indexes = [nearby_indexes, [offset_index]]\n", + "mappings = mapper.mappings_from(pix_indexes=pix_indexes)\n", + "aaplt.subplot_image_and_mapper(\n", + " mapper=mapper,\n", + " image=dataset.data,\n", + " regions=mappings,\n", + " region_labels=[str(group) for group in pix_indexes],\n", + " mesh_grid=mapper.source_plane_mesh_grid,\n", ")" ], "outputs": [], @@ -197,40 +235,40 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "However, the `Mapper` does contain lots of interesting information about our `Pixelization`, for example its \n", - "pixelization_grid tells us where the pixel centers are located." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(\"RectangularBilinearAdaptDensity Grid2D Pixel Centre 1:\")\n", - "print(mapper.source_plane_mesh_grid[0])\n", - "print(\"RectangularBilinearAdaptDensity Grid2D Pixel Centre 2:\")\n", - "print(mapper.source_plane_mesh_grid[1])\n", - "print(\"RectangularBilinearAdaptDensity Grid2D Pixel Centre 3:\")\n", - "print(mapper.source_plane_mesh_grid[2])\n", - "print(\"etc.\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can plot these centre on our grid, to make it look slightly less boring!" + "__An inversion__\n", + "\n", + "The mapper tells us how brightness would contribute to the image, but has not yet determined those brightnesses.\n", + "An inversion combines the mappings with the observed data, noise and PSF to infer the mesh values together.\n", + "Like the Gaussian intensities in Chapter 2, these values enter the predicted image linearly. Linear algebra handles\n", + "this large set of brightnesses without giving a non-linear search a free parameter for every mesh point.\n", + "\n", + "We also supplied `Constant` regularization with coefficient `1.0`. This smoothness prior discourages unsupported\n", + "variations between neighbours. The next tutorial explores why it is needed and how to choose its strength.\n", + "\n", + "Here there is only one mapper, so entry `j` in the reconstruction belongs to mesh index `j`. These values are jointly\n", + "inferred: interpolation and telescope blurring couple their effects on the image, while regularization couples\n", + "neighbouring brightnesses. They are not independent measurements of the selected coloured regions." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "plot_mapper(\n", + "\n", + "inversion = ag.Inversion(dataset=dataset, linear_obj_list=[mapper])\n", + "reconstruction = np.asarray(inversion.reconstruction)\n", + "for group in pix_indexes:\n", + " for mesh_index in group:\n", + " print(\n", + " f\"Mesh index {mesh_index}: reconstructed brightness={reconstruction[mesh_index]:.6g}\"\n", + " )\n", + "aaplt.plot_mapper(\n", " mapper=mapper,\n", + " solution_vector=reconstruction,\n", " mesh_grid=mapper.source_plane_mesh_grid,\n", - " title=\"Rectangular Grid With Pixel Centres\",\n", + " regions=[mapping.source_contours for mapping in mappings],\n", + " region_labels=[str(group) for group in pix_indexes],\n", + " title=\"Reconstructed Galaxy and Selected Mesh Indexes\",\n", ")" ], "outputs": [], @@ -240,45 +278,32 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The `Mapper` also has the grid that we passed when we set it up. Lets check they`re the same." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(\"Source Grid2D Pixel 1\")\n", - "print(grid[0])\n", - "print(mapper.source_plane_data_grid[0])\n", - "print(\"Source Grid2D Pixel 2\")\n", - "print(grid[1])\n", - "print(mapper.source_plane_data_grid[1])\n", - "print(\"etc.\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can over-lay this grid on the figure, which is starting to look a bit less boring now!" + "__A model image__\n", + "\n", + "The brightness reconstruction lives on the mesh. Mapping it onto the image grid and convolving with the PSF produces\n", + "the model image that we compare to the observations. Telescope blurring is already included in the inversion's solve;\n", + "it is not an extra correction applied after fitting an unblurred model to blurred data.\n", + "\n", + "The next figures distinguish the unblurred prediction, blurred model and residuals. A compact reconstructed feature\n", + "can be less distinct in the observed image because the PSF spreads its light. Inspect coherent residuals as well as\n", + "the reconstruction: a plausible-looking galaxy does not establish that the model explains the data." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "plot_mapper(\n", - " mapper=mapper,\n", - " mesh_grid=mapper.source_plane_data_grid,\n", - " title=\"Even less Boring Grid2D of RectangularBilinearAdaptDensity Pixels\",\n", - ")\n", "\n", - "plot_mapper(\n", - " mapper=mapper,\n", - " mesh_grid=mapper.source_plane_data_grid,\n", - " title=\"Zoomed Grid2D of RectangularBilinearAdaptDensity Pixels\",\n", + "image_before_blurring = inversion.mapped_reconstructed_data\n", + "model_image = inversion.mapped_reconstructed_operated_data\n", + "residual_map = dataset.data - model_image\n", + "aplt.plot_array(\n", + " array=image_before_blurring, title=\"Reconstructed Image Before Telescope Blurring\"\n", + ")\n", + "aplt.plot_array(array=model_image, title=\"Model Image Including Telescope Blurring\")\n", + "aplt.plot_array(array=residual_map, title=\"Residuals: Data Minus Model\")\n", + "aplt.plot_array(\n", + " array=residual_map / dataset.noise_map, title=\"Residuals Divided by the Noise\"\n", ")" ], "outputs": [], @@ -288,17 +313,28 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Finally, the mapper`s `mesh_grid` has lots of information about the pixelization, for example, the arc-second \n", - "size and dimensions." + "__Using FitImaging__\n", + "\n", + "We exposed the mapper and inversion to understand what they do. In everyday modelling, put a `Pixelization` in a\n", + "`Galaxy` and let `FitImaging` construct these ingredients. This evaluates a specified model; it is not a non-linear\n", + "search. The reconstruction still depends on the mesh, resolution, regularization and data treatment.\n", + "\n", + "**\ud83e\udd16 Ask AI:** Why is a reconstructed brightness on the mesh different from a measured image-pixel value, even though\n", + "we are modelling a directly observed galaxy without lensing?" ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(mapper.source_plane_mesh_grid.geometry.shape_native_scaled)\n", - "print(mapper.source_plane_mesh_grid.geometry.scaled_maxima)\n", - "print(mapper.source_plane_mesh_grid.geometry.scaled_minima)" + "\n", + "pixelization = ag.Pixelization(\n", + " mesh=ag.mesh.RectangularUniform(shape=mesh_shape),\n", + " regularization=ag.reg.Constant(coefficient=1.0),\n", + ")\n", + "galaxy = ag.Galaxy(redshift=0.5, pixelization=pixelization)\n", + "fit = ag.FitImaging(dataset=dataset, galaxies=ag.Galaxies(galaxies=[galaxy]))\n", + "aplt.subplot_fit_imaging(fit=fit)" ], "outputs": [], "execution_count": null @@ -309,11 +345,9 @@ "source": [ "__Wrap Up__\n", "\n", - "This was a relatively gentle overview of pixelizations, but one that was hopefully easy to follow. Think about the \n", - "following questions before moving on to the next tutorial:\n", - "\n", - " 1) The rectangular pixelization`s edges are aligned with the most exterior coordinates of the grid it was created\n", - " from. This is intentional, why do you think this is?" + "A mesh supplies brightness values, a mapper connects them to image coordinates, and an inversion infers them while\n", + "accounting for noise, telescope blurring and regularization. Next we investigate that regularization: a close image\n", + "fit alone does not tell us whether the inferred structure is trustworthy." ] } ], @@ -341,7 +375,7 @@ "24c2f562-da24-50bb-8eb9-5a887505fe54": { "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", "name": "PyAutoGalaxy assistant", - "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb in HowToGalaxy).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoGalaxy calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoGalaxy docs (https://pyautogalaxy.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_pixelization\n\n---\nname: ag_pixelization\ndescription: Reconstruct a galaxy's clumpy or irregular light directly on a regularized pixel mesh, using `ag.Pixelization` alongside a parametric `ag.lp_linear` bulge — the hybrid model that gives a smooth interpretable component plus a flexible flux map for everything the profile cannot explain. Covers when a pixelization is warranted and when it is overkill, choosing an `ag.mesh` and an `ag.reg` regularization scheme and what each costs in free parameters, why `mesh_shape` must be fixed before the fit, `over_sample_size_pixelization` rather than `over_sample_size_lp`, noise scaling instead of hard masking for contaminants, the positive-only solver, reading the reconstruction and its Bayesian-evidence terms out of the `Inversion`, exporting the reconstruction to CSV for collaborators, and the GPU/VRAM versus CPU run-time trade. Use when a Sersic, MGE or shapelet basis leaves structured residuals in discrete off-centre lumps. Not for morphology a basis can still fit (`ag_basis_profiles`), not for non-parametric isophote measurement (`ag_ellipse_fitting`), and not for the basics of model composition (`ag_build_imaging_model`).\n---\n\n# Reconstructing a galaxy on a pixel mesh\n\nEvery model in this workspace so far has been a *function*: you asserted a functional form and\nthe fit found its parameters. A pixelization drops the functional form. It lays a mesh of pixels\nover the galaxy, gives each pixel its own free flux value, and solves all of them at once by\nlinear inversion — thousands of amplitudes, none of them in the non-linear search's parameter\nspace. What stops that from simply fitting the noise is **regularization**: a prior that\npenalises solutions where neighbouring mesh pixels differ sharply, so the reconstruction is as\nsmooth as the data will allow and no smoother.\n\nThe science case is specific, and it is worth being honest about how specific. Galaxies with\nspiral arms, asymmetric star-forming clumps, tidal features or low-surface-brightness\nsubstructure have light that no smooth profile — and often no basis expansion either —\nreproduces. The canonical use is therefore **hybrid**: a linear `Sersic` for the smooth central\nbulge, and a pixelization for the irregular remainder. That split is the point. It gives you a\nlow-dimensional, physically interpretable description of the bulge *and* a flux map of exactly\nwhat the bulge could not explain, which is the quantity you want if the science question is \"how\nmuch of this galaxy's light is in its irregular components?\"\n\nThis is a **direct** reconstruction. There is no second plane, no de-projection, no inversion of\na geometric mapping — the mesh sits on the image plane, over the galaxy, at the same coordinates\nthe data occupies. If you have met pixelized reconstruction before in a different context, that\nextra step is the one that is absent here, and its absence makes everything simpler: what the\nmesh reconstructs is the galaxy's own surface brightness, and its coordinates are sky\ncoordinates in arcseconds.\n\nStatistically, the fit now has two nested layers. The non-linear search explores a handful of\nparameters — the bulge's shape, the regularization strength — and for each proposal an inversion\nsolves the mesh amplitudes exactly and returns a **Bayesian evidence** rather than a plain\nlikelihood. That evidence includes terms that penalise an unnecessarily complex reconstruction,\nwhich is what lets a model with 400 free flux values not simply win by over-fitting. The theory\nis [`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md);\nchapter 3 of HowToGalaxy derives it from scratch.\n\nThe canonical scripts are\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py` (via a search),\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` (one direct fit, with the\ninversion internals walked through) and\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py` (export).\n\n## Before you reach for one — the honest gate\n\nA pixelization is the most powerful and the most expensive model here, with failure modes the\nparametric models do not have. Three questions decide whether you need it:\n\n- *\"What do the residuals actually look like?\"* Structured residuals that **follow the\n isophotes** — a twist, a four-lobed pattern, an ellipticity that changes with radius — are a\n *shape* problem, and an MGE fixes them for four free parameters\n ([`ag_basis_profiles`](./ag_basis_profiles.md)). Residuals in **discrete off-centre lumps** are\n a substructure problem, and that is what a pixelization is for. Look before you choose.\n- *\"Is the structure resolved?\"* At low resolution the irregular structure is not in the data,\n and a pixelization will reconstruct noise while telling you it fitted well. The workspace is\n blunt about this: for low-resolution data pixelizations are unnecessary.\n- *\"Do you need global quantities or the light distribution?\"* If you want a total flux, a size,\n an axis ratio, a Sersic index — a parametric profile, an MGE or shapelets are enough and far\n cheaper. If you want the morphology itself, particularly for faint or low-surface-brightness\n features, nothing else comes close.\n\nIf the answer to the first is \"lumps\" and to the second \"yes\", continue. Otherwise you will\nspend hours to learn less.\n\n## Ask\n\n- *\"What is the smooth component?\"* Almost always a linear `Sersic`, sometimes a Sersic plus an\n Exponential disk. It matters that this exists: without it the pixelization has to reconstruct\n the bright central bulge too, which wastes mesh resolution on light a six-parameter profile\n describes perfectly and makes the regularization choice much harder.\n- *\"How many mesh pixels can you afford?\"* This is a hardware question as much as a science one\n (see the run-time branch). 20 × 20 is the workspace's default for a GPU run; 28 × 28 to 30 × 30\n for a better-resolved reconstruction; higher only with a large-VRAM GPU or a many-core CPU.\n- *\"Are there neighbours inside the mask?\"* For a pixelization the answer is *never* to mask\n their pixels out — that punches holes in the mesh and produces discontinuity systematics.\n Scale their noise instead (branch below).\n- *\"GPU or CPU?\"* Genuinely depends on your pixel scale, and the answer is counter-intuitive.\n Ask before assuming.\n\n## Branch — the hybrid model\n\nThe canonical composition. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py`.\n\n```python\n\"\"\"\nGalaxy Structure: Bulge Plus Pixelized Reconstruction\n=====================================================\n\nFit a galaxy whose light has two very different characters: a smooth central bulge, described by\na linear Sersic profile in six parameters, and asymmetric clumpy star formation, reconstructed\non a regularized rectangular mesh. The Sersic captures the smooth component interpretably; the\npixelization absorbs everything it cannot explain, and the reconstructed flux map is the\nmeasurement of the galaxy's irregular light.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the imaging, mask it, and apply pixelization over-sampling.\n- **Mesh Shape:** Fix the mesh dimensions before the model is composed.\n- **Model:** Compose the linear Sersic bulge plus the pixelization.\n- **Check:** Confirm the parameter count, evaluate one likelihood, and estimate VRAM.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPIXEL_SCALES = 0.1\nMASK_RADIUS = 2.0\n\n\"\"\"\n__Dataset__\n\nThe mask matters more than usual here. It defines the region the mesh is laid over, so a mask\nthat reaches well beyond the galaxy spends reconstruction pixels on empty sky, and one that\ntruncates the galaxy leaves its outer light unreconstructed\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe over-sampling argument changes too. A pixelization evaluates light on its *own* grid with\nits own over-sampling scheme, so the size is passed as `over_sample_size_pixelization`, not the\n`over_sample_size_lp` used for light profiles. Passing the wrong one silently leaves the\npixelization grid at its default.\n\"\"\"\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=PIXEL_SCALES,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\ndataset = dataset.apply_over_sampling(over_sample_size_pixelization=over_sample_size)\n\n\"\"\"\n__Mesh Shape__\n\nThe mesh dimensions are **fixed before the fit and cannot be a free parameter**. This is not a\nstylistic restriction: JAX compiles the likelihood against statically shaped arrays, and the\nmesh shape sets those shapes. A rectangular mesh uses the same number of pixels in y and x.\n\"\"\"\nmesh_pixels_yx = 20\nmesh_shape = (mesh_pixels_yx, mesh_pixels_yx)\n\n\"\"\"\n__Model__\n\n`ag.Pixelization` pairs a `mesh` — where the reconstruction pixels sit — with a `regularization`\nscheme — the prior that keeps the solution smooth. It is attached to the galaxy as a component\nalongside the light profiles, and the analysis knows to route it through the inversion\n(`PyAutoGalaxy:autogalaxy/galaxy/galaxy.py`).\n\nThe mesh itself contributes **zero** free parameters; the reconstruction's 400 flux values are\nsolved, not sampled. `ag.reg.GaussianKernel` contributes two (`coefficient`, `scale`). The bulge\nis `ag.lp_linear.Sersic` rather than `ag.lp.Sersic` deliberately: its `intensity` is then solved\nby the *same* inversion that solves the mesh amplitudes, which removes the degeneracy between\n\"bright bulge, faint reconstruction\" and \"faint bulge, bright reconstruction\" that a sampled\nintensity would create.\n\"\"\"\npixelization = af.Model(\n ag.Pixelization,\n mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n regularization=ag.reg.GaussianKernel,\n)\n\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n pixelization=pixelization,\n)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\nThree cheap checks, each catching a different class of mistake: the parameter count catches a\nmodel error, one likelihood evaluation catches an incompatibility between model, dataset and\nanalysis, and `print_vram_use` catches the resource error that otherwise appears as an\nout-of-memory failure mid-compile. Pixelizations use far more VRAM than profile-only models —\naround 0.05 GB per batched likelihood for 400 reconstruction pixels — which is why the\nworkspace uses a lower `n_batch` for these fits than for any other.\n\"\"\"\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\nlog_likelihood = analysis.log_likelihood_function(\n instance=model.instance_from_prior_medians()\n)\nprint(f\"log evidence at prior medians: {float(log_likelihood):.2f}\")\n```\n\n**N = 8**: the Sersic's centre (2), `ell_comps` (2), `effective_radius`, `sersic_index`, plus the\nregularization's `coefficient` and `scale`. Eight parameters, with 400 reconstruction pixels\nsolved. That is dramatically more parsimonious than stacking parametric profiles until every\nclump is described — a 20-plus-parameter approach that would still fail on genuinely irregular\nsubstructure.\n\nExtending the smooth side is exactly as you would expect — add components as further attributes\non the galaxy, keeping them linear so their intensities join the same inversion:\n\n```python\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n disk=ag.lp_linear.Exponential,\n pixelization=pixelization,\n)\n```\n\n## Branch — choosing a mesh and a regularization scheme\n\nThese are the two decisions that make or break a reconstruction, and the parameter cost is\nalmost entirely in the regularization.\n\n**Meshes** (`ag.mesh`, from `PyAutoArray:autoarray/inversion/mesh/`). All contribute zero free\nparameters, all take `shape=(y, x)`:\n\n| Mesh | Where the pixels go | Use when |\n|---|---|---|\n| `RectangularUniform` | a uniform grid over the masked region | you want the simplest, most predictable behaviour |\n| `RectangularBilinearAdaptDensity` | a rectangular grid whose spacing follows the density of image pixels mapping to it, via a rank CDF | **the default** — concentrates resolution where the data is, and the fast CPU path |\n| `RectangularBilinearAdaptImage` | adapts to the image's own brightness distribution | the irregular light is strongly concentrated |\n| `RectangularRTUAdaptDensity` / `RectangularRTUAdaptImage` | the same two adaptations through a kernel CDF | GPU, JAX gradient samplers and the interferometer sparse path — the only rectangular adaptive meshes with usable gradients |\n\n`Delaunay`, `KNearestNeighbor` and `KNNBarycentric` also exist for irregular tessellations. Start\nwith `RectangularBilinearAdaptDensity`; it is what every workspace example uses, and the\nrectangular meshes are what the fixed-`mesh_shape` JAX path is built around. (The unqualified\n`RectangularAdaptDensity` / `RectangularAdaptImage` names were split into the `Bilinear` and\n`RTU` families in PyAutoArray 2026.8.23.1 and no longer resolve.)\n\n**Regularization** (`ag.reg`, from `PyAutoArray:autoarray/inversion/regularization/`) is where\nthe free parameters are, and where the physics of \"how smooth should this be?\" lives:\n\n| Scheme | Free params | What it assumes |\n|---|---|---|\n| `ag.reg.Constant` | 1 (`coefficient`) | one smoothing strength everywhere — the simplest, and the right first try |\n| `ag.reg.GaussianKernel` | 2 (`coefficient`, `scale`) | smoothing with a Gaussian correlation length you also fit |\n| `ag.reg.MaternKernel` | 3 (`coefficient`, `scale`, `nu`) | as above, with the roughness `nu` free too |\n\nVerified counts, not guesses. `Constant` penalises the difference between neighbouring pixels\ndirectly; the kernel schemes impose a correlation *length*, which is physically closer to what a\ngalaxy's light does and generally reconstructs faint extended structure better at the cost of\none or two parameters. `ag.reg.Adapt` and its variants scale the smoothing with the\nreconstruction's own brightness — more flexible again, and requiring `adapt_images` on the\nanalysis, which is a step beyond this skill; ask if you want it.\n\nA practical route: fit once with `ag.reg.Constant`, look at the reconstruction. Over-smoothed\n(the clumps blurred into one blob) or over-fitted (isolated single-pixel spikes) both show up\nimmediately, and if `Constant` cannot get both the bright clumps and the faint envelope right at\none strength, that is the signal to move to `GaussianKernel`. Full discussion in\n[`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\n### The positive-only solver\n\nEvery pixelized reconstruction uses a **positive-only** linear solver: no mesh pixel may\nreconstruct negative flux. This is not a numerical nicety. A signed solver lets the\nreconstruction manufacture negative pixels that cancel positive ones to over-fit the data, and\nthat failure mode is a well-known systematic in the literature — many published methods allow\nit. Enforcing non-negativity efficiently needs bespoke linear algebra, which is why this is\nworth stating rather than assuming. You do not need to switch it on; it is the behaviour you get.\n(The one place in this workspace where you *must* disable it is a shapelet basis, which needs\nsigned amplitudes by construction — see [`ag_basis_profiles`](./ag_basis_profiles.md).)\n\n## Branch — contaminating neighbours: scale, never mask\n\nThe general advice for a neighbour inside the mask is to mask its pixels out. **For a\npixelization that advice is wrong.** Removing image pixels entirely removes their mapping into\nthe mesh, punching a hole in the reconstruction and producing discontinuities that show up as\nunexplained systematics.\n\nInstead, keep the pixels in the fit and make them contribute nothing: scale their data to zero\nand their noise to an enormous value, so the likelihood is indifferent to them while the mesh\nstays continuous. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py`.\n\n```python\n\"\"\"\n__Noise Scaling__\n\n`mask_extra_galaxies.fits` marks the contaminated pixels. It is loaded with `invert=True`\nbecause in this file `True` means \"scale this pixel\", the opposite of a modelling mask's\nconvention — getting this backwards scales the galaxy instead of the neighbour, so check the\nsubplot afterwards. `apply_noise_scaling` then zeroes those data values and inflates their\nnoise, driving their signal-to-noise to effectively zero without removing them from the mesh's\nmapping (`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nOrder matters: scale first, then apply the modelling mask.\n\"\"\"\nmask_extra_galaxies = ag.Mask2D.from_fits(\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n pixel_scales=PIXEL_SCALES,\n invert=True,\n)\n\ndataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=PIXEL_SCALES,\n centre=(0.0, 0.0),\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=\"scripts/scratch/my_galaxy/\",\n output_filename=\"noise_scaled\",\n output_format=\"png\",\n)\n```\n\nThe scaled pixels go to a noise value of order 1e8 — visibly so on the signal-to-noise panel of\nthe subplot, which is how you confirm you scaled the right region. Drawing that mask\ninteractively is `autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask_extra_galaxies.py`;\nthe modelling alternative, and when to prefer it, is\n[`ag_light_model_extras`](./ag_light_model_extras.md) and\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch — reading the reconstruction out\n\nThe reconstruction is the science product, and it lives on the `Inversion`. You can get there\nfrom a completed fit or from a single direct `ag.FitImaging` — the latter is the fast way to\nlearn the objects, and is what\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` does.\n\n```python\n\"\"\"\n__Reconstruction__\n\n`inversion.linear_obj_list` holds the linear objects the fit solved. For a hybrid model that is\none `LightProfileLinearObjFuncList` per linear light profile plus one `Mapper` for the\npixelization; with a non-linear `ag.lp.Sersic` bulge the `Mapper` is the only entry. The\n`Mapper` is the object that maps image pixels onto mesh pixels, and it is mesh-specific\n(`PyAutoArray:autoarray/inversion/mappers/`).\n\nThe reconstruction is a 1D array of one flux per mesh pixel, and the (y, x) arcsecond\ncoordinates of those pixels are `mapper.mesh_geometry.mesh_grid`. Pair them by index — they are\nthe same length and the same order — and you have the flux map.\n\"\"\"\ninversion = fit.inversion\n\nmapper = inversion.linear_obj_list[0]\n\nreconstruction = inversion.reconstruction\nmesh_grid = mapper.mesh_geometry.mesh_grid\n\nprint(f\"{len(reconstruction)} mesh pixels reconstructed\")\nprint(f\"coordinates shape: {mesh_grid.shape}\")\n\n\"\"\"\nThe reconstruction's own uncertainties, and its projection back onto the image, are also on the\ninversion. `mapped_reconstructed_operated_data` contains **only** the pixelized component — any\nparametric light profile in the model is excluded — which is exactly the quantity you want when\nasking how much light is in the irregular component.\n\"\"\"\nprint(inversion.reconstruction_noise_map)\nprint(inversion.mapped_reconstructed_operated_data.native.shape)\n```\n\nA caution on the `Mapper`'s grid attributes: `mapper.image_plane_mesh_grid` is `None` for a\nrectangular mesh, so do not reach for it. `mapper.mesh_geometry.mesh_grid` is the mesh pixel\ncentres (verified on the released stack), and `mapper.image_plane_data_grid` is the centre of\nevery masked *image* pixel. Some of the `Mapper`'s attribute names carry a plane-based prefix\ninherited from the shared inversion library that also serves a multi-plane use case; in\nPyAutoGalaxy there is only the one plane, so `mesh_geometry.mesh_grid` is both the clearer name\nand the one to use.\n\n### The evidence terms\n\nThe inversion's figure of merit is a Bayesian evidence, and its components are individually\nreadable — which is how you diagnose whether regularization is doing too much or too little:\n\n```python\nprint(f\"regularization term = {inversion.regularization_term}\")\nprint(f\"log det regularization = {inversion.log_det_regularization_matrix_term}\")\nprint(f\"log det curvature + reg = {inversion.log_det_curvature_reg_matrix_term}\")\n```\n\nThe `regularization_term` measures how non-smooth the solution is; the two log-determinant\nterms are the complexity penalty that stops a 400-pixel model winning by over-fitting. The\nmatrices themselves (`curvature_matrix`, `regularization_matrix`, `curvature_reg_matrix`) are\nthere too. The derivation is in HowToGalaxy chapter 3 and the papers it cites\n(arXiv:1708.07377, arXiv:astro-ph/0601493).\n\n### Diagnostic plots\n\n`aplt.subplot_fit_imaging` includes the reconstruction on the mesh alongside the usual data /\nmodel / residual panels, and is the first thing to look at. For the inversion's own internals\nthere are dedicated functions, which live in the shared inversion library rather than on `aplt`\nand so are imported explicitly — from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/plot.py`:\n\n```python\nfrom autoarray.inversion.plot.inversion_plots import subplot_of_mapper\nfrom autoarray.inversion.plot.mapper_plots import plot_mapper, subplot_image_and_mapper\n\nPLOT_DIR = \"scripts/scratch/my_galaxy/pixelization/\"\n\naplt.subplot_fit_imaging(fit=fit, output_path=PLOT_DIR, output_format=\"png\")\n\nsubplot_of_mapper(\n inversion=inversion, mapper_index=0, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nsubplot_image_and_mapper(\n mapper=mapper, image=dataset.data, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nprint(f\"Saved to: {Path(PLOT_DIR).resolve()}\")\n```\n\n`subplot_of_mapper` is the comprehensive diagnostic — reconstructed image, reconstruction, its\nnoise map and the regularization weights in one figure — and `mapper_index` selects which linear\nobject when there are several. `subplot_image_and_mapper` shows the data beside the mesh, which\nis how you check the mesh covers the structure you care about. Note that none of these three are\nexposed on the `aplt` module — `dir(aplt)` does not list them, so the explicit imports above are\nthe only route and writing them as `aplt.`-prefixed calls raises `AttributeError`. Quote the\nabsolute path back to the user and offer to open it.\n\n## Branch — exporting the reconstruction for downstream science\n\nA reconstruction that only exists inside a PyAutoGalaxy object is hard to share and hard to\nanalyse with other tools. Write it out as coordinates plus values and it becomes ordinary\ntabular data. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py`.\n\n```python\n\"\"\"\n__Export__\n\nFour columns — y, x, reconstruction, noise — is everything needed to rebuild, plot or analyse\nthe galaxy's irregular light without PyAutoGalaxy installed. A completed model-fit also writes\nthis file into its own `image/` folder automatically; glob for `*reconstruction_0.csv` there\nrather than hard-coding the stem, which carries a prefix from the shared inversion library.\n\"\"\"\nimport csv\n\nCSV_PATH = Path(\"scripts/scratch/my_galaxy/reconstruction.csv\")\nCSV_PATH.parent.mkdir(parents=True, exist_ok=True)\n\nwith CSV_PATH.open(\"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([\"y\", \"x\", \"reconstruction\", \"noise_map\"])\n for (y, x), value, sigma in zip(\n mesh_grid, inversion.reconstruction, inversion.reconstruction_noise_map\n ):\n writer.writerow([y, x, value, sigma])\n\nprint(f\"Reconstruction written to: {CSV_PATH.resolve()}\")\n```\n\nReloading needs nothing but the standard library, and from there the mesh is ordinary scattered\ndata. Two things the workspace does with it: a Delaunay triangulation via `scipy.spatial` for\nplotting on the mesh's own geometry, and interpolation onto a regular grid via\n`scipy.interpolate.griddata` for any tool that wants an image:\n\n```python\nimport numpy as np\nfrom scipy.interpolate import griddata\n\nwith CSV_PATH.open() as f:\n reader = csv.reader(f)\n header = next(reader) # ['y', 'x', 'reconstruction', 'noise_map']\n loaded = {key: [] for key in header}\n for row in reader:\n for key, value in zip(header, row):\n loaded[key].append(float(value))\n\npoints = np.stack((np.array(loaded[\"x\"]), np.array(loaded[\"y\"])), axis=-1)\n\ninterpolation_grid = ag.Grid2D.from_extent(\n extent=(-1.0, 1.0, -1.0, 1.0), shape_native=(201, 201)\n)\n\ninterpolated = griddata(\n points=points, values=np.array(loaded[\"reconstruction\"]), xi=interpolation_grid\n)\n```\n\nPick the `extent` to cover the reconstruction without over-resolving it — the mesh has a few\nhundred pixels, so interpolating to 201 × 201 is presentation, not information.\n\n## Branch — run time, VRAM, and the GPU-versus-CPU choice\n\nThis is the branch that decides whether your fit takes twenty minutes or three hours, and the\nanswer is not \"use the GPU\".\n\nPixelized inversions do linear algebra on very large, very **sparse** matrices. JAX has no sparse\nsupport and must work densely, which scales badly; the CPU implementation exploits the sparsity\nfully via `numba`. So the trade runs against pixel scale:\n\n- **Low resolution (`pixel_scales > 0.05`, e.g. Euclid)** — fewer sparse operations, modest VRAM.\n **GPU with JAX is usually fastest.**\n- **High resolution (`pixel_scales <= 0.03`, e.g. HST or JWST)** — the linear algebra is\n sparsity-dominated. **CPU with `numba` and many cores can beat a powerful GPU.**\n\nVRAM is the hard constraint on the GPU side. JAX must hold the whole batched likelihood in GPU\nmemory, and a pixelization needs far more than a profile model: around 0.05 GB per batched\nlikelihood at 400 reconstruction pixels, and more than 1 GB — occasionally more than 10 GB — at\nhigh resolution with a fine mesh. Two consequences: keep `n_batch` low (the workspace uses 20 for\npixelizations against 50 elsewhere), and run\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nbefore committing. It takes 20–30 seconds and it is the difference between knowing your limit\nand discovering it as an out-of-memory error mid-compile. If VRAM is exceeded the run time does\nnot degrade gracefully — it goes from under ten minutes to three hours or more.\n\nRough scaling with resolution, from the workspace's own measurements at a 20 × 20 mesh with VRAM\nunder control: ~10 minutes at 0.1\"/pixel, ~30 minutes at 0.05\", ~1 hour at 0.03\". Benchmark both\npaths for your own data and hardware rather than trusting either default; the search-side\nsettings are [`ag_configure_search`](./ag_configure_search.md) and\n[`../wiki/core/api/searches.md`](../wiki/core/api/searches.md).\n\n## Combine — where this hands off\n\n- **Try a basis first** → [`ag_basis_profiles`](./ag_basis_profiles.md). An MGE is four\n parameters and minutes, not hours, and it genuinely resolves the shape-mismatch case a\n pixelization is often reached for by mistake.\n- **Pick and configure the search** → [`ag_configure_search`](./ag_configure_search.md), with\n `n_batch` lowered for VRAM.\n- **Run the fit** → [`ag_run_search`](./ag_run_search.md); `image/fit.png` in the output folder\n refreshes on the fly and shows the reconstruction as it converges, which is worth watching for\n a fit this long.\n- **Plot and inspect** → [`ag_plot_fit`](./ag_plot_fit.md), plus the `subplot_of_mapper`\n diagnostics above.\n- **Load a completed fit programmatically** → [`ag_load_results`](./ag_load_results.md).\n- **Over-smoothed, over-fitted or unphysical reconstruction** →\n [`ag_debug_fit_failure`](./ag_debug_fit_failure.md). The pixelization-specific causes are a\n regularization scheme too rigid for the structure, a mask that punched holes via hard masking\n where noise scaling was needed, over-sampling passed as `over_sample_size_lp` instead of\n `over_sample_size_pixelization`, and VRAM exhaustion masquerading as a hung fit.\n- **Contaminating neighbours modelled rather than scaled** →\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- **Make the fit robust and fast by starting simple** → the search-chaining skill\n (`ag_chain_searches`). This is the biggest available win for a pixelization: fit a parametric\n model first, pass its bulge as priors, and let the expensive model start from a sensible place.\n The workspace recommends it explicitly.\n- **A non-parametric shape measurement instead of a reconstruction** →\n [`ag_ellipse_fitting`](./ag_ellipse_fitting.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording the mesh and its\nshape, the regularization scheme and why, the mask radius, the hardware path, and what the\nreconstruction showed — with a pixelization the choices *are* the result, and none of them are\nrecoverable from the output folder alone.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Bayesian regularization](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb):\n why a model with hundreds of free flux values does not simply over-fit, derived from scratch;\n `tutorial_6_model_fit` then runs the full fit.\n- **General reference** — [RTD: Pixelization API](https://pyautogalaxy.readthedocs.io/en/latest/api/pixelization.html):\n every mesh, regularization scheme and the objects that combine them.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n the hybrid fit end to end, with the run-time, VRAM and GPU-versus-CPU discussion in full.\n\n## Agent procedural checklist\n\n1. Look at the residual map of a parametric or basis fit first. Shape-following residuals mean\n `ag_basis_profiles`; discrete off-centre lumps mean a pixelization. Do not skip this.\n2. Confirm the structure is resolved — at coarse pixel scales a pixelization reconstructs noise.\n3. Always pair the pixelization with a linear light profile for the smooth component; never let\n the mesh reconstruct the bulge.\n4. Fix `mesh_shape` before composing the model; it cannot be a free parameter.\n5. Pass over-sampling as `over_sample_size_pixelization`, not `over_sample_size_lp`.\n6. Start with `RectangularBilinearAdaptDensity` + `ag.reg.Constant`; move to `GaussianKernel` only when\n one smoothing strength demonstrably cannot serve both the bright and faint structure.\n7. Scale contaminant noise (`apply_noise_scaling`, `invert=True`) — never hard-mask pixels inside\n a pixelization fit — and check the signal-to-noise panel afterwards.\n8. `print(model.info)`, evaluate one likelihood, then `print_vram_use` before any GPU run; keep\n `n_batch` low.\n9. Read the reconstruction via `inversion.reconstruction` +\n `mapper.mesh_geometry.mesh_grid`; export to CSV for anything downstream.\n10. Save the script to `scripts/`, quote every plot's absolute path and offer to open it, then\n offer the `wiki/project/` entry recording mesh, regularization and hardware choices.\n" + "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb in HowToGalaxy).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoGalaxy calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoGalaxy docs (https://pyautogalaxy.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_pixelization\n\n---\nname: ag_pixelization\ndescription: Reconstruct a galaxy's clumpy or irregular light directly on a regularized pixel mesh, using `ag.Pixelization` alongside a parametric `ag.lp_linear` bulge \u2014 the hybrid model that gives a smooth interpretable component plus a flexible flux map for everything the profile cannot explain. Covers when a pixelization is warranted and when it is overkill, choosing an `ag.mesh` and an `ag.reg` regularization scheme and what each costs in free parameters, why `mesh_shape` must be fixed before the fit, `over_sample_size_pixelization` rather than `over_sample_size_lp`, noise scaling instead of hard masking for contaminants, the positive-only solver, reading the reconstruction and its Bayesian-evidence terms out of the `Inversion`, exporting the reconstruction to CSV for collaborators, and the GPU/VRAM versus CPU run-time trade. Use when a Sersic, MGE or shapelet basis leaves structured residuals in discrete off-centre lumps. Not for morphology a basis can still fit (`ag_basis_profiles`), not for non-parametric isophote measurement (`ag_ellipse_fitting`), and not for the basics of model composition (`ag_build_imaging_model`).\n---\n\n# Reconstructing a galaxy on a pixel mesh\n\nEvery model in this workspace so far has been a *function*: you asserted a functional form and\nthe fit found its parameters. A pixelization drops the functional form. It lays a mesh of pixels\nover the galaxy, gives each pixel its own free flux value, and solves all of them at once by\nlinear inversion \u2014 thousands of amplitudes, none of them in the non-linear search's parameter\nspace. What stops that from simply fitting the noise is **regularization**: a prior that\npenalises solutions where neighbouring mesh pixels differ sharply, so the reconstruction is as\nsmooth as the data will allow and no smoother.\n\nThe science case is specific, and it is worth being honest about how specific. Galaxies with\nspiral arms, asymmetric star-forming clumps, tidal features or low-surface-brightness\nsubstructure have light that no smooth profile \u2014 and often no basis expansion either \u2014\nreproduces. The canonical use is therefore **hybrid**: a linear `Sersic` for the smooth central\nbulge, and a pixelization for the irregular remainder. That split is the point. It gives you a\nlow-dimensional, physically interpretable description of the bulge *and* a flux map of exactly\nwhat the bulge could not explain, which is the quantity you want if the science question is \"how\nmuch of this galaxy's light is in its irregular components?\"\n\nThis is a **direct** reconstruction. There is no second plane, no de-projection, no inversion of\na geometric mapping \u2014 the mesh sits on the image plane, over the galaxy, at the same coordinates\nthe data occupies. If you have met pixelized reconstruction before in a different context, that\nextra step is the one that is absent here, and its absence makes everything simpler: what the\nmesh reconstructs is the galaxy's own surface brightness, and its coordinates are sky\ncoordinates in arcseconds.\n\nStatistically, the fit now has two nested layers. The non-linear search explores a handful of\nparameters \u2014 the bulge's shape, the regularization strength \u2014 and for each proposal an inversion\nsolves the mesh amplitudes exactly and returns a **Bayesian evidence** rather than a plain\nlikelihood. That evidence includes terms that penalise an unnecessarily complex reconstruction,\nwhich is what lets a model with 400 free flux values not simply win by over-fitting. The theory\nis [`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md);\nchapter 3 of HowToGalaxy derives it from scratch.\n\nThe canonical scripts are\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py` (via a search),\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` (one direct fit, with the\ninversion internals walked through) and\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py` (export).\n\n## Before you reach for one \u2014 the honest gate\n\nA pixelization is the most powerful and the most expensive model here, with failure modes the\nparametric models do not have. Three questions decide whether you need it:\n\n- *\"What do the residuals actually look like?\"* Structured residuals that **follow the\n isophotes** \u2014 a twist, a four-lobed pattern, an ellipticity that changes with radius \u2014 are a\n *shape* problem, and an MGE fixes them for four free parameters\n ([`ag_basis_profiles`](./ag_basis_profiles.md)). Residuals in **discrete off-centre lumps** are\n a substructure problem, and that is what a pixelization is for. Look before you choose.\n- *\"Is the structure resolved?\"* At low resolution the irregular structure is not in the data,\n and a pixelization will reconstruct noise while telling you it fitted well. The workspace is\n blunt about this: for low-resolution data pixelizations are unnecessary.\n- *\"Do you need global quantities or the light distribution?\"* If you want a total flux, a size,\n an axis ratio, a Sersic index \u2014 a parametric profile, an MGE or shapelets are enough and far\n cheaper. If you want the morphology itself, particularly for faint or low-surface-brightness\n features, nothing else comes close.\n\nIf the answer to the first is \"lumps\" and to the second \"yes\", continue. Otherwise you will\nspend hours to learn less.\n\n## Ask\n\n- *\"What is the smooth component?\"* Almost always a linear `Sersic`, sometimes a Sersic plus an\n Exponential disk. It matters that this exists: without it the pixelization has to reconstruct\n the bright central bulge too, which wastes mesh resolution on light a six-parameter profile\n describes perfectly and makes the regularization choice much harder.\n- *\"How many mesh pixels can you afford?\"* This is a hardware question as much as a science one\n (see the run-time branch). 20 \u00d7 20 is the workspace's default for a GPU run; 28 \u00d7 28 to 30 \u00d7 30\n for a better-resolved reconstruction; higher only with a large-VRAM GPU or a many-core CPU.\n- *\"Are there neighbours inside the mask?\"* For a pixelization the answer is *never* to mask\n their pixels out \u2014 that punches holes in the mesh and produces discontinuity systematics.\n Scale their noise instead (branch below).\n- *\"GPU or CPU?\"* Genuinely depends on your pixel scale, and the answer is counter-intuitive.\n Ask before assuming.\n\n## Branch \u2014 the hybrid model\n\nThe canonical composition. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py`.\n\n```python\n\"\"\"\nGalaxy Structure: Bulge Plus Pixelized Reconstruction\n=====================================================\n\nFit a galaxy whose light has two very different characters: a smooth central bulge, described by\na linear Sersic profile in six parameters, and asymmetric clumpy star formation, reconstructed\non a regularized rectangular mesh. The Sersic captures the smooth component interpretably; the\npixelization absorbs everything it cannot explain, and the reconstructed flux map is the\nmeasurement of the galaxy's irregular light.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the imaging, mask it, and apply pixelization over-sampling.\n- **Mesh Shape:** Fix the mesh dimensions before the model is composed.\n- **Model:** Compose the linear Sersic bulge plus the pixelization.\n- **Check:** Confirm the parameter count, evaluate one likelihood, and estimate VRAM.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPIXEL_SCALES = 0.1\nMASK_RADIUS = 2.0\n\n\"\"\"\n__Dataset__\n\nThe mask matters more than usual here. It defines the region the mesh is laid over, so a mask\nthat reaches well beyond the galaxy spends reconstruction pixels on empty sky, and one that\ntruncates the galaxy leaves its outer light unreconstructed\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe over-sampling argument changes too. A pixelization evaluates light on its *own* grid with\nits own over-sampling scheme, so the size is passed as `over_sample_size_pixelization`, not the\n`over_sample_size_lp` used for light profiles. Passing the wrong one silently leaves the\npixelization grid at its default.\n\"\"\"\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=PIXEL_SCALES,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\ndataset = dataset.apply_over_sampling(over_sample_size_pixelization=over_sample_size)\n\n\"\"\"\n__Mesh Shape__\n\nThe mesh dimensions are **fixed before the fit and cannot be a free parameter**. This is not a\nstylistic restriction: JAX compiles the likelihood against statically shaped arrays, and the\nmesh shape sets those shapes. A rectangular mesh uses the same number of pixels in y and x.\n\"\"\"\nmesh_pixels_yx = 20\nmesh_shape = (mesh_pixels_yx, mesh_pixels_yx)\n\n\"\"\"\n__Model__\n\n`ag.Pixelization` pairs a `mesh` \u2014 where the reconstruction pixels sit \u2014 with a `regularization`\nscheme \u2014 the prior that keeps the solution smooth. It is attached to the galaxy as a component\nalongside the light profiles, and the analysis knows to route it through the inversion\n(`PyAutoGalaxy:autogalaxy/galaxy/galaxy.py`).\n\nThe mesh itself contributes **zero** free parameters; the reconstruction's 400 flux values are\nsolved, not sampled. `ag.reg.GaussianKernel` contributes two (`coefficient`, `scale`). The bulge\nis `ag.lp_linear.Sersic` rather than `ag.lp.Sersic` deliberately: its `intensity` is then solved\nby the *same* inversion that solves the mesh amplitudes, which removes the degeneracy between\n\"bright bulge, faint reconstruction\" and \"faint bulge, bright reconstruction\" that a sampled\nintensity would create.\n\"\"\"\npixelization = af.Model(\n ag.Pixelization,\n mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n regularization=ag.reg.GaussianKernel,\n)\n\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n pixelization=pixelization,\n)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\nThree cheap checks, each catching a different class of mistake: the parameter count catches a\nmodel error, one likelihood evaluation catches an incompatibility between model, dataset and\nanalysis, and `print_vram_use` catches the resource error that otherwise appears as an\nout-of-memory failure mid-compile. Pixelizations use far more VRAM than profile-only models \u2014\naround 0.05 GB per batched likelihood for 400 reconstruction pixels \u2014 which is why the\nworkspace uses a lower `n_batch` for these fits than for any other.\n\"\"\"\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\nlog_likelihood = analysis.log_likelihood_function(\n instance=model.instance_from_prior_medians()\n)\nprint(f\"log evidence at prior medians: {float(log_likelihood):.2f}\")\n```\n\n**N = 8**: the Sersic's centre (2), `ell_comps` (2), `effective_radius`, `sersic_index`, plus the\nregularization's `coefficient` and `scale`. Eight parameters, with 400 reconstruction pixels\nsolved. That is dramatically more parsimonious than stacking parametric profiles until every\nclump is described \u2014 a 20-plus-parameter approach that would still fail on genuinely irregular\nsubstructure.\n\nExtending the smooth side is exactly as you would expect \u2014 add components as further attributes\non the galaxy, keeping them linear so their intensities join the same inversion:\n\n```python\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n disk=ag.lp_linear.Exponential,\n pixelization=pixelization,\n)\n```\n\n## Branch \u2014 choosing a mesh and a regularization scheme\n\nThese are the two decisions that make or break a reconstruction, and the parameter cost is\nalmost entirely in the regularization.\n\n**Meshes** (`ag.mesh`, from `PyAutoArray:autoarray/inversion/mesh/`). All contribute zero free\nparameters, all take `shape=(y, x)`:\n\n| Mesh | Where the pixels go | Use when |\n|---|---|---|\n| `RectangularUniform` | a uniform grid over the masked region | you want the simplest, most predictable behaviour |\n| `RectangularBilinearAdaptDensity` | a rectangular grid whose spacing follows the density of image pixels mapping to it, via a rank CDF | **the default** \u2014 concentrates resolution where the data is, and the fast CPU path |\n| `RectangularBilinearAdaptImage` | adapts to the image's own brightness distribution | the irregular light is strongly concentrated |\n| `RectangularRTUAdaptDensity` / `RectangularRTUAdaptImage` | the same two adaptations through a kernel CDF | GPU, JAX gradient samplers and the interferometer sparse path \u2014 the only rectangular adaptive meshes with usable gradients |\n\n`Delaunay`, `KNearestNeighbor` and `KNNBarycentric` also exist for irregular tessellations. Start\nwith `RectangularBilinearAdaptDensity`; it is what every workspace example uses, and the\nrectangular meshes are what the fixed-`mesh_shape` JAX path is built around. (The unqualified\n`RectangularAdaptDensity` / `RectangularAdaptImage` names were split into the `Bilinear` and\n`RTU` families in PyAutoArray 2026.8.23.1 and no longer resolve.)\n\n**Regularization** (`ag.reg`, from `PyAutoArray:autoarray/inversion/regularization/`) is where\nthe free parameters are, and where the physics of \"how smooth should this be?\" lives:\n\n| Scheme | Free params | What it assumes |\n|---|---|---|\n| `ag.reg.Constant` | 1 (`coefficient`) | one smoothing strength everywhere \u2014 the simplest, and the right first try |\n| `ag.reg.GaussianKernel` | 2 (`coefficient`, `scale`) | smoothing with a Gaussian correlation length you also fit |\n| `ag.reg.MaternKernel` | 3 (`coefficient`, `scale`, `nu`) | as above, with the roughness `nu` free too |\n\nVerified counts, not guesses. `Constant` penalises the difference between neighbouring pixels\ndirectly; the kernel schemes impose a correlation *length*, which is physically closer to what a\ngalaxy's light does and generally reconstructs faint extended structure better at the cost of\none or two parameters. `ag.reg.Adapt` and its variants scale the smoothing with the\nreconstruction's own brightness \u2014 more flexible again, and requiring `adapt_images` on the\nanalysis, which is a step beyond this skill; ask if you want it.\n\nA practical route: fit once with `ag.reg.Constant`, look at the reconstruction. Over-smoothed\n(the clumps blurred into one blob) or over-fitted (isolated single-pixel spikes) both show up\nimmediately, and if `Constant` cannot get both the bright clumps and the faint envelope right at\none strength, that is the signal to move to `GaussianKernel`. Full discussion in\n[`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\n### The positive-only solver\n\nEvery pixelized reconstruction uses a **positive-only** linear solver: no mesh pixel may\nreconstruct negative flux. This is not a numerical nicety. A signed solver lets the\nreconstruction manufacture negative pixels that cancel positive ones to over-fit the data, and\nthat failure mode is a well-known systematic in the literature \u2014 many published methods allow\nit. Enforcing non-negativity efficiently needs bespoke linear algebra, which is why this is\nworth stating rather than assuming. You do not need to switch it on; it is the behaviour you get.\n(The one place in this workspace where you *must* disable it is a shapelet basis, which needs\nsigned amplitudes by construction \u2014 see [`ag_basis_profiles`](./ag_basis_profiles.md).)\n\n## Branch \u2014 contaminating neighbours: scale, never mask\n\nThe general advice for a neighbour inside the mask is to mask its pixels out. **For a\npixelization that advice is wrong.** Removing image pixels entirely removes their mapping into\nthe mesh, punching a hole in the reconstruction and producing discontinuities that show up as\nunexplained systematics.\n\nInstead, keep the pixels in the fit and make them contribute nothing: scale their data to zero\nand their noise to an enormous value, so the likelihood is indifferent to them while the mesh\nstays continuous. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py`.\n\n```python\n\"\"\"\n__Noise Scaling__\n\n`mask_extra_galaxies.fits` marks the contaminated pixels. It is loaded with `invert=True`\nbecause in this file `True` means \"scale this pixel\", the opposite of a modelling mask's\nconvention \u2014 getting this backwards scales the galaxy instead of the neighbour, so check the\nsubplot afterwards. `apply_noise_scaling` then zeroes those data values and inflates their\nnoise, driving their signal-to-noise to effectively zero without removing them from the mesh's\nmapping (`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nOrder matters: scale first, then apply the modelling mask.\n\"\"\"\nmask_extra_galaxies = ag.Mask2D.from_fits(\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n pixel_scales=PIXEL_SCALES,\n invert=True,\n)\n\ndataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=PIXEL_SCALES,\n centre=(0.0, 0.0),\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=\"scripts/scratch/my_galaxy/\",\n output_filename=\"noise_scaled\",\n output_format=\"png\",\n)\n```\n\nThe scaled pixels go to a noise value of order 1e8 \u2014 visibly so on the signal-to-noise panel of\nthe subplot, which is how you confirm you scaled the right region. Drawing that mask\ninteractively is `autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask_extra_galaxies.py`;\nthe modelling alternative, and when to prefer it, is\n[`ag_light_model_extras`](./ag_light_model_extras.md) and\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch \u2014 reading the reconstruction out\n\nThe reconstruction is the science product, and it lives on the `Inversion`. You can get there\nfrom a completed fit or from a single direct `ag.FitImaging` \u2014 the latter is the fast way to\nlearn the objects, and is what\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` does.\n\n```python\n\"\"\"\n__Reconstruction__\n\n`inversion.linear_obj_list` holds the linear objects the fit solved. For a hybrid model that is\none `LightProfileLinearObjFuncList` per linear light profile plus one `Mapper` for the\npixelization; with a non-linear `ag.lp.Sersic` bulge the `Mapper` is the only entry. The\n`Mapper` is the object that maps image pixels onto mesh pixels, and it is mesh-specific\n(`PyAutoArray:autoarray/inversion/mappers/`).\n\nThe reconstruction is a 1D array of one flux per mesh pixel, and the (y, x) arcsecond\ncoordinates of those pixels are `mapper.mesh_geometry.mesh_grid`. Pair them by index \u2014 they are\nthe same length and the same order \u2014 and you have the flux map.\n\"\"\"\ninversion = fit.inversion\n\nmapper = inversion.linear_obj_list[0]\n\nreconstruction = inversion.reconstruction\nmesh_grid = mapper.mesh_geometry.mesh_grid\n\nprint(f\"{len(reconstruction)} mesh pixels reconstructed\")\nprint(f\"coordinates shape: {mesh_grid.shape}\")\n\n\"\"\"\nThe reconstruction's own uncertainties, and its projection back onto the image, are also on the\ninversion. `mapped_reconstructed_operated_data` contains **only** the pixelized component \u2014 any\nparametric light profile in the model is excluded \u2014 which is exactly the quantity you want when\nasking how much light is in the irregular component.\n\"\"\"\nprint(inversion.reconstruction_noise_map)\nprint(inversion.mapped_reconstructed_operated_data.native.shape)\n```\n\nA caution on the `Mapper`'s grid attributes: `mapper.image_plane_mesh_grid` is `None` for a\nrectangular mesh, so do not reach for it. `mapper.mesh_geometry.mesh_grid` is the mesh pixel\ncentres (verified on the released stack), and `mapper.image_plane_data_grid` is the centre of\nevery masked *image* pixel. Some of the `Mapper`'s attribute names carry a plane-based prefix\ninherited from the shared inversion library that also serves a multi-plane use case; in\nPyAutoGalaxy there is only the one plane, so `mesh_geometry.mesh_grid` is both the clearer name\nand the one to use.\n\n### The evidence terms\n\nThe inversion's figure of merit is a Bayesian evidence, and its components are individually\nreadable \u2014 which is how you diagnose whether regularization is doing too much or too little:\n\n```python\nprint(f\"regularization term = {inversion.regularization_term}\")\nprint(f\"log det regularization = {inversion.log_det_regularization_matrix_term}\")\nprint(f\"log det curvature + reg = {inversion.log_det_curvature_reg_matrix_term}\")\n```\n\nThe `regularization_term` measures how non-smooth the solution is; the two log-determinant\nterms are the complexity penalty that stops a 400-pixel model winning by over-fitting. The\nmatrices themselves (`curvature_matrix`, `regularization_matrix`, `curvature_reg_matrix`) are\nthere too. The derivation is in HowToGalaxy chapter 3 and the papers it cites\n(arXiv:1708.07377, arXiv:astro-ph/0601493).\n\n### Diagnostic plots\n\n`aplt.subplot_fit_imaging` includes the reconstruction on the mesh alongside the usual data /\nmodel / residual panels, and is the first thing to look at. For the inversion's own internals\nthere are dedicated functions, which live in the shared inversion library rather than on `aplt`\nand so are imported explicitly \u2014 from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/plot.py`:\n\n```python\nfrom autoarray.inversion.plot.inversion_plots import subplot_of_mapper\nfrom autoarray.inversion.plot.mapper_plots import plot_mapper, subplot_image_and_mapper\n\nPLOT_DIR = \"scripts/scratch/my_galaxy/pixelization/\"\n\naplt.subplot_fit_imaging(fit=fit, output_path=PLOT_DIR, output_format=\"png\")\n\nsubplot_of_mapper(\n inversion=inversion, mapper_index=0, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nsubplot_image_and_mapper(\n mapper=mapper, image=dataset.data, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nprint(f\"Saved to: {Path(PLOT_DIR).resolve()}\")\n```\n\n`subplot_of_mapper` is the comprehensive diagnostic \u2014 reconstructed image, reconstruction, its\nnoise map and the regularization weights in one figure \u2014 and `mapper_index` selects which linear\nobject when there are several. `subplot_image_and_mapper` shows the data beside the mesh, which\nis how you check the mesh covers the structure you care about. Note that none of these three are\nexposed on the `aplt` module \u2014 `dir(aplt)` does not list them, so the explicit imports above are\nthe only route and writing them as `aplt.`-prefixed calls raises `AttributeError`. Quote the\nabsolute path back to the user and offer to open it.\n\n## Branch \u2014 exporting the reconstruction for downstream science\n\nA reconstruction that only exists inside a PyAutoGalaxy object is hard to share and hard to\nanalyse with other tools. Write it out as coordinates plus values and it becomes ordinary\ntabular data. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py`.\n\n```python\n\"\"\"\n__Export__\n\nFour columns \u2014 y, x, reconstruction, noise \u2014 is everything needed to rebuild, plot or analyse\nthe galaxy's irregular light without PyAutoGalaxy installed. A completed model-fit also writes\nthis file into its own `image/` folder automatically; glob for `*reconstruction_0.csv` there\nrather than hard-coding the stem, which carries a prefix from the shared inversion library.\n\"\"\"\nimport csv\n\nCSV_PATH = Path(\"scripts/scratch/my_galaxy/reconstruction.csv\")\nCSV_PATH.parent.mkdir(parents=True, exist_ok=True)\n\nwith CSV_PATH.open(\"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([\"y\", \"x\", \"reconstruction\", \"noise_map\"])\n for (y, x), value, sigma in zip(\n mesh_grid, inversion.reconstruction, inversion.reconstruction_noise_map\n ):\n writer.writerow([y, x, value, sigma])\n\nprint(f\"Reconstruction written to: {CSV_PATH.resolve()}\")\n```\n\nReloading needs nothing but the standard library, and from there the mesh is ordinary scattered\ndata. Two things the workspace does with it: a Delaunay triangulation via `scipy.spatial` for\nplotting on the mesh's own geometry, and interpolation onto a regular grid via\n`scipy.interpolate.griddata` for any tool that wants an image:\n\n```python\nimport numpy as np\nfrom scipy.interpolate import griddata\n\nwith CSV_PATH.open() as f:\n reader = csv.reader(f)\n header = next(reader) # ['y', 'x', 'reconstruction', 'noise_map']\n loaded = {key: [] for key in header}\n for row in reader:\n for key, value in zip(header, row):\n loaded[key].append(float(value))\n\npoints = np.stack((np.array(loaded[\"x\"]), np.array(loaded[\"y\"])), axis=-1)\n\ninterpolation_grid = ag.Grid2D.from_extent(\n extent=(-1.0, 1.0, -1.0, 1.0), shape_native=(201, 201)\n)\n\ninterpolated = griddata(\n points=points, values=np.array(loaded[\"reconstruction\"]), xi=interpolation_grid\n)\n```\n\nPick the `extent` to cover the reconstruction without over-resolving it \u2014 the mesh has a few\nhundred pixels, so interpolating to 201 \u00d7 201 is presentation, not information.\n\n## Branch \u2014 run time, VRAM, and the GPU-versus-CPU choice\n\nThis is the branch that decides whether your fit takes twenty minutes or three hours, and the\nanswer is not \"use the GPU\".\n\nPixelized inversions do linear algebra on very large, very **sparse** matrices. JAX has no sparse\nsupport and must work densely, which scales badly; the CPU implementation exploits the sparsity\nfully via `numba`. So the trade runs against pixel scale:\n\n- **Low resolution (`pixel_scales > 0.05`, e.g. Euclid)** \u2014 fewer sparse operations, modest VRAM.\n **GPU with JAX is usually fastest.**\n- **High resolution (`pixel_scales <= 0.03`, e.g. HST or JWST)** \u2014 the linear algebra is\n sparsity-dominated. **CPU with `numba` and many cores can beat a powerful GPU.**\n\nVRAM is the hard constraint on the GPU side. JAX must hold the whole batched likelihood in GPU\nmemory, and a pixelization needs far more than a profile model: around 0.05 GB per batched\nlikelihood at 400 reconstruction pixels, and more than 1 GB \u2014 occasionally more than 10 GB \u2014 at\nhigh resolution with a fine mesh. Two consequences: keep `n_batch` low (the workspace uses 20 for\npixelizations against 50 elsewhere), and run\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nbefore committing. It takes 20\u201330 seconds and it is the difference between knowing your limit\nand discovering it as an out-of-memory error mid-compile. If VRAM is exceeded the run time does\nnot degrade gracefully \u2014 it goes from under ten minutes to three hours or more.\n\nRough scaling with resolution, from the workspace's own measurements at a 20 \u00d7 20 mesh with VRAM\nunder control: ~10 minutes at 0.1\"/pixel, ~30 minutes at 0.05\", ~1 hour at 0.03\". Benchmark both\npaths for your own data and hardware rather than trusting either default; the search-side\nsettings are [`ag_configure_search`](./ag_configure_search.md) and\n[`../wiki/core/api/searches.md`](../wiki/core/api/searches.md).\n\n## Combine \u2014 where this hands off\n\n- **Try a basis first** \u2192 [`ag_basis_profiles`](./ag_basis_profiles.md). An MGE is four\n parameters and minutes, not hours, and it genuinely resolves the shape-mismatch case a\n pixelization is often reached for by mistake.\n- **Pick and configure the search** \u2192 [`ag_configure_search`](./ag_configure_search.md), with\n `n_batch` lowered for VRAM.\n- **Run the fit** \u2192 [`ag_run_search`](./ag_run_search.md); `image/fit.png` in the output folder\n refreshes on the fly and shows the reconstruction as it converges, which is worth watching for\n a fit this long.\n- **Plot and inspect** \u2192 [`ag_plot_fit`](./ag_plot_fit.md), plus the `subplot_of_mapper`\n diagnostics above.\n- **Load a completed fit programmatically** \u2192 [`ag_load_results`](./ag_load_results.md).\n- **Over-smoothed, over-fitted or unphysical reconstruction** \u2192\n [`ag_debug_fit_failure`](./ag_debug_fit_failure.md). The pixelization-specific causes are a\n regularization scheme too rigid for the structure, a mask that punched holes via hard masking\n where noise scaling was needed, over-sampling passed as `over_sample_size_lp` instead of\n `over_sample_size_pixelization`, and VRAM exhaustion masquerading as a hung fit.\n- **Contaminating neighbours modelled rather than scaled** \u2192\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- **Make the fit robust and fast by starting simple** \u2192 the search-chaining skill\n (`ag_chain_searches`). This is the biggest available win for a pixelization: fit a parametric\n model first, pass its bulge as priors, and let the expensive model start from a sensible place.\n The workspace recommends it explicitly.\n- **A non-parametric shape measurement instead of a reconstruction** \u2192\n [`ag_ellipse_fitting`](./ag_ellipse_fitting.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording the mesh and its\nshape, the regularization scheme and why, the mask radius, the hardware path, and what the\nreconstruction showed \u2014 with a pixelization the choices *are* the result, and none of them are\nrecoverable from the output folder alone.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [HowToGalaxy: Bayesian regularization](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb):\n why a model with hundreds of free flux values does not simply over-fit, derived from scratch;\n `tutorial_6_model_fit` then runs the full fit.\n- **General reference** \u2014 [RTD: Pixelization API](https://pyautogalaxy.readthedocs.io/en/latest/api/pixelization.html):\n every mesh, regularization scheme and the objects that combine them.\n- **Experienced PyAutoGalaxy user** \u2014 [workspace: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n the hybrid fit end to end, with the run-time, VRAM and GPU-versus-CPU discussion in full.\n\n## Agent procedural checklist\n\n1. Look at the residual map of a parametric or basis fit first. Shape-following residuals mean\n `ag_basis_profiles`; discrete off-centre lumps mean a pixelization. Do not skip this.\n2. Confirm the structure is resolved \u2014 at coarse pixel scales a pixelization reconstructs noise.\n3. Always pair the pixelization with a linear light profile for the smooth component; never let\n the mesh reconstruct the bulge.\n4. Fix `mesh_shape` before composing the model; it cannot be a free parameter.\n5. Pass over-sampling as `over_sample_size_pixelization`, not `over_sample_size_lp`.\n6. Start with `RectangularBilinearAdaptDensity` + `ag.reg.Constant`; move to `GaussianKernel` only when\n one smoothing strength demonstrably cannot serve both the bright and faint structure.\n7. Scale contaminant noise (`apply_noise_scaling`, `invert=True`) \u2014 never hard-mask pixels inside\n a pixelization fit \u2014 and check the signal-to-noise panel afterwards.\n8. `print(model.info)`, evaluate one likelihood, then `print_vram_use` before any GPU run; keep\n `n_batch` low.\n9. Read the reconstruction via `inversion.reconstruction` +\n `mapper.mesh_geometry.mesh_grid`; export to CSV for anything downstream.\n10. Save the script to `scripts/`, quote every plot's absolute path and offer to open it, then\n offer the `wiki/project/` entry recording mesh, regularization and hardware choices.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb b/notebooks/chapter_3_pixelizations/tutorial_2_bayesian_regularization.ipynb similarity index 57% rename from notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb rename to notebooks/chapter_3_pixelizations/tutorial_2_bayesian_regularization.ipynb index b30e7cc..2e98312 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_2_bayesian_regularization.ipynb @@ -4,30 +4,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Tutorial 4: Bayesian Regularization\n", - "===================================\n", - "\n", - "So far, we have:\n", - "\n", - " - Used pixelizations and mappers to map pixelization pixels to image-pixels and visa versa.\n", - " - Successfully used an inversion to reconstruct a galaxy.\n", - " - Seen that this reconstruction provides a good fit of the observed image, providing a high likelihood solution.\n", - "\n", - "The explanation of *how* an inversion works has so far been overly simplified. You'll have noted the regularization\n", - "inputs which we have not so far discussed. This will be the topic of this tutorial, and where inversions become more\n", - "conceptually challenging!\n", + "Tutorial 2: Bayesian Regularization\n", + "==================================\n", "\n", "__Contents__\n", "\n", - "- **Initial Setup:** Load the dataset for illustration.\n", - "- **Dataset Auto-Simulation:** Automatically simulate the dataset if it does not already exist.\n", - "- **Convenience Function:** A helper function for performing inversions.\n", - "- **Pixelization:** Perform inversions with different regularization coefficients.\n", - "- **Regularization:** Understand how regularization smooths the reconstruction.\n", - "- **Bayesian Evidence:** Use the Bayesian evidence to objectively choose the regularization coefficient.\n", - "- **Non-Linear and Linear:** Discussion of how regularization interacts with the non-linear search.\n", - "- **Detailed Description:** In-depth explanation of how the Bayesian evidence penalizes overfitting.\n", - "- **Wrap Up:** Summary of Bayesian regularization concepts." + "- Interpolation and our starting reconstruction.\n", + "- Reducing and increasing regularization.\n", + "- Bayesian evidence and a coefficient experiment.\n", + "- Inspecting the preferred reconstruction.\n", + "- Linear brightnesses and non-linear model choices.\n", + "- Comparing mesh resolutions." ] }, { @@ -69,16 +56,61 @@ ] }, { - "cell_type": "code", + "cell_type": "markdown", "metadata": {}, "source": [ + "__Interpolation and Bayesian regularization__\n", + "\n", + "So far, we have:\n", + "\n", + "- Used pixelizations and mappers to connect mesh points to image pixels.\n", + "- Used an inversion to reconstruct the galaxy\u2019s brightness.\n", + "- Mapped that reconstruction back into the image, including telescope blurring, to compare it with the data.\n", + "\n", + "Our explanation of how an inversion works has deliberately left some things unexplained. In particular, you will have\n", + "noticed the regularization input that we passed when creating our pixelization. We used a coefficient of `1.0`, but have\n", + "not established why that value should give an appropriate reconstruction.\n", + "\n", + "This tutorial explores what regularization does and why we need it. We will change its strength, inspect the resulting\n", + "galaxy reconstructions, and see why obtaining a close fit to the image is not enough on its own.\n", "\n", - "from autogalaxy import setup_notebook; setup_notebook()\n", + "First, we will revisit interpolation. It is easy to confuse interpolation with smoothing, because both affect the\n", + "appearance of the reconstructed galaxy. Understanding the distinction will help us interpret the experiments that\n", + "follow.\n", "\n", + "We use the same smooth bulge and disc dataset as tutorial 1. The mesh and data treatment remain fixed, so the first" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ "from pathlib import Path\n", + "import subprocess\n", + "import sys\n", + "import numpy as np\n", "import autogalaxy as ag\n", "import autogalaxy.plot as aplt\n", - "from autoarray.inversion.plot.inversion_plots import subplot_of_mapper" + "import autoarray.plot as aaplt\n", + "\n", + "dataset_path = Path(\"dataset\") / \"imaging\" / \"simple\"\n", + "if ag.util.dataset.should_simulate(str(dataset_path)):\n", + " subprocess.run([sys.executable, \"scripts/simulators/simple.py\"], check=True)\n", + "dataset = ag.Imaging.from_fits(\n", + " data_path=dataset_path / \"data.fits\",\n", + " noise_map_path=dataset_path / \"noise_map.fits\",\n", + " psf_path=dataset_path / \"psf.fits\",\n", + " pixel_scales=0.1,\n", + ")\n", + "mask = ag.Mask2D.circular(\n", + " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.0\n", + ")\n", + "dataset = dataset.apply_mask(mask=mask)\n", + "dataset = dataset.apply_over_sampling(over_sample_size_pixelization=1)\n", + "# Keep the smoke-test mesh smaller than its deliberately capped image.\n", + "mesh_pixels = min(25, min(dataset.shape_native) // 2)\n", + "mesh_shape = (mesh_pixels, mesh_pixels)\n", + "aplt.subplot_imaging_dataset(dataset=dataset)" ], "outputs": [], "execution_count": null @@ -87,20 +119,52 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Initial Setup__\n", + "The single sample per image pixel keeps the indexed mapping example straightforward. For scientific modelling, we would also check that our image sampling is sufficiently accurate.\n", + "\n", + "__Interpolation and our starting reconstruction__\n", + "\n", + "Let\u2019s look at our reconstruction from the previous tutorial in more detail.\n", "\n", - "we'll use the same galaxy data as the previous tutorial, where:\n", + "The `RectangularUniform` mesh describes the galaxy using brightness values at regularly spaced points. An image\n", + "coordinate generally falls between these points. Its predicted brightness is obtained by combining the four surrounding\n", + "values, with weights determined by its position. This is bilinear interpolation.\n", "\n", - " - The galaxy's bulge is an `Sersic`.\n", - " - The galaxy's disk is an `Exponential`." + "Interpolation tells us how to calculate brightness between mesh points, but it does not tell us what those mesh values\n", + "should be. Four neighbouring values could be similar, or one could be much brighter than the others. Both can be\n", + "interpolated. In the second case, however, the brightness changes much more sharply across the galaxy.\n", + "\n", + "Regularization influences the brightness values we infer, discouraging variations that are not sufficiently supported by\n", + "the data. Interpolation then determines how those values contribute between mesh points.\n", + "\n", + "We are going to evaluate several reconstructions, so the function below keeps their common setup in one place. Only the" ] }, { "cell_type": "code", "metadata": {}, "source": [ - "dataset_name = \"simple\"\n", - "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" + "mesh_shape = (mesh_pixels, mesh_pixels)\n", + "\n", + "\n", + "def fit_with_coefficient(coefficient):\n", + " pixelization = ag.Pixelization(\n", + " mesh=ag.mesh.RectangularUniform(shape=mesh_shape),\n", + " regularization=ag.reg.Constant(coefficient=coefficient),\n", + " )\n", + "\n", + " galaxy = ag.Galaxy(\n", + " redshift=0.5,\n", + " pixelization=pixelization,\n", + " )\n", + "\n", + " galaxies = ag.Galaxies(galaxies=[galaxy])\n", + "\n", + " return ag.FitImaging(dataset=dataset, galaxies=galaxies)\n", + "\n", + "\n", + "fit = fit_with_coefficient(coefficient=1.0)\n", + "\n", + "aplt.subplot_fit_imaging(fit=fit)" ], "outputs": [], "execution_count": null @@ -109,30 +173,37 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Dataset Auto-Simulation__\n", - "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." + "Here is the interpolation calculation for one image pixel. As in tutorial 1, the mapper supplies the contributing mesh indexes and their weights. This time, we also have reconstructed brightness values, so we can see how the contributions combine." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "if ag.util.dataset.should_simulate(str(dataset_path)):\n", - " import subprocess\n", - " import sys\n", + "mapper = fit.inversion.cls_list_from(ag.Mapper)[0]\n", + "reconstruction = np.asarray(fit.inversion.reconstruction)\n", + "\n", + "# Select an image pixel near the right-hand side of the galaxy.\n", + "image_coordinates = np.asarray(mapper.image_plane_data_grid)\n", + "image_index = int(\n", + " np.argmin(np.sum((image_coordinates - np.array([0.0, 0.5])) ** 2, axis=1))\n", + ")\n", + "\n", + "weights = np.asarray(mapper.mapping_matrix[image_index])\n", + "mesh_indexes = np.flatnonzero(np.abs(weights) > 1.0e-12)\n", "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulators/simple.py\"],\n", - " check=True,\n", + "for mesh_index in mesh_indexes:\n", + " brightness = reconstruction[mesh_index]\n", + " weight = weights[mesh_index]\n", + " print(\n", + " f\"Mesh index {mesh_index}: \"\n", + " f\"brightness={brightness:.5g}, weight={weight:.5g}, \"\n", + " f\"contribution={brightness * weight:.5g}\"\n", " )\n", "\n", - "dataset = ag.Imaging.from_fits(\n", - " data_path=dataset_path / \"data.fits\",\n", - " noise_map_path=dataset_path / \"noise_map.fits\",\n", - " psf_path=dataset_path / \"psf.fits\",\n", - " pixel_scales=0.1,\n", + "print(\n", + " \"Combined brightness before telescope blurring:\",\n", + " float(np.dot(weights, reconstruction)),\n", ")" ], "outputs": [], @@ -142,28 +213,77 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Convenience Function__\n", + "This is the image prediction before the PSF redistributes light between image pixels. We are inspecting a small part of the calculation, not replacing the inversion\u2019s treatment of telescope blurring.\n", + "\n", + "__Reducing regularization__\n", "\n", - "we're going to perform a lot of fits using an `Inversion` this tutorial. This would create a lot of code, so to keep \n", - "things tidy, I've setup this function which handles it all for us." + "Our starting reconstruction uses a regularization coefficient of `1.0`. Let\u2019s reduce it substantially and examine what\n", + "changes.\n", + "\n", + "We use `0.01` rather than exactly zero, retaining a small smoothness penalty. Keep the mesh and data unchanged: we want" ] }, { "cell_type": "code", "metadata": {}, "source": [ + "weak_regularization_fit = fit_with_coefficient(coefficient=0.01)\n", "\n", + "aplt.subplot_fit_imaging(fit=weak_regularization_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To understand this comparison, we need to look more closely at what regularization actually does.\n", "\n", - "def perform_fit_with_galaxy(dataset, galaxy):\n", - " mask = ag.Mask2D.circular(\n", - " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.0\n", - " )\n", + "When the inversion reconstructs the galaxy, it does not only seek brightness values that reproduce the image. With\n", + "`Constant` regularization, it also compares neighbouring brightness values on the rectangular galaxy mesh. Interior mesh\n", + "points have four immediate neighbours. Large differences between their brightnesses contribute a larger penalty.\n", "\n", - " dataset = dataset.apply_mask(mask=mask)\n", + "You can think of this as applying a **smoothness prior** to the reconstructed galaxy. It expresses a preference for\n", + "neighbouring regions to have similar brightness, unless the image provides enough evidence for them to differ.\n", "\n", - " galaxies = ag.Galaxies(galaxies=[galaxy])\n", + "The penalty depends on squared differences, so positive and negative differences cannot cancel. The coefficient controls\n", + "its strength. Reducing that coefficient makes a given amount of variation less costly; increasing it makes the same\n", + "variation more costly.\n", "\n", - " return ag.FitImaging(dataset=dataset, galaxies=galaxies)\n" + "In the language of linear algebra, this prior contributes a regularization matrix to the system the inversion solves. We\n", + "do not need to construct that matrix ourselves to understand its effect.\n", + "\n", + "Without sufficient regularization, the inversion has greater freedom to fit fluctuations in the observed image,\n", + "including noise. Some of those fluctuations can be explained by adding irregular structure to the galaxy. The image fit\n", + "may improve even though the inferred galaxy becomes less faithful to the galaxy that produced the data.\n", + "\n", + "Inspect the weakly regularized reconstruction for isolated bright values or rapid changes between neighbouring points.\n", + "Also look at its faint regions, where the image provides less information about the galaxy.\n", + "\n", + "A few extreme values can dominate the colour scale. We can compare both reconstructions using the starting" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "galaxy_vmax = float(np.max(np.asarray(fit.inversion.reconstruction)))\n", + "\n", + "for label, current_fit in [\n", + " (\"Starting Reconstruction\", fit),\n", + " (\"Weak Regularization\", weak_regularization_fit),\n", + "]:\n", + " current_mapper = current_fit.inversion.cls_list_from(ag.Mapper)[0]\n", + "\n", + " aaplt.plot_mapper(\n", + " mapper=current_mapper,\n", + " solution_vector=current_fit.inversion.reconstruction,\n", + " vmin=0.0,\n", + " vmax=galaxy_vmax,\n", + " zoom_to_brightest=False,\n", + " title=label,\n", + " )" ], "outputs": [], "execution_count": null @@ -172,35 +292,73 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Pixelization__\n", + "Values above this plotting limit share the highest colour, so use these figures alongside the original plots rather than treating them as the full brightness range.\n", + "\n", + "The important point is that recovering recognizable galaxy structure does not mean every reconstructed feature is\n", + "reliable. Genuine structure and noise-fitting can appear in the same reconstruction.\n", + "\n", + "__Increasing regularization__\n", "\n", - "Okay, so lets look at our fit from the previous tutorial in more detail." + "Now let\u2019s move in the other direction and use a much larger coefficient.\n", + "\n", + "With stronger regularization, the inversion pays a greater penalty for differences between neighbouring brightnesses.\n", + "This discourages the sharp variations that can fit noise. However, the real galaxy also contains brightness variations:\n", + "compact components, bright centres and the changes between those regions and their surroundings.\n", + "\n", + "Regularization cannot identify which variations are genuine simply by examining the galaxy. The image fit and the prior\n", + "must work together. If we make the smoothness preference too strong, the reconstruction can lose genuine structure" ] }, { "cell_type": "code", "metadata": {}, "source": [ - "# `PYAUTO_SMALL_DATASETS=1` (the CI smoke harness) caps the data to a 16 x 16 image, where a\n", - "# 50 x 50 mesh reconstructs 2500 source pixels from a few dozen image pixels. The mesh is\n", - "# capped alongside the data; a normal full-resolution run keeps the 50 x 50 grid described above.\n", - "mesh_shape = (\n", - " ag.util.dataset.SMALL_DATASETS_SHAPE_NATIVE\n", - " if dataset.shape_native == ag.util.dataset.SMALL_DATASETS_SHAPE_NATIVE\n", - " else (50, 50)\n", - ")\n", + "strong_regularization_fit = fit_with_coefficient(coefficient=100.0)\n", "\n", - "pixelization = ag.Pixelization(\n", - " mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n", - " regularization=ag.reg.Constant(coefficient=1.0),\n", + "strong_mapper = strong_regularization_fit.inversion.cls_list_from(ag.Mapper)[0]\n", + "\n", + "aaplt.plot_mapper(\n", + " mapper=strong_mapper,\n", + " solution_vector=strong_regularization_fit.inversion.reconstruction,\n", + " vmin=0.0,\n", + " vmax=galaxy_vmax,\n", + " zoom_to_brightest=False,\n", + " title=\"Strong Regularization\",\n", ")\n", "\n", - "galaxy = ag.Galaxy(redshift=1.0, pixelization=pixelization)\n", + "aplt.subplot_fit_imaging(fit=strong_regularization_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Compare the bright components with the starting reconstruction. Look for features becoming flatter or merging together, then inspect the corresponding regions of the image residuals.\n", "\n", - "fit = perform_fit_with_galaxy(dataset=dataset, galaxy=galaxy)\n", + "This illustrates the difficulty in choosing a coefficient. Too little smoothing can introduce structure that explains\n", + "noise. Too much can remove structure needed to explain the galaxy. Neither the smoothest galaxy nor the closest possible\n", + "image fit is automatically the reconstruction we want." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "fit_comparisons = [\n", + " (\"Weak\", 0.01, weak_regularization_fit),\n", + " (\"Starting\", 1.0, fit),\n", + " (\"Strong\", 100.0, strong_regularization_fit),\n", + "]\n", + "\n", + "for label, coefficient, current_fit in fit_comparisons:\n", + " normalized_residuals = np.asarray(\n", + " (dataset.data - current_fit.model_data) / dataset.noise_map\n", + " )\n", "\n", - "aplt.subplot_fit_imaging(fit=fit)\n", - "subplot_of_mapper(inversion=fit.inversion, mapper_index=0)" + " chi_squared = float(np.sum(normalized_residuals**2))\n", + " print(f\"{label}: coefficient={coefficient:g}, chi-squared={chi_squared:.3f}\")" ], "outputs": [], "execution_count": null @@ -209,29 +367,57 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Regularization__\n", + "A lower chi-squared means closer agreement with the image under the assumed noise map. It does not distinguish fitting genuine structure from fitting noise. This is why choosing the coefficient solely by image agreement would favour giving the galaxy too much freedom.\n", + "\n", + "**\ud83e\udd16 Ask AI:** Why might a weakly regularized reconstruction have a lower chi-squared but a less trustworthy galaxy than\n", + "a more strongly regularized reconstruction?\n", + "\n", + "__Bayesian evidence__\n", + "\n", + "For inversions, we therefore need more than image agreement to choose an appropriate level of regularization.\n", "\n", - "The galaxy reconstruction looks pretty good! \n", + "We use the **Bayesian evidence**, which accounts for both the fit to the image and the galaxy prior. It helps us compare\n", + "reconstructions that have different amounts of freedom, rather than simply choosing whichever one follows the observed\n", + "pixel values most closely.\n", "\n", - "However, the high quality of this solution was possible because I chose a `coefficient` for the regularization input of\n", - "1.0. If we reduce this `coefficient` to 0.01, the galaxy reconstruction goes *very* weird." + "There are two useful parts to this intuition.\n", + "\n", + "First, the reconstruction must explain the image. If strong regularization prevents it from reproducing genuine galaxy\n", + "structure, the resulting residuals count against that choice. Preferring a smooth galaxy is not useful if that galaxy\n", + "cannot explain the observed galaxy.\n", + "\n", + "Second, allowing a more flexible galaxy comes at a cost. Weak regularization permits many more patterns of brightness\n", + "across neighbouring mesh points. Some of that extra freedom may be needed to describe the galaxy, but some may only help\n", + "reproduce the particular noise fluctuations in this image.\n", + "\n", + "Evidence weighs the improvement in fit against the freedom allowed by the prior. An improvement must be sufficient to\n", + "justify that additional flexibility.\n", + "\n", + "This is also why complexity is not simply the number of mesh points. Our three examples have exactly the same mesh.\n", + "Stronger regularization ties neighbouring brightnesses together more closely, reducing their freedom to vary\n", + "independently. We can therefore change the effective flexibility of the reconstruction without changing the number of\n", + "mesh points." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "pixelization = ag.Pixelization(\n", - " mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n", - " regularization=ag.reg.Constant(coefficient=0.01),\n", - ")\n", + "log_evidences = []\n", + "\n", + "for label, coefficient, current_fit in fit_comparisons:\n", + " log_evidence = float(current_fit.log_evidence)\n", + " log_evidences.append(log_evidence)\n", "\n", - "galaxy = ag.Galaxy(redshift=1.0, pixelization=pixelization)\n", + " print(f\"{label}: coefficient={coefficient:g}, \" f\"log evidence={log_evidence:.3f}\")\n", "\n", - "no_regularization_fit = perform_fit_with_galaxy(dataset=dataset, galaxy=galaxy)\n", + "best_index = int(np.argmax(log_evidences))\n", + "best_label, best_coefficient, _ = fit_comparisons[best_index]\n", "\n", - "aplt.subplot_fit_imaging(fit=no_regularization_fit)\n", - "subplot_of_mapper(inversion=no_regularization_fit.inversion, mapper_index=0)" + "print(\n", + " f\"\\nHighest evidence among these examples: \"\n", + " f\"{best_label}, coefficient={best_coefficient:g}\"\n", + ")" ], "outputs": [], "execution_count": null @@ -240,45 +426,75 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "So, what is happening here? Why does reducing the `coefficient` do this to our reconstruction? First, we need\n", - "to understand what regularization actually does!\n", + "Compare this ranking with the galaxy plots and the chi-squared values. The highest evidence need not belong to the reconstruction with the lowest chi-squared, because image agreement is only part of the comparison.\n", + "\n", + "We still need to inspect the residuals ourselves. Evidence does not explicitly examine their spatial pattern or\n", + "guarantee that a preferred model is correct. Structured residuals can reveal shortcomings in the galaxy, PSF or other\n", + "assumptions that this three-coefficient comparison does not address.\n", + "\n", + "For now, we have compared only three choices. The starting value of `1.0` has no special status, and the best of these\n", + "three is not necessarily the best coefficient overall. Next, we will explore a broader range and see how this choice\n", + "fits into the wider modelling process.\n", "\n", - "When the inversion reconstructs the galaxy, it does not *only* compute the set of pixelization pixel fluxes that\n", - "best-fit the image. It also regularizes this solution, whereby it goes to every pixel on the rectangular grid\n", - "and computes the difference between the reconstructed flux values of every pixel with its 4 neighboring pixels.\n", - "If the difference in flux is large the solution is penalized, reducing its log likelihood. You can think of this as \n", - "us applying a 'smoothness prior' on the reconstructed galaxy's light.\n", "\n", - "This smoothing adds a 'penalty term' to the log likelihood of an inversion which is the summed difference between the \n", - "reconstructed fluxes of every pixelization pixel pair multiplied by the `coefficient`. By setting the regularization \n", - "coefficient to zero, we set this penalty term to zero, meaning that regularization is completely omitted.\n", + "__Exploring the regularization coefficient__\n", "\n", - "Why do we need to regularize our solution? We just saw why, if we do not apply this smoothness prior to the galaxy \n", - "reconstruction, we `over-fit` the image and reconstruct a noisy galaxy with lots of extraneous features. This is what \n", - "the aliasing chequer-board effect is caused by. If the inversions's sole aim is to maximize the log likelihood, it can \n", - "do this by fitting *everything* accurately, including the noise.\n", + "We have compared weak, moderate and strong regularization, but those three values were chosen to illustrate different\n", + "behaviours. They do not tell us where the evidence reaches its highest value.\n", "\n", - "Over-fitting is why regularization is necessary. Solutions like this will completely ruin our attempts to model a \n", - "galaxy. By smoothing our galaxy reconstruction we ensure it does not over fit noise in the image. \n", + "Let\u2019s explore the coefficient more systematically. We will keep the mesh resolution, mask and noise map fixed, and\n", + "reconstruct the galaxy for a sequence of coefficients.\n", "\n", - "So, what happens if we apply a high value for the regularization coefficient?" + "Regularization coefficients can span several orders of magnitude, so we use logarithmically spaced values. This gives us\n", + "comparable coverage between `0.01` and `0.1`, between `0.1` and `1.0`, and so on.\n", + "\n", + "Every point in this experiment requires a new galaxy reconstruction. We are not taking one reconstructed galaxy and" ] }, { "cell_type": "code", "metadata": {}, "source": [ - "pixelization = ag.Pixelization(\n", - " mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n", - " regularization=ag.reg.Constant(coefficient=100.0),\n", - ")\n", + "import matplotlib.pyplot as plt\n", "\n", - "galaxy = ag.Galaxy(redshift=1.0, pixelization=pixelization)\n", + "coefficient_grid = np.logspace(-2, 2, 13)\n", "\n", - "high_regularization_fit = perform_fit_with_galaxy(dataset=dataset, galaxy=galaxy)\n", + "# Reuse the three reconstructions already calculated.\n", + "known_fits = {\n", + " 0.01: weak_regularization_fit,\n", + " 1.0: fit,\n", + " 100.0: strong_regularization_fit,\n", + "}\n", "\n", - "aplt.subplot_fit_imaging(fit=high_regularization_fit)\n", - "subplot_of_mapper(inversion=high_regularization_fit.inversion, mapper_index=0)" + "evidence_grid = []\n", + "\n", + "for coefficient in coefficient_grid:\n", + " coefficient = float(coefficient)\n", + "\n", + " if coefficient in known_fits:\n", + " current_fit = known_fits[coefficient]\n", + " else:\n", + " current_fit = fit_with_coefficient(coefficient=coefficient)\n", + "\n", + " evidence_grid.append(float(current_fit.log_evidence))\n", + "\n", + "evidence_grid = np.asarray(evidence_grid)\n", + "\n", + "if not np.all(np.isfinite(evidence_grid)):\n", + " raise ValueError(\n", + " \"Some evidence values are not finite. Inspect those fits before comparing.\"\n", + " )\n", + "\n", + "fig, ax = plt.subplots()\n", + "ax.semilogx(\n", + " coefficient_grid,\n", + " evidence_grid - np.max(evidence_grid),\n", + " marker=\"o\",\n", + ")\n", + "ax.set_xlabel(\"Regularization coefficient\")\n", + "ax.set_ylabel(\"Log evidence relative to the highest sampled value\")\n", + "ax.set_title(\"Choosing the Strength of Regularization\")\n", + "plt.show()" ], "outputs": [], "execution_count": null @@ -287,25 +503,56 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The figure above shows that we completely remove over-fitting. However, we now fit the image data more poorly,\n", - "due to the much higher level of smoothing.\n", + "Look for the part of the curve where the evidence is highest. Moving towards weaker regularization gives the galaxy more freedom; moving towards stronger regularization increasingly restricts its variations.\n", + "\n", + "We may find a clear peak, a broad region with similar evidence, or a highest value at one end of the range. These\n", + "outcomes mean different things. A boundary maximum tells us that this experiment has not bracketed the preferred\n", + "coefficient\u2014we should extend the range before claiming to have located it.\n", + "\n", + "The plotted points are also discrete samples. Even an interior maximum only identifies the best coefficient we have\n", + "tried so far.\n", + "\n", + "__Inspecting the preferred reconstruction__\n", "\n", - "So, we now understand what regularization is and why it is necessary. There is one nagging question that remains, how \n", - "do I choose the regularization coefficient value? We can not use the log likelihood, as decreasing the regularization\n", - "coefficient will always increase the log likelihood, because less smoothing allows the reconstruction to fit \n", - "the data better." + "Let\u2019s inspect the reconstruction with the highest evidence in our sampled range.\n", + "\n", + "It is tempting to treat the highest number as the end of the analysis. However, we should connect that number back to\n", + "the galaxy and image. We want to understand what this choice preserves, what it smooths away, and what the resulting\n", + "model still fails to explain.\n", + "\n", + "Compare it with the weakly and strongly regularized examples. In particular, examine the bright central regions and the" ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(\"Likelihood Without Regularization:\")\n", - "print(no_regularization_fit.log_likelihood_with_regularization)\n", - "print(\"Likelihood With Normal Regularization:\")\n", - "print(fit.log_likelihood_with_regularization)\n", - "print(\"Likelihood With High Regularization:\")\n", - "print(high_regularization_fit.log_likelihood_with_regularization)" + "best_index = int(np.argmax(evidence_grid))\n", + "preferred_coefficient = float(coefficient_grid[best_index])\n", + "\n", + "if preferred_coefficient in known_fits:\n", + " preferred_fit = known_fits[preferred_coefficient]\n", + "else:\n", + " preferred_fit = fit_with_coefficient(coefficient=preferred_coefficient)\n", + "\n", + "print(\"Preferred sampled coefficient:\", preferred_coefficient)\n", + "\n", + "if best_index in (0, len(coefficient_grid) - 1):\n", + " print(\n", + " \"The highest evidence lies at the boundary. \"\n", + " \"Extend the coefficient range before interpreting this as a peak.\"\n", + " )\n", + "\n", + "preferred_mapper = preferred_fit.inversion.cls_list_from(ag.Mapper)[0]\n", + "\n", + "aaplt.plot_mapper(\n", + " mapper=preferred_mapper,\n", + " solution_vector=preferred_fit.inversion.reconstruction,\n", + " zoom_to_brightest=False,\n", + " title=\"Galaxy at the Preferred Sampled Coefficient\",\n", + ")\n", + "\n", + "aplt.subplot_fit_imaging(fit=preferred_fit)" ], "outputs": [], "execution_count": null @@ -314,43 +561,39 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Bayesian Evidence__\n", + "A preferred coefficient does not establish that every visible feature in the galaxy is real. The reconstruction remains conditional on the galaxy mesh, noise map and telescope blurring.\n", "\n", - "For inversions, we therefore need a different goodness-of-fit measure to choose the appropriate level of regularization. \n", + "Nor does a good-looking galaxy excuse coherent residuals in the image. The galaxy and residual plots provide\n", + "complementary information: one shows what we inferred, while the other shows what that inference leaves unexplained.\n", "\n", - "For this, we invoke the `Bayesian Evidence`, which quantifies the goodness of the fit as follows:\n", + "**\ud83e\udd16 Ask AI:** If the evidence prefers a particular regularization coefficient but the residuals still follow the shape\n", + "of the galaxy, what modelling assumptions should I investigate next?\n", "\n", - " - It requires that the residuals of the fit are consistent with Gaussian noise (which is the type of noise expected \n", - " in the imaging data). If this Gaussian pattern is not visible in the residuals, the noise must have been over-fitted\n", - " by the inversion. The Bayesian evidence will therefore decrease. If the image is fitted poorly due to over smoothing, \n", - " the residuals will again not appear Gaussian either, again producing a decrease in the Bayesian evidence value.\n", + "__What is linear, and what requires a search?__\n", "\n", - " - There can be many solutions which fit the data to the noise level, without over-fitting. To determine the best \n", - " solutions from these solutions, the Bayesian evidence therefore also quantifies the complexity of the galaxy \n", - " reconstruction. If an inversion requires many pixels and a low level of regularization to achieve a good fit, the \n", - " Bayesian evidence will decrease. The evidence penalizes solutions which are complex, which, in a Bayesian sense, are \n", - " less probable (you may want to look up `Occam`s Razor`).\n", + "Before going further, let\u2019s separate two parts of the calculation that are easy to confuse.\n", "\n", - "The Bayesian evidence therefore ensures we only invoke a more complex galaxy reconstruction when the data absolutely\n", - "necessitates it.\n", + "For each coefficient we supplied, the inversion solved for the galaxy brightnesses. We did not give a non-linear search\n", + "hundreds of independent galaxy brightness parameters and ask it to explore their possible combinations. Instead, the\n", + "galaxy enters the predicted image linearly, allowing these brightnesses to be solved together using linear algebra.\n", "\n", - "(This tutorial describes the Bayesian evidence in words; tutorial 5 writes it down as an equation, deriving each of\n", - "its terms via the linear algebra of the inversion.)\n", + "Regularization is included in that solve. The galaxy is not first reconstructed without a prior and then smoothed\n", + "afterwards. The inferred brightnesses already reflect the balance between fitting the image and satisfying the\n", + "smoothness prior.\n", "\n", - "Lets take a look at the Bayesian evidence of the fits that we performed above, which is accessible from a `FitImaging` \n", - "object via the `log_evidence` property:" + "Choosing the regularization coefficient is a different problem. We supplied several coefficients, performed an inversion\n", + "for each, and compared their evidence values. Our loop is a simple grid search over one quantity." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(\"Bayesian Evidence Without Regularization:\")\n", - "print(no_regularization_fit.log_evidence)\n", - "print(\"Bayesian Evidence With Normal Regularization:\")\n", - "print(fit.log_evidence)\n", - "print(\"Bayesian Evidence With High Regularization:\")\n", - "print(high_regularization_fit.log_evidence)" + "mesh_brightnesses = np.asarray(preferred_fit.inversion.reconstruction)\n", + "\n", + "print(\"Number of galaxy mesh values:\", preferred_mapper.pixels)\n", + "print(\"Number of reconstructed entries:\", mesh_brightnesses.size)\n", + "print(\"Number of coefficients evaluated:\", coefficient_grid.size)" ], "outputs": [], "execution_count": null @@ -359,52 +602,96 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "As expected, the solution that we could see `by-eye` was the best solution corresponds to the highest log evidence \n", - "solution.\n", + "The reconstruction contains an entry for each galaxy mesh point in this single-mapper example. Some values may be constrained to zero at the mesh boundary, and regularization couples neighbouring values, so the number of entries is not the number of independently constrained galaxy features.\n", + "\n", + "During galaxy modelling, a search can also change the geometry of accompanying analytic profiles. For each proposal,\n", + "we calculate their contribution and solve again for the linear brightnesses, including the pixelization.\n", + "\n", + "The sequence is therefore:\n", "\n", - "__Non-Linear and Linear__\n", + "1. Propose the non-linear parameters, including the regularization coefficient and any analytic-profile geometry.\n", + "2. Construct the corresponding image model and mappings.\n", + "3. Solve for the linear brightnesses.\n", + "4. Evaluate the fit, accounting for the reconstruction prior.\n", "\n", - "Before we end, lets consider which aspects of an inversion are linear and which are non-linear.\n", + "This makes pixelizations practical: the search explores non-linear choices while the inversion handles the many\n", + "brightness values.\n", "\n", - "The linear part of the inversion is the step that solves for the reconstructed pixelization pixel fluxes, including\n", - "accounting for the smoothing via regularization. We do not have to perform a non-linear search to determine the pixel\n", - "fluxes or compute the Bayesian evidence discussed above.\n", + "__Mesh resolution and regularization belong together__\n", "\n", - "However, determining the regularization `coefficient` that maximizes the Bayesian log evidence is a non-linear problem \n", - "that requires a non-linear search. The Bayesian evidence also depends on the grid resolution, which means the \n", - "pixel-grid's `shape` parameter may also now become dimensions of non linear parameter space (albeit it is common\n", - "practise for us to simply use the resolution of the image data, or a multiple of this). \n", + "We have held the galaxy mesh at `(25, 25)` (a smaller mesh in capped smoke runs). The preferred coefficient we found\n", + "belongs to that choice of mesh.\n", "\n", - "Nevertheless, these total only 3 non-linear parameters, far fewer than the 20+ that are required when modeling such a\n", - "complex galaxy using light profiles for every individual clump! \n", + "Changing the mesh changes the locations and number of galaxy brightness values, their neighbours, and how they\n", + "contribute to the image. The same numerical coefficient therefore need not give an equivalent amount of smoothing on\n", + "another mesh.\n", "\n", - "Here are a few questions for you to think about.\n", + "This matters when testing resolution. If we increase the number of mesh points but keep the coefficient fixed, any\n", + "change in the reconstruction reflects both the new resolution and its interaction with the prior. We cannot assume that\n", + "we have made a fair comparison of the best reconstructions available at each resolution.\n", "\n", - " 1) We maximize the log evidence by using simpler galaxy reconstructions. Therefore, decreasing the pixel-grid \n", - " size should provide a higher log_evidence, provided it still has sufficiently high resolution to fit the image well \n", - " (and provided that the regularization coefficient is set to an appropriate value). Can you increase the log evidence \n", - " from the value above by changing these parameters, I've set you up with a code to do so below." + "Let\u2019s repeat the coefficient experiment for `(15, 15)` and `(35, 35)`, alongside our existing `(25, 25)` results. The\n", + "same comparison uses smaller meshes when the dataset is capped for a smoke run. We extend our helper so the mesh shape" ] }, { "cell_type": "code", "metadata": {}, "source": [ - "pixelization = ag.Pixelization(\n", - " mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n", - " regularization=ag.reg.Constant(coefficient=1.0),\n", - ")\n", "\n", - "galaxy = ag.Galaxy(redshift=1.0, pixelization=pixelization)\n", "\n", - "fit = perform_fit_with_galaxy(dataset=dataset, galaxy=galaxy)\n", + "def fit_with_coefficient(coefficient, mesh_shape=mesh_shape):\n", + " pixelization = ag.Pixelization(\n", + " mesh=ag.mesh.RectangularUniform(shape=mesh_shape),\n", + " regularization=ag.reg.Constant(coefficient=coefficient),\n", + " )\n", "\n", - "print(\"Previous Bayesian Evidence:\")\n", - "print(3988.0716851250163)\n", - "print(\"New Bayesian Evidence:\")\n", - "print(fit.log_evidence)\n", + " galaxy = ag.Galaxy(\n", + " redshift=0.5,\n", + " pixelization=pixelization,\n", + " )\n", "\n", - "aplt.subplot_fit_imaging(fit=fit)" + " galaxies = ag.Galaxies(galaxies=[galaxy])\n", + "\n", + " return ag.FitImaging(dataset=dataset, galaxies=galaxies)\n", + "\n", + "\n", + "evidence_by_shape = {mesh_shape: evidence_grid}\n", + "\n", + "comparison_sizes = [max(4, mesh_pixels - 10), min(35, min(dataset.shape_native) - 4)]\n", + "for size in comparison_sizes:\n", + " shape = (size, size)\n", + " values = []\n", + "\n", + " for coefficient in coefficient_grid:\n", + " current_fit = fit_with_coefficient(\n", + " coefficient=float(coefficient),\n", + " mesh_shape=shape,\n", + " )\n", + " values.append(float(current_fit.log_evidence))\n", + "\n", + " evidence_by_shape[shape] = np.asarray(values)\n", + "\n", + "if not all(np.all(np.isfinite(values)) for values in evidence_by_shape.values()):\n", + " raise ValueError(\"Inspect non-finite evidence values before comparing meshes.\")\n", + "\n", + "reference_evidence = max(float(np.max(values)) for values in evidence_by_shape.values())\n", + "\n", + "fig, ax = plt.subplots()\n", + "\n", + "for shape, values in sorted(evidence_by_shape.items()):\n", + " ax.semilogx(\n", + " coefficient_grid,\n", + " values - reference_evidence,\n", + " marker=\"o\",\n", + " label=f\"{shape[0]} \u00d7 {shape[1]}\",\n", + " )\n", + "\n", + "ax.set_xlabel(\"Regularization coefficient\")\n", + "ax.set_ylabel(\"Log evidence relative to the highest sampled value\")\n", + "ax.set_title(\"Mesh Resolution and Regularization\")\n", + "ax.legend()\n", + "plt.show()" ], "outputs": [], "execution_count": null @@ -413,46 +700,65 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Detailed Description__\n", - "\n", - "Below, I provide a more detailed discussion of the Bayesian evidence. It is not paramount that you understand this to\n", - "use **PyAutoGalaxy**, but I recommend you give it a read to get an intuition for how the evidence works.\n", - "\n", - "The Bayesian log evidence quantifies the following 3 aspects of a fit to galaxy imaging data:\n", - "\n", - "1) *The quality of the image reconstruction:* The galaxy reconstruction is a linear inversion which uses the observed\n", - " values in the image-data to fit it and reconstruct the galaxy. It is in principle able to perfectly reconstruct the\n", - " image regardless of the image\u2019s noise or the accuracy of the model (e.g. at infinite resolution without\n", - " regularization). The problem is therefore \u2018ill-posed\u2019 and this is why regularization is necessary.\n", - "\n", - " However, this raises the question of what constitutes a \u2018good\u2019 solution? The Bayesian evidence defines this by\n", - " assuming that the image data consists of independent Gaussian noise in every image pixel. A \u2018good\u2019 solution is one\n", - " whose chi-squared residuals are consistent with Gaussian noise, producing a reduced chi-squared near 1.0 .Solutions\n", - " which give a reduced chi squared below 1 are penalized for being overly complex and fitting the image\u2019s noise, whereas\n", - " solutions with a reduced chi-squared above are penalized for not invoking a more complex galaxy model when the data it\n", - " is necessary to fit the data bettter. In both circumstances, these penalties reduce the inferred Bayesian evidence!\n", - "\n", - "2) *The complexity of the galaxy reconstruction:* The log evidence estimates the number of pixelization pixels that are used \n", - " to reconstruct the image, after accounting for their correlation with one another due to regularization. Solutions that\n", - " require fewer correlated galaxy pixels increase the Bayesian evidence. Thus, simpler and less complex galaxy \n", - " reconstructions are favoured.\n", - "\n", - "3) *The signal-to-noise (S/N) of the image that is fitted:* The Bayesian evidence favours models which fit higher S/N\n", - " realizations of the observed data (where the S/N is determined using the image-pixel variances, e.g. the noise-map). Up \n", - " to now, all **PyAutoGalaxy** fits assumed fixed variances, meaning that this aspect of the Bayeisan evidence has no impact \n", - " on the inferred evidence values. \n", - " \n", - " The premise is that whilst increasing the variances of image pixels lowers their S/N values and therefore also\n", - " decreases the log evidence, doing so may produce a net increase in log evidence. This occurs when the chi-squared \n", - " values of the image pixels whose variances are increased were initially very high (e.g. they were fit poorly by the \n", - " model).\n", + "This experiment performs 26 additional reconstructions, so it takes longer than our earlier three-way comparison.\n", + "\n", + "Look at both the locations and heights of the curves\u2019 maxima. The preferred coefficient may shift as the mesh changes. A\n", + "finer mesh may help describe galaxy structure, but adding points does not guarantee a higher evidence.\n", + "\n", + "All three curves use the same image pixels and noise model. We also subtract one common reference evidence, preserving\n", + "differences between the meshes. Subtracting each curve\u2019s own maximum would hide those differences.\n", + "\n", + "As before, a boundary maximum means that the coefficient range needs extending. These are controlled resolution checks,\n", + "not a demonstration that mesh dimensions should become free parameters in every galaxy-model search.\n", "\n", "__Wrap Up__\n", "\n", - "In summary, the log evidence is maximized for solutions which most accurately reconstruct the highest S/N realization of\n", - "the observed image, without over-fitting its noise and using the fewest correlated pixelization pixels. By employing\n", - "this framework throughout, **PyAutoGalaxy** objectively determines the final model following the principles of Bayesian\n", - "analysis and Occam\u2019s Razor." + "We can now give the regularization input a more meaningful interpretation.\n", + "\n", + "The galaxy mesh supplies brightness values that can vary to explain the image. Interpolation defines the brightness\n", + "between those values. Regularization places a prior on their variation, discouraging unnecessary differences between\n", + "neighbours.\n", + "\n", + "Too little regularization can allow the reconstruction to explain noise through spurious galaxy structure. Too much can\n", + "suppress real structure and leave it visible in the image residuals. Evidence helps compare these choices by accounting\n", + "for both image agreement and the freedom allowed by the galaxy prior.\n", + "\n", + "We also saw that the coefficient is not a universal setting. Its appropriate value depends on the dataset, mesh and\n", + "regularization scheme. A value that works for one reconstruction should not simply be carried into another analysis\n", + "without checking it." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for shape, values in sorted(evidence_by_shape.items()):\n", + " index = int(np.argmax(values))\n", + " coefficient = float(coefficient_grid[index])\n", + " boundary = index in (0, len(coefficient_grid) - 1)\n", + "\n", + " print(\n", + " f\"Mesh {shape}: coefficient={coefficient:.4g}, \"\n", + " f\"log evidence={values[index]:.3f}\"\n", + " + (\" \u2014 boundary maximum; extend the range\" if boundary else \"\")\n", + " )\n", + "\n", + "# Retain the original mesh's preferred fit for subsequent inspection.\n", + "fit = preferred_fit" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Throughout this tutorial, we evaluated reconstructions of a specified galaxy dataset. In the next tutorial, we use\n", + "a non-linear search and combine an MGE with a pixelization through search chaining.\n", + "\n", + "For readers who want the underlying equations, the workspace's [pixelization likelihood guide](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/pixelization/likelihood_function.py)\n", + "follows the mapping, blurring, regularization and evidence calculations step by step. That derivation complements\n", + "the experiments here; it is not required to continue using pixelizations." ] } ], @@ -480,7 +786,7 @@ "24c2f562-da24-50bb-8eb9-5a887505fe54": { "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", "name": "PyAutoGalaxy assistant", - "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb in HowToGalaxy).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoGalaxy calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoGalaxy docs (https://pyautogalaxy.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_pixelization\n\n---\nname: ag_pixelization\ndescription: Reconstruct a galaxy's clumpy or irregular light directly on a regularized pixel mesh, using `ag.Pixelization` alongside a parametric `ag.lp_linear` bulge \u2014 the hybrid model that gives a smooth interpretable component plus a flexible flux map for everything the profile cannot explain. Covers when a pixelization is warranted and when it is overkill, choosing an `ag.mesh` and an `ag.reg` regularization scheme and what each costs in free parameters, why `mesh_shape` must be fixed before the fit, `over_sample_size_pixelization` rather than `over_sample_size_lp`, noise scaling instead of hard masking for contaminants, the positive-only solver, reading the reconstruction and its Bayesian-evidence terms out of the `Inversion`, exporting the reconstruction to CSV for collaborators, and the GPU/VRAM versus CPU run-time trade. Use when a Sersic, MGE or shapelet basis leaves structured residuals in discrete off-centre lumps. Not for morphology a basis can still fit (`ag_basis_profiles`), not for non-parametric isophote measurement (`ag_ellipse_fitting`), and not for the basics of model composition (`ag_build_imaging_model`).\n---\n\n# Reconstructing a galaxy on a pixel mesh\n\nEvery model in this workspace so far has been a *function*: you asserted a functional form and\nthe fit found its parameters. A pixelization drops the functional form. It lays a mesh of pixels\nover the galaxy, gives each pixel its own free flux value, and solves all of them at once by\nlinear inversion \u2014 thousands of amplitudes, none of them in the non-linear search's parameter\nspace. What stops that from simply fitting the noise is **regularization**: a prior that\npenalises solutions where neighbouring mesh pixels differ sharply, so the reconstruction is as\nsmooth as the data will allow and no smoother.\n\nThe science case is specific, and it is worth being honest about how specific. Galaxies with\nspiral arms, asymmetric star-forming clumps, tidal features or low-surface-brightness\nsubstructure have light that no smooth profile \u2014 and often no basis expansion either \u2014\nreproduces. The canonical use is therefore **hybrid**: a linear `Sersic` for the smooth central\nbulge, and a pixelization for the irregular remainder. That split is the point. It gives you a\nlow-dimensional, physically interpretable description of the bulge *and* a flux map of exactly\nwhat the bulge could not explain, which is the quantity you want if the science question is \"how\nmuch of this galaxy's light is in its irregular components?\"\n\nThis is a **direct** reconstruction. There is no second plane, no de-projection, no inversion of\na geometric mapping \u2014 the mesh sits on the image plane, over the galaxy, at the same coordinates\nthe data occupies. If you have met pixelized reconstruction before in a different context, that\nextra step is the one that is absent here, and its absence makes everything simpler: what the\nmesh reconstructs is the galaxy's own surface brightness, and its coordinates are sky\ncoordinates in arcseconds.\n\nStatistically, the fit now has two nested layers. The non-linear search explores a handful of\nparameters \u2014 the bulge's shape, the regularization strength \u2014 and for each proposal an inversion\nsolves the mesh amplitudes exactly and returns a **Bayesian evidence** rather than a plain\nlikelihood. That evidence includes terms that penalise an unnecessarily complex reconstruction,\nwhich is what lets a model with 400 free flux values not simply win by over-fitting. The theory\nis [`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md);\nchapter 3 of HowToGalaxy derives it from scratch.\n\nThe canonical scripts are\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py` (via a search),\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` (one direct fit, with the\ninversion internals walked through) and\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py` (export).\n\n## Before you reach for one \u2014 the honest gate\n\nA pixelization is the most powerful and the most expensive model here, with failure modes the\nparametric models do not have. Three questions decide whether you need it:\n\n- *\"What do the residuals actually look like?\"* Structured residuals that **follow the\n isophotes** \u2014 a twist, a four-lobed pattern, an ellipticity that changes with radius \u2014 are a\n *shape* problem, and an MGE fixes them for four free parameters\n ([`ag_basis_profiles`](./ag_basis_profiles.md)). Residuals in **discrete off-centre lumps** are\n a substructure problem, and that is what a pixelization is for. Look before you choose.\n- *\"Is the structure resolved?\"* At low resolution the irregular structure is not in the data,\n and a pixelization will reconstruct noise while telling you it fitted well. The workspace is\n blunt about this: for low-resolution data pixelizations are unnecessary.\n- *\"Do you need global quantities or the light distribution?\"* If you want a total flux, a size,\n an axis ratio, a Sersic index \u2014 a parametric profile, an MGE or shapelets are enough and far\n cheaper. If you want the morphology itself, particularly for faint or low-surface-brightness\n features, nothing else comes close.\n\nIf the answer to the first is \"lumps\" and to the second \"yes\", continue. Otherwise you will\nspend hours to learn less.\n\n## Ask\n\n- *\"What is the smooth component?\"* Almost always a linear `Sersic`, sometimes a Sersic plus an\n Exponential disk. It matters that this exists: without it the pixelization has to reconstruct\n the bright central bulge too, which wastes mesh resolution on light a six-parameter profile\n describes perfectly and makes the regularization choice much harder.\n- *\"How many mesh pixels can you afford?\"* This is a hardware question as much as a science one\n (see the run-time branch). 20 \u00d7 20 is the workspace's default for a GPU run; 28 \u00d7 28 to 30 \u00d7 30\n for a better-resolved reconstruction; higher only with a large-VRAM GPU or a many-core CPU.\n- *\"Are there neighbours inside the mask?\"* For a pixelization the answer is *never* to mask\n their pixels out \u2014 that punches holes in the mesh and produces discontinuity systematics.\n Scale their noise instead (branch below).\n- *\"GPU or CPU?\"* Genuinely depends on your pixel scale, and the answer is counter-intuitive.\n Ask before assuming.\n\n## Branch \u2014 the hybrid model\n\nThe canonical composition. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py`.\n\n```python\n\"\"\"\nGalaxy Structure: Bulge Plus Pixelized Reconstruction\n=====================================================\n\nFit a galaxy whose light has two very different characters: a smooth central bulge, described by\na linear Sersic profile in six parameters, and asymmetric clumpy star formation, reconstructed\non a regularized rectangular mesh. The Sersic captures the smooth component interpretably; the\npixelization absorbs everything it cannot explain, and the reconstructed flux map is the\nmeasurement of the galaxy's irregular light.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the imaging, mask it, and apply pixelization over-sampling.\n- **Mesh Shape:** Fix the mesh dimensions before the model is composed.\n- **Model:** Compose the linear Sersic bulge plus the pixelization.\n- **Check:** Confirm the parameter count, evaluate one likelihood, and estimate VRAM.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPIXEL_SCALES = 0.1\nMASK_RADIUS = 2.0\n\n\"\"\"\n__Dataset__\n\nThe mask matters more than usual here. It defines the region the mesh is laid over, so a mask\nthat reaches well beyond the galaxy spends reconstruction pixels on empty sky, and one that\ntruncates the galaxy leaves its outer light unreconstructed\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe over-sampling argument changes too. A pixelization evaluates light on its *own* grid with\nits own over-sampling scheme, so the size is passed as `over_sample_size_pixelization`, not the\n`over_sample_size_lp` used for light profiles. Passing the wrong one silently leaves the\npixelization grid at its default.\n\"\"\"\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=PIXEL_SCALES,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\ndataset = dataset.apply_over_sampling(over_sample_size_pixelization=over_sample_size)\n\n\"\"\"\n__Mesh Shape__\n\nThe mesh dimensions are **fixed before the fit and cannot be a free parameter**. This is not a\nstylistic restriction: JAX compiles the likelihood against statically shaped arrays, and the\nmesh shape sets those shapes. A rectangular mesh uses the same number of pixels in y and x.\n\"\"\"\nmesh_pixels_yx = 20\nmesh_shape = (mesh_pixels_yx, mesh_pixels_yx)\n\n\"\"\"\n__Model__\n\n`ag.Pixelization` pairs a `mesh` \u2014 where the reconstruction pixels sit \u2014 with a `regularization`\nscheme \u2014 the prior that keeps the solution smooth. It is attached to the galaxy as a component\nalongside the light profiles, and the analysis knows to route it through the inversion\n(`PyAutoGalaxy:autogalaxy/galaxy/galaxy.py`).\n\nThe mesh itself contributes **zero** free parameters; the reconstruction's 400 flux values are\nsolved, not sampled. `ag.reg.GaussianKernel` contributes two (`coefficient`, `scale`). The bulge\nis `ag.lp_linear.Sersic` rather than `ag.lp.Sersic` deliberately: its `intensity` is then solved\nby the *same* inversion that solves the mesh amplitudes, which removes the degeneracy between\n\"bright bulge, faint reconstruction\" and \"faint bulge, bright reconstruction\" that a sampled\nintensity would create.\n\"\"\"\npixelization = af.Model(\n ag.Pixelization,\n mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n regularization=ag.reg.GaussianKernel,\n)\n\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n pixelization=pixelization,\n)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\nThree cheap checks, each catching a different class of mistake: the parameter count catches a\nmodel error, one likelihood evaluation catches an incompatibility between model, dataset and\nanalysis, and `print_vram_use` catches the resource error that otherwise appears as an\nout-of-memory failure mid-compile. Pixelizations use far more VRAM than profile-only models \u2014\naround 0.05 GB per batched likelihood for 400 reconstruction pixels \u2014 which is why the\nworkspace uses a lower `n_batch` for these fits than for any other.\n\"\"\"\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\nlog_likelihood = analysis.log_likelihood_function(\n instance=model.instance_from_prior_medians()\n)\nprint(f\"log evidence at prior medians: {float(log_likelihood):.2f}\")\n```\n\n**N = 8**: the Sersic's centre (2), `ell_comps` (2), `effective_radius`, `sersic_index`, plus the\nregularization's `coefficient` and `scale`. Eight parameters, with 400 reconstruction pixels\nsolved. That is dramatically more parsimonious than stacking parametric profiles until every\nclump is described \u2014 a 20-plus-parameter approach that would still fail on genuinely irregular\nsubstructure.\n\nExtending the smooth side is exactly as you would expect \u2014 add components as further attributes\non the galaxy, keeping them linear so their intensities join the same inversion:\n\n```python\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n disk=ag.lp_linear.Exponential,\n pixelization=pixelization,\n)\n```\n\n## Branch \u2014 choosing a mesh and a regularization scheme\n\nThese are the two decisions that make or break a reconstruction, and the parameter cost is\nalmost entirely in the regularization.\n\n**Meshes** (`ag.mesh`, from `PyAutoArray:autoarray/inversion/mesh/`). All contribute zero free\nparameters, all take `shape=(y, x)`:\n\n| Mesh | Where the pixels go | Use when |\n|---|---|---|\n| `RectangularUniform` | a uniform grid over the masked region | you want the simplest, most predictable behaviour |\n| `RectangularBilinearAdaptDensity` | a rectangular grid whose spacing follows the density of image pixels mapping to it, via a rank CDF | **the default** \u2014 concentrates resolution where the data is, and the fast CPU path |\n| `RectangularBilinearAdaptImage` | adapts to the image's own brightness distribution | the irregular light is strongly concentrated |\n| `RectangularRTUAdaptDensity` / `RectangularRTUAdaptImage` | the same two adaptations through a kernel CDF | GPU, JAX gradient samplers and the interferometer sparse path \u2014 the only rectangular adaptive meshes with usable gradients |\n\n`Delaunay`, `KNearestNeighbor` and `KNNBarycentric` also exist for irregular tessellations. Start\nwith `RectangularBilinearAdaptDensity`; it is what every workspace example uses, and the\nrectangular meshes are what the fixed-`mesh_shape` JAX path is built around. (The unqualified\n`RectangularAdaptDensity` / `RectangularAdaptImage` names were split into the `Bilinear` and\n`RTU` families in PyAutoArray 2026.8.23.1 and no longer resolve.)\n\n**Regularization** (`ag.reg`, from `PyAutoArray:autoarray/inversion/regularization/`) is where\nthe free parameters are, and where the physics of \"how smooth should this be?\" lives:\n\n| Scheme | Free params | What it assumes |\n|---|---|---|\n| `ag.reg.Constant` | 1 (`coefficient`) | one smoothing strength everywhere \u2014 the simplest, and the right first try |\n| `ag.reg.GaussianKernel` | 2 (`coefficient`, `scale`) | smoothing with a Gaussian correlation length you also fit |\n| `ag.reg.MaternKernel` | 3 (`coefficient`, `scale`, `nu`) | as above, with the roughness `nu` free too |\n\nVerified counts, not guesses. `Constant` penalises the difference between neighbouring pixels\ndirectly; the kernel schemes impose a correlation *length*, which is physically closer to what a\ngalaxy's light does and generally reconstructs faint extended structure better at the cost of\none or two parameters. `ag.reg.Adapt` and its variants scale the smoothing with the\nreconstruction's own brightness \u2014 more flexible again, and requiring `adapt_images` on the\nanalysis, which is a step beyond this skill; ask if you want it.\n\nA practical route: fit once with `ag.reg.Constant`, look at the reconstruction. Over-smoothed\n(the clumps blurred into one blob) or over-fitted (isolated single-pixel spikes) both show up\nimmediately, and if `Constant` cannot get both the bright clumps and the faint envelope right at\none strength, that is the signal to move to `GaussianKernel`. Full discussion in\n[`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\n### The positive-only solver\n\nEvery pixelized reconstruction uses a **positive-only** linear solver: no mesh pixel may\nreconstruct negative flux. This is not a numerical nicety. A signed solver lets the\nreconstruction manufacture negative pixels that cancel positive ones to over-fit the data, and\nthat failure mode is a well-known systematic in the literature \u2014 many published methods allow\nit. Enforcing non-negativity efficiently needs bespoke linear algebra, which is why this is\nworth stating rather than assuming. You do not need to switch it on; it is the behaviour you get.\n(The one place in this workspace where you *must* disable it is a shapelet basis, which needs\nsigned amplitudes by construction \u2014 see [`ag_basis_profiles`](./ag_basis_profiles.md).)\n\n## Branch \u2014 contaminating neighbours: scale, never mask\n\nThe general advice for a neighbour inside the mask is to mask its pixels out. **For a\npixelization that advice is wrong.** Removing image pixels entirely removes their mapping into\nthe mesh, punching a hole in the reconstruction and producing discontinuities that show up as\nunexplained systematics.\n\nInstead, keep the pixels in the fit and make them contribute nothing: scale their data to zero\nand their noise to an enormous value, so the likelihood is indifferent to them while the mesh\nstays continuous. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py`.\n\n```python\n\"\"\"\n__Noise Scaling__\n\n`mask_extra_galaxies.fits` marks the contaminated pixels. It is loaded with `invert=True`\nbecause in this file `True` means \"scale this pixel\", the opposite of a modelling mask's\nconvention \u2014 getting this backwards scales the galaxy instead of the neighbour, so check the\nsubplot afterwards. `apply_noise_scaling` then zeroes those data values and inflates their\nnoise, driving their signal-to-noise to effectively zero without removing them from the mesh's\nmapping (`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nOrder matters: scale first, then apply the modelling mask.\n\"\"\"\nmask_extra_galaxies = ag.Mask2D.from_fits(\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n pixel_scales=PIXEL_SCALES,\n invert=True,\n)\n\ndataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=PIXEL_SCALES,\n centre=(0.0, 0.0),\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=\"scripts/scratch/my_galaxy/\",\n output_filename=\"noise_scaled\",\n output_format=\"png\",\n)\n```\n\nThe scaled pixels go to a noise value of order 1e8 \u2014 visibly so on the signal-to-noise panel of\nthe subplot, which is how you confirm you scaled the right region. Drawing that mask\ninteractively is `autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask_extra_galaxies.py`;\nthe modelling alternative, and when to prefer it, is\n[`ag_light_model_extras`](./ag_light_model_extras.md) and\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch \u2014 reading the reconstruction out\n\nThe reconstruction is the science product, and it lives on the `Inversion`. You can get there\nfrom a completed fit or from a single direct `ag.FitImaging` \u2014 the latter is the fast way to\nlearn the objects, and is what\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` does.\n\n```python\n\"\"\"\n__Reconstruction__\n\n`inversion.linear_obj_list` holds the linear objects the fit solved. For a hybrid model that is\none `LightProfileLinearObjFuncList` per linear light profile plus one `Mapper` for the\npixelization; with a non-linear `ag.lp.Sersic` bulge the `Mapper` is the only entry. The\n`Mapper` is the object that maps image pixels onto mesh pixels, and it is mesh-specific\n(`PyAutoArray:autoarray/inversion/mappers/`).\n\nThe reconstruction is a 1D array of one flux per mesh pixel, and the (y, x) arcsecond\ncoordinates of those pixels are `mapper.mesh_geometry.mesh_grid`. Pair them by index \u2014 they are\nthe same length and the same order \u2014 and you have the flux map.\n\"\"\"\ninversion = fit.inversion\n\nmapper = inversion.linear_obj_list[0]\n\nreconstruction = inversion.reconstruction\nmesh_grid = mapper.mesh_geometry.mesh_grid\n\nprint(f\"{len(reconstruction)} mesh pixels reconstructed\")\nprint(f\"coordinates shape: {mesh_grid.shape}\")\n\n\"\"\"\nThe reconstruction's own uncertainties, and its projection back onto the image, are also on the\ninversion. `mapped_reconstructed_operated_data` contains **only** the pixelized component \u2014 any\nparametric light profile in the model is excluded \u2014 which is exactly the quantity you want when\nasking how much light is in the irregular component.\n\"\"\"\nprint(inversion.reconstruction_noise_map)\nprint(inversion.mapped_reconstructed_operated_data.native.shape)\n```\n\nA caution on the `Mapper`'s grid attributes: `mapper.image_plane_mesh_grid` is `None` for a\nrectangular mesh, so do not reach for it. `mapper.mesh_geometry.mesh_grid` is the mesh pixel\ncentres (verified on the released stack), and `mapper.image_plane_data_grid` is the centre of\nevery masked *image* pixel. Some of the `Mapper`'s attribute names carry a plane-based prefix\ninherited from the shared inversion library that also serves a multi-plane use case; in\nPyAutoGalaxy there is only the one plane, so `mesh_geometry.mesh_grid` is both the clearer name\nand the one to use.\n\n### The evidence terms\n\nThe inversion's figure of merit is a Bayesian evidence, and its components are individually\nreadable \u2014 which is how you diagnose whether regularization is doing too much or too little:\n\n```python\nprint(f\"regularization term = {inversion.regularization_term}\")\nprint(f\"log det regularization = {inversion.log_det_regularization_matrix_term}\")\nprint(f\"log det curvature + reg = {inversion.log_det_curvature_reg_matrix_term}\")\n```\n\nThe `regularization_term` measures how non-smooth the solution is; the two log-determinant\nterms are the complexity penalty that stops a 400-pixel model winning by over-fitting. The\nmatrices themselves (`curvature_matrix`, `regularization_matrix`, `curvature_reg_matrix`) are\nthere too. The derivation is in HowToGalaxy chapter 3 and the papers it cites\n(arXiv:1708.07377, arXiv:astro-ph/0601493).\n\n### Diagnostic plots\n\n`aplt.subplot_fit_imaging` includes the reconstruction on the mesh alongside the usual data /\nmodel / residual panels, and is the first thing to look at. For the inversion's own internals\nthere are dedicated functions, which live in the shared inversion library rather than on `aplt`\nand so are imported explicitly \u2014 from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/plot.py`:\n\n```python\nfrom autoarray.inversion.plot.inversion_plots import subplot_of_mapper\nfrom autoarray.inversion.plot.mapper_plots import plot_mapper, subplot_image_and_mapper\n\nPLOT_DIR = \"scripts/scratch/my_galaxy/pixelization/\"\n\naplt.subplot_fit_imaging(fit=fit, output_path=PLOT_DIR, output_format=\"png\")\n\nsubplot_of_mapper(\n inversion=inversion, mapper_index=0, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nsubplot_image_and_mapper(\n mapper=mapper, image=dataset.data, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nprint(f\"Saved to: {Path(PLOT_DIR).resolve()}\")\n```\n\n`subplot_of_mapper` is the comprehensive diagnostic \u2014 reconstructed image, reconstruction, its\nnoise map and the regularization weights in one figure \u2014 and `mapper_index` selects which linear\nobject when there are several. `subplot_image_and_mapper` shows the data beside the mesh, which\nis how you check the mesh covers the structure you care about. Note that none of these three are\nexposed on the `aplt` module \u2014 `dir(aplt)` does not list them, so the explicit imports above are\nthe only route and writing them as `aplt.`-prefixed calls raises `AttributeError`. Quote the\nabsolute path back to the user and offer to open it.\n\n## Branch \u2014 exporting the reconstruction for downstream science\n\nA reconstruction that only exists inside a PyAutoGalaxy object is hard to share and hard to\nanalyse with other tools. Write it out as coordinates plus values and it becomes ordinary\ntabular data. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py`.\n\n```python\n\"\"\"\n__Export__\n\nFour columns \u2014 y, x, reconstruction, noise \u2014 is everything needed to rebuild, plot or analyse\nthe galaxy's irregular light without PyAutoGalaxy installed. A completed model-fit also writes\nthis file into its own `image/` folder automatically; glob for `*reconstruction_0.csv` there\nrather than hard-coding the stem, which carries a prefix from the shared inversion library.\n\"\"\"\nimport csv\n\nCSV_PATH = Path(\"scripts/scratch/my_galaxy/reconstruction.csv\")\nCSV_PATH.parent.mkdir(parents=True, exist_ok=True)\n\nwith CSV_PATH.open(\"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([\"y\", \"x\", \"reconstruction\", \"noise_map\"])\n for (y, x), value, sigma in zip(\n mesh_grid, inversion.reconstruction, inversion.reconstruction_noise_map\n ):\n writer.writerow([y, x, value, sigma])\n\nprint(f\"Reconstruction written to: {CSV_PATH.resolve()}\")\n```\n\nReloading needs nothing but the standard library, and from there the mesh is ordinary scattered\ndata. Two things the workspace does with it: a Delaunay triangulation via `scipy.spatial` for\nplotting on the mesh's own geometry, and interpolation onto a regular grid via\n`scipy.interpolate.griddata` for any tool that wants an image:\n\n```python\nimport numpy as np\nfrom scipy.interpolate import griddata\n\nwith CSV_PATH.open() as f:\n reader = csv.reader(f)\n header = next(reader) # ['y', 'x', 'reconstruction', 'noise_map']\n loaded = {key: [] for key in header}\n for row in reader:\n for key, value in zip(header, row):\n loaded[key].append(float(value))\n\npoints = np.stack((np.array(loaded[\"x\"]), np.array(loaded[\"y\"])), axis=-1)\n\ninterpolation_grid = ag.Grid2D.from_extent(\n extent=(-1.0, 1.0, -1.0, 1.0), shape_native=(201, 201)\n)\n\ninterpolated = griddata(\n points=points, values=np.array(loaded[\"reconstruction\"]), xi=interpolation_grid\n)\n```\n\nPick the `extent` to cover the reconstruction without over-resolving it \u2014 the mesh has a few\nhundred pixels, so interpolating to 201 \u00d7 201 is presentation, not information.\n\n## Branch \u2014 run time, VRAM, and the GPU-versus-CPU choice\n\nThis is the branch that decides whether your fit takes twenty minutes or three hours, and the\nanswer is not \"use the GPU\".\n\nPixelized inversions do linear algebra on very large, very **sparse** matrices. JAX has no sparse\nsupport and must work densely, which scales badly; the CPU implementation exploits the sparsity\nfully via `numba`. So the trade runs against pixel scale:\n\n- **Low resolution (`pixel_scales > 0.05`, e.g. Euclid)** \u2014 fewer sparse operations, modest VRAM.\n **GPU with JAX is usually fastest.**\n- **High resolution (`pixel_scales <= 0.03`, e.g. HST or JWST)** \u2014 the linear algebra is\n sparsity-dominated. **CPU with `numba` and many cores can beat a powerful GPU.**\n\nVRAM is the hard constraint on the GPU side. JAX must hold the whole batched likelihood in GPU\nmemory, and a pixelization needs far more than a profile model: around 0.05 GB per batched\nlikelihood at 400 reconstruction pixels, and more than 1 GB \u2014 occasionally more than 10 GB \u2014 at\nhigh resolution with a fine mesh. Two consequences: keep `n_batch` low (the workspace uses 20 for\npixelizations against 50 elsewhere), and run\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nbefore committing. It takes 20\u201330 seconds and it is the difference between knowing your limit\nand discovering it as an out-of-memory error mid-compile. If VRAM is exceeded the run time does\nnot degrade gracefully \u2014 it goes from under ten minutes to three hours or more.\n\nRough scaling with resolution, from the workspace's own measurements at a 20 \u00d7 20 mesh with VRAM\nunder control: ~10 minutes at 0.1\"/pixel, ~30 minutes at 0.05\", ~1 hour at 0.03\". Benchmark both\npaths for your own data and hardware rather than trusting either default; the search-side\nsettings are [`ag_configure_search`](./ag_configure_search.md) and\n[`../wiki/core/api/searches.md`](../wiki/core/api/searches.md).\n\n## Combine \u2014 where this hands off\n\n- **Try a basis first** \u2192 [`ag_basis_profiles`](./ag_basis_profiles.md). An MGE is four\n parameters and minutes, not hours, and it genuinely resolves the shape-mismatch case a\n pixelization is often reached for by mistake.\n- **Pick and configure the search** \u2192 [`ag_configure_search`](./ag_configure_search.md), with\n `n_batch` lowered for VRAM.\n- **Run the fit** \u2192 [`ag_run_search`](./ag_run_search.md); `image/fit.png` in the output folder\n refreshes on the fly and shows the reconstruction as it converges, which is worth watching for\n a fit this long.\n- **Plot and inspect** \u2192 [`ag_plot_fit`](./ag_plot_fit.md), plus the `subplot_of_mapper`\n diagnostics above.\n- **Load a completed fit programmatically** \u2192 [`ag_load_results`](./ag_load_results.md).\n- **Over-smoothed, over-fitted or unphysical reconstruction** \u2192\n [`ag_debug_fit_failure`](./ag_debug_fit_failure.md). The pixelization-specific causes are a\n regularization scheme too rigid for the structure, a mask that punched holes via hard masking\n where noise scaling was needed, over-sampling passed as `over_sample_size_lp` instead of\n `over_sample_size_pixelization`, and VRAM exhaustion masquerading as a hung fit.\n- **Contaminating neighbours modelled rather than scaled** \u2192\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- **Make the fit robust and fast by starting simple** \u2192 the search-chaining skill\n (`ag_chain_searches`). This is the biggest available win for a pixelization: fit a parametric\n model first, pass its bulge as priors, and let the expensive model start from a sensible place.\n The workspace recommends it explicitly.\n- **A non-parametric shape measurement instead of a reconstruction** \u2192\n [`ag_ellipse_fitting`](./ag_ellipse_fitting.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording the mesh and its\nshape, the regularization scheme and why, the mask radius, the hardware path, and what the\nreconstruction showed \u2014 with a pixelization the choices *are* the result, and none of them are\nrecoverable from the output folder alone.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [HowToGalaxy: Bayesian regularization](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb):\n why a model with hundreds of free flux values does not simply over-fit, derived from scratch;\n `tutorial_6_model_fit` then runs the full fit.\n- **General reference** \u2014 [RTD: Pixelization API](https://pyautogalaxy.readthedocs.io/en/latest/api/pixelization.html):\n every mesh, regularization scheme and the objects that combine them.\n- **Experienced PyAutoGalaxy user** \u2014 [workspace: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n the hybrid fit end to end, with the run-time, VRAM and GPU-versus-CPU discussion in full.\n\n## Agent procedural checklist\n\n1. Look at the residual map of a parametric or basis fit first. Shape-following residuals mean\n `ag_basis_profiles`; discrete off-centre lumps mean a pixelization. Do not skip this.\n2. Confirm the structure is resolved \u2014 at coarse pixel scales a pixelization reconstructs noise.\n3. Always pair the pixelization with a linear light profile for the smooth component; never let\n the mesh reconstruct the bulge.\n4. Fix `mesh_shape` before composing the model; it cannot be a free parameter.\n5. Pass over-sampling as `over_sample_size_pixelization`, not `over_sample_size_lp`.\n6. Start with `RectangularBilinearAdaptDensity` + `ag.reg.Constant`; move to `GaussianKernel` only when\n one smoothing strength demonstrably cannot serve both the bright and faint structure.\n7. Scale contaminant noise (`apply_noise_scaling`, `invert=True`) \u2014 never hard-mask pixels inside\n a pixelization fit \u2014 and check the signal-to-noise panel afterwards.\n8. `print(model.info)`, evaluate one likelihood, then `print_vram_use` before any GPU run; keep\n `n_batch` low.\n9. Read the reconstruction via `inversion.reconstruction` +\n `mapper.mesh_geometry.mesh_grid`; export to CSV for anything downstream.\n10. Save the script to `scripts/`, quote every plot's absolute path and offer to open it, then\n offer the `wiki/project/` entry recording mesh, regularization and hardware choices.\n" + "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_3_pixelizations/tutorial_2_bayesian_regularization.ipynb in HowToGalaxy).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoGalaxy calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoGalaxy docs (https://pyautogalaxy.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_pixelization\n\n---\nname: ag_pixelization\ndescription: Reconstruct a galaxy's clumpy or irregular light directly on a regularized pixel mesh, using `ag.Pixelization` alongside a parametric `ag.lp_linear` bulge \u2014 the hybrid model that gives a smooth interpretable component plus a flexible flux map for everything the profile cannot explain. Covers when a pixelization is warranted and when it is overkill, choosing an `ag.mesh` and an `ag.reg` regularization scheme and what each costs in free parameters, why `mesh_shape` must be fixed before the fit, `over_sample_size_pixelization` rather than `over_sample_size_lp`, noise scaling instead of hard masking for contaminants, the positive-only solver, reading the reconstruction and its Bayesian-evidence terms out of the `Inversion`, exporting the reconstruction to CSV for collaborators, and the GPU/VRAM versus CPU run-time trade. Use when a Sersic, MGE or shapelet basis leaves structured residuals in discrete off-centre lumps. Not for morphology a basis can still fit (`ag_basis_profiles`), not for non-parametric isophote measurement (`ag_ellipse_fitting`), and not for the basics of model composition (`ag_build_imaging_model`).\n---\n\n# Reconstructing a galaxy on a pixel mesh\n\nEvery model in this workspace so far has been a *function*: you asserted a functional form and\nthe fit found its parameters. A pixelization drops the functional form. It lays a mesh of pixels\nover the galaxy, gives each pixel its own free flux value, and solves all of them at once by\nlinear inversion \u2014 thousands of amplitudes, none of them in the non-linear search's parameter\nspace. What stops that from simply fitting the noise is **regularization**: a prior that\npenalises solutions where neighbouring mesh pixels differ sharply, so the reconstruction is as\nsmooth as the data will allow and no smoother.\n\nThe science case is specific, and it is worth being honest about how specific. Galaxies with\nspiral arms, asymmetric star-forming clumps, tidal features or low-surface-brightness\nsubstructure have light that no smooth profile \u2014 and often no basis expansion either \u2014\nreproduces. The canonical use is therefore **hybrid**: a linear `Sersic` for the smooth central\nbulge, and a pixelization for the irregular remainder. That split is the point. It gives you a\nlow-dimensional, physically interpretable description of the bulge *and* a flux map of exactly\nwhat the bulge could not explain, which is the quantity you want if the science question is \"how\nmuch of this galaxy's light is in its irregular components?\"\n\nThis is a **direct** reconstruction. There is no second plane, no de-projection, no inversion of\na geometric mapping \u2014 the mesh sits on the image plane, over the galaxy, at the same coordinates\nthe data occupies. If you have met pixelized reconstruction before in a different context, that\nextra step is the one that is absent here, and its absence makes everything simpler: what the\nmesh reconstructs is the galaxy's own surface brightness, and its coordinates are sky\ncoordinates in arcseconds.\n\nStatistically, the fit now has two nested layers. The non-linear search explores a handful of\nparameters \u2014 the bulge's shape, the regularization strength \u2014 and for each proposal an inversion\nsolves the mesh amplitudes exactly and returns a **Bayesian evidence** rather than a plain\nlikelihood. That evidence includes terms that penalise an unnecessarily complex reconstruction,\nwhich is what lets a model with 400 free flux values not simply win by over-fitting. The theory\nis [`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md);\nchapter 3 of HowToGalaxy derives it from scratch.\n\nThe canonical scripts are\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py` (via a search),\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` (one direct fit, with the\ninversion internals walked through) and\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py` (export).\n\n## Before you reach for one \u2014 the honest gate\n\nA pixelization is the most powerful and the most expensive model here, with failure modes the\nparametric models do not have. Three questions decide whether you need it:\n\n- *\"What do the residuals actually look like?\"* Structured residuals that **follow the\n isophotes** \u2014 a twist, a four-lobed pattern, an ellipticity that changes with radius \u2014 are a\n *shape* problem, and an MGE fixes them for four free parameters\n ([`ag_basis_profiles`](./ag_basis_profiles.md)). Residuals in **discrete off-centre lumps** are\n a substructure problem, and that is what a pixelization is for. Look before you choose.\n- *\"Is the structure resolved?\"* At low resolution the irregular structure is not in the data,\n and a pixelization will reconstruct noise while telling you it fitted well. The workspace is\n blunt about this: for low-resolution data pixelizations are unnecessary.\n- *\"Do you need global quantities or the light distribution?\"* If you want a total flux, a size,\n an axis ratio, a Sersic index \u2014 a parametric profile, an MGE or shapelets are enough and far\n cheaper. If you want the morphology itself, particularly for faint or low-surface-brightness\n features, nothing else comes close.\n\nIf the answer to the first is \"lumps\" and to the second \"yes\", continue. Otherwise you will\nspend hours to learn less.\n\n## Ask\n\n- *\"What is the smooth component?\"* Almost always a linear `Sersic`, sometimes a Sersic plus an\n Exponential disk. It matters that this exists: without it the pixelization has to reconstruct\n the bright central bulge too, which wastes mesh resolution on light a six-parameter profile\n describes perfectly and makes the regularization choice much harder.\n- *\"How many mesh pixels can you afford?\"* This is a hardware question as much as a science one\n (see the run-time branch). 20 \u00d7 20 is the workspace's default for a GPU run; 28 \u00d7 28 to 30 \u00d7 30\n for a better-resolved reconstruction; higher only with a large-VRAM GPU or a many-core CPU.\n- *\"Are there neighbours inside the mask?\"* For a pixelization the answer is *never* to mask\n their pixels out \u2014 that punches holes in the mesh and produces discontinuity systematics.\n Scale their noise instead (branch below).\n- *\"GPU or CPU?\"* Genuinely depends on your pixel scale, and the answer is counter-intuitive.\n Ask before assuming.\n\n## Branch \u2014 the hybrid model\n\nThe canonical composition. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py`.\n\n```python\n\"\"\"\nGalaxy Structure: Bulge Plus Pixelized Reconstruction\n=====================================================\n\nFit a galaxy whose light has two very different characters: a smooth central bulge, described by\na linear Sersic profile in six parameters, and asymmetric clumpy star formation, reconstructed\non a regularized rectangular mesh. The Sersic captures the smooth component interpretably; the\npixelization absorbs everything it cannot explain, and the reconstructed flux map is the\nmeasurement of the galaxy's irregular light.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the imaging, mask it, and apply pixelization over-sampling.\n- **Mesh Shape:** Fix the mesh dimensions before the model is composed.\n- **Model:** Compose the linear Sersic bulge plus the pixelization.\n- **Check:** Confirm the parameter count, evaluate one likelihood, and estimate VRAM.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPIXEL_SCALES = 0.1\nMASK_RADIUS = 2.0\n\n\"\"\"\n__Dataset__\n\nThe mask matters more than usual here. It defines the region the mesh is laid over, so a mask\nthat reaches well beyond the galaxy spends reconstruction pixels on empty sky, and one that\ntruncates the galaxy leaves its outer light unreconstructed\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe over-sampling argument changes too. A pixelization evaluates light on its *own* grid with\nits own over-sampling scheme, so the size is passed as `over_sample_size_pixelization`, not the\n`over_sample_size_lp` used for light profiles. Passing the wrong one silently leaves the\npixelization grid at its default.\n\"\"\"\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=PIXEL_SCALES,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\ndataset = dataset.apply_over_sampling(over_sample_size_pixelization=over_sample_size)\n\n\"\"\"\n__Mesh Shape__\n\nThe mesh dimensions are **fixed before the fit and cannot be a free parameter**. This is not a\nstylistic restriction: JAX compiles the likelihood against statically shaped arrays, and the\nmesh shape sets those shapes. A rectangular mesh uses the same number of pixels in y and x.\n\"\"\"\nmesh_pixels_yx = 20\nmesh_shape = (mesh_pixels_yx, mesh_pixels_yx)\n\n\"\"\"\n__Model__\n\n`ag.Pixelization` pairs a `mesh` \u2014 where the reconstruction pixels sit \u2014 with a `regularization`\nscheme \u2014 the prior that keeps the solution smooth. It is attached to the galaxy as a component\nalongside the light profiles, and the analysis knows to route it through the inversion\n(`PyAutoGalaxy:autogalaxy/galaxy/galaxy.py`).\n\nThe mesh itself contributes **zero** free parameters; the reconstruction's 400 flux values are\nsolved, not sampled. `ag.reg.GaussianKernel` contributes two (`coefficient`, `scale`). The bulge\nis `ag.lp_linear.Sersic` rather than `ag.lp.Sersic` deliberately: its `intensity` is then solved\nby the *same* inversion that solves the mesh amplitudes, which removes the degeneracy between\n\"bright bulge, faint reconstruction\" and \"faint bulge, bright reconstruction\" that a sampled\nintensity would create.\n\"\"\"\npixelization = af.Model(\n ag.Pixelization,\n mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n regularization=ag.reg.GaussianKernel,\n)\n\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n pixelization=pixelization,\n)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\nThree cheap checks, each catching a different class of mistake: the parameter count catches a\nmodel error, one likelihood evaluation catches an incompatibility between model, dataset and\nanalysis, and `print_vram_use` catches the resource error that otherwise appears as an\nout-of-memory failure mid-compile. Pixelizations use far more VRAM than profile-only models \u2014\naround 0.05 GB per batched likelihood for 400 reconstruction pixels \u2014 which is why the\nworkspace uses a lower `n_batch` for these fits than for any other.\n\"\"\"\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\nlog_likelihood = analysis.log_likelihood_function(\n instance=model.instance_from_prior_medians()\n)\nprint(f\"log evidence at prior medians: {float(log_likelihood):.2f}\")\n```\n\n**N = 8**: the Sersic's centre (2), `ell_comps` (2), `effective_radius`, `sersic_index`, plus the\nregularization's `coefficient` and `scale`. Eight parameters, with 400 reconstruction pixels\nsolved. That is dramatically more parsimonious than stacking parametric profiles until every\nclump is described \u2014 a 20-plus-parameter approach that would still fail on genuinely irregular\nsubstructure.\n\nExtending the smooth side is exactly as you would expect \u2014 add components as further attributes\non the galaxy, keeping them linear so their intensities join the same inversion:\n\n```python\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n disk=ag.lp_linear.Exponential,\n pixelization=pixelization,\n)\n```\n\n## Branch \u2014 choosing a mesh and a regularization scheme\n\nThese are the two decisions that make or break a reconstruction, and the parameter cost is\nalmost entirely in the regularization.\n\n**Meshes** (`ag.mesh`, from `PyAutoArray:autoarray/inversion/mesh/`). All contribute zero free\nparameters, all take `shape=(y, x)`:\n\n| Mesh | Where the pixels go | Use when |\n|---|---|---|\n| `RectangularUniform` | a uniform grid over the masked region | you want the simplest, most predictable behaviour |\n| `RectangularBilinearAdaptDensity` | a rectangular grid whose spacing follows the density of image pixels mapping to it, via a rank CDF | **the default** \u2014 concentrates resolution where the data is, and the fast CPU path |\n| `RectangularBilinearAdaptImage` | adapts to the image's own brightness distribution | the irregular light is strongly concentrated |\n| `RectangularRTUAdaptDensity` / `RectangularRTUAdaptImage` | the same two adaptations through a kernel CDF | GPU, JAX gradient samplers and the interferometer sparse path \u2014 the only rectangular adaptive meshes with usable gradients |\n\n`Delaunay`, `KNearestNeighbor` and `KNNBarycentric` also exist for irregular tessellations. Start\nwith `RectangularBilinearAdaptDensity`; it is what every workspace example uses, and the\nrectangular meshes are what the fixed-`mesh_shape` JAX path is built around. (The unqualified\n`RectangularAdaptDensity` / `RectangularAdaptImage` names were split into the `Bilinear` and\n`RTU` families in PyAutoArray 2026.8.23.1 and no longer resolve.)\n\n**Regularization** (`ag.reg`, from `PyAutoArray:autoarray/inversion/regularization/`) is where\nthe free parameters are, and where the physics of \"how smooth should this be?\" lives:\n\n| Scheme | Free params | What it assumes |\n|---|---|---|\n| `ag.reg.Constant` | 1 (`coefficient`) | one smoothing strength everywhere \u2014 the simplest, and the right first try |\n| `ag.reg.GaussianKernel` | 2 (`coefficient`, `scale`) | smoothing with a Gaussian correlation length you also fit |\n| `ag.reg.MaternKernel` | 3 (`coefficient`, `scale`, `nu`) | as above, with the roughness `nu` free too |\n\nVerified counts, not guesses. `Constant` penalises the difference between neighbouring pixels\ndirectly; the kernel schemes impose a correlation *length*, which is physically closer to what a\ngalaxy's light does and generally reconstructs faint extended structure better at the cost of\none or two parameters. `ag.reg.Adapt` and its variants scale the smoothing with the\nreconstruction's own brightness \u2014 more flexible again, and requiring `adapt_images` on the\nanalysis, which is a step beyond this skill; ask if you want it.\n\nA practical route: fit once with `ag.reg.Constant`, look at the reconstruction. Over-smoothed\n(the clumps blurred into one blob) or over-fitted (isolated single-pixel spikes) both show up\nimmediately, and if `Constant` cannot get both the bright clumps and the faint envelope right at\none strength, that is the signal to move to `GaussianKernel`. Full discussion in\n[`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\n### The positive-only solver\n\nEvery pixelized reconstruction uses a **positive-only** linear solver: no mesh pixel may\nreconstruct negative flux. This is not a numerical nicety. A signed solver lets the\nreconstruction manufacture negative pixels that cancel positive ones to over-fit the data, and\nthat failure mode is a well-known systematic in the literature \u2014 many published methods allow\nit. Enforcing non-negativity efficiently needs bespoke linear algebra, which is why this is\nworth stating rather than assuming. You do not need to switch it on; it is the behaviour you get.\n(The one place in this workspace where you *must* disable it is a shapelet basis, which needs\nsigned amplitudes by construction \u2014 see [`ag_basis_profiles`](./ag_basis_profiles.md).)\n\n## Branch \u2014 contaminating neighbours: scale, never mask\n\nThe general advice for a neighbour inside the mask is to mask its pixels out. **For a\npixelization that advice is wrong.** Removing image pixels entirely removes their mapping into\nthe mesh, punching a hole in the reconstruction and producing discontinuities that show up as\nunexplained systematics.\n\nInstead, keep the pixels in the fit and make them contribute nothing: scale their data to zero\nand their noise to an enormous value, so the likelihood is indifferent to them while the mesh\nstays continuous. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py`.\n\n```python\n\"\"\"\n__Noise Scaling__\n\n`mask_extra_galaxies.fits` marks the contaminated pixels. It is loaded with `invert=True`\nbecause in this file `True` means \"scale this pixel\", the opposite of a modelling mask's\nconvention \u2014 getting this backwards scales the galaxy instead of the neighbour, so check the\nsubplot afterwards. `apply_noise_scaling` then zeroes those data values and inflates their\nnoise, driving their signal-to-noise to effectively zero without removing them from the mesh's\nmapping (`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nOrder matters: scale first, then apply the modelling mask.\n\"\"\"\nmask_extra_galaxies = ag.Mask2D.from_fits(\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n pixel_scales=PIXEL_SCALES,\n invert=True,\n)\n\ndataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=PIXEL_SCALES,\n centre=(0.0, 0.0),\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=\"scripts/scratch/my_galaxy/\",\n output_filename=\"noise_scaled\",\n output_format=\"png\",\n)\n```\n\nThe scaled pixels go to a noise value of order 1e8 \u2014 visibly so on the signal-to-noise panel of\nthe subplot, which is how you confirm you scaled the right region. Drawing that mask\ninteractively is `autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask_extra_galaxies.py`;\nthe modelling alternative, and when to prefer it, is\n[`ag_light_model_extras`](./ag_light_model_extras.md) and\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch \u2014 reading the reconstruction out\n\nThe reconstruction is the science product, and it lives on the `Inversion`. You can get there\nfrom a completed fit or from a single direct `ag.FitImaging` \u2014 the latter is the fast way to\nlearn the objects, and is what\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` does.\n\n```python\n\"\"\"\n__Reconstruction__\n\n`inversion.linear_obj_list` holds the linear objects the fit solved. For a hybrid model that is\none `LightProfileLinearObjFuncList` per linear light profile plus one `Mapper` for the\npixelization; with a non-linear `ag.lp.Sersic` bulge the `Mapper` is the only entry. The\n`Mapper` is the object that maps image pixels onto mesh pixels, and it is mesh-specific\n(`PyAutoArray:autoarray/inversion/mappers/`).\n\nThe reconstruction is a 1D array of one flux per mesh pixel, and the (y, x) arcsecond\ncoordinates of those pixels are `mapper.mesh_geometry.mesh_grid`. Pair them by index \u2014 they are\nthe same length and the same order \u2014 and you have the flux map.\n\"\"\"\ninversion = fit.inversion\n\nmapper = inversion.linear_obj_list[0]\n\nreconstruction = inversion.reconstruction\nmesh_grid = mapper.mesh_geometry.mesh_grid\n\nprint(f\"{len(reconstruction)} mesh pixels reconstructed\")\nprint(f\"coordinates shape: {mesh_grid.shape}\")\n\n\"\"\"\nThe reconstruction's own uncertainties, and its projection back onto the image, are also on the\ninversion. `mapped_reconstructed_operated_data` contains **only** the pixelized component \u2014 any\nparametric light profile in the model is excluded \u2014 which is exactly the quantity you want when\nasking how much light is in the irregular component.\n\"\"\"\nprint(inversion.reconstruction_noise_map)\nprint(inversion.mapped_reconstructed_operated_data.native.shape)\n```\n\nA caution on the `Mapper`'s grid attributes: `mapper.image_plane_mesh_grid` is `None` for a\nrectangular mesh, so do not reach for it. `mapper.mesh_geometry.mesh_grid` is the mesh pixel\ncentres (verified on the released stack), and `mapper.image_plane_data_grid` is the centre of\nevery masked *image* pixel. Some of the `Mapper`'s attribute names carry a plane-based prefix\ninherited from the shared inversion library that also serves a multi-plane use case; in\nPyAutoGalaxy there is only the one plane, so `mesh_geometry.mesh_grid` is both the clearer name\nand the one to use.\n\n### The evidence terms\n\nThe inversion's figure of merit is a Bayesian evidence, and its components are individually\nreadable \u2014 which is how you diagnose whether regularization is doing too much or too little:\n\n```python\nprint(f\"regularization term = {inversion.regularization_term}\")\nprint(f\"log det regularization = {inversion.log_det_regularization_matrix_term}\")\nprint(f\"log det curvature + reg = {inversion.log_det_curvature_reg_matrix_term}\")\n```\n\nThe `regularization_term` measures how non-smooth the solution is; the two log-determinant\nterms are the complexity penalty that stops a 400-pixel model winning by over-fitting. The\nmatrices themselves (`curvature_matrix`, `regularization_matrix`, `curvature_reg_matrix`) are\nthere too. The derivation is in HowToGalaxy chapter 3 and the papers it cites\n(arXiv:1708.07377, arXiv:astro-ph/0601493).\n\n### Diagnostic plots\n\n`aplt.subplot_fit_imaging` includes the reconstruction on the mesh alongside the usual data /\nmodel / residual panels, and is the first thing to look at. For the inversion's own internals\nthere are dedicated functions, which live in the shared inversion library rather than on `aplt`\nand so are imported explicitly \u2014 from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/plot.py`:\n\n```python\nfrom autoarray.inversion.plot.inversion_plots import subplot_of_mapper\nfrom autoarray.inversion.plot.mapper_plots import plot_mapper, subplot_image_and_mapper\n\nPLOT_DIR = \"scripts/scratch/my_galaxy/pixelization/\"\n\naplt.subplot_fit_imaging(fit=fit, output_path=PLOT_DIR, output_format=\"png\")\n\nsubplot_of_mapper(\n inversion=inversion, mapper_index=0, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nsubplot_image_and_mapper(\n mapper=mapper, image=dataset.data, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nprint(f\"Saved to: {Path(PLOT_DIR).resolve()}\")\n```\n\n`subplot_of_mapper` is the comprehensive diagnostic \u2014 reconstructed image, reconstruction, its\nnoise map and the regularization weights in one figure \u2014 and `mapper_index` selects which linear\nobject when there are several. `subplot_image_and_mapper` shows the data beside the mesh, which\nis how you check the mesh covers the structure you care about. Note that none of these three are\nexposed on the `aplt` module \u2014 `dir(aplt)` does not list them, so the explicit imports above are\nthe only route and writing them as `aplt.`-prefixed calls raises `AttributeError`. Quote the\nabsolute path back to the user and offer to open it.\n\n## Branch \u2014 exporting the reconstruction for downstream science\n\nA reconstruction that only exists inside a PyAutoGalaxy object is hard to share and hard to\nanalyse with other tools. Write it out as coordinates plus values and it becomes ordinary\ntabular data. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py`.\n\n```python\n\"\"\"\n__Export__\n\nFour columns \u2014 y, x, reconstruction, noise \u2014 is everything needed to rebuild, plot or analyse\nthe galaxy's irregular light without PyAutoGalaxy installed. A completed model-fit also writes\nthis file into its own `image/` folder automatically; glob for `*reconstruction_0.csv` there\nrather than hard-coding the stem, which carries a prefix from the shared inversion library.\n\"\"\"\nimport csv\n\nCSV_PATH = Path(\"scripts/scratch/my_galaxy/reconstruction.csv\")\nCSV_PATH.parent.mkdir(parents=True, exist_ok=True)\n\nwith CSV_PATH.open(\"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([\"y\", \"x\", \"reconstruction\", \"noise_map\"])\n for (y, x), value, sigma in zip(\n mesh_grid, inversion.reconstruction, inversion.reconstruction_noise_map\n ):\n writer.writerow([y, x, value, sigma])\n\nprint(f\"Reconstruction written to: {CSV_PATH.resolve()}\")\n```\n\nReloading needs nothing but the standard library, and from there the mesh is ordinary scattered\ndata. Two things the workspace does with it: a Delaunay triangulation via `scipy.spatial` for\nplotting on the mesh's own geometry, and interpolation onto a regular grid via\n`scipy.interpolate.griddata` for any tool that wants an image:\n\n```python\nimport numpy as np\nfrom scipy.interpolate import griddata\n\nwith CSV_PATH.open() as f:\n reader = csv.reader(f)\n header = next(reader) # ['y', 'x', 'reconstruction', 'noise_map']\n loaded = {key: [] for key in header}\n for row in reader:\n for key, value in zip(header, row):\n loaded[key].append(float(value))\n\npoints = np.stack((np.array(loaded[\"x\"]), np.array(loaded[\"y\"])), axis=-1)\n\ninterpolation_grid = ag.Grid2D.from_extent(\n extent=(-1.0, 1.0, -1.0, 1.0), shape_native=(201, 201)\n)\n\ninterpolated = griddata(\n points=points, values=np.array(loaded[\"reconstruction\"]), xi=interpolation_grid\n)\n```\n\nPick the `extent` to cover the reconstruction without over-resolving it \u2014 the mesh has a few\nhundred pixels, so interpolating to 201 \u00d7 201 is presentation, not information.\n\n## Branch \u2014 run time, VRAM, and the GPU-versus-CPU choice\n\nThis is the branch that decides whether your fit takes twenty minutes or three hours, and the\nanswer is not \"use the GPU\".\n\nPixelized inversions do linear algebra on very large, very **sparse** matrices. JAX has no sparse\nsupport and must work densely, which scales badly; the CPU implementation exploits the sparsity\nfully via `numba`. So the trade runs against pixel scale:\n\n- **Low resolution (`pixel_scales > 0.05`, e.g. Euclid)** \u2014 fewer sparse operations, modest VRAM.\n **GPU with JAX is usually fastest.**\n- **High resolution (`pixel_scales <= 0.03`, e.g. HST or JWST)** \u2014 the linear algebra is\n sparsity-dominated. **CPU with `numba` and many cores can beat a powerful GPU.**\n\nVRAM is the hard constraint on the GPU side. JAX must hold the whole batched likelihood in GPU\nmemory, and a pixelization needs far more than a profile model: around 0.05 GB per batched\nlikelihood at 400 reconstruction pixels, and more than 1 GB \u2014 occasionally more than 10 GB \u2014 at\nhigh resolution with a fine mesh. Two consequences: keep `n_batch` low (the workspace uses 20 for\npixelizations against 50 elsewhere), and run\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nbefore committing. It takes 20\u201330 seconds and it is the difference between knowing your limit\nand discovering it as an out-of-memory error mid-compile. If VRAM is exceeded the run time does\nnot degrade gracefully \u2014 it goes from under ten minutes to three hours or more.\n\nRough scaling with resolution, from the workspace's own measurements at a 20 \u00d7 20 mesh with VRAM\nunder control: ~10 minutes at 0.1\"/pixel, ~30 minutes at 0.05\", ~1 hour at 0.03\". Benchmark both\npaths for your own data and hardware rather than trusting either default; the search-side\nsettings are [`ag_configure_search`](./ag_configure_search.md) and\n[`../wiki/core/api/searches.md`](../wiki/core/api/searches.md).\n\n## Combine \u2014 where this hands off\n\n- **Try a basis first** \u2192 [`ag_basis_profiles`](./ag_basis_profiles.md). An MGE is four\n parameters and minutes, not hours, and it genuinely resolves the shape-mismatch case a\n pixelization is often reached for by mistake.\n- **Pick and configure the search** \u2192 [`ag_configure_search`](./ag_configure_search.md), with\n `n_batch` lowered for VRAM.\n- **Run the fit** \u2192 [`ag_run_search`](./ag_run_search.md); `image/fit.png` in the output folder\n refreshes on the fly and shows the reconstruction as it converges, which is worth watching for\n a fit this long.\n- **Plot and inspect** \u2192 [`ag_plot_fit`](./ag_plot_fit.md), plus the `subplot_of_mapper`\n diagnostics above.\n- **Load a completed fit programmatically** \u2192 [`ag_load_results`](./ag_load_results.md).\n- **Over-smoothed, over-fitted or unphysical reconstruction** \u2192\n [`ag_debug_fit_failure`](./ag_debug_fit_failure.md). The pixelization-specific causes are a\n regularization scheme too rigid for the structure, a mask that punched holes via hard masking\n where noise scaling was needed, over-sampling passed as `over_sample_size_lp` instead of\n `over_sample_size_pixelization`, and VRAM exhaustion masquerading as a hung fit.\n- **Contaminating neighbours modelled rather than scaled** \u2192\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- **Make the fit robust and fast by starting simple** \u2192 the search-chaining skill\n (`ag_chain_searches`). This is the biggest available win for a pixelization: fit a parametric\n model first, pass its bulge as priors, and let the expensive model start from a sensible place.\n The workspace recommends it explicitly.\n- **A non-parametric shape measurement instead of a reconstruction** \u2192\n [`ag_ellipse_fitting`](./ag_ellipse_fitting.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording the mesh and its\nshape, the regularization scheme and why, the mask radius, the hardware path, and what the\nreconstruction showed \u2014 with a pixelization the choices *are* the result, and none of them are\nrecoverable from the output folder alone.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [HowToGalaxy: Bayesian regularization](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb):\n why a model with hundreds of free flux values does not simply over-fit, derived from scratch;\n `tutorial_6_model_fit` then runs the full fit.\n- **General reference** \u2014 [RTD: Pixelization API](https://pyautogalaxy.readthedocs.io/en/latest/api/pixelization.html):\n every mesh, regularization scheme and the objects that combine them.\n- **Experienced PyAutoGalaxy user** \u2014 [workspace: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n the hybrid fit end to end, with the run-time, VRAM and GPU-versus-CPU discussion in full.\n\n## Agent procedural checklist\n\n1. Look at the residual map of a parametric or basis fit first. Shape-following residuals mean\n `ag_basis_profiles`; discrete off-centre lumps mean a pixelization. Do not skip this.\n2. Confirm the structure is resolved \u2014 at coarse pixel scales a pixelization reconstructs noise.\n3. Always pair the pixelization with a linear light profile for the smooth component; never let\n the mesh reconstruct the bulge.\n4. Fix `mesh_shape` before composing the model; it cannot be a free parameter.\n5. Pass over-sampling as `over_sample_size_pixelization`, not `over_sample_size_lp`.\n6. Start with `RectangularBilinearAdaptDensity` + `ag.reg.Constant`; move to `GaussianKernel` only when\n one smoothing strength demonstrably cannot serve both the bright and faint structure.\n7. Scale contaminant noise (`apply_noise_scaling`, `invert=True`) \u2014 never hard-mask pixels inside\n a pixelization fit \u2014 and check the signal-to-noise panel afterwards.\n8. `print(model.info)`, evaluate one likelihood, then `print_vram_use` before any GPU run; keep\n `n_batch` low.\n9. Read the reconstruction via `inversion.reconstruction` +\n `mapper.mesh_geometry.mesh_grid`; export to CSV for anything downstream.\n10. Save the script to `scripts/`, quote every plot's absolute path and offer to open it, then\n offer the `wiki/project/` entry recording mesh, regularization and hardware choices.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_3_pixelizations/tutorial_2_mappers.ipynb b/notebooks/chapter_3_pixelizations/tutorial_2_mappers.ipynb deleted file mode 100644 index 935843a..0000000 --- a/notebooks/chapter_3_pixelizations/tutorial_2_mappers.ipynb +++ /dev/null @@ -1,395 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 2: Mappers\n", - "===================\n", - "\n", - "In the previous tutorial, we used a pixelization to create a `Mapper`. However, it was not clear what a `Mapper`\n", - "does, why it was called a mapper and whether it was mapping anything at all!\n", - "\n", - "Therefore, in this tutorial, we'll cover mappers in more detail.\n", - "\n", - "__Contents__\n", - "\n", - "- **Initial Setup:** Load the dataset for illustration.\n", - "- **Dataset Auto-Simulation:** Automatically simulate the dataset if it does not already exist.\n", - "- **Mappers:** Understand how mappers map image-plane pixels to pixelization pixels.\n", - "- **Mask:** Apply a mask and see how it affects the mapper.\n", - "- **Wrap Up:** Summary of mapper concepts." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Google Colab Setup__\n", - "\n", - "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "jupyter": { - "source_hidden": true - } - }, - "outputs": [], - "source": [ - "# @title Set up Google Colab { display-mode: \"form\" }\n", - "try:\n", - " import google.colab\n", - "except ImportError:\n", - " from autogalaxy import setup_colab as _setup_colab\n", - "else:\n", - " import importlib\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.check_call(\n", - " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", - " )\n", - " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", - "\n", - "_setup_colab.setup(\"howtogalaxy\")" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autogalaxy import setup_notebook; setup_notebook()\n", - "\n", - "from pathlib import Path\n", - "import numpy as np\n", - "import autogalaxy as ag\n", - "import autogalaxy.plot as aplt\n", - "import autoarray.plot as aaplt" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Initial Setup__\n", - "\n", - "we'll use galaxy data, where:\n", - "\n", - " - The galaxy's bulge is an `Sersic`.\n", - " - The galaxy's disk is an `Exponential`." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "dataset_name = \"simple\"\n", - "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Dataset Auto-Simulation__\n", - "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "if ag.util.dataset.should_simulate(str(dataset_path)):\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulators/simple.py\"],\n", - " check=True,\n", - " )\n", - "\n", - "dataset = ag.Imaging.from_fits(\n", - " data_path=dataset_path / \"data.fits\",\n", - " noise_map_path=dataset_path / \"noise_map.fits\",\n", - " psf_path=dataset_path / \"psf.fits\",\n", - " pixel_scales=0.1,\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now, lets set up our `Grid2D` (using the image above)." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "grid = ag.Grid2D.uniform(\n", - " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Mappers__\n", - "\n", - "We now setup a `Pixelization` and use it to create a `Mapper` via the image's grid, just like we did in\n", - "the previous tutorial.\n", - "\n", - "We will make its pixelization resolution half that of the grid above." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mesh = ag.mesh.RectangularBilinearAdaptDensity(\n", - " shape=(dataset.shape_native[0] / 2, dataset.shape_native[1] / 2)\n", - ")\n", - "\n", - "pixelization = ag.Pixelization(mesh=mesh)\n", - "\n", - "interpolator = mesh.interpolator_from(\n", - " source_plane_data_grid=grid, source_plane_mesh_grid=None\n", - ")\n", - "\n", - "mapper = ag.Mapper(interpolator=interpolator)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now plot the `Mapper` alongside the image we used to generate the grid: the image on the left, and on the right the\n", - "rectangular mesh the image-pixel coordinates land on." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aaplt.subplot_image_and_mapper(mapper=mapper, image=dataset.data)\n" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "That shows us the two grids, but not the thing which links them. A mapper's actual job is to record, for every\n", - "pixelization pixel, which image-pixels fall inside it -- and we can ask it for exactly that.\n", - "\n", - "`mapper.mappings_from` takes a list of pixelization-pixel index *groups* and returns one `Mapping` per group. Each\n", - "`Mapping` carries `source_contours` (the outline of the pixelization cell(s) in the group) and `image_contours` (the\n", - "outlines of the connected regions of image-pixels which map into it). Both are polygons in arc-seconds, so\n", - "`subplot_image_and_mapper` can draw them in matched colours: the cell on the right, the image-pixels it owns on the\n", - "left.\n", - "\n", - "Lets map the pixelization pixels at the centre of the mesh to the image. The mesh above adapts its resolution to the\n", - "galaxy's light, so its central cells are far smaller than its outer ones -- a single central cell would be a speck on\n", - "the figure. We therefore take the 25 cells closest to the mesh centre as one group, which draws as one visible patch." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mesh_grid = np.asarray(mapper.source_plane_mesh_grid)\n", - "\n", - "distances = np.hypot(mesh_grid[:, 0], mesh_grid[:, 1])\n", - "\n", - "pix_indexes = [np.argsort(distances)[:25]]\n", - "\n", - "mappings = mapper.mappings_from(pix_indexes=pix_indexes)\n", - "\n", - "aaplt.subplot_image_and_mapper(mapper=mapper, image=dataset.data, regions=mappings)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "On the right, a red patch of the pixelization. On the left, the same red marks the image-pixels which map into it,\n", - "sitting exactly on the galaxy's bright centre. The colour is the statement: these image-pixels and those cells are the\n", - "same thing, seen from the two sides of the mapper.\n", - "\n", - "Notice that the image-plane patch is a little wider than the cells strictly contain. This is because the pairing is\n", - "not one-to-one: a bilinear interpolation scheme is used, so an image-pixel which lands just outside a cell is still\n", - "paired with it, with a weight.\n", - "\n", - "Okay, so I think we can agree, mapper's map things! More specifically, they map pixelization pixels to multiple pixels \n", - "in the observed image of a galaxy.\n", - "\n", - "__Mask__\n", - "\n", - "Finally, lets repeat the steps that we performed above, but now using a masked image. By applying a `Mask2D`, the \n", - "mapper only maps image-pixels that are not removed by the mask. This removes the (many) image pixels at the edge of the \n", - "image, where the galaxy is not present.\n", - "\n", - "Lets just have a quick look at these edges pixels:\n", - "\n", - "Lets use an circular `Mask2D`, which will capture the central galaxy light and clumps." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mask = ag.Mask2D.circular(\n", - " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.0\n", - ")\n", - "\n", - "dataset = dataset.apply_mask(mask=mask)\n", - "aplt.plot_array(array=dataset.data, title=\"Data\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can now use the masked grid to create a new `Mapper` (using the same rectangular pixelization as before)." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "interpolator = mesh.interpolator_from(\n", - " source_plane_data_grid=dataset.grids.pixelization, source_plane_mesh_grid=None\n", - ")\n", - "mapper = ag.Mapper(interpolator=interpolator)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Lets plot it." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aaplt.subplot_image_and_mapper(mapper=mapper, image=dataset.data)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First, we can see a red circle of dots in both the image and pixelization, showing where the edge of the mask\n", - "maps to in the pixelization.\n", - "\n", - "Now lets show that when we draw pixelization pixels, they still appear in the same place in the image. We take the 100\n", - "cells closest to the mesh centre and split them into four groups of 25, working outwards, so each group is drawn in\n", - "its own colour." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mesh_grid = np.asarray(mapper.source_plane_mesh_grid)\n", - "\n", - "distances = np.hypot(mesh_grid[:, 0], mesh_grid[:, 1])\n", - "\n", - "order = np.argsort(distances)\n", - "\n", - "pix_indexes = [order[index * 25 : (index + 1) * 25] for index in range(4)]\n", - "\n", - "mappings = mapper.mappings_from(pix_indexes=pix_indexes)\n", - "\n", - "aaplt.subplot_image_and_mapper(mapper=mapper, image=dataset.data, regions=mappings)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Four groups, four colours, and each colour appears in exactly one place in the image -- unlike a strong lens, where\n", - "the same source region appears in several images, an unlensed galaxy maps one-to-one. Groups which are neighbours in\n", - "the pixelization own image-pixels which are neighbours in the image, so the colours nest outwards from the galaxy's\n", - "centre in both panels.\n", - "\n", - "The mask has not moved anything: it has only removed the image-pixels outside it, so the cells beyond the mask's edge\n", - "now own nothing at all.\n", - "\n", - "__Wrap Up__\n", - "\n", - "In this tutorial, we learnt about mappers, and we used them to understand how the image and pixelization map to one \n", - "another. Your exercises are:\n", - " \n", - " 1) Think about how this could help us actually model galaxies. We have said we're going to reconstruct our galaxies\n", - " on the pixel-grid. So, how does knowing how each pixel maps to the image actually help us? If you`ve not got\n", - " any bright ideas, then worry not, that's exactly what we're going to cover in the next tutorial." - ] - } - ], - "metadata": { - "anaconda-cloud": {}, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - }, - "colab": { - "aiContexts": { - "24c2f562-da24-50bb-8eb9-5a887505fe54": { - "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", - "name": "PyAutoGalaxy assistant", - "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_3_pixelizations/tutorial_2_mappers.ipynb in HowToGalaxy).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoGalaxy calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoGalaxy docs (https://pyautogalaxy.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_pixelization\n\n---\nname: ag_pixelization\ndescription: Reconstruct a galaxy's clumpy or irregular light directly on a regularized pixel mesh, using `ag.Pixelization` alongside a parametric `ag.lp_linear` bulge — the hybrid model that gives a smooth interpretable component plus a flexible flux map for everything the profile cannot explain. Covers when a pixelization is warranted and when it is overkill, choosing an `ag.mesh` and an `ag.reg` regularization scheme and what each costs in free parameters, why `mesh_shape` must be fixed before the fit, `over_sample_size_pixelization` rather than `over_sample_size_lp`, noise scaling instead of hard masking for contaminants, the positive-only solver, reading the reconstruction and its Bayesian-evidence terms out of the `Inversion`, exporting the reconstruction to CSV for collaborators, and the GPU/VRAM versus CPU run-time trade. Use when a Sersic, MGE or shapelet basis leaves structured residuals in discrete off-centre lumps. Not for morphology a basis can still fit (`ag_basis_profiles`), not for non-parametric isophote measurement (`ag_ellipse_fitting`), and not for the basics of model composition (`ag_build_imaging_model`).\n---\n\n# Reconstructing a galaxy on a pixel mesh\n\nEvery model in this workspace so far has been a *function*: you asserted a functional form and\nthe fit found its parameters. A pixelization drops the functional form. It lays a mesh of pixels\nover the galaxy, gives each pixel its own free flux value, and solves all of them at once by\nlinear inversion — thousands of amplitudes, none of them in the non-linear search's parameter\nspace. What stops that from simply fitting the noise is **regularization**: a prior that\npenalises solutions where neighbouring mesh pixels differ sharply, so the reconstruction is as\nsmooth as the data will allow and no smoother.\n\nThe science case is specific, and it is worth being honest about how specific. Galaxies with\nspiral arms, asymmetric star-forming clumps, tidal features or low-surface-brightness\nsubstructure have light that no smooth profile — and often no basis expansion either —\nreproduces. The canonical use is therefore **hybrid**: a linear `Sersic` for the smooth central\nbulge, and a pixelization for the irregular remainder. That split is the point. It gives you a\nlow-dimensional, physically interpretable description of the bulge *and* a flux map of exactly\nwhat the bulge could not explain, which is the quantity you want if the science question is \"how\nmuch of this galaxy's light is in its irregular components?\"\n\nThis is a **direct** reconstruction. There is no second plane, no de-projection, no inversion of\na geometric mapping — the mesh sits on the image plane, over the galaxy, at the same coordinates\nthe data occupies. If you have met pixelized reconstruction before in a different context, that\nextra step is the one that is absent here, and its absence makes everything simpler: what the\nmesh reconstructs is the galaxy's own surface brightness, and its coordinates are sky\ncoordinates in arcseconds.\n\nStatistically, the fit now has two nested layers. The non-linear search explores a handful of\nparameters — the bulge's shape, the regularization strength — and for each proposal an inversion\nsolves the mesh amplitudes exactly and returns a **Bayesian evidence** rather than a plain\nlikelihood. That evidence includes terms that penalise an unnecessarily complex reconstruction,\nwhich is what lets a model with 400 free flux values not simply win by over-fitting. The theory\nis [`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md);\nchapter 3 of HowToGalaxy derives it from scratch.\n\nThe canonical scripts are\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py` (via a search),\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` (one direct fit, with the\ninversion internals walked through) and\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py` (export).\n\n## Before you reach for one — the honest gate\n\nA pixelization is the most powerful and the most expensive model here, with failure modes the\nparametric models do not have. Three questions decide whether you need it:\n\n- *\"What do the residuals actually look like?\"* Structured residuals that **follow the\n isophotes** — a twist, a four-lobed pattern, an ellipticity that changes with radius — are a\n *shape* problem, and an MGE fixes them for four free parameters\n ([`ag_basis_profiles`](./ag_basis_profiles.md)). Residuals in **discrete off-centre lumps** are\n a substructure problem, and that is what a pixelization is for. Look before you choose.\n- *\"Is the structure resolved?\"* At low resolution the irregular structure is not in the data,\n and a pixelization will reconstruct noise while telling you it fitted well. The workspace is\n blunt about this: for low-resolution data pixelizations are unnecessary.\n- *\"Do you need global quantities or the light distribution?\"* If you want a total flux, a size,\n an axis ratio, a Sersic index — a parametric profile, an MGE or shapelets are enough and far\n cheaper. If you want the morphology itself, particularly for faint or low-surface-brightness\n features, nothing else comes close.\n\nIf the answer to the first is \"lumps\" and to the second \"yes\", continue. Otherwise you will\nspend hours to learn less.\n\n## Ask\n\n- *\"What is the smooth component?\"* Almost always a linear `Sersic`, sometimes a Sersic plus an\n Exponential disk. It matters that this exists: without it the pixelization has to reconstruct\n the bright central bulge too, which wastes mesh resolution on light a six-parameter profile\n describes perfectly and makes the regularization choice much harder.\n- *\"How many mesh pixels can you afford?\"* This is a hardware question as much as a science one\n (see the run-time branch). 20 × 20 is the workspace's default for a GPU run; 28 × 28 to 30 × 30\n for a better-resolved reconstruction; higher only with a large-VRAM GPU or a many-core CPU.\n- *\"Are there neighbours inside the mask?\"* For a pixelization the answer is *never* to mask\n their pixels out — that punches holes in the mesh and produces discontinuity systematics.\n Scale their noise instead (branch below).\n- *\"GPU or CPU?\"* Genuinely depends on your pixel scale, and the answer is counter-intuitive.\n Ask before assuming.\n\n## Branch — the hybrid model\n\nThe canonical composition. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py`.\n\n```python\n\"\"\"\nGalaxy Structure: Bulge Plus Pixelized Reconstruction\n=====================================================\n\nFit a galaxy whose light has two very different characters: a smooth central bulge, described by\na linear Sersic profile in six parameters, and asymmetric clumpy star formation, reconstructed\non a regularized rectangular mesh. The Sersic captures the smooth component interpretably; the\npixelization absorbs everything it cannot explain, and the reconstructed flux map is the\nmeasurement of the galaxy's irregular light.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the imaging, mask it, and apply pixelization over-sampling.\n- **Mesh Shape:** Fix the mesh dimensions before the model is composed.\n- **Model:** Compose the linear Sersic bulge plus the pixelization.\n- **Check:** Confirm the parameter count, evaluate one likelihood, and estimate VRAM.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPIXEL_SCALES = 0.1\nMASK_RADIUS = 2.0\n\n\"\"\"\n__Dataset__\n\nThe mask matters more than usual here. It defines the region the mesh is laid over, so a mask\nthat reaches well beyond the galaxy spends reconstruction pixels on empty sky, and one that\ntruncates the galaxy leaves its outer light unreconstructed\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe over-sampling argument changes too. A pixelization evaluates light on its *own* grid with\nits own over-sampling scheme, so the size is passed as `over_sample_size_pixelization`, not the\n`over_sample_size_lp` used for light profiles. Passing the wrong one silently leaves the\npixelization grid at its default.\n\"\"\"\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=PIXEL_SCALES,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\ndataset = dataset.apply_over_sampling(over_sample_size_pixelization=over_sample_size)\n\n\"\"\"\n__Mesh Shape__\n\nThe mesh dimensions are **fixed before the fit and cannot be a free parameter**. This is not a\nstylistic restriction: JAX compiles the likelihood against statically shaped arrays, and the\nmesh shape sets those shapes. A rectangular mesh uses the same number of pixels in y and x.\n\"\"\"\nmesh_pixels_yx = 20\nmesh_shape = (mesh_pixels_yx, mesh_pixels_yx)\n\n\"\"\"\n__Model__\n\n`ag.Pixelization` pairs a `mesh` — where the reconstruction pixels sit — with a `regularization`\nscheme — the prior that keeps the solution smooth. It is attached to the galaxy as a component\nalongside the light profiles, and the analysis knows to route it through the inversion\n(`PyAutoGalaxy:autogalaxy/galaxy/galaxy.py`).\n\nThe mesh itself contributes **zero** free parameters; the reconstruction's 400 flux values are\nsolved, not sampled. `ag.reg.GaussianKernel` contributes two (`coefficient`, `scale`). The bulge\nis `ag.lp_linear.Sersic` rather than `ag.lp.Sersic` deliberately: its `intensity` is then solved\nby the *same* inversion that solves the mesh amplitudes, which removes the degeneracy between\n\"bright bulge, faint reconstruction\" and \"faint bulge, bright reconstruction\" that a sampled\nintensity would create.\n\"\"\"\npixelization = af.Model(\n ag.Pixelization,\n mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n regularization=ag.reg.GaussianKernel,\n)\n\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n pixelization=pixelization,\n)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\nThree cheap checks, each catching a different class of mistake: the parameter count catches a\nmodel error, one likelihood evaluation catches an incompatibility between model, dataset and\nanalysis, and `print_vram_use` catches the resource error that otherwise appears as an\nout-of-memory failure mid-compile. Pixelizations use far more VRAM than profile-only models —\naround 0.05 GB per batched likelihood for 400 reconstruction pixels — which is why the\nworkspace uses a lower `n_batch` for these fits than for any other.\n\"\"\"\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\nlog_likelihood = analysis.log_likelihood_function(\n instance=model.instance_from_prior_medians()\n)\nprint(f\"log evidence at prior medians: {float(log_likelihood):.2f}\")\n```\n\n**N = 8**: the Sersic's centre (2), `ell_comps` (2), `effective_radius`, `sersic_index`, plus the\nregularization's `coefficient` and `scale`. Eight parameters, with 400 reconstruction pixels\nsolved. That is dramatically more parsimonious than stacking parametric profiles until every\nclump is described — a 20-plus-parameter approach that would still fail on genuinely irregular\nsubstructure.\n\nExtending the smooth side is exactly as you would expect — add components as further attributes\non the galaxy, keeping them linear so their intensities join the same inversion:\n\n```python\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n disk=ag.lp_linear.Exponential,\n pixelization=pixelization,\n)\n```\n\n## Branch — choosing a mesh and a regularization scheme\n\nThese are the two decisions that make or break a reconstruction, and the parameter cost is\nalmost entirely in the regularization.\n\n**Meshes** (`ag.mesh`, from `PyAutoArray:autoarray/inversion/mesh/`). All contribute zero free\nparameters, all take `shape=(y, x)`:\n\n| Mesh | Where the pixels go | Use when |\n|---|---|---|\n| `RectangularUniform` | a uniform grid over the masked region | you want the simplest, most predictable behaviour |\n| `RectangularBilinearAdaptDensity` | a rectangular grid whose spacing follows the density of image pixels mapping to it, via a rank CDF | **the default** — concentrates resolution where the data is, and the fast CPU path |\n| `RectangularBilinearAdaptImage` | adapts to the image's own brightness distribution | the irregular light is strongly concentrated |\n| `RectangularRTUAdaptDensity` / `RectangularRTUAdaptImage` | the same two adaptations through a kernel CDF | GPU, JAX gradient samplers and the interferometer sparse path — the only rectangular adaptive meshes with usable gradients |\n\n`Delaunay`, `KNearestNeighbor` and `KNNBarycentric` also exist for irregular tessellations. Start\nwith `RectangularBilinearAdaptDensity`; it is what every workspace example uses, and the\nrectangular meshes are what the fixed-`mesh_shape` JAX path is built around. (The unqualified\n`RectangularAdaptDensity` / `RectangularAdaptImage` names were split into the `Bilinear` and\n`RTU` families in PyAutoArray 2026.8.23.1 and no longer resolve.)\n\n**Regularization** (`ag.reg`, from `PyAutoArray:autoarray/inversion/regularization/`) is where\nthe free parameters are, and where the physics of \"how smooth should this be?\" lives:\n\n| Scheme | Free params | What it assumes |\n|---|---|---|\n| `ag.reg.Constant` | 1 (`coefficient`) | one smoothing strength everywhere — the simplest, and the right first try |\n| `ag.reg.GaussianKernel` | 2 (`coefficient`, `scale`) | smoothing with a Gaussian correlation length you also fit |\n| `ag.reg.MaternKernel` | 3 (`coefficient`, `scale`, `nu`) | as above, with the roughness `nu` free too |\n\nVerified counts, not guesses. `Constant` penalises the difference between neighbouring pixels\ndirectly; the kernel schemes impose a correlation *length*, which is physically closer to what a\ngalaxy's light does and generally reconstructs faint extended structure better at the cost of\none or two parameters. `ag.reg.Adapt` and its variants scale the smoothing with the\nreconstruction's own brightness — more flexible again, and requiring `adapt_images` on the\nanalysis, which is a step beyond this skill; ask if you want it.\n\nA practical route: fit once with `ag.reg.Constant`, look at the reconstruction. Over-smoothed\n(the clumps blurred into one blob) or over-fitted (isolated single-pixel spikes) both show up\nimmediately, and if `Constant` cannot get both the bright clumps and the faint envelope right at\none strength, that is the signal to move to `GaussianKernel`. Full discussion in\n[`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\n### The positive-only solver\n\nEvery pixelized reconstruction uses a **positive-only** linear solver: no mesh pixel may\nreconstruct negative flux. This is not a numerical nicety. A signed solver lets the\nreconstruction manufacture negative pixels that cancel positive ones to over-fit the data, and\nthat failure mode is a well-known systematic in the literature — many published methods allow\nit. Enforcing non-negativity efficiently needs bespoke linear algebra, which is why this is\nworth stating rather than assuming. You do not need to switch it on; it is the behaviour you get.\n(The one place in this workspace where you *must* disable it is a shapelet basis, which needs\nsigned amplitudes by construction — see [`ag_basis_profiles`](./ag_basis_profiles.md).)\n\n## Branch — contaminating neighbours: scale, never mask\n\nThe general advice for a neighbour inside the mask is to mask its pixels out. **For a\npixelization that advice is wrong.** Removing image pixels entirely removes their mapping into\nthe mesh, punching a hole in the reconstruction and producing discontinuities that show up as\nunexplained systematics.\n\nInstead, keep the pixels in the fit and make them contribute nothing: scale their data to zero\nand their noise to an enormous value, so the likelihood is indifferent to them while the mesh\nstays continuous. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py`.\n\n```python\n\"\"\"\n__Noise Scaling__\n\n`mask_extra_galaxies.fits` marks the contaminated pixels. It is loaded with `invert=True`\nbecause in this file `True` means \"scale this pixel\", the opposite of a modelling mask's\nconvention — getting this backwards scales the galaxy instead of the neighbour, so check the\nsubplot afterwards. `apply_noise_scaling` then zeroes those data values and inflates their\nnoise, driving their signal-to-noise to effectively zero without removing them from the mesh's\nmapping (`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nOrder matters: scale first, then apply the modelling mask.\n\"\"\"\nmask_extra_galaxies = ag.Mask2D.from_fits(\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n pixel_scales=PIXEL_SCALES,\n invert=True,\n)\n\ndataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=PIXEL_SCALES,\n centre=(0.0, 0.0),\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=\"scripts/scratch/my_galaxy/\",\n output_filename=\"noise_scaled\",\n output_format=\"png\",\n)\n```\n\nThe scaled pixels go to a noise value of order 1e8 — visibly so on the signal-to-noise panel of\nthe subplot, which is how you confirm you scaled the right region. Drawing that mask\ninteractively is `autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask_extra_galaxies.py`;\nthe modelling alternative, and when to prefer it, is\n[`ag_light_model_extras`](./ag_light_model_extras.md) and\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch — reading the reconstruction out\n\nThe reconstruction is the science product, and it lives on the `Inversion`. You can get there\nfrom a completed fit or from a single direct `ag.FitImaging` — the latter is the fast way to\nlearn the objects, and is what\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` does.\n\n```python\n\"\"\"\n__Reconstruction__\n\n`inversion.linear_obj_list` holds the linear objects the fit solved. For a hybrid model that is\none `LightProfileLinearObjFuncList` per linear light profile plus one `Mapper` for the\npixelization; with a non-linear `ag.lp.Sersic` bulge the `Mapper` is the only entry. The\n`Mapper` is the object that maps image pixels onto mesh pixels, and it is mesh-specific\n(`PyAutoArray:autoarray/inversion/mappers/`).\n\nThe reconstruction is a 1D array of one flux per mesh pixel, and the (y, x) arcsecond\ncoordinates of those pixels are `mapper.mesh_geometry.mesh_grid`. Pair them by index — they are\nthe same length and the same order — and you have the flux map.\n\"\"\"\ninversion = fit.inversion\n\nmapper = inversion.linear_obj_list[0]\n\nreconstruction = inversion.reconstruction\nmesh_grid = mapper.mesh_geometry.mesh_grid\n\nprint(f\"{len(reconstruction)} mesh pixels reconstructed\")\nprint(f\"coordinates shape: {mesh_grid.shape}\")\n\n\"\"\"\nThe reconstruction's own uncertainties, and its projection back onto the image, are also on the\ninversion. `mapped_reconstructed_operated_data` contains **only** the pixelized component — any\nparametric light profile in the model is excluded — which is exactly the quantity you want when\nasking how much light is in the irregular component.\n\"\"\"\nprint(inversion.reconstruction_noise_map)\nprint(inversion.mapped_reconstructed_operated_data.native.shape)\n```\n\nA caution on the `Mapper`'s grid attributes: `mapper.image_plane_mesh_grid` is `None` for a\nrectangular mesh, so do not reach for it. `mapper.mesh_geometry.mesh_grid` is the mesh pixel\ncentres (verified on the released stack), and `mapper.image_plane_data_grid` is the centre of\nevery masked *image* pixel. Some of the `Mapper`'s attribute names carry a plane-based prefix\ninherited from the shared inversion library that also serves a multi-plane use case; in\nPyAutoGalaxy there is only the one plane, so `mesh_geometry.mesh_grid` is both the clearer name\nand the one to use.\n\n### The evidence terms\n\nThe inversion's figure of merit is a Bayesian evidence, and its components are individually\nreadable — which is how you diagnose whether regularization is doing too much or too little:\n\n```python\nprint(f\"regularization term = {inversion.regularization_term}\")\nprint(f\"log det regularization = {inversion.log_det_regularization_matrix_term}\")\nprint(f\"log det curvature + reg = {inversion.log_det_curvature_reg_matrix_term}\")\n```\n\nThe `regularization_term` measures how non-smooth the solution is; the two log-determinant\nterms are the complexity penalty that stops a 400-pixel model winning by over-fitting. The\nmatrices themselves (`curvature_matrix`, `regularization_matrix`, `curvature_reg_matrix`) are\nthere too. The derivation is in HowToGalaxy chapter 3 and the papers it cites\n(arXiv:1708.07377, arXiv:astro-ph/0601493).\n\n### Diagnostic plots\n\n`aplt.subplot_fit_imaging` includes the reconstruction on the mesh alongside the usual data /\nmodel / residual panels, and is the first thing to look at. For the inversion's own internals\nthere are dedicated functions, which live in the shared inversion library rather than on `aplt`\nand so are imported explicitly — from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/plot.py`:\n\n```python\nfrom autoarray.inversion.plot.inversion_plots import subplot_of_mapper\nfrom autoarray.inversion.plot.mapper_plots import plot_mapper, subplot_image_and_mapper\n\nPLOT_DIR = \"scripts/scratch/my_galaxy/pixelization/\"\n\naplt.subplot_fit_imaging(fit=fit, output_path=PLOT_DIR, output_format=\"png\")\n\nsubplot_of_mapper(\n inversion=inversion, mapper_index=0, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nsubplot_image_and_mapper(\n mapper=mapper, image=dataset.data, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nprint(f\"Saved to: {Path(PLOT_DIR).resolve()}\")\n```\n\n`subplot_of_mapper` is the comprehensive diagnostic — reconstructed image, reconstruction, its\nnoise map and the regularization weights in one figure — and `mapper_index` selects which linear\nobject when there are several. `subplot_image_and_mapper` shows the data beside the mesh, which\nis how you check the mesh covers the structure you care about. Note that none of these three are\nexposed on the `aplt` module — `dir(aplt)` does not list them, so the explicit imports above are\nthe only route and writing them as `aplt.`-prefixed calls raises `AttributeError`. Quote the\nabsolute path back to the user and offer to open it.\n\n## Branch — exporting the reconstruction for downstream science\n\nA reconstruction that only exists inside a PyAutoGalaxy object is hard to share and hard to\nanalyse with other tools. Write it out as coordinates plus values and it becomes ordinary\ntabular data. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py`.\n\n```python\n\"\"\"\n__Export__\n\nFour columns — y, x, reconstruction, noise — is everything needed to rebuild, plot or analyse\nthe galaxy's irregular light without PyAutoGalaxy installed. A completed model-fit also writes\nthis file into its own `image/` folder automatically; glob for `*reconstruction_0.csv` there\nrather than hard-coding the stem, which carries a prefix from the shared inversion library.\n\"\"\"\nimport csv\n\nCSV_PATH = Path(\"scripts/scratch/my_galaxy/reconstruction.csv\")\nCSV_PATH.parent.mkdir(parents=True, exist_ok=True)\n\nwith CSV_PATH.open(\"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([\"y\", \"x\", \"reconstruction\", \"noise_map\"])\n for (y, x), value, sigma in zip(\n mesh_grid, inversion.reconstruction, inversion.reconstruction_noise_map\n ):\n writer.writerow([y, x, value, sigma])\n\nprint(f\"Reconstruction written to: {CSV_PATH.resolve()}\")\n```\n\nReloading needs nothing but the standard library, and from there the mesh is ordinary scattered\ndata. Two things the workspace does with it: a Delaunay triangulation via `scipy.spatial` for\nplotting on the mesh's own geometry, and interpolation onto a regular grid via\n`scipy.interpolate.griddata` for any tool that wants an image:\n\n```python\nimport numpy as np\nfrom scipy.interpolate import griddata\n\nwith CSV_PATH.open() as f:\n reader = csv.reader(f)\n header = next(reader) # ['y', 'x', 'reconstruction', 'noise_map']\n loaded = {key: [] for key in header}\n for row in reader:\n for key, value in zip(header, row):\n loaded[key].append(float(value))\n\npoints = np.stack((np.array(loaded[\"x\"]), np.array(loaded[\"y\"])), axis=-1)\n\ninterpolation_grid = ag.Grid2D.from_extent(\n extent=(-1.0, 1.0, -1.0, 1.0), shape_native=(201, 201)\n)\n\ninterpolated = griddata(\n points=points, values=np.array(loaded[\"reconstruction\"]), xi=interpolation_grid\n)\n```\n\nPick the `extent` to cover the reconstruction without over-resolving it — the mesh has a few\nhundred pixels, so interpolating to 201 × 201 is presentation, not information.\n\n## Branch — run time, VRAM, and the GPU-versus-CPU choice\n\nThis is the branch that decides whether your fit takes twenty minutes or three hours, and the\nanswer is not \"use the GPU\".\n\nPixelized inversions do linear algebra on very large, very **sparse** matrices. JAX has no sparse\nsupport and must work densely, which scales badly; the CPU implementation exploits the sparsity\nfully via `numba`. So the trade runs against pixel scale:\n\n- **Low resolution (`pixel_scales > 0.05`, e.g. Euclid)** — fewer sparse operations, modest VRAM.\n **GPU with JAX is usually fastest.**\n- **High resolution (`pixel_scales <= 0.03`, e.g. HST or JWST)** — the linear algebra is\n sparsity-dominated. **CPU with `numba` and many cores can beat a powerful GPU.**\n\nVRAM is the hard constraint on the GPU side. JAX must hold the whole batched likelihood in GPU\nmemory, and a pixelization needs far more than a profile model: around 0.05 GB per batched\nlikelihood at 400 reconstruction pixels, and more than 1 GB — occasionally more than 10 GB — at\nhigh resolution with a fine mesh. Two consequences: keep `n_batch` low (the workspace uses 20 for\npixelizations against 50 elsewhere), and run\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nbefore committing. It takes 20–30 seconds and it is the difference between knowing your limit\nand discovering it as an out-of-memory error mid-compile. If VRAM is exceeded the run time does\nnot degrade gracefully — it goes from under ten minutes to three hours or more.\n\nRough scaling with resolution, from the workspace's own measurements at a 20 × 20 mesh with VRAM\nunder control: ~10 minutes at 0.1\"/pixel, ~30 minutes at 0.05\", ~1 hour at 0.03\". Benchmark both\npaths for your own data and hardware rather than trusting either default; the search-side\nsettings are [`ag_configure_search`](./ag_configure_search.md) and\n[`../wiki/core/api/searches.md`](../wiki/core/api/searches.md).\n\n## Combine — where this hands off\n\n- **Try a basis first** → [`ag_basis_profiles`](./ag_basis_profiles.md). An MGE is four\n parameters and minutes, not hours, and it genuinely resolves the shape-mismatch case a\n pixelization is often reached for by mistake.\n- **Pick and configure the search** → [`ag_configure_search`](./ag_configure_search.md), with\n `n_batch` lowered for VRAM.\n- **Run the fit** → [`ag_run_search`](./ag_run_search.md); `image/fit.png` in the output folder\n refreshes on the fly and shows the reconstruction as it converges, which is worth watching for\n a fit this long.\n- **Plot and inspect** → [`ag_plot_fit`](./ag_plot_fit.md), plus the `subplot_of_mapper`\n diagnostics above.\n- **Load a completed fit programmatically** → [`ag_load_results`](./ag_load_results.md).\n- **Over-smoothed, over-fitted or unphysical reconstruction** →\n [`ag_debug_fit_failure`](./ag_debug_fit_failure.md). The pixelization-specific causes are a\n regularization scheme too rigid for the structure, a mask that punched holes via hard masking\n where noise scaling was needed, over-sampling passed as `over_sample_size_lp` instead of\n `over_sample_size_pixelization`, and VRAM exhaustion masquerading as a hung fit.\n- **Contaminating neighbours modelled rather than scaled** →\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- **Make the fit robust and fast by starting simple** → the search-chaining skill\n (`ag_chain_searches`). This is the biggest available win for a pixelization: fit a parametric\n model first, pass its bulge as priors, and let the expensive model start from a sensible place.\n The workspace recommends it explicitly.\n- **A non-parametric shape measurement instead of a reconstruction** →\n [`ag_ellipse_fitting`](./ag_ellipse_fitting.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording the mesh and its\nshape, the regularization scheme and why, the mask radius, the hardware path, and what the\nreconstruction showed — with a pixelization the choices *are* the result, and none of them are\nrecoverable from the output folder alone.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Bayesian regularization](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb):\n why a model with hundreds of free flux values does not simply over-fit, derived from scratch;\n `tutorial_6_model_fit` then runs the full fit.\n- **General reference** — [RTD: Pixelization API](https://pyautogalaxy.readthedocs.io/en/latest/api/pixelization.html):\n every mesh, regularization scheme and the objects that combine them.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n the hybrid fit end to end, with the run-time, VRAM and GPU-versus-CPU discussion in full.\n\n## Agent procedural checklist\n\n1. Look at the residual map of a parametric or basis fit first. Shape-following residuals mean\n `ag_basis_profiles`; discrete off-centre lumps mean a pixelization. Do not skip this.\n2. Confirm the structure is resolved — at coarse pixel scales a pixelization reconstructs noise.\n3. Always pair the pixelization with a linear light profile for the smooth component; never let\n the mesh reconstruct the bulge.\n4. Fix `mesh_shape` before composing the model; it cannot be a free parameter.\n5. Pass over-sampling as `over_sample_size_pixelization`, not `over_sample_size_lp`.\n6. Start with `RectangularBilinearAdaptDensity` + `ag.reg.Constant`; move to `GaussianKernel` only when\n one smoothing strength demonstrably cannot serve both the bright and faint structure.\n7. Scale contaminant noise (`apply_noise_scaling`, `invert=True`) — never hard-mask pixels inside\n a pixelization fit — and check the signal-to-noise panel afterwards.\n8. `print(model.info)`, evaluate one likelihood, then `print_vram_use` before any GPU run; keep\n `n_batch` low.\n9. Read the reconstruction via `inversion.reconstruction` +\n `mapper.mesh_geometry.mesh_grid`; export to CSV for anything downstream.\n10. Save the script to `scripts/`, quote every plot's absolute path and offer to open it, then\n offer the `wiki/project/` entry recording mesh, regularization and hardware choices.\n" - } - }, - "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file diff --git a/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb b/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb deleted file mode 100644 index 601d865..0000000 --- a/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb +++ /dev/null @@ -1,443 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 3: Inversions\n", - "======================\n", - "\n", - "In the previous two tutorials, we introduced:\n", - "\n", - " - `Pixelization`'s: which place a pixel-grid over the image data.\n", - " - `Mappers`'s: which describe how each pixelization pixel maps to one or more image pixels.\n", - "\n", - "However, none of this has actually helped us fit galaxy data or reconstruct the galaxy. This is the subject\n", - "of this tutorial, where the process of reconstructing the galaxy's light on the pixelization is called an `Inversion`.\n", - "\n", - "__Contents__\n", - "\n", - "- **Initial Setup:** Load the dataset for illustration.\n", - "- **Dataset Auto-Simulation:** Automatically simulate the dataset if it does not already exist.\n", - "- **Pixelization:** Create a pixelization and perform an inversion to reconstruct the galaxy.\n", - "- **Positive Only Solver:** Ensure the reconstruction has only positive intensity values.\n", - "- **Detailed Explanation:** Where the linear algebra behind inversions is derived in full.\n", - "- **Wrap Up:** Summary of inversion concepts." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Google Colab Setup__\n", - "\n", - "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "jupyter": { - "source_hidden": true - } - }, - "outputs": [], - "source": [ - "# @title Set up Google Colab { display-mode: \"form\" }\n", - "try:\n", - " import google.colab\n", - "except ImportError:\n", - " from autogalaxy import setup_colab as _setup_colab\n", - "else:\n", - " import importlib\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.check_call(\n", - " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", - " )\n", - " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", - "\n", - "_setup_colab.setup(\"howtogalaxy\")" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autogalaxy import setup_notebook; setup_notebook()\n", - "\n", - "from pathlib import Path\n", - "import autogalaxy as ag\n", - "import autogalaxy.plot as aplt\n", - "import autoarray.plot as aaplt" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Initial Setup__\n", - "\n", - "we'll use the same galaxy data as the previous tutorial, where:\n", - "\n", - " - The galaxy's bulge is an `Sersic`.\n", - " - The galaxy's disk is an `Exponential`." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "dataset_name = \"simple\"\n", - "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Dataset Auto-Simulation__\n", - "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "if ag.util.dataset.should_simulate(str(dataset_path)):\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulators/simple.py\"],\n", - " check=True,\n", - " )\n", - "\n", - "dataset = ag.Imaging.from_fits(\n", - " data_path=dataset_path / \"data.fits\",\n", - " noise_map_path=dataset_path / \"noise_map.fits\",\n", - " psf_path=dataset_path / \"psf.fits\",\n", - " pixel_scales=0.1,\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Lets create a circular mask which contains the galaxy's emission:" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mask = ag.Mask2D.circular(\n", - " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.0\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now create the masked imaging, as we did in the previous tutorial." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "dataset = dataset.apply_mask(mask=mask)\n", - "\n", - "aplt.plot_array(array=dataset.data, title=\"Data\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "we again use the rectangular pixelization to create the mapper.\n", - "\n", - "(Ignore the regularization input below for now, we will cover this in the next tutorial)." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mesh = ag.mesh.RectangularBilinearAdaptDensity(shape=(25, 25))\n", - "\n", - "pixelization = ag.Pixelization(mesh=mesh)\n", - "\n", - "interpolator = mesh.interpolator_from(\n", - " source_plane_data_grid=dataset.grids.pixelization,\n", - " source_plane_mesh_grid=None,\n", - ")\n", - "\n", - "mapper = ag.Mapper(\n", - " interpolator=interpolator,\n", - " regularization=ag.reg.Constant(coefficient=1.0),\n", - ")\n", - "\n", - "aaplt.subplot_image_and_mapper(mapper=mapper, image=dataset.data)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Pixelization__\n", - "\n", - "Finally, we can now use the `Mapper` to reconstruct the galaxy via an `Inversion`. I'll explain how this works in a \n", - "second, but lets just go ahead and create the inversion first. " - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "inversion = ag.Inversion(dataset=dataset, linear_obj_list=[mapper])" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The inversion has reconstructed the galaxy's light on the rectangular pixel grid, which is called the \n", - "`reconstruction`. \n", - "\n", - "This reconstruction can be mapped back to the same resolution as the image to produce the `mapped_reconstructed_operated_data`." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(inversion.reconstruction)\n", - "print(inversion.mapped_reconstructed_operated_data)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Both of these can be plotted using `subplot_of_mapper`.\n", - "\n", - "It is possible for an inversion to have multiple `Mapper`'s, therefore for certain figures we specify the index \n", - "of the mapper we wish to plot. In this case, because we only have one mapper we specify the index 0." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.plot_array(\n", - " array=inversion.mapped_reconstructed_operated_data, title=\"Reconstruction\"\n", - ")\n", - "aaplt.subplot_of_mapper(inversion=inversion, mapper_index=0)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "There we have it, we have successfully reconstructed the galaxy using a rectangular pixel-grid, capturing the\n", - "structure of its light without assuming an analytic form for it.\n", - "\n", - "Pretty great, huh? If you fitted this galaxy via search chaining at the end of chapter 2 (tutorials 9-10), you'll\n", - "remember how much effort a good model image took. With an inversion, we can do this with ease and without having to\n", - "perform model-fitting with 20+ parameters for the galaxy's light!\n", - "\n", - "We will now briefly discuss how an inversion actually works, however the explanation given in this tutorial will be\n", - "overly-simplified. (The full linear algebra -- the mapping matrices, the linear solve and the equations behind\n", - "them -- is derived step-by-step in tutorial 5.) To be good at modeling you do not need to understand the details of\n", - "how an inversion works, you simply need to be able to use an inversion to model a galaxy.\n", - "\n", - "To begin, lets consider some random mappings between our mapper`s pixelization pixels and the image.\n", - "\n", - "`mapper.mappings_from` returns one `Mapping` per group of pixelization pixels, which we pass straight to\n", - "`subplot_image_and_mapper` as `regions=`. Each mapping is drawn in its own colour: the pixelization cell on the right,\n", - "and the image-pixels which map into it on the left. Tutorial 2 covers this in detail." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "pix_indexes = [[min(index, mapper.pixels - 1)] for index in [445, 285, 313, 132, 211]]\n", - "\n", - "mappings = mapper.mappings_from(pix_indexes=pix_indexes)\n", - "\n", - "aaplt.subplot_image_and_mapper(mapper=mapper, image=dataset.data, regions=mappings)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "These mappings are known before the inversion reconstructs the galaxy, which means before this inversion is performed \n", - "we know two key pieces of information:\n", - "\n", - " 1) The mappings between every pixelization pixel and a set of image-pixels.\n", - " 2) The flux values in every observed image-pixel, which are the values we want to fit successfully.\n", - "\n", - "It turns out that with these two pieces of information we can linearly solve for the set of pixelization pixel fluxes \n", - "that best-fit (e.g. maximize the log likelihood) our observed image. Essentially, we set up the mappings between\n", - "pixelization and image pixels as a large matrix and solve for the pixelization pixel fluxes in an analogous fashion to \n", - "how you would solve a set of simultaneous linear equations. This process is called a `linear inversion`.\n", - "\n", - "There are three more things about a linear inversion that are worth knowing:\n", - "\n", - " 1) When performing fits using light profiles, we discussed how a `model_image` was generated by convolving the light\n", - " profile images with the data's PSF. A similar blurring operation is incorporated into the inversion, such that it \n", - " reconstructs a galaxy (and therefore image) which fully accounts for the telescope optics and effect of the PSF.\n", - "\n", - " 2) You may be familiar with image sub-gridding, which splits each image-pixel into a sub-pixel (if you are not \n", - " familiar then feel free to checkout the optional **HowToGalaxy** tutorial on sub-gridding. If a sub-grid is used, it is \n", - " the mapping between every sub-pixel -pixel that is computed and used to perform the inversion. This prevents \n", - " aliasing effects degrading the image reconstruction. By default **PyAutoGalaxy** uses sub-gridding of degree 4x4.\n", - "\n", - " 3) The inversion`s solution is regularized. But wait, that`s what we'll cover in the next tutorial!\n", - "\n", - "Finally, let me show you how easy it is to fit an image with an `Inversion` using a `FitImaging` object. Instead of \n", - "giving the galaxy a light profile, we simply pass it a `Pixelization` and regularization, and pass it to a \n", - "galaxies." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "pixelization = ag.Pixelization(\n", - " mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=(25, 25)),\n", - " regularization=ag.reg.Constant(coefficient=1.0),\n", - ")\n", - "\n", - "galaxy = ag.Galaxy(redshift=1.0, pixelization=pixelization)\n", - "\n", - "galaxies = ag.Galaxies(galaxies=[galaxy])" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Then, like before, we pass the imaging and galaxies `FitImaging` object. \n", - "\n", - "We see some pretty good looking residuals, albeit there is faint flux leftover. We will consider how we can address \n", - "this in the next tutorial. \n", - "\n", - "We can use the `subplot_of_galaxies` method to specifically visualize the inversion and plot the reconstruction." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "fit = ag.FitImaging(dataset=dataset, galaxies=galaxies)\n", - "\n", - "aplt.subplot_fit_imaging(fit=fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Positive Only Solver__\n", - "\n", - "All pixelized galaxy reconstructions use a positive-only solver, meaning that every pixelization pixel is only\n", - "allowed to reconstruct positive flux values. This ensures that the reconstruction is physical and that we don't\n", - "reconstruct negative flux values that don't exist in the real galaxy (a common unphysical systematic in methods\n", - "without this constraint).\n", - "\n", - "It may be surprising to hear that this is a feature worth pointing out, but it turns out setting up the linear algebra\n", - "to enforce positive reconstructions is difficult to make efficient. A lot of development time went into making this\n", - "possible, where a bespoke fast non-negative linear solver was developed to achieve this.\n", - "\n", - "Other methods in the literature often do not use a positive only solver, and therefore suffer from these\n", - "unphysical solutions, which can degrade the results of galaxy models in general.\n", - "\n", - "__Detailed Explanation__\n", - "\n", - "The linear algebra sketched above -- setting up the mappings as a matrix and solving for the pixelization pixel\n", - "fluxes -- is derived in full in tutorial 5 of this chapter, where we build every matrix by hand and perform the\n", - "solve ourselves. The file `autogalaxy_workspace/*/imaging/features/pixelization/likelihood_function.ipynb` gives a\n", - "further visual step-by-step guide of the process alongside equations and references to literature on the subject.\n", - "\n", - "__Wrap Up__\n", - "\n", - "And, we're done, here are a few questions to get you thinking about inversions:\n", - "\n", - " 1) The inversion provides the maximum log likelihood solution to the observed image. Is there a problem with seeking\n", - " the highest likelihood solution? Is there a risk that we're going to fit other things in the image than just the\n", - " galaxy? What happens if you reduce the `coefficient` of the regularization object above to zero?\n", - "\n", - " 2) The exterior pixels in the rectangular pixel-grid have no image-pixels in them. However, they are still given a\n", - " reconstructed flux. Given these pixels do not map to the data, where is this value coming from?" - ] - } - ], - "metadata": { - "anaconda-cloud": {}, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - }, - "colab": { - "aiContexts": { - "24c2f562-da24-50bb-8eb9-5a887505fe54": { - "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", - "name": "PyAutoGalaxy assistant", - "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb in HowToGalaxy).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoGalaxy calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoGalaxy docs (https://pyautogalaxy.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_pixelization\n\n---\nname: ag_pixelization\ndescription: Reconstruct a galaxy's clumpy or irregular light directly on a regularized pixel mesh, using `ag.Pixelization` alongside a parametric `ag.lp_linear` bulge — the hybrid model that gives a smooth interpretable component plus a flexible flux map for everything the profile cannot explain. Covers when a pixelization is warranted and when it is overkill, choosing an `ag.mesh` and an `ag.reg` regularization scheme and what each costs in free parameters, why `mesh_shape` must be fixed before the fit, `over_sample_size_pixelization` rather than `over_sample_size_lp`, noise scaling instead of hard masking for contaminants, the positive-only solver, reading the reconstruction and its Bayesian-evidence terms out of the `Inversion`, exporting the reconstruction to CSV for collaborators, and the GPU/VRAM versus CPU run-time trade. Use when a Sersic, MGE or shapelet basis leaves structured residuals in discrete off-centre lumps. Not for morphology a basis can still fit (`ag_basis_profiles`), not for non-parametric isophote measurement (`ag_ellipse_fitting`), and not for the basics of model composition (`ag_build_imaging_model`).\n---\n\n# Reconstructing a galaxy on a pixel mesh\n\nEvery model in this workspace so far has been a *function*: you asserted a functional form and\nthe fit found its parameters. A pixelization drops the functional form. It lays a mesh of pixels\nover the galaxy, gives each pixel its own free flux value, and solves all of them at once by\nlinear inversion — thousands of amplitudes, none of them in the non-linear search's parameter\nspace. What stops that from simply fitting the noise is **regularization**: a prior that\npenalises solutions where neighbouring mesh pixels differ sharply, so the reconstruction is as\nsmooth as the data will allow and no smoother.\n\nThe science case is specific, and it is worth being honest about how specific. Galaxies with\nspiral arms, asymmetric star-forming clumps, tidal features or low-surface-brightness\nsubstructure have light that no smooth profile — and often no basis expansion either —\nreproduces. The canonical use is therefore **hybrid**: a linear `Sersic` for the smooth central\nbulge, and a pixelization for the irregular remainder. That split is the point. It gives you a\nlow-dimensional, physically interpretable description of the bulge *and* a flux map of exactly\nwhat the bulge could not explain, which is the quantity you want if the science question is \"how\nmuch of this galaxy's light is in its irregular components?\"\n\nThis is a **direct** reconstruction. There is no second plane, no de-projection, no inversion of\na geometric mapping — the mesh sits on the image plane, over the galaxy, at the same coordinates\nthe data occupies. If you have met pixelized reconstruction before in a different context, that\nextra step is the one that is absent here, and its absence makes everything simpler: what the\nmesh reconstructs is the galaxy's own surface brightness, and its coordinates are sky\ncoordinates in arcseconds.\n\nStatistically, the fit now has two nested layers. The non-linear search explores a handful of\nparameters — the bulge's shape, the regularization strength — and for each proposal an inversion\nsolves the mesh amplitudes exactly and returns a **Bayesian evidence** rather than a plain\nlikelihood. That evidence includes terms that penalise an unnecessarily complex reconstruction,\nwhich is what lets a model with 400 free flux values not simply win by over-fitting. The theory\nis [`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md);\nchapter 3 of HowToGalaxy derives it from scratch.\n\nThe canonical scripts are\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py` (via a search),\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` (one direct fit, with the\ninversion internals walked through) and\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py` (export).\n\n## Before you reach for one — the honest gate\n\nA pixelization is the most powerful and the most expensive model here, with failure modes the\nparametric models do not have. Three questions decide whether you need it:\n\n- *\"What do the residuals actually look like?\"* Structured residuals that **follow the\n isophotes** — a twist, a four-lobed pattern, an ellipticity that changes with radius — are a\n *shape* problem, and an MGE fixes them for four free parameters\n ([`ag_basis_profiles`](./ag_basis_profiles.md)). Residuals in **discrete off-centre lumps** are\n a substructure problem, and that is what a pixelization is for. Look before you choose.\n- *\"Is the structure resolved?\"* At low resolution the irregular structure is not in the data,\n and a pixelization will reconstruct noise while telling you it fitted well. The workspace is\n blunt about this: for low-resolution data pixelizations are unnecessary.\n- *\"Do you need global quantities or the light distribution?\"* If you want a total flux, a size,\n an axis ratio, a Sersic index — a parametric profile, an MGE or shapelets are enough and far\n cheaper. If you want the morphology itself, particularly for faint or low-surface-brightness\n features, nothing else comes close.\n\nIf the answer to the first is \"lumps\" and to the second \"yes\", continue. Otherwise you will\nspend hours to learn less.\n\n## Ask\n\n- *\"What is the smooth component?\"* Almost always a linear `Sersic`, sometimes a Sersic plus an\n Exponential disk. It matters that this exists: without it the pixelization has to reconstruct\n the bright central bulge too, which wastes mesh resolution on light a six-parameter profile\n describes perfectly and makes the regularization choice much harder.\n- *\"How many mesh pixels can you afford?\"* This is a hardware question as much as a science one\n (see the run-time branch). 20 × 20 is the workspace's default for a GPU run; 28 × 28 to 30 × 30\n for a better-resolved reconstruction; higher only with a large-VRAM GPU or a many-core CPU.\n- *\"Are there neighbours inside the mask?\"* For a pixelization the answer is *never* to mask\n their pixels out — that punches holes in the mesh and produces discontinuity systematics.\n Scale their noise instead (branch below).\n- *\"GPU or CPU?\"* Genuinely depends on your pixel scale, and the answer is counter-intuitive.\n Ask before assuming.\n\n## Branch — the hybrid model\n\nThe canonical composition. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py`.\n\n```python\n\"\"\"\nGalaxy Structure: Bulge Plus Pixelized Reconstruction\n=====================================================\n\nFit a galaxy whose light has two very different characters: a smooth central bulge, described by\na linear Sersic profile in six parameters, and asymmetric clumpy star formation, reconstructed\non a regularized rectangular mesh. The Sersic captures the smooth component interpretably; the\npixelization absorbs everything it cannot explain, and the reconstructed flux map is the\nmeasurement of the galaxy's irregular light.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the imaging, mask it, and apply pixelization over-sampling.\n- **Mesh Shape:** Fix the mesh dimensions before the model is composed.\n- **Model:** Compose the linear Sersic bulge plus the pixelization.\n- **Check:** Confirm the parameter count, evaluate one likelihood, and estimate VRAM.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPIXEL_SCALES = 0.1\nMASK_RADIUS = 2.0\n\n\"\"\"\n__Dataset__\n\nThe mask matters more than usual here. It defines the region the mesh is laid over, so a mask\nthat reaches well beyond the galaxy spends reconstruction pixels on empty sky, and one that\ntruncates the galaxy leaves its outer light unreconstructed\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe over-sampling argument changes too. A pixelization evaluates light on its *own* grid with\nits own over-sampling scheme, so the size is passed as `over_sample_size_pixelization`, not the\n`over_sample_size_lp` used for light profiles. Passing the wrong one silently leaves the\npixelization grid at its default.\n\"\"\"\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=PIXEL_SCALES,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\ndataset = dataset.apply_over_sampling(over_sample_size_pixelization=over_sample_size)\n\n\"\"\"\n__Mesh Shape__\n\nThe mesh dimensions are **fixed before the fit and cannot be a free parameter**. This is not a\nstylistic restriction: JAX compiles the likelihood against statically shaped arrays, and the\nmesh shape sets those shapes. A rectangular mesh uses the same number of pixels in y and x.\n\"\"\"\nmesh_pixels_yx = 20\nmesh_shape = (mesh_pixels_yx, mesh_pixels_yx)\n\n\"\"\"\n__Model__\n\n`ag.Pixelization` pairs a `mesh` — where the reconstruction pixels sit — with a `regularization`\nscheme — the prior that keeps the solution smooth. It is attached to the galaxy as a component\nalongside the light profiles, and the analysis knows to route it through the inversion\n(`PyAutoGalaxy:autogalaxy/galaxy/galaxy.py`).\n\nThe mesh itself contributes **zero** free parameters; the reconstruction's 400 flux values are\nsolved, not sampled. `ag.reg.GaussianKernel` contributes two (`coefficient`, `scale`). The bulge\nis `ag.lp_linear.Sersic` rather than `ag.lp.Sersic` deliberately: its `intensity` is then solved\nby the *same* inversion that solves the mesh amplitudes, which removes the degeneracy between\n\"bright bulge, faint reconstruction\" and \"faint bulge, bright reconstruction\" that a sampled\nintensity would create.\n\"\"\"\npixelization = af.Model(\n ag.Pixelization,\n mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n regularization=ag.reg.GaussianKernel,\n)\n\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n pixelization=pixelization,\n)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\nThree cheap checks, each catching a different class of mistake: the parameter count catches a\nmodel error, one likelihood evaluation catches an incompatibility between model, dataset and\nanalysis, and `print_vram_use` catches the resource error that otherwise appears as an\nout-of-memory failure mid-compile. Pixelizations use far more VRAM than profile-only models —\naround 0.05 GB per batched likelihood for 400 reconstruction pixels — which is why the\nworkspace uses a lower `n_batch` for these fits than for any other.\n\"\"\"\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\nlog_likelihood = analysis.log_likelihood_function(\n instance=model.instance_from_prior_medians()\n)\nprint(f\"log evidence at prior medians: {float(log_likelihood):.2f}\")\n```\n\n**N = 8**: the Sersic's centre (2), `ell_comps` (2), `effective_radius`, `sersic_index`, plus the\nregularization's `coefficient` and `scale`. Eight parameters, with 400 reconstruction pixels\nsolved. That is dramatically more parsimonious than stacking parametric profiles until every\nclump is described — a 20-plus-parameter approach that would still fail on genuinely irregular\nsubstructure.\n\nExtending the smooth side is exactly as you would expect — add components as further attributes\non the galaxy, keeping them linear so their intensities join the same inversion:\n\n```python\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n disk=ag.lp_linear.Exponential,\n pixelization=pixelization,\n)\n```\n\n## Branch — choosing a mesh and a regularization scheme\n\nThese are the two decisions that make or break a reconstruction, and the parameter cost is\nalmost entirely in the regularization.\n\n**Meshes** (`ag.mesh`, from `PyAutoArray:autoarray/inversion/mesh/`). All contribute zero free\nparameters, all take `shape=(y, x)`:\n\n| Mesh | Where the pixels go | Use when |\n|---|---|---|\n| `RectangularUniform` | a uniform grid over the masked region | you want the simplest, most predictable behaviour |\n| `RectangularBilinearAdaptDensity` | a rectangular grid whose spacing follows the density of image pixels mapping to it, via a rank CDF | **the default** — concentrates resolution where the data is, and the fast CPU path |\n| `RectangularBilinearAdaptImage` | adapts to the image's own brightness distribution | the irregular light is strongly concentrated |\n| `RectangularRTUAdaptDensity` / `RectangularRTUAdaptImage` | the same two adaptations through a kernel CDF | GPU, JAX gradient samplers and the interferometer sparse path — the only rectangular adaptive meshes with usable gradients |\n\n`Delaunay`, `KNearestNeighbor` and `KNNBarycentric` also exist for irregular tessellations. Start\nwith `RectangularBilinearAdaptDensity`; it is what every workspace example uses, and the\nrectangular meshes are what the fixed-`mesh_shape` JAX path is built around. (The unqualified\n`RectangularAdaptDensity` / `RectangularAdaptImage` names were split into the `Bilinear` and\n`RTU` families in PyAutoArray 2026.8.23.1 and no longer resolve.)\n\n**Regularization** (`ag.reg`, from `PyAutoArray:autoarray/inversion/regularization/`) is where\nthe free parameters are, and where the physics of \"how smooth should this be?\" lives:\n\n| Scheme | Free params | What it assumes |\n|---|---|---|\n| `ag.reg.Constant` | 1 (`coefficient`) | one smoothing strength everywhere — the simplest, and the right first try |\n| `ag.reg.GaussianKernel` | 2 (`coefficient`, `scale`) | smoothing with a Gaussian correlation length you also fit |\n| `ag.reg.MaternKernel` | 3 (`coefficient`, `scale`, `nu`) | as above, with the roughness `nu` free too |\n\nVerified counts, not guesses. `Constant` penalises the difference between neighbouring pixels\ndirectly; the kernel schemes impose a correlation *length*, which is physically closer to what a\ngalaxy's light does and generally reconstructs faint extended structure better at the cost of\none or two parameters. `ag.reg.Adapt` and its variants scale the smoothing with the\nreconstruction's own brightness — more flexible again, and requiring `adapt_images` on the\nanalysis, which is a step beyond this skill; ask if you want it.\n\nA practical route: fit once with `ag.reg.Constant`, look at the reconstruction. Over-smoothed\n(the clumps blurred into one blob) or over-fitted (isolated single-pixel spikes) both show up\nimmediately, and if `Constant` cannot get both the bright clumps and the faint envelope right at\none strength, that is the signal to move to `GaussianKernel`. Full discussion in\n[`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\n### The positive-only solver\n\nEvery pixelized reconstruction uses a **positive-only** linear solver: no mesh pixel may\nreconstruct negative flux. This is not a numerical nicety. A signed solver lets the\nreconstruction manufacture negative pixels that cancel positive ones to over-fit the data, and\nthat failure mode is a well-known systematic in the literature — many published methods allow\nit. Enforcing non-negativity efficiently needs bespoke linear algebra, which is why this is\nworth stating rather than assuming. You do not need to switch it on; it is the behaviour you get.\n(The one place in this workspace where you *must* disable it is a shapelet basis, which needs\nsigned amplitudes by construction — see [`ag_basis_profiles`](./ag_basis_profiles.md).)\n\n## Branch — contaminating neighbours: scale, never mask\n\nThe general advice for a neighbour inside the mask is to mask its pixels out. **For a\npixelization that advice is wrong.** Removing image pixels entirely removes their mapping into\nthe mesh, punching a hole in the reconstruction and producing discontinuities that show up as\nunexplained systematics.\n\nInstead, keep the pixels in the fit and make them contribute nothing: scale their data to zero\nand their noise to an enormous value, so the likelihood is indifferent to them while the mesh\nstays continuous. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py`.\n\n```python\n\"\"\"\n__Noise Scaling__\n\n`mask_extra_galaxies.fits` marks the contaminated pixels. It is loaded with `invert=True`\nbecause in this file `True` means \"scale this pixel\", the opposite of a modelling mask's\nconvention — getting this backwards scales the galaxy instead of the neighbour, so check the\nsubplot afterwards. `apply_noise_scaling` then zeroes those data values and inflates their\nnoise, driving their signal-to-noise to effectively zero without removing them from the mesh's\nmapping (`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nOrder matters: scale first, then apply the modelling mask.\n\"\"\"\nmask_extra_galaxies = ag.Mask2D.from_fits(\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n pixel_scales=PIXEL_SCALES,\n invert=True,\n)\n\ndataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=PIXEL_SCALES,\n centre=(0.0, 0.0),\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=\"scripts/scratch/my_galaxy/\",\n output_filename=\"noise_scaled\",\n output_format=\"png\",\n)\n```\n\nThe scaled pixels go to a noise value of order 1e8 — visibly so on the signal-to-noise panel of\nthe subplot, which is how you confirm you scaled the right region. Drawing that mask\ninteractively is `autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask_extra_galaxies.py`;\nthe modelling alternative, and when to prefer it, is\n[`ag_light_model_extras`](./ag_light_model_extras.md) and\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch — reading the reconstruction out\n\nThe reconstruction is the science product, and it lives on the `Inversion`. You can get there\nfrom a completed fit or from a single direct `ag.FitImaging` — the latter is the fast way to\nlearn the objects, and is what\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` does.\n\n```python\n\"\"\"\n__Reconstruction__\n\n`inversion.linear_obj_list` holds the linear objects the fit solved. For a hybrid model that is\none `LightProfileLinearObjFuncList` per linear light profile plus one `Mapper` for the\npixelization; with a non-linear `ag.lp.Sersic` bulge the `Mapper` is the only entry. The\n`Mapper` is the object that maps image pixels onto mesh pixels, and it is mesh-specific\n(`PyAutoArray:autoarray/inversion/mappers/`).\n\nThe reconstruction is a 1D array of one flux per mesh pixel, and the (y, x) arcsecond\ncoordinates of those pixels are `mapper.mesh_geometry.mesh_grid`. Pair them by index — they are\nthe same length and the same order — and you have the flux map.\n\"\"\"\ninversion = fit.inversion\n\nmapper = inversion.linear_obj_list[0]\n\nreconstruction = inversion.reconstruction\nmesh_grid = mapper.mesh_geometry.mesh_grid\n\nprint(f\"{len(reconstruction)} mesh pixels reconstructed\")\nprint(f\"coordinates shape: {mesh_grid.shape}\")\n\n\"\"\"\nThe reconstruction's own uncertainties, and its projection back onto the image, are also on the\ninversion. `mapped_reconstructed_operated_data` contains **only** the pixelized component — any\nparametric light profile in the model is excluded — which is exactly the quantity you want when\nasking how much light is in the irregular component.\n\"\"\"\nprint(inversion.reconstruction_noise_map)\nprint(inversion.mapped_reconstructed_operated_data.native.shape)\n```\n\nA caution on the `Mapper`'s grid attributes: `mapper.image_plane_mesh_grid` is `None` for a\nrectangular mesh, so do not reach for it. `mapper.mesh_geometry.mesh_grid` is the mesh pixel\ncentres (verified on the released stack), and `mapper.image_plane_data_grid` is the centre of\nevery masked *image* pixel. Some of the `Mapper`'s attribute names carry a plane-based prefix\ninherited from the shared inversion library that also serves a multi-plane use case; in\nPyAutoGalaxy there is only the one plane, so `mesh_geometry.mesh_grid` is both the clearer name\nand the one to use.\n\n### The evidence terms\n\nThe inversion's figure of merit is a Bayesian evidence, and its components are individually\nreadable — which is how you diagnose whether regularization is doing too much or too little:\n\n```python\nprint(f\"regularization term = {inversion.regularization_term}\")\nprint(f\"log det regularization = {inversion.log_det_regularization_matrix_term}\")\nprint(f\"log det curvature + reg = {inversion.log_det_curvature_reg_matrix_term}\")\n```\n\nThe `regularization_term` measures how non-smooth the solution is; the two log-determinant\nterms are the complexity penalty that stops a 400-pixel model winning by over-fitting. The\nmatrices themselves (`curvature_matrix`, `regularization_matrix`, `curvature_reg_matrix`) are\nthere too. The derivation is in HowToGalaxy chapter 3 and the papers it cites\n(arXiv:1708.07377, arXiv:astro-ph/0601493).\n\n### Diagnostic plots\n\n`aplt.subplot_fit_imaging` includes the reconstruction on the mesh alongside the usual data /\nmodel / residual panels, and is the first thing to look at. For the inversion's own internals\nthere are dedicated functions, which live in the shared inversion library rather than on `aplt`\nand so are imported explicitly — from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/plot.py`:\n\n```python\nfrom autoarray.inversion.plot.inversion_plots import subplot_of_mapper\nfrom autoarray.inversion.plot.mapper_plots import plot_mapper, subplot_image_and_mapper\n\nPLOT_DIR = \"scripts/scratch/my_galaxy/pixelization/\"\n\naplt.subplot_fit_imaging(fit=fit, output_path=PLOT_DIR, output_format=\"png\")\n\nsubplot_of_mapper(\n inversion=inversion, mapper_index=0, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nsubplot_image_and_mapper(\n mapper=mapper, image=dataset.data, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nprint(f\"Saved to: {Path(PLOT_DIR).resolve()}\")\n```\n\n`subplot_of_mapper` is the comprehensive diagnostic — reconstructed image, reconstruction, its\nnoise map and the regularization weights in one figure — and `mapper_index` selects which linear\nobject when there are several. `subplot_image_and_mapper` shows the data beside the mesh, which\nis how you check the mesh covers the structure you care about. Note that none of these three are\nexposed on the `aplt` module — `dir(aplt)` does not list them, so the explicit imports above are\nthe only route and writing them as `aplt.`-prefixed calls raises `AttributeError`. Quote the\nabsolute path back to the user and offer to open it.\n\n## Branch — exporting the reconstruction for downstream science\n\nA reconstruction that only exists inside a PyAutoGalaxy object is hard to share and hard to\nanalyse with other tools. Write it out as coordinates plus values and it becomes ordinary\ntabular data. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py`.\n\n```python\n\"\"\"\n__Export__\n\nFour columns — y, x, reconstruction, noise — is everything needed to rebuild, plot or analyse\nthe galaxy's irregular light without PyAutoGalaxy installed. A completed model-fit also writes\nthis file into its own `image/` folder automatically; glob for `*reconstruction_0.csv` there\nrather than hard-coding the stem, which carries a prefix from the shared inversion library.\n\"\"\"\nimport csv\n\nCSV_PATH = Path(\"scripts/scratch/my_galaxy/reconstruction.csv\")\nCSV_PATH.parent.mkdir(parents=True, exist_ok=True)\n\nwith CSV_PATH.open(\"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([\"y\", \"x\", \"reconstruction\", \"noise_map\"])\n for (y, x), value, sigma in zip(\n mesh_grid, inversion.reconstruction, inversion.reconstruction_noise_map\n ):\n writer.writerow([y, x, value, sigma])\n\nprint(f\"Reconstruction written to: {CSV_PATH.resolve()}\")\n```\n\nReloading needs nothing but the standard library, and from there the mesh is ordinary scattered\ndata. Two things the workspace does with it: a Delaunay triangulation via `scipy.spatial` for\nplotting on the mesh's own geometry, and interpolation onto a regular grid via\n`scipy.interpolate.griddata` for any tool that wants an image:\n\n```python\nimport numpy as np\nfrom scipy.interpolate import griddata\n\nwith CSV_PATH.open() as f:\n reader = csv.reader(f)\n header = next(reader) # ['y', 'x', 'reconstruction', 'noise_map']\n loaded = {key: [] for key in header}\n for row in reader:\n for key, value in zip(header, row):\n loaded[key].append(float(value))\n\npoints = np.stack((np.array(loaded[\"x\"]), np.array(loaded[\"y\"])), axis=-1)\n\ninterpolation_grid = ag.Grid2D.from_extent(\n extent=(-1.0, 1.0, -1.0, 1.0), shape_native=(201, 201)\n)\n\ninterpolated = griddata(\n points=points, values=np.array(loaded[\"reconstruction\"]), xi=interpolation_grid\n)\n```\n\nPick the `extent` to cover the reconstruction without over-resolving it — the mesh has a few\nhundred pixels, so interpolating to 201 × 201 is presentation, not information.\n\n## Branch — run time, VRAM, and the GPU-versus-CPU choice\n\nThis is the branch that decides whether your fit takes twenty minutes or three hours, and the\nanswer is not \"use the GPU\".\n\nPixelized inversions do linear algebra on very large, very **sparse** matrices. JAX has no sparse\nsupport and must work densely, which scales badly; the CPU implementation exploits the sparsity\nfully via `numba`. So the trade runs against pixel scale:\n\n- **Low resolution (`pixel_scales > 0.05`, e.g. Euclid)** — fewer sparse operations, modest VRAM.\n **GPU with JAX is usually fastest.**\n- **High resolution (`pixel_scales <= 0.03`, e.g. HST or JWST)** — the linear algebra is\n sparsity-dominated. **CPU with `numba` and many cores can beat a powerful GPU.**\n\nVRAM is the hard constraint on the GPU side. JAX must hold the whole batched likelihood in GPU\nmemory, and a pixelization needs far more than a profile model: around 0.05 GB per batched\nlikelihood at 400 reconstruction pixels, and more than 1 GB — occasionally more than 10 GB — at\nhigh resolution with a fine mesh. Two consequences: keep `n_batch` low (the workspace uses 20 for\npixelizations against 50 elsewhere), and run\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nbefore committing. It takes 20–30 seconds and it is the difference between knowing your limit\nand discovering it as an out-of-memory error mid-compile. If VRAM is exceeded the run time does\nnot degrade gracefully — it goes from under ten minutes to three hours or more.\n\nRough scaling with resolution, from the workspace's own measurements at a 20 × 20 mesh with VRAM\nunder control: ~10 minutes at 0.1\"/pixel, ~30 minutes at 0.05\", ~1 hour at 0.03\". Benchmark both\npaths for your own data and hardware rather than trusting either default; the search-side\nsettings are [`ag_configure_search`](./ag_configure_search.md) and\n[`../wiki/core/api/searches.md`](../wiki/core/api/searches.md).\n\n## Combine — where this hands off\n\n- **Try a basis first** → [`ag_basis_profiles`](./ag_basis_profiles.md). An MGE is four\n parameters and minutes, not hours, and it genuinely resolves the shape-mismatch case a\n pixelization is often reached for by mistake.\n- **Pick and configure the search** → [`ag_configure_search`](./ag_configure_search.md), with\n `n_batch` lowered for VRAM.\n- **Run the fit** → [`ag_run_search`](./ag_run_search.md); `image/fit.png` in the output folder\n refreshes on the fly and shows the reconstruction as it converges, which is worth watching for\n a fit this long.\n- **Plot and inspect** → [`ag_plot_fit`](./ag_plot_fit.md), plus the `subplot_of_mapper`\n diagnostics above.\n- **Load a completed fit programmatically** → [`ag_load_results`](./ag_load_results.md).\n- **Over-smoothed, over-fitted or unphysical reconstruction** →\n [`ag_debug_fit_failure`](./ag_debug_fit_failure.md). The pixelization-specific causes are a\n regularization scheme too rigid for the structure, a mask that punched holes via hard masking\n where noise scaling was needed, over-sampling passed as `over_sample_size_lp` instead of\n `over_sample_size_pixelization`, and VRAM exhaustion masquerading as a hung fit.\n- **Contaminating neighbours modelled rather than scaled** →\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- **Make the fit robust and fast by starting simple** → the search-chaining skill\n (`ag_chain_searches`). This is the biggest available win for a pixelization: fit a parametric\n model first, pass its bulge as priors, and let the expensive model start from a sensible place.\n The workspace recommends it explicitly.\n- **A non-parametric shape measurement instead of a reconstruction** →\n [`ag_ellipse_fitting`](./ag_ellipse_fitting.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording the mesh and its\nshape, the regularization scheme and why, the mask radius, the hardware path, and what the\nreconstruction showed — with a pixelization the choices *are* the result, and none of them are\nrecoverable from the output folder alone.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Bayesian regularization](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb):\n why a model with hundreds of free flux values does not simply over-fit, derived from scratch;\n `tutorial_6_model_fit` then runs the full fit.\n- **General reference** — [RTD: Pixelization API](https://pyautogalaxy.readthedocs.io/en/latest/api/pixelization.html):\n every mesh, regularization scheme and the objects that combine them.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n the hybrid fit end to end, with the run-time, VRAM and GPU-versus-CPU discussion in full.\n\n## Agent procedural checklist\n\n1. Look at the residual map of a parametric or basis fit first. Shape-following residuals mean\n `ag_basis_profiles`; discrete off-centre lumps mean a pixelization. Do not skip this.\n2. Confirm the structure is resolved — at coarse pixel scales a pixelization reconstructs noise.\n3. Always pair the pixelization with a linear light profile for the smooth component; never let\n the mesh reconstruct the bulge.\n4. Fix `mesh_shape` before composing the model; it cannot be a free parameter.\n5. Pass over-sampling as `over_sample_size_pixelization`, not `over_sample_size_lp`.\n6. Start with `RectangularBilinearAdaptDensity` + `ag.reg.Constant`; move to `GaussianKernel` only when\n one smoothing strength demonstrably cannot serve both the bright and faint structure.\n7. Scale contaminant noise (`apply_noise_scaling`, `invert=True`) — never hard-mask pixels inside\n a pixelization fit — and check the signal-to-noise panel afterwards.\n8. `print(model.info)`, evaluate one likelihood, then `print_vram_use` before any GPU run; keep\n `n_batch` low.\n9. Read the reconstruction via `inversion.reconstruction` +\n `mapper.mesh_geometry.mesh_grid`; export to CSV for anything downstream.\n10. Save the script to `scripts/`, quote every plot's absolute path and offer to open it, then\n offer the `wiki/project/` entry recording mesh, regularization and hardware choices.\n" - } - }, - "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file diff --git a/notebooks/chapter_3_pixelizations/tutorial_3_model_fit.ipynb b/notebooks/chapter_3_pixelizations/tutorial_3_model_fit.ipynb new file mode 100644 index 0000000..cb4579e --- /dev/null +++ b/notebooks/chapter_3_pixelizations/tutorial_3_model_fit.ipynb @@ -0,0 +1,334 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Tutorial 3: Model Fit\n", + "=====================\n", + "\n", + "A pixelization can describe a galaxy without assigning an analytic centre and shape to every visible feature.\n", + "However, analytic profiles remain useful when we want to describe its smooth components. In this tutorial we combine\n", + "an MGE with a pixelization and use search chaining to put the smooth light model in place first.\n", + "\n", + "This is a continuation of Chapter 2's linear profiles. Gaussian widths are fixed, Gaussian intensities are solved\n", + "linearly, and the search explores their shared geometry. The second fit adds mesh brightnesses and searches for the\n", + "regularization coefficient. We actually perform both fits, so the second model inherits a fitted MGE.\n", + "\n", + "Our smooth bulge-and-disc simulation is a controlled starting point. A pixelization need not reveal new clumps in\n", + "such data: inspect whether it captures genuine residual structure or merely compensates for modelling choices.\n", + "For irregular observed galaxies, the same procedure offers extra spatial freedom without choosing a separate\n", + "analytic profile for every knot.\n", + "\n", + "__Contents__\n", + "\n", + "- **Dataset:** Load, mask and oversample the image.\n", + "- **Search 1:** Fit the smooth galaxy light with an MGE.\n", + "- **Search 2:** Add a regularized pixelization using the fitted MGE geometry.\n", + "- **Search 3:** Refine the MGE geometry together with the pixelization.\n", + "- **Interpretation:** Inspect both the residuals and the component decomposition." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Google Colab Setup__\n", + "\n", + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, + "outputs": [], + "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", + "try:\n", + " import google.colab\n", + "except ImportError:\n", + " from autogalaxy import setup_colab as _setup_colab\n", + "else:\n", + " import importlib\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.check_call(\n", + " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", + " )\n", + " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", + "\n", + "_setup_colab.setup(\"howtogalaxy\")" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from pathlib import Path\n", + "import subprocess\n", + "import sys\n", + "import numpy as np\n", + "import autogalaxy as ag\n", + "import autogalaxy.plot as aplt\n", + "import autoarray.plot as aaplt\n", + "\n", + "dataset_path = Path(\"dataset\") / \"imaging\" / \"simple\"\n", + "if ag.util.dataset.should_simulate(str(dataset_path)):\n", + " subprocess.run([sys.executable, \"scripts/simulators/simple.py\"], check=True)\n", + "dataset = ag.Imaging.from_fits(\n", + " data_path=dataset_path / \"data.fits\",\n", + " noise_map_path=dataset_path / \"noise_map.fits\",\n", + " psf_path=dataset_path / \"psf.fits\",\n", + " pixel_scales=0.1,\n", + ")\n", + "mask = ag.Mask2D.circular(\n", + " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.0\n", + ")\n", + "dataset = dataset.apply_mask(mask=mask)\n", + "dataset = dataset.apply_over_sampling(over_sample_size_pixelization=1)\n", + "# Keep the smoke-test mesh smaller than its deliberately capped image.\n", + "mesh_pixels = min(25, min(dataset.shape_native) // 2)\n", + "mesh_shape = (mesh_pixels, mesh_pixels)\n", + "aplt.subplot_imaging_dataset(dataset=dataset)\n", + "\n", + "import autofit as af\n", + "\n", + "over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n", + " grid=dataset.grid,\n", + " sub_size_list=[8, 4, 2],\n", + " radial_list=[0.3, 0.6],\n", + " centre_list=[(0.0, 0.0)],\n", + ")\n", + "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Search 1: Fit the MGE__\n", + "\n", + "An MGE combines Gaussians with fixed widths and linearly solved intensities. We use two Gaussian groups so that the\n", + "smooth model can describe light with different flattenings and orientations. Each group's Gaussians share their\n", + "elliptical shape; their centre is fixed at the known simulation centre in this example. For real data, the centre\n", + "should be inferred or justified independently.\n", + "\n", + "The search therefore adjusts the shapes of these groups rather than a separate intensity and width for every\n", + "Gaussian. The helper below sets up those shared parameters. Look at `model_1.info` to inspect the resulting model.\n", + "This first fit supplies a useful starting description, not a guarantee that every smooth or compact feature has\n", + "been assigned to the correct physical component." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "mge = ag.model_util.mge_model_from(\n", + " mask_radius=2.0,\n", + " total_gaussians=20,\n", + " gaussian_per_basis=2,\n", + " centre_fixed=(0.0, 0.0),\n", + " sigma_min=0.01,\n", + ")\n", + "model_1 = af.Collection(\n", + " galaxies=af.Collection(galaxy=af.Model(ag.Galaxy, redshift=0.5, bulge=mge))\n", + ")\n", + "print(model_1.info)\n", + "search_1 = af.Nautilus(\n", + " path_prefix=Path(\"howtogalaxy\") / \"chapter_3\",\n", + " name=\"mge_search_1\",\n", + " unique_tag=\"simple\",\n", + " n_live=100,\n", + " n_batch=50,\n", + ")\n", + "result_1 = search_1.fit(\n", + " model=model_1, analysis=ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", + ")\n", + "aplt.subplot_fit_imaging(fit=result_1.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Search 2: Add the pixelization__\n", + "\n", + "Inspect the MGE residuals before adding freedom. Compact coherent residuals might need a more flexible brightness\n", + "description, but PSF or background errors can also leave structure. A pixelization can absorb those errors too;\n", + "a better-looking fit does not identify their cause.\n", + "\n", + "We now hold the MGE geometry at `result_1.instance` and add a rectangular brightness mesh. The mesh shape is fixed\n", + "before the search; JAX needs this array shape to remain static. The regularization coefficient is inferred, and the\n", + "mesh brightnesses are solved linearly for every proposal.\n", + "\n", + "Using `.instance` makes this fit simpler because it does not need to rediscover the smooth galaxy geometry. The\n", + "MGE's linear Gaussian intensities are still solved together with the pixelized brightnesses. We are fitting one\n", + "combined image model, not subtracting a noisy observed image and pretending that subtraction is exact." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "pixelization = af.Model(\n", + " ag.Pixelization,\n", + " mesh=ag.mesh.RectangularUniform(shape=mesh_shape),\n", + " regularization=af.Model(ag.reg.Constant),\n", + ")\n", + "pixelization.regularization.coefficient = af.LogUniformPrior(\n", + " lower_limit=0.01, upper_limit=100.0\n", + ")\n", + "model_2 = af.Collection(\n", + " galaxies=af.Collection(\n", + " galaxy=af.Model(\n", + " ag.Galaxy,\n", + " redshift=0.5,\n", + " bulge=result_1.instance.galaxies.galaxy.bulge,\n", + " pixelization=pixelization,\n", + " )\n", + " )\n", + ")\n", + "search_2 = af.Nautilus(\n", + " path_prefix=Path(\"howtogalaxy\") / \"chapter_3\",\n", + " name=\"mge_pixelization_search_2\",\n", + " unique_tag=\"simple\",\n", + " n_live=50,\n", + " n_batch=50,\n", + ")\n", + "result_2 = search_2.fit(\n", + " model=model_2, analysis=ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", + ")\n", + "fit_2 = result_2.max_log_likelihood_fit\n", + "aplt.subplot_fit_imaging(fit=fit_2)\n", + "mapper_2 = fit_2.inversion.cls_list_from(ag.Mapper)[0]\n", + "aaplt.plot_mapper(\n", + " mapper=mapper_2,\n", + " solution_vector=fit_2.inversion.reconstruction_dict[mapper_2],\n", + " title=\"Pixelized Component Alongside the MGE\",\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Search 3: Refine both components__\n", + "\n", + "Fixing geometry helped us get started, but its uncertainty should not disappear from a final scientific analysis.\n", + "Using `result_1.model` returns the MGE geometry to the search with priors informed by the first fit. We also pass the\n", + "regularization model from the second fit. Their linear intensities continue to be solved for each proposal.\n", + "\n", + "Search chaining is a practical way to initialize this combined model. Priors passed between searches should be\n", + "checked: if an initial analytic fit was inadequate, it can provide an overconfident starting point. In that case,\n", + "widen the relevant priors and investigate the competing solutions." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "model_3 = af.Collection(\n", + " galaxies=af.Collection(\n", + " galaxy=af.Model(\n", + " ag.Galaxy,\n", + " redshift=0.5,\n", + " bulge=result_1.model.galaxies.galaxy.bulge,\n", + " pixelization=result_2.model.galaxies.galaxy.pixelization,\n", + " )\n", + " )\n", + ")\n", + "search_3 = af.Nautilus(\n", + " path_prefix=Path(\"howtogalaxy\") / \"chapter_3\",\n", + " name=\"mge_pixelization_search_3\",\n", + " unique_tag=\"simple\",\n", + " n_live=100,\n", + " n_batch=50,\n", + ")\n", + "result_3 = search_3.fit(\n", + " model=model_3, analysis=ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", + ")\n", + "fit_3 = result_3.max_log_likelihood_fit\n", + "aplt.subplot_fit_imaging(fit=fit_3)\n", + "mapper_3 = fit_3.inversion.cls_list_from(ag.Mapper)[0]\n", + "aaplt.plot_mapper(\n", + " mapper=mapper_3,\n", + " solution_vector=fit_3.inversion.reconstruction_dict[mapper_3],\n", + " title=\"Pixelized Component After Joint Geometry Refinement\",\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Wrap Up__\n", + "\n", + "The MGE describes smooth light while the mesh gives the combined model more spatial freedom. Their decomposition\n", + "is not automatically unique: a pixelization can represent some light that an MGE could also explain. Regularization,\n", + "mesh resolution and analytic-model choices affect which component receives it.\n", + "\n", + "Inspect the residuals, the pixelized component and the inferred MGE geometry together. A small residual map does not\n", + "guarantee unbiased component measurements. Check that scientific conclusions remain stable under reasonable mesh,\n", + "regularization and prior changes, and use the posterior samples when reporting uncertainty.\n", + "\n", + "**\ud83e\udd16 Ask AI:** Why can the total galaxy image be well constrained while the division of its light between an MGE and\n", + "a pixelization remains uncertain?\n", + "\n", + "This chapter has connected pixelized brightnesses to the linear intensities from Chapter 2, followed their mappings\n", + "into the image, explored regularization, and performed a chained model fit. MGE remains a useful modelling tool;\n", + "pixelization adds another way to represent galaxy structure when analytic components alone become cumbersome." + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.1" + }, + "colab": { + "aiContexts": { + "24c2f562-da24-50bb-8eb9-5a887505fe54": { + "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", + "name": "PyAutoGalaxy assistant", + "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_3_pixelizations/tutorial_3_model_fit.ipynb in HowToGalaxy).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoGalaxy calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoGalaxy docs (https://pyautogalaxy.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_pixelization\n\n---\nname: ag_pixelization\ndescription: Reconstruct a galaxy's clumpy or irregular light directly on a regularized pixel mesh, using `ag.Pixelization` alongside a parametric `ag.lp_linear` bulge \u2014 the hybrid model that gives a smooth interpretable component plus a flexible flux map for everything the profile cannot explain. Covers when a pixelization is warranted and when it is overkill, choosing an `ag.mesh` and an `ag.reg` regularization scheme and what each costs in free parameters, why `mesh_shape` must be fixed before the fit, `over_sample_size_pixelization` rather than `over_sample_size_lp`, noise scaling instead of hard masking for contaminants, the positive-only solver, reading the reconstruction and its Bayesian-evidence terms out of the `Inversion`, exporting the reconstruction to CSV for collaborators, and the GPU/VRAM versus CPU run-time trade. Use when a Sersic, MGE or shapelet basis leaves structured residuals in discrete off-centre lumps. Not for morphology a basis can still fit (`ag_basis_profiles`), not for non-parametric isophote measurement (`ag_ellipse_fitting`), and not for the basics of model composition (`ag_build_imaging_model`).\n---\n\n# Reconstructing a galaxy on a pixel mesh\n\nEvery model in this workspace so far has been a *function*: you asserted a functional form and\nthe fit found its parameters. A pixelization drops the functional form. It lays a mesh of pixels\nover the galaxy, gives each pixel its own free flux value, and solves all of them at once by\nlinear inversion \u2014 thousands of amplitudes, none of them in the non-linear search's parameter\nspace. What stops that from simply fitting the noise is **regularization**: a prior that\npenalises solutions where neighbouring mesh pixels differ sharply, so the reconstruction is as\nsmooth as the data will allow and no smoother.\n\nThe science case is specific, and it is worth being honest about how specific. Galaxies with\nspiral arms, asymmetric star-forming clumps, tidal features or low-surface-brightness\nsubstructure have light that no smooth profile \u2014 and often no basis expansion either \u2014\nreproduces. The canonical use is therefore **hybrid**: a linear `Sersic` for the smooth central\nbulge, and a pixelization for the irregular remainder. That split is the point. It gives you a\nlow-dimensional, physically interpretable description of the bulge *and* a flux map of exactly\nwhat the bulge could not explain, which is the quantity you want if the science question is \"how\nmuch of this galaxy's light is in its irregular components?\"\n\nThis is a **direct** reconstruction. There is no second plane, no de-projection, no inversion of\na geometric mapping \u2014 the mesh sits on the image plane, over the galaxy, at the same coordinates\nthe data occupies. If you have met pixelized reconstruction before in a different context, that\nextra step is the one that is absent here, and its absence makes everything simpler: what the\nmesh reconstructs is the galaxy's own surface brightness, and its coordinates are sky\ncoordinates in arcseconds.\n\nStatistically, the fit now has two nested layers. The non-linear search explores a handful of\nparameters \u2014 the bulge's shape, the regularization strength \u2014 and for each proposal an inversion\nsolves the mesh amplitudes exactly and returns a **Bayesian evidence** rather than a plain\nlikelihood. That evidence includes terms that penalise an unnecessarily complex reconstruction,\nwhich is what lets a model with 400 free flux values not simply win by over-fitting. The theory\nis [`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md);\nchapter 3 of HowToGalaxy derives it from scratch.\n\nThe canonical scripts are\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py` (via a search),\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` (one direct fit, with the\ninversion internals walked through) and\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py` (export).\n\n## Before you reach for one \u2014 the honest gate\n\nA pixelization is the most powerful and the most expensive model here, with failure modes the\nparametric models do not have. Three questions decide whether you need it:\n\n- *\"What do the residuals actually look like?\"* Structured residuals that **follow the\n isophotes** \u2014 a twist, a four-lobed pattern, an ellipticity that changes with radius \u2014 are a\n *shape* problem, and an MGE fixes them for four free parameters\n ([`ag_basis_profiles`](./ag_basis_profiles.md)). Residuals in **discrete off-centre lumps** are\n a substructure problem, and that is what a pixelization is for. Look before you choose.\n- *\"Is the structure resolved?\"* At low resolution the irregular structure is not in the data,\n and a pixelization will reconstruct noise while telling you it fitted well. The workspace is\n blunt about this: for low-resolution data pixelizations are unnecessary.\n- *\"Do you need global quantities or the light distribution?\"* If you want a total flux, a size,\n an axis ratio, a Sersic index \u2014 a parametric profile, an MGE or shapelets are enough and far\n cheaper. If you want the morphology itself, particularly for faint or low-surface-brightness\n features, nothing else comes close.\n\nIf the answer to the first is \"lumps\" and to the second \"yes\", continue. Otherwise you will\nspend hours to learn less.\n\n## Ask\n\n- *\"What is the smooth component?\"* Almost always a linear `Sersic`, sometimes a Sersic plus an\n Exponential disk. It matters that this exists: without it the pixelization has to reconstruct\n the bright central bulge too, which wastes mesh resolution on light a six-parameter profile\n describes perfectly and makes the regularization choice much harder.\n- *\"How many mesh pixels can you afford?\"* This is a hardware question as much as a science one\n (see the run-time branch). 20 \u00d7 20 is the workspace's default for a GPU run; 28 \u00d7 28 to 30 \u00d7 30\n for a better-resolved reconstruction; higher only with a large-VRAM GPU or a many-core CPU.\n- *\"Are there neighbours inside the mask?\"* For a pixelization the answer is *never* to mask\n their pixels out \u2014 that punches holes in the mesh and produces discontinuity systematics.\n Scale their noise instead (branch below).\n- *\"GPU or CPU?\"* Genuinely depends on your pixel scale, and the answer is counter-intuitive.\n Ask before assuming.\n\n## Branch \u2014 the hybrid model\n\nThe canonical composition. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py`.\n\n```python\n\"\"\"\nGalaxy Structure: Bulge Plus Pixelized Reconstruction\n=====================================================\n\nFit a galaxy whose light has two very different characters: a smooth central bulge, described by\na linear Sersic profile in six parameters, and asymmetric clumpy star formation, reconstructed\non a regularized rectangular mesh. The Sersic captures the smooth component interpretably; the\npixelization absorbs everything it cannot explain, and the reconstructed flux map is the\nmeasurement of the galaxy's irregular light.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the imaging, mask it, and apply pixelization over-sampling.\n- **Mesh Shape:** Fix the mesh dimensions before the model is composed.\n- **Model:** Compose the linear Sersic bulge plus the pixelization.\n- **Check:** Confirm the parameter count, evaluate one likelihood, and estimate VRAM.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPIXEL_SCALES = 0.1\nMASK_RADIUS = 2.0\n\n\"\"\"\n__Dataset__\n\nThe mask matters more than usual here. It defines the region the mesh is laid over, so a mask\nthat reaches well beyond the galaxy spends reconstruction pixels on empty sky, and one that\ntruncates the galaxy leaves its outer light unreconstructed\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe over-sampling argument changes too. A pixelization evaluates light on its *own* grid with\nits own over-sampling scheme, so the size is passed as `over_sample_size_pixelization`, not the\n`over_sample_size_lp` used for light profiles. Passing the wrong one silently leaves the\npixelization grid at its default.\n\"\"\"\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=PIXEL_SCALES,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\ndataset = dataset.apply_over_sampling(over_sample_size_pixelization=over_sample_size)\n\n\"\"\"\n__Mesh Shape__\n\nThe mesh dimensions are **fixed before the fit and cannot be a free parameter**. This is not a\nstylistic restriction: JAX compiles the likelihood against statically shaped arrays, and the\nmesh shape sets those shapes. A rectangular mesh uses the same number of pixels in y and x.\n\"\"\"\nmesh_pixels_yx = 20\nmesh_shape = (mesh_pixels_yx, mesh_pixels_yx)\n\n\"\"\"\n__Model__\n\n`ag.Pixelization` pairs a `mesh` \u2014 where the reconstruction pixels sit \u2014 with a `regularization`\nscheme \u2014 the prior that keeps the solution smooth. It is attached to the galaxy as a component\nalongside the light profiles, and the analysis knows to route it through the inversion\n(`PyAutoGalaxy:autogalaxy/galaxy/galaxy.py`).\n\nThe mesh itself contributes **zero** free parameters; the reconstruction's 400 flux values are\nsolved, not sampled. `ag.reg.GaussianKernel` contributes two (`coefficient`, `scale`). The bulge\nis `ag.lp_linear.Sersic` rather than `ag.lp.Sersic` deliberately: its `intensity` is then solved\nby the *same* inversion that solves the mesh amplitudes, which removes the degeneracy between\n\"bright bulge, faint reconstruction\" and \"faint bulge, bright reconstruction\" that a sampled\nintensity would create.\n\"\"\"\npixelization = af.Model(\n ag.Pixelization,\n mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n regularization=ag.reg.GaussianKernel,\n)\n\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n pixelization=pixelization,\n)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\nThree cheap checks, each catching a different class of mistake: the parameter count catches a\nmodel error, one likelihood evaluation catches an incompatibility between model, dataset and\nanalysis, and `print_vram_use` catches the resource error that otherwise appears as an\nout-of-memory failure mid-compile. Pixelizations use far more VRAM than profile-only models \u2014\naround 0.05 GB per batched likelihood for 400 reconstruction pixels \u2014 which is why the\nworkspace uses a lower `n_batch` for these fits than for any other.\n\"\"\"\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\nlog_likelihood = analysis.log_likelihood_function(\n instance=model.instance_from_prior_medians()\n)\nprint(f\"log evidence at prior medians: {float(log_likelihood):.2f}\")\n```\n\n**N = 8**: the Sersic's centre (2), `ell_comps` (2), `effective_radius`, `sersic_index`, plus the\nregularization's `coefficient` and `scale`. Eight parameters, with 400 reconstruction pixels\nsolved. That is dramatically more parsimonious than stacking parametric profiles until every\nclump is described \u2014 a 20-plus-parameter approach that would still fail on genuinely irregular\nsubstructure.\n\nExtending the smooth side is exactly as you would expect \u2014 add components as further attributes\non the galaxy, keeping them linear so their intensities join the same inversion:\n\n```python\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n disk=ag.lp_linear.Exponential,\n pixelization=pixelization,\n)\n```\n\n## Branch \u2014 choosing a mesh and a regularization scheme\n\nThese are the two decisions that make or break a reconstruction, and the parameter cost is\nalmost entirely in the regularization.\n\n**Meshes** (`ag.mesh`, from `PyAutoArray:autoarray/inversion/mesh/`). All contribute zero free\nparameters, all take `shape=(y, x)`:\n\n| Mesh | Where the pixels go | Use when |\n|---|---|---|\n| `RectangularUniform` | a uniform grid over the masked region | you want the simplest, most predictable behaviour |\n| `RectangularBilinearAdaptDensity` | a rectangular grid whose spacing follows the density of image pixels mapping to it, via a rank CDF | **the default** \u2014 concentrates resolution where the data is, and the fast CPU path |\n| `RectangularBilinearAdaptImage` | adapts to the image's own brightness distribution | the irregular light is strongly concentrated |\n| `RectangularRTUAdaptDensity` / `RectangularRTUAdaptImage` | the same two adaptations through a kernel CDF | GPU, JAX gradient samplers and the interferometer sparse path \u2014 the only rectangular adaptive meshes with usable gradients |\n\n`Delaunay`, `KNearestNeighbor` and `KNNBarycentric` also exist for irregular tessellations. Start\nwith `RectangularBilinearAdaptDensity`; it is what every workspace example uses, and the\nrectangular meshes are what the fixed-`mesh_shape` JAX path is built around. (The unqualified\n`RectangularAdaptDensity` / `RectangularAdaptImage` names were split into the `Bilinear` and\n`RTU` families in PyAutoArray 2026.8.23.1 and no longer resolve.)\n\n**Regularization** (`ag.reg`, from `PyAutoArray:autoarray/inversion/regularization/`) is where\nthe free parameters are, and where the physics of \"how smooth should this be?\" lives:\n\n| Scheme | Free params | What it assumes |\n|---|---|---|\n| `ag.reg.Constant` | 1 (`coefficient`) | one smoothing strength everywhere \u2014 the simplest, and the right first try |\n| `ag.reg.GaussianKernel` | 2 (`coefficient`, `scale`) | smoothing with a Gaussian correlation length you also fit |\n| `ag.reg.MaternKernel` | 3 (`coefficient`, `scale`, `nu`) | as above, with the roughness `nu` free too |\n\nVerified counts, not guesses. `Constant` penalises the difference between neighbouring pixels\ndirectly; the kernel schemes impose a correlation *length*, which is physically closer to what a\ngalaxy's light does and generally reconstructs faint extended structure better at the cost of\none or two parameters. `ag.reg.Adapt` and its variants scale the smoothing with the\nreconstruction's own brightness \u2014 more flexible again, and requiring `adapt_images` on the\nanalysis, which is a step beyond this skill; ask if you want it.\n\nA practical route: fit once with `ag.reg.Constant`, look at the reconstruction. Over-smoothed\n(the clumps blurred into one blob) or over-fitted (isolated single-pixel spikes) both show up\nimmediately, and if `Constant` cannot get both the bright clumps and the faint envelope right at\none strength, that is the signal to move to `GaussianKernel`. Full discussion in\n[`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\n### The positive-only solver\n\nEvery pixelized reconstruction uses a **positive-only** linear solver: no mesh pixel may\nreconstruct negative flux. This is not a numerical nicety. A signed solver lets the\nreconstruction manufacture negative pixels that cancel positive ones to over-fit the data, and\nthat failure mode is a well-known systematic in the literature \u2014 many published methods allow\nit. Enforcing non-negativity efficiently needs bespoke linear algebra, which is why this is\nworth stating rather than assuming. You do not need to switch it on; it is the behaviour you get.\n(The one place in this workspace where you *must* disable it is a shapelet basis, which needs\nsigned amplitudes by construction \u2014 see [`ag_basis_profiles`](./ag_basis_profiles.md).)\n\n## Branch \u2014 contaminating neighbours: scale, never mask\n\nThe general advice for a neighbour inside the mask is to mask its pixels out. **For a\npixelization that advice is wrong.** Removing image pixels entirely removes their mapping into\nthe mesh, punching a hole in the reconstruction and producing discontinuities that show up as\nunexplained systematics.\n\nInstead, keep the pixels in the fit and make them contribute nothing: scale their data to zero\nand their noise to an enormous value, so the likelihood is indifferent to them while the mesh\nstays continuous. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py`.\n\n```python\n\"\"\"\n__Noise Scaling__\n\n`mask_extra_galaxies.fits` marks the contaminated pixels. It is loaded with `invert=True`\nbecause in this file `True` means \"scale this pixel\", the opposite of a modelling mask's\nconvention \u2014 getting this backwards scales the galaxy instead of the neighbour, so check the\nsubplot afterwards. `apply_noise_scaling` then zeroes those data values and inflates their\nnoise, driving their signal-to-noise to effectively zero without removing them from the mesh's\nmapping (`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nOrder matters: scale first, then apply the modelling mask.\n\"\"\"\nmask_extra_galaxies = ag.Mask2D.from_fits(\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n pixel_scales=PIXEL_SCALES,\n invert=True,\n)\n\ndataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=PIXEL_SCALES,\n centre=(0.0, 0.0),\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=\"scripts/scratch/my_galaxy/\",\n output_filename=\"noise_scaled\",\n output_format=\"png\",\n)\n```\n\nThe scaled pixels go to a noise value of order 1e8 \u2014 visibly so on the signal-to-noise panel of\nthe subplot, which is how you confirm you scaled the right region. Drawing that mask\ninteractively is `autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask_extra_galaxies.py`;\nthe modelling alternative, and when to prefer it, is\n[`ag_light_model_extras`](./ag_light_model_extras.md) and\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch \u2014 reading the reconstruction out\n\nThe reconstruction is the science product, and it lives on the `Inversion`. You can get there\nfrom a completed fit or from a single direct `ag.FitImaging` \u2014 the latter is the fast way to\nlearn the objects, and is what\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` does.\n\n```python\n\"\"\"\n__Reconstruction__\n\n`inversion.linear_obj_list` holds the linear objects the fit solved. For a hybrid model that is\none `LightProfileLinearObjFuncList` per linear light profile plus one `Mapper` for the\npixelization; with a non-linear `ag.lp.Sersic` bulge the `Mapper` is the only entry. The\n`Mapper` is the object that maps image pixels onto mesh pixels, and it is mesh-specific\n(`PyAutoArray:autoarray/inversion/mappers/`).\n\nThe reconstruction is a 1D array of one flux per mesh pixel, and the (y, x) arcsecond\ncoordinates of those pixels are `mapper.mesh_geometry.mesh_grid`. Pair them by index \u2014 they are\nthe same length and the same order \u2014 and you have the flux map.\n\"\"\"\ninversion = fit.inversion\n\nmapper = inversion.linear_obj_list[0]\n\nreconstruction = inversion.reconstruction\nmesh_grid = mapper.mesh_geometry.mesh_grid\n\nprint(f\"{len(reconstruction)} mesh pixels reconstructed\")\nprint(f\"coordinates shape: {mesh_grid.shape}\")\n\n\"\"\"\nThe reconstruction's own uncertainties, and its projection back onto the image, are also on the\ninversion. `mapped_reconstructed_operated_data` contains **only** the pixelized component \u2014 any\nparametric light profile in the model is excluded \u2014 which is exactly the quantity you want when\nasking how much light is in the irregular component.\n\"\"\"\nprint(inversion.reconstruction_noise_map)\nprint(inversion.mapped_reconstructed_operated_data.native.shape)\n```\n\nA caution on the `Mapper`'s grid attributes: `mapper.image_plane_mesh_grid` is `None` for a\nrectangular mesh, so do not reach for it. `mapper.mesh_geometry.mesh_grid` is the mesh pixel\ncentres (verified on the released stack), and `mapper.image_plane_data_grid` is the centre of\nevery masked *image* pixel. Some of the `Mapper`'s attribute names carry a plane-based prefix\ninherited from the shared inversion library that also serves a multi-plane use case; in\nPyAutoGalaxy there is only the one plane, so `mesh_geometry.mesh_grid` is both the clearer name\nand the one to use.\n\n### The evidence terms\n\nThe inversion's figure of merit is a Bayesian evidence, and its components are individually\nreadable \u2014 which is how you diagnose whether regularization is doing too much or too little:\n\n```python\nprint(f\"regularization term = {inversion.regularization_term}\")\nprint(f\"log det regularization = {inversion.log_det_regularization_matrix_term}\")\nprint(f\"log det curvature + reg = {inversion.log_det_curvature_reg_matrix_term}\")\n```\n\nThe `regularization_term` measures how non-smooth the solution is; the two log-determinant\nterms are the complexity penalty that stops a 400-pixel model winning by over-fitting. The\nmatrices themselves (`curvature_matrix`, `regularization_matrix`, `curvature_reg_matrix`) are\nthere too. The derivation is in HowToGalaxy chapter 3 and the papers it cites\n(arXiv:1708.07377, arXiv:astro-ph/0601493).\n\n### Diagnostic plots\n\n`aplt.subplot_fit_imaging` includes the reconstruction on the mesh alongside the usual data /\nmodel / residual panels, and is the first thing to look at. For the inversion's own internals\nthere are dedicated functions, which live in the shared inversion library rather than on `aplt`\nand so are imported explicitly \u2014 from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/plot.py`:\n\n```python\nfrom autoarray.inversion.plot.inversion_plots import subplot_of_mapper\nfrom autoarray.inversion.plot.mapper_plots import plot_mapper, subplot_image_and_mapper\n\nPLOT_DIR = \"scripts/scratch/my_galaxy/pixelization/\"\n\naplt.subplot_fit_imaging(fit=fit, output_path=PLOT_DIR, output_format=\"png\")\n\nsubplot_of_mapper(\n inversion=inversion, mapper_index=0, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nsubplot_image_and_mapper(\n mapper=mapper, image=dataset.data, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nprint(f\"Saved to: {Path(PLOT_DIR).resolve()}\")\n```\n\n`subplot_of_mapper` is the comprehensive diagnostic \u2014 reconstructed image, reconstruction, its\nnoise map and the regularization weights in one figure \u2014 and `mapper_index` selects which linear\nobject when there are several. `subplot_image_and_mapper` shows the data beside the mesh, which\nis how you check the mesh covers the structure you care about. Note that none of these three are\nexposed on the `aplt` module \u2014 `dir(aplt)` does not list them, so the explicit imports above are\nthe only route and writing them as `aplt.`-prefixed calls raises `AttributeError`. Quote the\nabsolute path back to the user and offer to open it.\n\n## Branch \u2014 exporting the reconstruction for downstream science\n\nA reconstruction that only exists inside a PyAutoGalaxy object is hard to share and hard to\nanalyse with other tools. Write it out as coordinates plus values and it becomes ordinary\ntabular data. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py`.\n\n```python\n\"\"\"\n__Export__\n\nFour columns \u2014 y, x, reconstruction, noise \u2014 is everything needed to rebuild, plot or analyse\nthe galaxy's irregular light without PyAutoGalaxy installed. A completed model-fit also writes\nthis file into its own `image/` folder automatically; glob for `*reconstruction_0.csv` there\nrather than hard-coding the stem, which carries a prefix from the shared inversion library.\n\"\"\"\nimport csv\n\nCSV_PATH = Path(\"scripts/scratch/my_galaxy/reconstruction.csv\")\nCSV_PATH.parent.mkdir(parents=True, exist_ok=True)\n\nwith CSV_PATH.open(\"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([\"y\", \"x\", \"reconstruction\", \"noise_map\"])\n for (y, x), value, sigma in zip(\n mesh_grid, inversion.reconstruction, inversion.reconstruction_noise_map\n ):\n writer.writerow([y, x, value, sigma])\n\nprint(f\"Reconstruction written to: {CSV_PATH.resolve()}\")\n```\n\nReloading needs nothing but the standard library, and from there the mesh is ordinary scattered\ndata. Two things the workspace does with it: a Delaunay triangulation via `scipy.spatial` for\nplotting on the mesh's own geometry, and interpolation onto a regular grid via\n`scipy.interpolate.griddata` for any tool that wants an image:\n\n```python\nimport numpy as np\nfrom scipy.interpolate import griddata\n\nwith CSV_PATH.open() as f:\n reader = csv.reader(f)\n header = next(reader) # ['y', 'x', 'reconstruction', 'noise_map']\n loaded = {key: [] for key in header}\n for row in reader:\n for key, value in zip(header, row):\n loaded[key].append(float(value))\n\npoints = np.stack((np.array(loaded[\"x\"]), np.array(loaded[\"y\"])), axis=-1)\n\ninterpolation_grid = ag.Grid2D.from_extent(\n extent=(-1.0, 1.0, -1.0, 1.0), shape_native=(201, 201)\n)\n\ninterpolated = griddata(\n points=points, values=np.array(loaded[\"reconstruction\"]), xi=interpolation_grid\n)\n```\n\nPick the `extent` to cover the reconstruction without over-resolving it \u2014 the mesh has a few\nhundred pixels, so interpolating to 201 \u00d7 201 is presentation, not information.\n\n## Branch \u2014 run time, VRAM, and the GPU-versus-CPU choice\n\nThis is the branch that decides whether your fit takes twenty minutes or three hours, and the\nanswer is not \"use the GPU\".\n\nPixelized inversions do linear algebra on very large, very **sparse** matrices. JAX has no sparse\nsupport and must work densely, which scales badly; the CPU implementation exploits the sparsity\nfully via `numba`. So the trade runs against pixel scale:\n\n- **Low resolution (`pixel_scales > 0.05`, e.g. Euclid)** \u2014 fewer sparse operations, modest VRAM.\n **GPU with JAX is usually fastest.**\n- **High resolution (`pixel_scales <= 0.03`, e.g. HST or JWST)** \u2014 the linear algebra is\n sparsity-dominated. **CPU with `numba` and many cores can beat a powerful GPU.**\n\nVRAM is the hard constraint on the GPU side. JAX must hold the whole batched likelihood in GPU\nmemory, and a pixelization needs far more than a profile model: around 0.05 GB per batched\nlikelihood at 400 reconstruction pixels, and more than 1 GB \u2014 occasionally more than 10 GB \u2014 at\nhigh resolution with a fine mesh. Two consequences: keep `n_batch` low (the workspace uses 20 for\npixelizations against 50 elsewhere), and run\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nbefore committing. It takes 20\u201330 seconds and it is the difference between knowing your limit\nand discovering it as an out-of-memory error mid-compile. If VRAM is exceeded the run time does\nnot degrade gracefully \u2014 it goes from under ten minutes to three hours or more.\n\nRough scaling with resolution, from the workspace's own measurements at a 20 \u00d7 20 mesh with VRAM\nunder control: ~10 minutes at 0.1\"/pixel, ~30 minutes at 0.05\", ~1 hour at 0.03\". Benchmark both\npaths for your own data and hardware rather than trusting either default; the search-side\nsettings are [`ag_configure_search`](./ag_configure_search.md) and\n[`../wiki/core/api/searches.md`](../wiki/core/api/searches.md).\n\n## Combine \u2014 where this hands off\n\n- **Try a basis first** \u2192 [`ag_basis_profiles`](./ag_basis_profiles.md). An MGE is four\n parameters and minutes, not hours, and it genuinely resolves the shape-mismatch case a\n pixelization is often reached for by mistake.\n- **Pick and configure the search** \u2192 [`ag_configure_search`](./ag_configure_search.md), with\n `n_batch` lowered for VRAM.\n- **Run the fit** \u2192 [`ag_run_search`](./ag_run_search.md); `image/fit.png` in the output folder\n refreshes on the fly and shows the reconstruction as it converges, which is worth watching for\n a fit this long.\n- **Plot and inspect** \u2192 [`ag_plot_fit`](./ag_plot_fit.md), plus the `subplot_of_mapper`\n diagnostics above.\n- **Load a completed fit programmatically** \u2192 [`ag_load_results`](./ag_load_results.md).\n- **Over-smoothed, over-fitted or unphysical reconstruction** \u2192\n [`ag_debug_fit_failure`](./ag_debug_fit_failure.md). The pixelization-specific causes are a\n regularization scheme too rigid for the structure, a mask that punched holes via hard masking\n where noise scaling was needed, over-sampling passed as `over_sample_size_lp` instead of\n `over_sample_size_pixelization`, and VRAM exhaustion masquerading as a hung fit.\n- **Contaminating neighbours modelled rather than scaled** \u2192\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- **Make the fit robust and fast by starting simple** \u2192 the search-chaining skill\n (`ag_chain_searches`). This is the biggest available win for a pixelization: fit a parametric\n model first, pass its bulge as priors, and let the expensive model start from a sensible place.\n The workspace recommends it explicitly.\n- **A non-parametric shape measurement instead of a reconstruction** \u2192\n [`ag_ellipse_fitting`](./ag_ellipse_fitting.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording the mesh and its\nshape, the regularization scheme and why, the mask radius, the hardware path, and what the\nreconstruction showed \u2014 with a pixelization the choices *are* the result, and none of them are\nrecoverable from the output folder alone.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [HowToGalaxy: Bayesian regularization](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb):\n why a model with hundreds of free flux values does not simply over-fit, derived from scratch;\n `tutorial_6_model_fit` then runs the full fit.\n- **General reference** \u2014 [RTD: Pixelization API](https://pyautogalaxy.readthedocs.io/en/latest/api/pixelization.html):\n every mesh, regularization scheme and the objects that combine them.\n- **Experienced PyAutoGalaxy user** \u2014 [workspace: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n the hybrid fit end to end, with the run-time, VRAM and GPU-versus-CPU discussion in full.\n\n## Agent procedural checklist\n\n1. Look at the residual map of a parametric or basis fit first. Shape-following residuals mean\n `ag_basis_profiles`; discrete off-centre lumps mean a pixelization. Do not skip this.\n2. Confirm the structure is resolved \u2014 at coarse pixel scales a pixelization reconstructs noise.\n3. Always pair the pixelization with a linear light profile for the smooth component; never let\n the mesh reconstruct the bulge.\n4. Fix `mesh_shape` before composing the model; it cannot be a free parameter.\n5. Pass over-sampling as `over_sample_size_pixelization`, not `over_sample_size_lp`.\n6. Start with `RectangularBilinearAdaptDensity` + `ag.reg.Constant`; move to `GaussianKernel` only when\n one smoothing strength demonstrably cannot serve both the bright and faint structure.\n7. Scale contaminant noise (`apply_noise_scaling`, `invert=True`) \u2014 never hard-mask pixels inside\n a pixelization fit \u2014 and check the signal-to-noise panel afterwards.\n8. `print(model.info)`, evaluate one likelihood, then `print_vram_use` before any GPU run; keep\n `n_batch` low.\n9. Read the reconstruction via `inversion.reconstruction` +\n `mapper.mesh_geometry.mesh_grid`; export to CSV for anything downstream.\n10. Save the script to `scripts/`, quote every plot's absolute path and offer to open it, then\n offer the `wiki/project/` entry recording mesh, regularization and hardware choices.\n" + } + }, + "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file diff --git a/notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb b/notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb deleted file mode 100644 index e8b9297..0000000 --- a/notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb +++ /dev/null @@ -1,984 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 5: Bayesian Formalism\n", - "==============================\n", - "\n", - "In tutorials 1 to 4, we built an intuition for how pixelized galaxy reconstruction works: pixelizations place a\n", - "pixel-grid over the galaxy's image, mappers pair pixelization pixels with image-pixels, inversions solve for the\n", - "pixel fluxes that best fit the data, and regularization smooths the solution within a Bayesian framework.\n", - "\n", - "This tutorial collects the linear algebra behind all of that in one place. The hands-on tutorials built intuition,\n", - "and now we write down the equations. We will construct, step-by-step and in code, every matrix and vector the\n", - "inversion uses, solve for the galaxy reconstruction ourselves and compute the Bayesian evidence by hand, comparing\n", - "our answer at the end to the `FitImaging` object which performs this calculation internally.\n", - "\n", - "None of this is required to *use* **PyAutoGalaxy** for galaxy modeling. However, if you publish results which use a\n", - "pixelization, this is the calculation your paper's likelihood function section will describe, and understanding it\n", - "removes any sense that the galaxy reconstruction is a \"black box\".\n", - "\n", - "The formalism follows Warren & Dye 2003 (https://arxiv.org/abs/astro-ph/0302587), hereafter WD03, with the data\n", - "vector notation of Nightingale & Dye 2015 (https://arxiv.org/abs/1412.7436), hereafter N15. These papers derived\n", - "the method for reconstructing gravitationally lensed sources, but the linear algebra is identical for a galaxy's\n", - "own light -- the only lensing-specific step (ray tracing image-pixel coordinates to a source-plane) is simply\n", - "absent, with the mesh laid directly over the galaxy's image. The Bayesian evidence was derived by Suyu et al. 2006\n", - "(https://arxiv.org/abs/astro-ph/0601493) and translated to **PyAutoGalaxy** notation in Dye et al. 2008\n", - "(https://arxiv.org/abs/0804.4002).\n", - "\n", - "__Contents__\n", - "\n", - "- **Initial Setup:** Load the dataset the previous tutorials fitted.\n", - "- **Dataset Auto-Simulation:** Automatically simulate the dataset if it does not already exist.\n", - "- **Mask:** Mask the data so the likelihood is evaluated only where the galaxy's light is.\n", - "- **Over Sampling:** Disable over sampling so the algebra stays simple.\n", - "- **Mesh Shape:** Fix the rectangular mesh's shape and note why edge pixels are zeroed.\n", - "- **Galaxy:** Create the galaxy whose pixelization pairs the mesh with `Constant` regularization.\n", - "- **Image Grid:** The masked image-pixel coordinates the mesh is laid over -- no ray tracing occurs.\n", - "- **Mesh Pixel Centres:** Overlay the rectangular mesh over the masked image grid.\n", - "- **Interpolation:** Pair every image-pixel with mesh pixels via bilinear interpolation.\n", - "- **Mapper:** Package the interpolation into a `Mapper` describing all image-to-mesh mappings.\n", - "- **Mapping Matrix:** Express the mappings as the 2D matrix $f$.\n", - "- **Blurred Mapping Matrix:** Convolve every column of $f$ with the imaging PSF.\n", - "- **Data Vector (D):** Compute the data vector $D$ from the blurred mapping matrix, data and noise-map.\n", - "- **Curvature Matrix (F):** Compute the curvature matrix $F$.\n", - "- **Unregularized Solve:** Solve $s = F^{-1} D$ and see the over-fitted mess this produces.\n", - "- **Regularization Matrix (H):** Compute the regularization matrix $H$ encoding the smoothness prior.\n", - "- **Galaxy Reconstruction (s):** Solve the regularized system $s = [F + H]^{-1} D$.\n", - "- **Image Reconstruction:** Map the reconstruction back to image resolution via the blurred mapping matrix.\n", - "- **Likelihood Function:** The five terms which combine into the log evidence.\n", - "- **Chi Squared:** The goodness-of-fit of the reconstructed image to the data.\n", - "- **Regularization Term:** The penalty $s^{T} H s$ applied by the smoothness prior.\n", - "- **Complexity Terms:** The log determinant terms which penalize complex galaxy reconstructions.\n", - "- **Noise Normalization Term:** The Gaussian noise normalization.\n", - "- **Log Evidence:** Combine all five terms into the log evidence.\n", - "- **Fit:** Compare our by-hand log evidence to the `FitImaging` object's internal calculation.\n", - "- **Wrap Up:** Summary and next steps." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Google Colab Setup__\n", - "\n", - "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "jupyter": { - "source_hidden": true - } - }, - "outputs": [], - "source": [ - "# @title Set up Google Colab { display-mode: \"form\" }\n", - "try:\n", - " import google.colab\n", - "except ImportError:\n", - " from autogalaxy import setup_colab as _setup_colab\n", - "else:\n", - " import importlib\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.check_call(\n", - " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", - " )\n", - " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", - "\n", - "_setup_colab.setup(\"howtogalaxy\")" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autogalaxy import setup_notebook; setup_notebook()\n", - "\n", - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from pathlib import Path\n", - "\n", - "import autogalaxy as ag\n", - "import autogalaxy.plot as aplt\n", - "from autoarray.inversion.plot.mapper_plots import plot_mapper" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Initial Setup__\n", - "\n", - "we'll use the same galaxy data as the previous tutorials, where:\n", - "\n", - " - The galaxy's bulge is an `Sersic`.\n", - " - The galaxy's disk is an `Exponential`.\n", - "\n", - "For simplicity, the model in this tutorial is a pixelization only, with no light profiles: the mesh absorbs the\n", - "bulge and disk together. In WD03's notation this means the light profile model image $b_{j}$ is zero everywhere. If\n", - "light profiles are included in the galaxy model, their PSF-convolved image is computed first and subtracted from\n", - "the data before the steps below -- nothing else about the formalism changes." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "dataset_name = \"simple\"\n", - "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Dataset Auto-Simulation__\n", - "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "if ag.util.dataset.should_simulate(str(dataset_path)):\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulators/simple.py\"],\n", - " check=True,\n", - " )\n", - "\n", - "dataset = ag.Imaging.from_fits(\n", - " data_path=dataset_path / \"data.fits\",\n", - " noise_map_path=dataset_path / \"noise_map.fits\",\n", - " psf_path=dataset_path / \"psf.fits\",\n", - " pixel_scales=0.1,\n", - ")\n", - "\n", - "aplt.subplot_imaging_dataset(dataset=dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Mask__\n", - "\n", - "The likelihood is only evaluated within a mask, which we define as the same 2.0\" circle used in the previous\n", - "tutorials, containing all of the galaxy's light." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mask = ag.Mask2D.circular(\n", - " shape_native=dataset.shape_native,\n", - " pixel_scales=dataset.pixel_scales,\n", - " radius=2.0,\n", - ")\n", - "\n", - "masked_dataset = dataset.apply_mask(mask=mask)\n", - "\n", - "aplt.subplot_imaging_dataset(dataset=masked_dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Over Sampling__\n", - "\n", - "Over sampling splits every image pixel into a sub-grid of sub-pixels, each of which is paired with mesh pixels\n", - "individually. It improves accuracy, but it also multiplies the number of rows in every matrix below by the number\n", - "of sub-pixels.\n", - "\n", - "To keep the algebra as easy to follow as possible, we disable over sampling by setting both sub-grid sizes to 1, so\n", - "each image pixel is represented by the single coordinate at its centre." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "masked_dataset = masked_dataset.apply_over_sampling(\n", - " over_sample_size_lp=1,\n", - " over_sample_size_pixelization=1,\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Mesh Shape__\n", - "\n", - "The `mesh_shape` defines the number of pixels in the rectangular mesh used to reconstruct the galaxy, set below\n", - "to 20 x 20 = 400 mesh pixels.\n", - "\n", - "We use the `RectangularUniform` mesh, where all rectangular mesh pixels have the same size, rather than the\n", - "`RectangularBilinearAdaptDensity` mesh used in the previous tutorials. The uniform mesh keeps the geometry simple, and every\n", - "equation below applies unchanged to the adaptive meshes -- only the mesh pixel centres move.\n", - "\n", - "By default, mesh pixels at the edge of the mesh are forced to solutions of zero flux by the linear algebra solver.\n", - "This prevents unphysical solutions where the mesh edge lights up to fit residuals, and does not change any of the\n", - "formalism below." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mesh_pixels_yx = 20\n", - "mesh_shape = (mesh_pixels_yx, mesh_pixels_yx)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Galaxy__\n", - "\n", - "We create the galaxy whose `Pixelization` pairs the `RectangularUniform` mesh with `Constant` regularization (whose\n", - "role appears later, when we reach the matrix $H$).\n", - "\n", - "The galaxy has no light profiles -- the mesh alone will reconstruct its bulge and disk." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "pixelization = ag.Pixelization(\n", - " mesh=ag.mesh.RectangularUniform(shape=mesh_shape),\n", - " regularization=ag.reg.Constant(coefficient=1.0),\n", - ")\n", - "\n", - "galaxy = ag.Galaxy(redshift=0.5, pixelization=pixelization)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Image Grid__\n", - "\n", - "In the lensing version of this formalism (see **PyAutoLens**), every image-pixel coordinate is first ray-traced to\n", - "a source-plane, and the mesh is laid over the traced coordinates. For a galaxy there is no lensing, so this step\n", - "simply does not exist: the mesh is laid directly over the galaxy's own image, and the grid the inversion uses is\n", - "the grid of masked image-pixel centres itself.\n", - "\n", - "This grid is `masked_dataset.grids.pixelization`, with one coordinate at the centre of every masked image pixel\n", - "(because we disabled over sampling above).\n", - "\n", - "(The `Mapper` attributes below carry `source_plane_` prefixes because **PyAutoGalaxy** and **PyAutoLens** share one\n", - "inversion implementation. For a galaxy, the \"source plane\" is just the image plane the galaxy lives in.)" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.plot_grid(grid=masked_dataset.grids.pixelization, title=\"Masked Image Grid\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Mesh Pixel Centres__\n", - "\n", - "To reconstruct the galaxy on a `RectangularUniform` mesh, we need the centres of its rectangular mesh pixels.\n", - "\n", - "We compute these by overlaying a uniform rectangular grid over the masked image grid, sized so the mesh fully\n", - "contains the masked region without wasted edge pixels beyond it." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "from autoarray.inversion.mesh.mesh.rectangular_rtu_adapt_density import (\n", - " overlay_grid_from,\n", - ")\n", - "\n", - "mesh_grid = overlay_grid_from(\n", - " shape_native=mesh_shape, grid=masked_dataset.grids.pixelization\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Interpolation__\n", - "\n", - "We now combine the two grids to create an `Interpolator`, which describes how every image-pixel coordinate maps to\n", - "the rectangular mesh pixels.\n", - "\n", - "For a rectangular mesh the scheme is bilinear interpolation: every image pixel maps to the rectangular pixel it\n", - "lands in *and* its three nearest neighbours, with weights set by how close the coordinate is to each pixel centre.\n", - "Interpolation is what lets the mesh reconstruct smooth galaxy morphologies. We can print the mappings and weights\n", - "of the first image pixel to confirm it pairs with four mesh pixels." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "interpolator = pixelization.mesh.interpolator_from(\n", - " source_plane_data_grid=masked_dataset.grids.pixelization,\n", - " source_plane_mesh_grid=mesh_grid,\n", - ")\n", - "\n", - "print(interpolator.mappings[0])\n", - "print(interpolator.weights[0])" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Mapper__\n", - "\n", - "The interpolator creates a `Mapper`, the object tutorials 1 and 2 introduced. It packages up the mapping between\n", - "every image pixel and every rectangular mesh pixel.\n", - "\n", - "The key attribute is `pix_indexes_for_sub_slim_index`, mapping every image-pixel index (`sub_slim_index`) to the\n", - "mesh-pixel indexes (`pix_indexes`) it interpolates onto, alongside the number of mappings per image pixel and\n", - "their interpolation weights." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mapper = ag.Mapper(interpolator=interpolator)\n", - "\n", - "pix_indexes_for_sub_slim_index = mapper.pix_indexes_for_sub_slim_index\n", - "\n", - "print(pix_indexes_for_sub_slim_index[0:9])\n", - "print(mapper.pix_sizes_for_sub_slim_index[0:9])\n", - "print(mapper.pix_weights_for_sub_slim_index[0:9])" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Mapping Matrix__\n", - "\n", - "The `mapping_matrix` expresses these image-pixel to mesh-pixel mappings as a single 2D matrix, with\n", - "dimensions `(total_image_pixels, total_mesh_pixels)`.\n", - "\n", - "Each column is the \"image\" of one mesh pixel: entries are the interpolation weights for image pixels which map to\n", - "that mesh pixel and zero everywhere else." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mapping_matrix = ag.util.mapper.mapping_matrix_from(\n", - " pix_indexes_for_sub_slim_index=pix_indexes_for_sub_slim_index,\n", - " pix_size_for_sub_slim_index=mapper.pix_sizes_for_sub_slim_index,\n", - " pix_weights_for_sub_slim_index=mapper.pix_weights_for_sub_slim_index,\n", - " pixels=mapper.pixels,\n", - " total_mask_pixels=mapper.source_plane_data_grid.mask.pixels_in_mask,\n", - " slim_index_for_sub_slim_index=mapper.slim_index_for_sub_slim_index,\n", - " sub_fraction=mapper.over_sampler.sub_fraction,\n", - ")\n", - "\n", - "plt.imshow(mapping_matrix, aspect=(mapping_matrix.shape[1] / mapping_matrix.shape[0]))\n", - "plt.show()\n", - "plt.close()" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Because each column is an image of zeros and interpolation weights, we can plot any column as a 2D image showing\n", - "all image pixels its mesh pixel maps to. For a mesh pixel near the mesh centre, these image pixels sit at the\n", - "centre of the galaxy, where its bulge is brightest." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "central_mesh_pixel = (mesh_shape[0] // 2) * mesh_shape[1] + mesh_shape[1] // 2\n", - "\n", - "array_2d = ag.Array2D(\n", - " values=mapping_matrix[:, central_mesh_pixel], mask=masked_dataset.mask\n", - ")\n", - "\n", - "aplt.plot_array(array=array_2d, title=\"Image of Central Mesh Pixel\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Blurred Mapping Matrix__\n", - "\n", - "The imaging data is blurred by the telescope's PSF, so the model must be too. Since each column of the mapping\n", - "matrix is an image, we simply convolve each column with the PSF via 2D convolution.\n", - "\n", - "This produces the `blurred_mapping_matrix`, with the same dimensions `(total_image_pixels, total_mesh_pixels)`.\n", - "\n", - "In WD03 this matrix is denoted $f_{ij}$, where $i$ runs over all $I$ mesh pixels and $j$ over all $J$ image\n", - "pixels. For example:\n", - "\n", - " - $f_{0, 2} = 0.3$ indicates that image-pixel $2$ maps to mesh-pixel $0$ with a weight of $0.3$ after PSF\n", - " convolution.\n", - " - $f_{4, 8} = 0$ indicates that image-pixel $8$ does not map to mesh-pixel $4$, even after PSF convolution.\n", - "\n", - "(The indexing of the code's `mapping_matrix` is transposed relative to WD03's $f$: image pixels are the first index\n", - "in the code, but the second index in the equations.)\n", - "\n", - "PSF blurring has an important consequence: it correlates neighbouring columns, so the images of nearby mesh pixels\n", - "now overlap far more than the interpolation alone produced." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "blurred_mapping_matrix = masked_dataset.psf.convolved_mapping_matrix_from(\n", - " mapping_matrix=mapping_matrix, mask=masked_dataset.mask\n", - ")\n", - "\n", - "plt.imshow(\n", - " blurred_mapping_matrix,\n", - " aspect=(blurred_mapping_matrix.shape[1] / blurred_mapping_matrix.shape[0]),\n", - ")\n", - "plt.colorbar()\n", - "plt.show()\n", - "plt.close()" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Data Vector (D)__\n", - "\n", - "We now pose the reconstruction as a linear inversion, converting the blurred mapping matrix, data and noise-map\n", - "into two objects: the data vector $D$ and the curvature matrix $F$.\n", - "\n", - "The data vector has dimensions `(total_mesh_pixels,)` and is given by (WD03 / N15):\n", - "\n", - " $\\vec{D}_{i} = \\sum_{j=1}^{J} f_{ij} (d_{j} - b_{j}) / \\sigma_{j}^2 \\, \\, .$\n", - "\n", - "Where:\n", - "\n", - " - $d_{j}$ are the image-pixel data values.\n", - " - $b_{j}$ are the model images of any light profiles in the galaxy model (zero here, because our model is a\n", - " pixelization only).\n", - " - $\\sigma_{j}^2$ are the statistical uncertainties of each image pixel.\n", - "\n", - "Each entry of $D$ is therefore the noise-weighted overlap between one mesh pixel's blurred image and the data:\n", - "it measures how much evidence the data provides for flux in that mesh pixel, with the PSF fully accounted for." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "data_vector = ag.util.inversion_imaging.data_vector_via_blurred_mapping_matrix_from(\n", - " blurred_mapping_matrix=blurred_mapping_matrix,\n", - " image=np.array(masked_dataset.data),\n", - " noise_map=np.array(masked_dataset.noise_map),\n", - ")\n", - "\n", - "plt.imshow(\n", - " data_vector.reshape(data_vector.shape[0], 1), aspect=10.0 / data_vector.shape[0]\n", - ")\n", - "plt.colorbar()\n", - "plt.show()\n", - "plt.close()" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Curvature Matrix (F)__\n", - "\n", - "The curvature matrix has dimensions `(total_mesh_pixels, total_mesh_pixels)` and is given by (WD03):\n", - "\n", - " ${F}_{ik} = \\sum_{j=1}^{J} f_{ij} f_{kj} / \\sigma_{j}^2 \\, \\, .$\n", - "\n", - "Every entry of $F$ is the noise-weighted overlap between the blurred images of two mesh pixels: $F_{ik}$ sums the\n", - "product of columns $i$ and $k$ of $f$ over all image pixels. For $F_{ik}$ to be non-zero, mesh pixels $i$ and $k$\n", - "must share at least one image pixel, which happens for neighbouring pixels via interpolation and for pixels\n", - "further apart via PSF blurring.\n", - "\n", - "$F$ describes how degenerate pairs of mesh pixels are with one another: two mesh pixels whose blurred images\n", - "overlap heavily can trade flux between themselves whilst fitting the data almost equally well." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "curvature_matrix = ag.util.inversion.curvature_matrix_via_mapping_matrix_from(\n", - " mapping_matrix=blurred_mapping_matrix, noise_map=masked_dataset.noise_map\n", - ")\n", - "\n", - "plt.imshow(curvature_matrix)\n", - "plt.colorbar()\n", - "plt.show()\n", - "plt.close()" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Unregularized Solve__\n", - "\n", - "The inversion seeks the mesh-pixel fluxes $s$ (a vector with one entry per mesh pixel) that minimize the\n", - "chi-squared:\n", - "\n", - " $\\chi^2 = \\sum_{j=1}^{J} \\bigg[ \\frac{(\\sum_{i=1}^{I} s_{i} f_{ij}) + b_{j} - d_{j}}{\\sigma_{j}} \\bigg]^2$\n", - "\n", - "Setting the derivative of $\\chi^2$ with respect to each $s_{i}$ to zero gives the linear system whose solution is\n", - "(equation 5 of WD03):\n", - "\n", - " $s = F^{-1} D$\n", - "\n", - "We can solve this directly with NumPy. (Without regularization the curvature matrix is often singular, so the loop\n", - "below adds a tiny value to its diagonal to avoid a `LinAlgError` -- it is a numerical crutch, not part of the\n", - "formalism.)" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "for i in range(curvature_matrix.shape[0]):\n", - " curvature_matrix[i, i] += 1e-8\n", - "\n", - "reconstruction = np.linalg.solve(curvature_matrix, data_vector)\n", - "\n", - "plot_mapper(mapper=mapper, solution_vector=reconstruction)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The reconstructed mesh-pixel fluxes are a noisy, unsmooth mess -- exactly the over-fitting we saw in tutorial 4\n", - "when we lowered the regularization coefficient towards zero. The linear inversion is fitting the noise in the\n", - "data, because this system of equations is ill-posed: we need a smoothness prior.\n", - "\n", - "__Regularization Matrix (H)__\n", - "\n", - "Regularization adds a linear regularization term $G_{L}$ to the merit function we minimize (equation 11 of WD03):\n", - "\n", - " $G = \\chi^2 + \\lambda \\, G_{L}$\n", - "\n", - "where $\\lambda$ is the `regularization_coefficient` controlling the degree of smoothing. The `Constant` scheme uses\n", - "gradient regularization (equation 14 of WD03):\n", - "\n", - " $G_{L} = \\sum_{i}^{I} \\sum_{n=1}^{N} [s_{i} - s_{i, n}]^2$\n", - "\n", - "In words: for every mesh pixel, compare its flux with each of its $N$ neighbours $n$, and penalize solutions where\n", - "the differences are large. This is precisely the \"smoothness prior\" of tutorial 4, now written as an equation.\n", - "\n", - "To fold this into the linear algebra we define the regularization matrix $H$, with\n", - "dimensions `(total_mesh_pixels, total_mesh_pixels)` (equation 13 of WD03):\n", - "\n", - " $H_{ik} = \\frac{1}{2} \\frac{\\partial^{2} G_{L}}{\\partial s_{i} \\partial s_{k}}$\n", - "\n", - "$H$ has the coefficient $\\lambda$ folded into it. Its non-zero off-diagonal entries mark pairs of mesh pixels\n", - "which are neighbours and therefore regularized with one another; most entries are zero because most mesh pixels\n", - "are not neighbours." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "regularization_matrix = ag.util.regularization.constant_regularization_matrix_from(\n", - " coefficient=galaxy.pixelization.regularization.coefficient,\n", - " neighbors=mapper.neighbors,\n", - " neighbors_sizes=mapper.neighbors.sizes,\n", - ")\n", - "\n", - "plt.imshow(regularization_matrix)\n", - "plt.colorbar()\n", - "plt.show()\n", - "plt.close()" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Galaxy Reconstruction (s)__\n", - "\n", - "$H$ enters the linear system as follows (equation 12 of WD03):\n", - "\n", - " $s = [F + H]^{-1} D$\n", - "\n", - "We add the two matrices and solve again. The diagonal jitter used above is no longer needed, because $H$ makes the\n", - "system well-posed." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "curvature_reg_matrix = np.add(curvature_matrix, regularization_matrix)\n", - "\n", - "reconstruction = np.linalg.solve(curvature_reg_matrix, data_vector)\n", - "\n", - "plot_mapper(mapper=mapper, solution_vector=reconstruction)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The reconstructed fluxes are now smooth and physical: regularization has suppressed the noisy solution and the\n", - "reconstruction actually looks like the galaxy's bulge and disk, without over-fitting the noise.\n", - "\n", - "__Image Reconstruction__\n", - "\n", - "Using the reconstructed mesh-pixel fluxes, we map the reconstruction back to image resolution via the blurred\n", - "mapping matrix (so the reconstructed image includes PSF blurring) to produce the model image of the galaxy." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mapped_reconstructed_data = (\n", - " ag.util.inversion.mapped_reconstructed_data_via_mapping_matrix_from(\n", - " mapping_matrix=blurred_mapping_matrix, reconstruction=reconstruction\n", - " )\n", - ")\n", - "\n", - "mapped_reconstructed_data = ag.Array2D(\n", - " values=mapped_reconstructed_data, mask=masked_dataset.mask\n", - ")\n", - "\n", - "aplt.plot_array(array=mapped_reconstructed_data, title=\"Reconstructed Image\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Likelihood Function__\n", - "\n", - "We now quantify the goodness-of-fit of the galaxy reconstruction, computing the quantity tutorial 4 called the\n", - "Bayesian evidence. The log evidence consists of five terms:\n", - "\n", - " $-2 \\, \\mathrm{ln} \\, \\epsilon = \\chi^2 + s^{T} H s + \\mathrm{ln} \\, [ \\mathrm{det} (F + H) ] - \\mathrm{ln} \\, [ \\mathrm{det} (H) ] + \\sum_{j=1}^{J} \\mathrm{ln} \\, [2 \\pi (\\sigma_{j})^2 ] \\, .$\n", - "\n", - "This expression was first derived by Suyu et al. 2006 (https://arxiv.org/abs/astro-ph/0601493), equation (19), and\n", - "is given in **PyAutoGalaxy** notation by Dye et al. 2008 (https://arxiv.org/abs/0804.4002), equation (5).\n", - "\n", - "We now compute each term in turn.\n", - "\n", - "__Chi Squared__\n", - "\n", - "The first term is the $\\chi^2$ statistic from the merit function above, computed as:\n", - "\n", - " - `model_data` = the reconstructed image of the galaxy (plus any light profile model images, zero here).\n", - " - `residual_map` = (`data` - `model_data`)\n", - " - `normalized_residual_map` = (`data` - `model_data`) / `noise_map`\n", - " - `chi_squared_map` = (`normalized_residual_map`) ** 2.0\n", - " - `chi_squared` = sum(`chi_squared_map`)\n", - "\n", - "High chi-squared values indicate image pixels the reconstruction fits poorly, lowering the likelihood." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "model_image = mapped_reconstructed_data\n", - "\n", - "residual_map = masked_dataset.data - model_image\n", - "normalized_residual_map = residual_map / masked_dataset.noise_map\n", - "chi_squared_map = normalized_residual_map**2.0\n", - "\n", - "chi_squared = np.sum(chi_squared_map)\n", - "\n", - "print(chi_squared)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Regularization Term__\n", - "\n", - "The second term, $s^{T} H s$, is the $\\lambda \\, G_{L}$ regularization penalty evaluated at the solution: the\n", - "summed difference in flux between all neighbouring mesh pixels, weighted by the regularization coefficient (which\n", - "is already folded into $H$).\n", - "\n", - "Less smooth solutions have larger values of this term and therefore lower likelihoods." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "regularization_term = np.matmul(\n", - " reconstruction.T, np.matmul(regularization_matrix, reconstruction)\n", - ")\n", - "\n", - "print(regularization_term)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Complexity Terms__\n", - "\n", - "Up to this point, nothing has justified our choice of `regularization_coefficient=1.0`. We cannot choose it using\n", - "the two terms above, because increasing the coefficient smooths the solution more, which *both* worsens the\n", - "chi-squared *and* (for a fixed solution) raises the regularization penalty. Optimizing those two terms alone would\n", - "drive the coefficient to zero and put us right back at the over-fitted mess.\n", - "\n", - "The two log determinant terms, $\\mathrm{ln} \\, [ \\mathrm{det} (F + H) ]$ and $- \\mathrm{ln} \\, [ \\mathrm{det} (H) ]$,\n", - "fix this. Together they measure how *complex* the galaxy reconstruction is -- roughly, how many effective degrees\n", - "of freedom the mesh uses after regularization correlates its pixels -- and penalize more complex solutions.\n", - "Lowering the regularization coefficient frees the mesh to use more of its flexibility, increasing this complexity\n", - "penalty.\n", - "\n", - "These terms therefore counteract the chi-squared and regularization terms, so the highest evidence goes to\n", - "solutions which fit the data well with the *simplest* galaxy reconstruction. This is the Occam's razor behaviour\n", - "that tutorial 4 demonstrated empirically." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "log_curvature_reg_matrix_term = np.linalg.slogdet(curvature_reg_matrix)[1]\n", - "log_regularization_matrix_term = np.linalg.slogdet(regularization_matrix)[1]\n", - "\n", - "print(log_curvature_reg_matrix_term)\n", - "print(log_regularization_matrix_term)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Noise Normalization Term__\n", - "\n", - "The likelihood function assumes the imaging data consists of independent Gaussian noise in every image pixel, and\n", - "the final term is the normalization of those Gaussians: the sum of the log of every noise-map value squared.\n", - "\n", - "Because the noise-map is fixed, this term is constant throughout galaxy modeling and has no impact on the model\n", - "we infer -- it simply normalizes the likelihood." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "noise_normalization = float(np.sum(np.log(2 * np.pi * masked_dataset.noise_map**2.0)))\n", - "\n", - "print(noise_normalization)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Log Evidence__\n", - "\n", - "We can now combine the five terms into the log evidence of the galaxy reconstruction." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "log_evidence = float(\n", - " -0.5\n", - " * (\n", - " chi_squared\n", - " + regularization_term\n", - " + log_curvature_reg_matrix_term\n", - " - log_regularization_matrix_term\n", - " + noise_normalization\n", - " )\n", - ")\n", - "\n", - "print(log_evidence)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Fit__\n", - "\n", - "Everything above is what the `FitImaging` object does internally when it fits a galaxy with a pixelization. We can\n", - "see this by performing the fit and comparing its `log_evidence` to ours.\n", - "\n", - "The two values do not agree exactly, because the real fit improves on our simplified solve in two ways mentioned\n", - "along the way: it uses the positive-only solver (tutorial 3), which forbids the negative mesh-pixel fluxes our\n", - "unconstrained `np.linalg.solve` permits, and it zeroes the pixels at the edge of the mesh. Our unconstrained solve\n", - "exploits that extra (unphysical) freedom to push its chi-squared lower than the real solver allows, which is why\n", - "our by-hand log evidence comes out somewhat higher. Neither constraint changes the formalism -- the same $f$, $D$,\n", - "$F$ and $H$ feed a solver with extra conditions on $s$." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "galaxies = ag.Galaxies(galaxies=[galaxy])\n", - "\n", - "fit = ag.FitImaging(dataset=masked_dataset, galaxies=galaxies)\n", - "\n", - "print(fit.log_evidence)\n", - "\n", - "aplt.subplot_fit_imaging(fit=fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Wrap Up__\n", - "\n", - "We have walked through the complete linear algebra of a pixelized galaxy reconstruction:\n", - "\n", - " - The `mapping_matrix` and PSF-blurred mapping matrix $f$, whose columns are the blurred images of each\n", - " mesh pixel.\n", - "\n", - " - The data vector $D$ and curvature matrix $F$, the noise-weighted overlaps of those images with the data and with\n", - " each other.\n", - "\n", - " - The regularization matrix $H$, which encodes the smoothness prior, and the linear solve $s = [F + H]^{-1} D$ for\n", - " the galaxy reconstruction.\n", - "\n", - " - The five terms of the Suyu et al. 2006 log evidence -- chi-squared, the regularization penalty, the two log\n", - " determinant complexity terms and the noise normalization -- and their Bayesian interpretation as an Occam's\n", - " razor which favours the simplest galaxy reconstruction the data allows.\n", - "\n", - "During galaxy modeling, this whole calculation is one likelihood evaluation: the non-linear search varies the\n", - "model's parameters (for example the mesh resolution, the regularization coefficient, or the light profiles fitted\n", - "alongside the mesh), and each sample triggers the full solve and evidence computation above.\n", - "\n", - "Two simplifications are worth remembering: real fits use over sampling (each image pixel contributes several\n", - "sub-pixel rows to $f$) and **PyAutoGalaxy** uses a positive-only solver for $s$ rather than the unconstrained\n", - "`np.linalg.solve` used here (see tutorial 3). The workspace\n", - "guide `autogalaxy_workspace/*/imaging/features/pixelization/likelihood_function.ipynb` repeats this walk-through\n", - "with additional visualization of every step, including how light profiles combine with the mesh.\n", - "\n", - "In the next tutorial, we return to hands-on territory and use pixelizations in an actual model-fit, combining light\n", - "profiles and an inversion via search chaining." - ] - } - ], - "metadata": { - "anaconda-cloud": {}, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - }, - "colab": { - "aiContexts": { - "24c2f562-da24-50bb-8eb9-5a887505fe54": { - "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", - "name": "PyAutoGalaxy assistant", - "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb in HowToGalaxy).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoGalaxy calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoGalaxy docs (https://pyautogalaxy.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_pixelization\n\n---\nname: ag_pixelization\ndescription: Reconstruct a galaxy's clumpy or irregular light directly on a regularized pixel mesh, using `ag.Pixelization` alongside a parametric `ag.lp_linear` bulge — the hybrid model that gives a smooth interpretable component plus a flexible flux map for everything the profile cannot explain. Covers when a pixelization is warranted and when it is overkill, choosing an `ag.mesh` and an `ag.reg` regularization scheme and what each costs in free parameters, why `mesh_shape` must be fixed before the fit, `over_sample_size_pixelization` rather than `over_sample_size_lp`, noise scaling instead of hard masking for contaminants, the positive-only solver, reading the reconstruction and its Bayesian-evidence terms out of the `Inversion`, exporting the reconstruction to CSV for collaborators, and the GPU/VRAM versus CPU run-time trade. Use when a Sersic, MGE or shapelet basis leaves structured residuals in discrete off-centre lumps. Not for morphology a basis can still fit (`ag_basis_profiles`), not for non-parametric isophote measurement (`ag_ellipse_fitting`), and not for the basics of model composition (`ag_build_imaging_model`).\n---\n\n# Reconstructing a galaxy on a pixel mesh\n\nEvery model in this workspace so far has been a *function*: you asserted a functional form and\nthe fit found its parameters. A pixelization drops the functional form. It lays a mesh of pixels\nover the galaxy, gives each pixel its own free flux value, and solves all of them at once by\nlinear inversion — thousands of amplitudes, none of them in the non-linear search's parameter\nspace. What stops that from simply fitting the noise is **regularization**: a prior that\npenalises solutions where neighbouring mesh pixels differ sharply, so the reconstruction is as\nsmooth as the data will allow and no smoother.\n\nThe science case is specific, and it is worth being honest about how specific. Galaxies with\nspiral arms, asymmetric star-forming clumps, tidal features or low-surface-brightness\nsubstructure have light that no smooth profile — and often no basis expansion either —\nreproduces. The canonical use is therefore **hybrid**: a linear `Sersic` for the smooth central\nbulge, and a pixelization for the irregular remainder. That split is the point. It gives you a\nlow-dimensional, physically interpretable description of the bulge *and* a flux map of exactly\nwhat the bulge could not explain, which is the quantity you want if the science question is \"how\nmuch of this galaxy's light is in its irregular components?\"\n\nThis is a **direct** reconstruction. There is no second plane, no de-projection, no inversion of\na geometric mapping — the mesh sits on the image plane, over the galaxy, at the same coordinates\nthe data occupies. If you have met pixelized reconstruction before in a different context, that\nextra step is the one that is absent here, and its absence makes everything simpler: what the\nmesh reconstructs is the galaxy's own surface brightness, and its coordinates are sky\ncoordinates in arcseconds.\n\nStatistically, the fit now has two nested layers. The non-linear search explores a handful of\nparameters — the bulge's shape, the regularization strength — and for each proposal an inversion\nsolves the mesh amplitudes exactly and returns a **Bayesian evidence** rather than a plain\nlikelihood. That evidence includes terms that penalise an unnecessarily complex reconstruction,\nwhich is what lets a model with 400 free flux values not simply win by over-fitting. The theory\nis [`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md);\nchapter 3 of HowToGalaxy derives it from scratch.\n\nThe canonical scripts are\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py` (via a search),\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` (one direct fit, with the\ninversion internals walked through) and\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py` (export).\n\n## Before you reach for one — the honest gate\n\nA pixelization is the most powerful and the most expensive model here, with failure modes the\nparametric models do not have. Three questions decide whether you need it:\n\n- *\"What do the residuals actually look like?\"* Structured residuals that **follow the\n isophotes** — a twist, a four-lobed pattern, an ellipticity that changes with radius — are a\n *shape* problem, and an MGE fixes them for four free parameters\n ([`ag_basis_profiles`](./ag_basis_profiles.md)). Residuals in **discrete off-centre lumps** are\n a substructure problem, and that is what a pixelization is for. Look before you choose.\n- *\"Is the structure resolved?\"* At low resolution the irregular structure is not in the data,\n and a pixelization will reconstruct noise while telling you it fitted well. The workspace is\n blunt about this: for low-resolution data pixelizations are unnecessary.\n- *\"Do you need global quantities or the light distribution?\"* If you want a total flux, a size,\n an axis ratio, a Sersic index — a parametric profile, an MGE or shapelets are enough and far\n cheaper. If you want the morphology itself, particularly for faint or low-surface-brightness\n features, nothing else comes close.\n\nIf the answer to the first is \"lumps\" and to the second \"yes\", continue. Otherwise you will\nspend hours to learn less.\n\n## Ask\n\n- *\"What is the smooth component?\"* Almost always a linear `Sersic`, sometimes a Sersic plus an\n Exponential disk. It matters that this exists: without it the pixelization has to reconstruct\n the bright central bulge too, which wastes mesh resolution on light a six-parameter profile\n describes perfectly and makes the regularization choice much harder.\n- *\"How many mesh pixels can you afford?\"* This is a hardware question as much as a science one\n (see the run-time branch). 20 × 20 is the workspace's default for a GPU run; 28 × 28 to 30 × 30\n for a better-resolved reconstruction; higher only with a large-VRAM GPU or a many-core CPU.\n- *\"Are there neighbours inside the mask?\"* For a pixelization the answer is *never* to mask\n their pixels out — that punches holes in the mesh and produces discontinuity systematics.\n Scale their noise instead (branch below).\n- *\"GPU or CPU?\"* Genuinely depends on your pixel scale, and the answer is counter-intuitive.\n Ask before assuming.\n\n## Branch — the hybrid model\n\nThe canonical composition. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py`.\n\n```python\n\"\"\"\nGalaxy Structure: Bulge Plus Pixelized Reconstruction\n=====================================================\n\nFit a galaxy whose light has two very different characters: a smooth central bulge, described by\na linear Sersic profile in six parameters, and asymmetric clumpy star formation, reconstructed\non a regularized rectangular mesh. The Sersic captures the smooth component interpretably; the\npixelization absorbs everything it cannot explain, and the reconstructed flux map is the\nmeasurement of the galaxy's irregular light.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the imaging, mask it, and apply pixelization over-sampling.\n- **Mesh Shape:** Fix the mesh dimensions before the model is composed.\n- **Model:** Compose the linear Sersic bulge plus the pixelization.\n- **Check:** Confirm the parameter count, evaluate one likelihood, and estimate VRAM.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPIXEL_SCALES = 0.1\nMASK_RADIUS = 2.0\n\n\"\"\"\n__Dataset__\n\nThe mask matters more than usual here. It defines the region the mesh is laid over, so a mask\nthat reaches well beyond the galaxy spends reconstruction pixels on empty sky, and one that\ntruncates the galaxy leaves its outer light unreconstructed\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe over-sampling argument changes too. A pixelization evaluates light on its *own* grid with\nits own over-sampling scheme, so the size is passed as `over_sample_size_pixelization`, not the\n`over_sample_size_lp` used for light profiles. Passing the wrong one silently leaves the\npixelization grid at its default.\n\"\"\"\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=PIXEL_SCALES,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\ndataset = dataset.apply_over_sampling(over_sample_size_pixelization=over_sample_size)\n\n\"\"\"\n__Mesh Shape__\n\nThe mesh dimensions are **fixed before the fit and cannot be a free parameter**. This is not a\nstylistic restriction: JAX compiles the likelihood against statically shaped arrays, and the\nmesh shape sets those shapes. A rectangular mesh uses the same number of pixels in y and x.\n\"\"\"\nmesh_pixels_yx = 20\nmesh_shape = (mesh_pixels_yx, mesh_pixels_yx)\n\n\"\"\"\n__Model__\n\n`ag.Pixelization` pairs a `mesh` — where the reconstruction pixels sit — with a `regularization`\nscheme — the prior that keeps the solution smooth. It is attached to the galaxy as a component\nalongside the light profiles, and the analysis knows to route it through the inversion\n(`PyAutoGalaxy:autogalaxy/galaxy/galaxy.py`).\n\nThe mesh itself contributes **zero** free parameters; the reconstruction's 400 flux values are\nsolved, not sampled. `ag.reg.GaussianKernel` contributes two (`coefficient`, `scale`). The bulge\nis `ag.lp_linear.Sersic` rather than `ag.lp.Sersic` deliberately: its `intensity` is then solved\nby the *same* inversion that solves the mesh amplitudes, which removes the degeneracy between\n\"bright bulge, faint reconstruction\" and \"faint bulge, bright reconstruction\" that a sampled\nintensity would create.\n\"\"\"\npixelization = af.Model(\n ag.Pixelization,\n mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n regularization=ag.reg.GaussianKernel,\n)\n\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n pixelization=pixelization,\n)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\nThree cheap checks, each catching a different class of mistake: the parameter count catches a\nmodel error, one likelihood evaluation catches an incompatibility between model, dataset and\nanalysis, and `print_vram_use` catches the resource error that otherwise appears as an\nout-of-memory failure mid-compile. Pixelizations use far more VRAM than profile-only models —\naround 0.05 GB per batched likelihood for 400 reconstruction pixels — which is why the\nworkspace uses a lower `n_batch` for these fits than for any other.\n\"\"\"\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\nlog_likelihood = analysis.log_likelihood_function(\n instance=model.instance_from_prior_medians()\n)\nprint(f\"log evidence at prior medians: {float(log_likelihood):.2f}\")\n```\n\n**N = 8**: the Sersic's centre (2), `ell_comps` (2), `effective_radius`, `sersic_index`, plus the\nregularization's `coefficient` and `scale`. Eight parameters, with 400 reconstruction pixels\nsolved. That is dramatically more parsimonious than stacking parametric profiles until every\nclump is described — a 20-plus-parameter approach that would still fail on genuinely irregular\nsubstructure.\n\nExtending the smooth side is exactly as you would expect — add components as further attributes\non the galaxy, keeping them linear so their intensities join the same inversion:\n\n```python\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n disk=ag.lp_linear.Exponential,\n pixelization=pixelization,\n)\n```\n\n## Branch — choosing a mesh and a regularization scheme\n\nThese are the two decisions that make or break a reconstruction, and the parameter cost is\nalmost entirely in the regularization.\n\n**Meshes** (`ag.mesh`, from `PyAutoArray:autoarray/inversion/mesh/`). All contribute zero free\nparameters, all take `shape=(y, x)`:\n\n| Mesh | Where the pixels go | Use when |\n|---|---|---|\n| `RectangularUniform` | a uniform grid over the masked region | you want the simplest, most predictable behaviour |\n| `RectangularBilinearAdaptDensity` | a rectangular grid whose spacing follows the density of image pixels mapping to it, via a rank CDF | **the default** — concentrates resolution where the data is, and the fast CPU path |\n| `RectangularBilinearAdaptImage` | adapts to the image's own brightness distribution | the irregular light is strongly concentrated |\n| `RectangularRTUAdaptDensity` / `RectangularRTUAdaptImage` | the same two adaptations through a kernel CDF | GPU, JAX gradient samplers and the interferometer sparse path — the only rectangular adaptive meshes with usable gradients |\n\n`Delaunay`, `KNearestNeighbor` and `KNNBarycentric` also exist for irregular tessellations. Start\nwith `RectangularBilinearAdaptDensity`; it is what every workspace example uses, and the\nrectangular meshes are what the fixed-`mesh_shape` JAX path is built around. (The unqualified\n`RectangularAdaptDensity` / `RectangularAdaptImage` names were split into the `Bilinear` and\n`RTU` families in PyAutoArray 2026.8.23.1 and no longer resolve.)\n\n**Regularization** (`ag.reg`, from `PyAutoArray:autoarray/inversion/regularization/`) is where\nthe free parameters are, and where the physics of \"how smooth should this be?\" lives:\n\n| Scheme | Free params | What it assumes |\n|---|---|---|\n| `ag.reg.Constant` | 1 (`coefficient`) | one smoothing strength everywhere — the simplest, and the right first try |\n| `ag.reg.GaussianKernel` | 2 (`coefficient`, `scale`) | smoothing with a Gaussian correlation length you also fit |\n| `ag.reg.MaternKernel` | 3 (`coefficient`, `scale`, `nu`) | as above, with the roughness `nu` free too |\n\nVerified counts, not guesses. `Constant` penalises the difference between neighbouring pixels\ndirectly; the kernel schemes impose a correlation *length*, which is physically closer to what a\ngalaxy's light does and generally reconstructs faint extended structure better at the cost of\none or two parameters. `ag.reg.Adapt` and its variants scale the smoothing with the\nreconstruction's own brightness — more flexible again, and requiring `adapt_images` on the\nanalysis, which is a step beyond this skill; ask if you want it.\n\nA practical route: fit once with `ag.reg.Constant`, look at the reconstruction. Over-smoothed\n(the clumps blurred into one blob) or over-fitted (isolated single-pixel spikes) both show up\nimmediately, and if `Constant` cannot get both the bright clumps and the faint envelope right at\none strength, that is the signal to move to `GaussianKernel`. Full discussion in\n[`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\n### The positive-only solver\n\nEvery pixelized reconstruction uses a **positive-only** linear solver: no mesh pixel may\nreconstruct negative flux. This is not a numerical nicety. A signed solver lets the\nreconstruction manufacture negative pixels that cancel positive ones to over-fit the data, and\nthat failure mode is a well-known systematic in the literature — many published methods allow\nit. Enforcing non-negativity efficiently needs bespoke linear algebra, which is why this is\nworth stating rather than assuming. You do not need to switch it on; it is the behaviour you get.\n(The one place in this workspace where you *must* disable it is a shapelet basis, which needs\nsigned amplitudes by construction — see [`ag_basis_profiles`](./ag_basis_profiles.md).)\n\n## Branch — contaminating neighbours: scale, never mask\n\nThe general advice for a neighbour inside the mask is to mask its pixels out. **For a\npixelization that advice is wrong.** Removing image pixels entirely removes their mapping into\nthe mesh, punching a hole in the reconstruction and producing discontinuities that show up as\nunexplained systematics.\n\nInstead, keep the pixels in the fit and make them contribute nothing: scale their data to zero\nand their noise to an enormous value, so the likelihood is indifferent to them while the mesh\nstays continuous. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py`.\n\n```python\n\"\"\"\n__Noise Scaling__\n\n`mask_extra_galaxies.fits` marks the contaminated pixels. It is loaded with `invert=True`\nbecause in this file `True` means \"scale this pixel\", the opposite of a modelling mask's\nconvention — getting this backwards scales the galaxy instead of the neighbour, so check the\nsubplot afterwards. `apply_noise_scaling` then zeroes those data values and inflates their\nnoise, driving their signal-to-noise to effectively zero without removing them from the mesh's\nmapping (`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nOrder matters: scale first, then apply the modelling mask.\n\"\"\"\nmask_extra_galaxies = ag.Mask2D.from_fits(\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n pixel_scales=PIXEL_SCALES,\n invert=True,\n)\n\ndataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=PIXEL_SCALES,\n centre=(0.0, 0.0),\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=\"scripts/scratch/my_galaxy/\",\n output_filename=\"noise_scaled\",\n output_format=\"png\",\n)\n```\n\nThe scaled pixels go to a noise value of order 1e8 — visibly so on the signal-to-noise panel of\nthe subplot, which is how you confirm you scaled the right region. Drawing that mask\ninteractively is `autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask_extra_galaxies.py`;\nthe modelling alternative, and when to prefer it, is\n[`ag_light_model_extras`](./ag_light_model_extras.md) and\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch — reading the reconstruction out\n\nThe reconstruction is the science product, and it lives on the `Inversion`. You can get there\nfrom a completed fit or from a single direct `ag.FitImaging` — the latter is the fast way to\nlearn the objects, and is what\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` does.\n\n```python\n\"\"\"\n__Reconstruction__\n\n`inversion.linear_obj_list` holds the linear objects the fit solved. For a hybrid model that is\none `LightProfileLinearObjFuncList` per linear light profile plus one `Mapper` for the\npixelization; with a non-linear `ag.lp.Sersic` bulge the `Mapper` is the only entry. The\n`Mapper` is the object that maps image pixels onto mesh pixels, and it is mesh-specific\n(`PyAutoArray:autoarray/inversion/mappers/`).\n\nThe reconstruction is a 1D array of one flux per mesh pixel, and the (y, x) arcsecond\ncoordinates of those pixels are `mapper.mesh_geometry.mesh_grid`. Pair them by index — they are\nthe same length and the same order — and you have the flux map.\n\"\"\"\ninversion = fit.inversion\n\nmapper = inversion.linear_obj_list[0]\n\nreconstruction = inversion.reconstruction\nmesh_grid = mapper.mesh_geometry.mesh_grid\n\nprint(f\"{len(reconstruction)} mesh pixels reconstructed\")\nprint(f\"coordinates shape: {mesh_grid.shape}\")\n\n\"\"\"\nThe reconstruction's own uncertainties, and its projection back onto the image, are also on the\ninversion. `mapped_reconstructed_operated_data` contains **only** the pixelized component — any\nparametric light profile in the model is excluded — which is exactly the quantity you want when\nasking how much light is in the irregular component.\n\"\"\"\nprint(inversion.reconstruction_noise_map)\nprint(inversion.mapped_reconstructed_operated_data.native.shape)\n```\n\nA caution on the `Mapper`'s grid attributes: `mapper.image_plane_mesh_grid` is `None` for a\nrectangular mesh, so do not reach for it. `mapper.mesh_geometry.mesh_grid` is the mesh pixel\ncentres (verified on the released stack), and `mapper.image_plane_data_grid` is the centre of\nevery masked *image* pixel. Some of the `Mapper`'s attribute names carry a plane-based prefix\ninherited from the shared inversion library that also serves a multi-plane use case; in\nPyAutoGalaxy there is only the one plane, so `mesh_geometry.mesh_grid` is both the clearer name\nand the one to use.\n\n### The evidence terms\n\nThe inversion's figure of merit is a Bayesian evidence, and its components are individually\nreadable — which is how you diagnose whether regularization is doing too much or too little:\n\n```python\nprint(f\"regularization term = {inversion.regularization_term}\")\nprint(f\"log det regularization = {inversion.log_det_regularization_matrix_term}\")\nprint(f\"log det curvature + reg = {inversion.log_det_curvature_reg_matrix_term}\")\n```\n\nThe `regularization_term` measures how non-smooth the solution is; the two log-determinant\nterms are the complexity penalty that stops a 400-pixel model winning by over-fitting. The\nmatrices themselves (`curvature_matrix`, `regularization_matrix`, `curvature_reg_matrix`) are\nthere too. The derivation is in HowToGalaxy chapter 3 and the papers it cites\n(arXiv:1708.07377, arXiv:astro-ph/0601493).\n\n### Diagnostic plots\n\n`aplt.subplot_fit_imaging` includes the reconstruction on the mesh alongside the usual data /\nmodel / residual panels, and is the first thing to look at. For the inversion's own internals\nthere are dedicated functions, which live in the shared inversion library rather than on `aplt`\nand so are imported explicitly — from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/plot.py`:\n\n```python\nfrom autoarray.inversion.plot.inversion_plots import subplot_of_mapper\nfrom autoarray.inversion.plot.mapper_plots import plot_mapper, subplot_image_and_mapper\n\nPLOT_DIR = \"scripts/scratch/my_galaxy/pixelization/\"\n\naplt.subplot_fit_imaging(fit=fit, output_path=PLOT_DIR, output_format=\"png\")\n\nsubplot_of_mapper(\n inversion=inversion, mapper_index=0, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nsubplot_image_and_mapper(\n mapper=mapper, image=dataset.data, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nprint(f\"Saved to: {Path(PLOT_DIR).resolve()}\")\n```\n\n`subplot_of_mapper` is the comprehensive diagnostic — reconstructed image, reconstruction, its\nnoise map and the regularization weights in one figure — and `mapper_index` selects which linear\nobject when there are several. `subplot_image_and_mapper` shows the data beside the mesh, which\nis how you check the mesh covers the structure you care about. Note that none of these three are\nexposed on the `aplt` module — `dir(aplt)` does not list them, so the explicit imports above are\nthe only route and writing them as `aplt.`-prefixed calls raises `AttributeError`. Quote the\nabsolute path back to the user and offer to open it.\n\n## Branch — exporting the reconstruction for downstream science\n\nA reconstruction that only exists inside a PyAutoGalaxy object is hard to share and hard to\nanalyse with other tools. Write it out as coordinates plus values and it becomes ordinary\ntabular data. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py`.\n\n```python\n\"\"\"\n__Export__\n\nFour columns — y, x, reconstruction, noise — is everything needed to rebuild, plot or analyse\nthe galaxy's irregular light without PyAutoGalaxy installed. A completed model-fit also writes\nthis file into its own `image/` folder automatically; glob for `*reconstruction_0.csv` there\nrather than hard-coding the stem, which carries a prefix from the shared inversion library.\n\"\"\"\nimport csv\n\nCSV_PATH = Path(\"scripts/scratch/my_galaxy/reconstruction.csv\")\nCSV_PATH.parent.mkdir(parents=True, exist_ok=True)\n\nwith CSV_PATH.open(\"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([\"y\", \"x\", \"reconstruction\", \"noise_map\"])\n for (y, x), value, sigma in zip(\n mesh_grid, inversion.reconstruction, inversion.reconstruction_noise_map\n ):\n writer.writerow([y, x, value, sigma])\n\nprint(f\"Reconstruction written to: {CSV_PATH.resolve()}\")\n```\n\nReloading needs nothing but the standard library, and from there the mesh is ordinary scattered\ndata. Two things the workspace does with it: a Delaunay triangulation via `scipy.spatial` for\nplotting on the mesh's own geometry, and interpolation onto a regular grid via\n`scipy.interpolate.griddata` for any tool that wants an image:\n\n```python\nimport numpy as np\nfrom scipy.interpolate import griddata\n\nwith CSV_PATH.open() as f:\n reader = csv.reader(f)\n header = next(reader) # ['y', 'x', 'reconstruction', 'noise_map']\n loaded = {key: [] for key in header}\n for row in reader:\n for key, value in zip(header, row):\n loaded[key].append(float(value))\n\npoints = np.stack((np.array(loaded[\"x\"]), np.array(loaded[\"y\"])), axis=-1)\n\ninterpolation_grid = ag.Grid2D.from_extent(\n extent=(-1.0, 1.0, -1.0, 1.0), shape_native=(201, 201)\n)\n\ninterpolated = griddata(\n points=points, values=np.array(loaded[\"reconstruction\"]), xi=interpolation_grid\n)\n```\n\nPick the `extent` to cover the reconstruction without over-resolving it — the mesh has a few\nhundred pixels, so interpolating to 201 × 201 is presentation, not information.\n\n## Branch — run time, VRAM, and the GPU-versus-CPU choice\n\nThis is the branch that decides whether your fit takes twenty minutes or three hours, and the\nanswer is not \"use the GPU\".\n\nPixelized inversions do linear algebra on very large, very **sparse** matrices. JAX has no sparse\nsupport and must work densely, which scales badly; the CPU implementation exploits the sparsity\nfully via `numba`. So the trade runs against pixel scale:\n\n- **Low resolution (`pixel_scales > 0.05`, e.g. Euclid)** — fewer sparse operations, modest VRAM.\n **GPU with JAX is usually fastest.**\n- **High resolution (`pixel_scales <= 0.03`, e.g. HST or JWST)** — the linear algebra is\n sparsity-dominated. **CPU with `numba` and many cores can beat a powerful GPU.**\n\nVRAM is the hard constraint on the GPU side. JAX must hold the whole batched likelihood in GPU\nmemory, and a pixelization needs far more than a profile model: around 0.05 GB per batched\nlikelihood at 400 reconstruction pixels, and more than 1 GB — occasionally more than 10 GB — at\nhigh resolution with a fine mesh. Two consequences: keep `n_batch` low (the workspace uses 20 for\npixelizations against 50 elsewhere), and run\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nbefore committing. It takes 20–30 seconds and it is the difference between knowing your limit\nand discovering it as an out-of-memory error mid-compile. If VRAM is exceeded the run time does\nnot degrade gracefully — it goes from under ten minutes to three hours or more.\n\nRough scaling with resolution, from the workspace's own measurements at a 20 × 20 mesh with VRAM\nunder control: ~10 minutes at 0.1\"/pixel, ~30 minutes at 0.05\", ~1 hour at 0.03\". Benchmark both\npaths for your own data and hardware rather than trusting either default; the search-side\nsettings are [`ag_configure_search`](./ag_configure_search.md) and\n[`../wiki/core/api/searches.md`](../wiki/core/api/searches.md).\n\n## Combine — where this hands off\n\n- **Try a basis first** → [`ag_basis_profiles`](./ag_basis_profiles.md). An MGE is four\n parameters and minutes, not hours, and it genuinely resolves the shape-mismatch case a\n pixelization is often reached for by mistake.\n- **Pick and configure the search** → [`ag_configure_search`](./ag_configure_search.md), with\n `n_batch` lowered for VRAM.\n- **Run the fit** → [`ag_run_search`](./ag_run_search.md); `image/fit.png` in the output folder\n refreshes on the fly and shows the reconstruction as it converges, which is worth watching for\n a fit this long.\n- **Plot and inspect** → [`ag_plot_fit`](./ag_plot_fit.md), plus the `subplot_of_mapper`\n diagnostics above.\n- **Load a completed fit programmatically** → [`ag_load_results`](./ag_load_results.md).\n- **Over-smoothed, over-fitted or unphysical reconstruction** →\n [`ag_debug_fit_failure`](./ag_debug_fit_failure.md). The pixelization-specific causes are a\n regularization scheme too rigid for the structure, a mask that punched holes via hard masking\n where noise scaling was needed, over-sampling passed as `over_sample_size_lp` instead of\n `over_sample_size_pixelization`, and VRAM exhaustion masquerading as a hung fit.\n- **Contaminating neighbours modelled rather than scaled** →\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- **Make the fit robust and fast by starting simple** → the search-chaining skill\n (`ag_chain_searches`). This is the biggest available win for a pixelization: fit a parametric\n model first, pass its bulge as priors, and let the expensive model start from a sensible place.\n The workspace recommends it explicitly.\n- **A non-parametric shape measurement instead of a reconstruction** →\n [`ag_ellipse_fitting`](./ag_ellipse_fitting.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording the mesh and its\nshape, the regularization scheme and why, the mask radius, the hardware path, and what the\nreconstruction showed — with a pixelization the choices *are* the result, and none of them are\nrecoverable from the output folder alone.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Bayesian regularization](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb):\n why a model with hundreds of free flux values does not simply over-fit, derived from scratch;\n `tutorial_6_model_fit` then runs the full fit.\n- **General reference** — [RTD: Pixelization API](https://pyautogalaxy.readthedocs.io/en/latest/api/pixelization.html):\n every mesh, regularization scheme and the objects that combine them.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n the hybrid fit end to end, with the run-time, VRAM and GPU-versus-CPU discussion in full.\n\n## Agent procedural checklist\n\n1. Look at the residual map of a parametric or basis fit first. Shape-following residuals mean\n `ag_basis_profiles`; discrete off-centre lumps mean a pixelization. Do not skip this.\n2. Confirm the structure is resolved — at coarse pixel scales a pixelization reconstructs noise.\n3. Always pair the pixelization with a linear light profile for the smooth component; never let\n the mesh reconstruct the bulge.\n4. Fix `mesh_shape` before composing the model; it cannot be a free parameter.\n5. Pass over-sampling as `over_sample_size_pixelization`, not `over_sample_size_lp`.\n6. Start with `RectangularBilinearAdaptDensity` + `ag.reg.Constant`; move to `GaussianKernel` only when\n one smoothing strength demonstrably cannot serve both the bright and faint structure.\n7. Scale contaminant noise (`apply_noise_scaling`, `invert=True`) — never hard-mask pixels inside\n a pixelization fit — and check the signal-to-noise panel afterwards.\n8. `print(model.info)`, evaluate one likelihood, then `print_vram_use` before any GPU run; keep\n `n_batch` low.\n9. Read the reconstruction via `inversion.reconstruction` +\n `mapper.mesh_geometry.mesh_grid`; export to CSV for anything downstream.\n10. Save the script to `scripts/`, quote every plot's absolute path and offer to open it, then\n offer the `wiki/project/` entry recording mesh, regularization and hardware choices.\n" - } - }, - "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file diff --git a/notebooks/chapter_3_pixelizations/tutorial_6_model_fit.ipynb b/notebooks/chapter_3_pixelizations/tutorial_6_model_fit.ipynb deleted file mode 100644 index c27ccd5..0000000 --- a/notebooks/chapter_3_pixelizations/tutorial_6_model_fit.ipynb +++ /dev/null @@ -1,410 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 6: Model Fit\n", - "=====================\n", - "\n", - "In the previous tutorials we used an inversion to reconstruct a complex galaxy. However, from the perspective of\n", - "a scientific analysis, it is not clear how useful this was. When we fit a galaxy with light profiles, we learn about\n", - "its brightness (`intensity`), size (`effective_radius`), compactness (`sersic_index`), etc.\n", - "\n", - "What did we learn about the galaxy we reconstructed? Not a lot, perhaps.\n", - "\n", - "Inversions are most useful when combined with light profiles. For the complex galaxy we have used throughout this\n", - "chapter, we can fit it with light profiles to quantify the properties of its `bulge` and `disk` components, whilst\n", - "simultaneously fitting any residual structure with the inversion so as to ensure it does not impact the fit.\n", - "\n", - "To illustrate modeling using an inversion, this tutorial therefore revisits the complex galaxy model-fit that we\n", - "performed via search chaining at the end of chapter 2 (tutorials 9-10). This time, as you have probably guessed, we\n", - "will fit part of the galaxy using an inversion.\n", - "\n", - "We will use search chaining to do this, first fitting the main galaxy components with light profiles, thereby\n", - "initializing the bulge and disk components. In the later searches we will switch to an `Inversion`.\n", - "\n", - "__Contents__\n", - "\n", - "- **Initial Setup:** Load the galaxy dataset and apply a mask.\n", - "- **Dataset Auto-Simulation:** Automatically simulate the dataset if it does not already exist.\n", - "- **Model + Search + Analysis + Model-Fit (Search 1):** Fit light profiles to the main galaxy components.\n", - "- **Mesh Shape:** Discussion of how mesh shape affects the inversion.\n", - "- **Model + Search + Analysis + Model-Fit (Search 2):** Fit with a pixelization for residual structure.\n", - "- **Model + Search (Search 3):** Final simultaneous fit of light profiles and pixelization.\n", - "- **Wrap Up:** Summary of combining light profiles with pixelizations via search chaining." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Google Colab Setup__\n", - "\n", - "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "jupyter": { - "source_hidden": true - } - }, - "outputs": [], - "source": [ - "# @title Set up Google Colab { display-mode: \"form\" }\n", - "try:\n", - " import google.colab\n", - "except ImportError:\n", - " from autogalaxy import setup_colab as _setup_colab\n", - "else:\n", - " import importlib\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.check_call(\n", - " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", - " )\n", - " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", - "\n", - "_setup_colab.setup(\"howtogalaxy\")" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autogalaxy import setup_notebook; setup_notebook()\n", - "\n", - "from pathlib import Path\n", - "import autofit as af\n", - "import autogalaxy as ag\n", - "import autogalaxy.plot as aplt" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Initial Setup__\n", - "\n", - "we'll use the same galaxy data as the previous tutorials, where:\n", - "\n", - " - The galaxy's bulge is an `Sersic`.\n", - " - The galaxy's disk is an `Exponential`." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "dataset_name = \"simple\"\n", - "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Dataset Auto-Simulation__\n", - "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "if ag.util.dataset.should_simulate(str(dataset_path)):\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulators/simple.py\"],\n", - " check=True,\n", - " )\n", - "\n", - "dataset = ag.Imaging.from_fits(\n", - " data_path=dataset_path / \"data.fits\",\n", - " noise_map_path=dataset_path / \"noise_map.fits\",\n", - " psf_path=dataset_path / \"psf.fits\",\n", - " pixel_scales=0.1,\n", - ")\n", - "\n", - "mask = ag.Mask2D.circular(\n", - " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.0\n", - ")\n", - "\n", - "\n", - "dataset = dataset.apply_mask(mask=mask)\n", - "\n", - "over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n", - " grid=dataset.grid,\n", - " sub_size_list=[8, 4, 2],\n", - " radial_list=[0.3, 0.6],\n", - " centre_list=[(0.0, 0.0)],\n", - ")\n", - "\n", - "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n", - "\n", - "aplt.subplot_imaging_dataset(dataset=dataset)\n" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Model + Search + Analysis + Model-Fit (Search 1)__\n", - "\n", - "Search 1 we fit a model where:\n", - "\n", - " - The galaxy's bulge is an `Sersic` with fixed centre [5 parameters].\n", - " \n", - " - The galaxy's disk is an `Exponential` with fixed centre [4 parameters].\n", - " \n", - "The number of free parameters and therefore the dimensionality of non-linear parameter space is N=9." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge = af.Model(ag.lp.Sersic)\n", - "disk = af.Model(ag.lp.Exponential)\n", - "\n", - "bulge.centre_0 = 0.0\n", - "bulge.centre_1 = 0.0\n", - "disk.centre_0 = 0.0\n", - "disk.centre_1 = 0.0\n", - "\n", - "galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n", - "\n", - "model_1 = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n", - "\n", - "search_1 = af.Nautilus(\n", - " path_prefix=Path(\"howtogalaxy\", \"chapter_3\"),\n", - " name=\"search[1]\",\n", - " unique_tag=dataset_name,\n", - " n_live=100,\n", - " n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2.\n", - ")\n", - "\n", - "analysis_1 = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", - "\n", - "result_1 = search_1.fit(model=model_1, analysis=analysis_1)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Mesh Shape__\n", - "\n", - "The `mesh_shape` parameter defines the number of pixels used by the rectangular mesh to reconstruct the galaxy,\n", - "set below to 28 x 28.\n", - "\n", - "The `mesh_shape` must be fixed before modeling and cannot be a free parameter of the model, because JAX uses the\n", - "mesh shape to define static shaped arrays which use the mesh to reconstruct the galaxy. For a rectangular\n", - "mesh, the same number of pixels must be used in the y and x directions." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mesh_pixels_yx = 28\n", - "mesh_shape = (mesh_pixels_yx, mesh_pixels_yx)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Model + Search + Analysis + Model-Fit (Search 2)__\n", - "\n", - "We use the results of search 1 to create the model fitted in search 2, where:\n", - "\n", - " - The galaxy's bulge is an `Sersic` [0 parameters: parameters fixed from search 1].\n", - "\n", - " - The galaxy's disk is an `Exponential` [0 parameters: parameters fixed from search 1].\n", - "\n", - " - Residual galaxy structure is reconstructed using a `RectangularBilinearAdaptDensity` mesh with a fixed 28 x 28\n", - " shape [0 parameters].\n", - "\n", - " - This pixelization is regularized using a `GaussianKernel` scheme [2 parameters].\n", - "\n", - "The number of free parameters and therefore the dimensionality of non-linear parameter space is N=2.\n", - "\n", - "This search allows us to very efficiently set up the regularization scheme's parameters, before refitting the\n", - "galaxy's bulge and disk alongside the inversion in search 3." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "pixelization = af.Model(\n", - " ag.Pixelization,\n", - " mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n", - " regularization=ag.reg.GaussianKernel,\n", - ")\n", - "\n", - "galaxy = af.Model(\n", - " ag.Galaxy,\n", - " redshift=0.5,\n", - " bulge=result_1.instance.galaxies.galaxy.bulge,\n", - " disk=result_1.instance.galaxies.galaxy.disk,\n", - " pixelization=pixelization,\n", - ")\n", - "\n", - "model_2 = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n", - "\n", - "search_2 = af.Nautilus(\n", - " path_prefix=Path(\"howtogalaxy\", \"chapter_3\"),\n", - " name=\"search[2]\",\n", - " unique_tag=dataset_name,\n", - " n_live=50,\n", - " n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2.\n", - ")\n", - "\n", - "analysis_2 = ag.AnalysisImaging(\n", - " dataset=dataset,\n", - " settings=ag.Settings(use_border_relocator=True),\n", - " use_jax=True,\n", - ")\n", - "\n", - "result_2 = search_2.fit(model=model_2, analysis=analysis_2)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Model + Search (Search 3)__\n", - "\n", - "We use the results of searches 1 and 2 to create the model fitted in search 3, where:\n", - "\n", - " - The galaxy's bulge is an `Sersic` [7 parameters: priors initialized from search 1].\n", - "\n", - " - The galaxy's disk is an `Sersic` [7 parameters: priors initialized from search 1].\n", - "\n", - " - Residual galaxy structure uses a `RectangularBilinearAdaptDensity` mesh with a fixed 28 x 28 shape [0 parameters].\n", - "\n", - " - This pixelization is regularized using a `GaussianKernel` scheme [2 parameters].\n", - "\n", - "The number of free parameters and therefore the dimensionality of non-linear parameter space is N=16.\n", - "\n", - "This search allows us to refit the bulge and disk components with an inversion that takes care of any residual\n", - "structure the light profiles do not capture." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge = af.Model(ag.lp.Sersic)\n", - "bulge.ell_comps = result_1.model.galaxies.galaxy.bulge.ell_comps\n", - "bulge.intensity = result_1.model.galaxies.galaxy.bulge.intensity\n", - "bulge.effective_radius = result_1.model.galaxies.galaxy.bulge.effective_radius\n", - "bulge.sersic_index = result_1.model.galaxies.galaxy.bulge.sersic_index\n", - "\n", - "disk = af.Model(ag.lp.Sersic)\n", - "disk.ell_comps = result_1.model.galaxies.galaxy.disk.ell_comps\n", - "disk.intensity = result_1.model.galaxies.galaxy.disk.intensity\n", - "disk.effective_radius = result_1.model.galaxies.galaxy.disk.effective_radius\n", - "\n", - "pixelization = af.Model(\n", - " ag.Pixelization,\n", - " mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n", - " regularization=ag.reg.GaussianKernel,\n", - ")\n", - "\n", - "galaxy = af.Model(\n", - " ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk, pixelization=pixelization\n", - ")\n", - "\n", - "model_3 = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n", - "\n", - "search_3 = af.Nautilus(\n", - " path_prefix=Path(\"howtogalaxy\", \"chapter_3\"),\n", - " name=\"search[3]\",\n", - " unique_tag=dataset_name,\n", - " n_live=100,\n", - " n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2.\n", - ")\n", - "\n", - "analysis_3 = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", - "\n", - "result_3 = search_3.fit(model=model_3, analysis=analysis_3)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Wrap Up__\n", - "\n", - "And with that, we now have a pipeline to model galaxies using an inversion!\n", - "\n", - "This concludes the pixelizations chapter. You now have every tool this chapter set out to teach: pixelizations and\n", - "mappers (tutorials 1-2), inversions (tutorial 3), Bayesian regularization and the evidence (tutorials 4-5), and a\n", - "search-chained pipeline which combines light profiles with an inversion (this tutorial).\n", - "\n", - "In chapter 4, we scale up from a single galaxy to the busier fields real imaging surveys deliver: datasets with\n", - "extra galaxies near the main galaxy, blended multi-galaxy systems modeled simultaneously, and cluster fields with\n", - "many member galaxies." - ] - } - ], - "metadata": { - "anaconda-cloud": {}, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - }, - "colab": { - "aiContexts": { - "24c2f562-da24-50bb-8eb9-5a887505fe54": { - "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", - "name": "PyAutoGalaxy assistant", - "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_3_pixelizations/tutorial_6_model_fit.ipynb in HowToGalaxy).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoGalaxy calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoGalaxy docs (https://pyautogalaxy.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_pixelization\n\n---\nname: ag_pixelization\ndescription: Reconstruct a galaxy's clumpy or irregular light directly on a regularized pixel mesh, using `ag.Pixelization` alongside a parametric `ag.lp_linear` bulge — the hybrid model that gives a smooth interpretable component plus a flexible flux map for everything the profile cannot explain. Covers when a pixelization is warranted and when it is overkill, choosing an `ag.mesh` and an `ag.reg` regularization scheme and what each costs in free parameters, why `mesh_shape` must be fixed before the fit, `over_sample_size_pixelization` rather than `over_sample_size_lp`, noise scaling instead of hard masking for contaminants, the positive-only solver, reading the reconstruction and its Bayesian-evidence terms out of the `Inversion`, exporting the reconstruction to CSV for collaborators, and the GPU/VRAM versus CPU run-time trade. Use when a Sersic, MGE or shapelet basis leaves structured residuals in discrete off-centre lumps. Not for morphology a basis can still fit (`ag_basis_profiles`), not for non-parametric isophote measurement (`ag_ellipse_fitting`), and not for the basics of model composition (`ag_build_imaging_model`).\n---\n\n# Reconstructing a galaxy on a pixel mesh\n\nEvery model in this workspace so far has been a *function*: you asserted a functional form and\nthe fit found its parameters. A pixelization drops the functional form. It lays a mesh of pixels\nover the galaxy, gives each pixel its own free flux value, and solves all of them at once by\nlinear inversion — thousands of amplitudes, none of them in the non-linear search's parameter\nspace. What stops that from simply fitting the noise is **regularization**: a prior that\npenalises solutions where neighbouring mesh pixels differ sharply, so the reconstruction is as\nsmooth as the data will allow and no smoother.\n\nThe science case is specific, and it is worth being honest about how specific. Galaxies with\nspiral arms, asymmetric star-forming clumps, tidal features or low-surface-brightness\nsubstructure have light that no smooth profile — and often no basis expansion either —\nreproduces. The canonical use is therefore **hybrid**: a linear `Sersic` for the smooth central\nbulge, and a pixelization for the irregular remainder. That split is the point. It gives you a\nlow-dimensional, physically interpretable description of the bulge *and* a flux map of exactly\nwhat the bulge could not explain, which is the quantity you want if the science question is \"how\nmuch of this galaxy's light is in its irregular components?\"\n\nThis is a **direct** reconstruction. There is no second plane, no de-projection, no inversion of\na geometric mapping — the mesh sits on the image plane, over the galaxy, at the same coordinates\nthe data occupies. If you have met pixelized reconstruction before in a different context, that\nextra step is the one that is absent here, and its absence makes everything simpler: what the\nmesh reconstructs is the galaxy's own surface brightness, and its coordinates are sky\ncoordinates in arcseconds.\n\nStatistically, the fit now has two nested layers. The non-linear search explores a handful of\nparameters — the bulge's shape, the regularization strength — and for each proposal an inversion\nsolves the mesh amplitudes exactly and returns a **Bayesian evidence** rather than a plain\nlikelihood. That evidence includes terms that penalise an unnecessarily complex reconstruction,\nwhich is what lets a model with 400 free flux values not simply win by over-fitting. The theory\nis [`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md);\nchapter 3 of HowToGalaxy derives it from scratch.\n\nThe canonical scripts are\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py` (via a search),\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` (one direct fit, with the\ninversion internals walked through) and\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py` (export).\n\n## Before you reach for one — the honest gate\n\nA pixelization is the most powerful and the most expensive model here, with failure modes the\nparametric models do not have. Three questions decide whether you need it:\n\n- *\"What do the residuals actually look like?\"* Structured residuals that **follow the\n isophotes** — a twist, a four-lobed pattern, an ellipticity that changes with radius — are a\n *shape* problem, and an MGE fixes them for four free parameters\n ([`ag_basis_profiles`](./ag_basis_profiles.md)). Residuals in **discrete off-centre lumps** are\n a substructure problem, and that is what a pixelization is for. Look before you choose.\n- *\"Is the structure resolved?\"* At low resolution the irregular structure is not in the data,\n and a pixelization will reconstruct noise while telling you it fitted well. The workspace is\n blunt about this: for low-resolution data pixelizations are unnecessary.\n- *\"Do you need global quantities or the light distribution?\"* If you want a total flux, a size,\n an axis ratio, a Sersic index — a parametric profile, an MGE or shapelets are enough and far\n cheaper. If you want the morphology itself, particularly for faint or low-surface-brightness\n features, nothing else comes close.\n\nIf the answer to the first is \"lumps\" and to the second \"yes\", continue. Otherwise you will\nspend hours to learn less.\n\n## Ask\n\n- *\"What is the smooth component?\"* Almost always a linear `Sersic`, sometimes a Sersic plus an\n Exponential disk. It matters that this exists: without it the pixelization has to reconstruct\n the bright central bulge too, which wastes mesh resolution on light a six-parameter profile\n describes perfectly and makes the regularization choice much harder.\n- *\"How many mesh pixels can you afford?\"* This is a hardware question as much as a science one\n (see the run-time branch). 20 × 20 is the workspace's default for a GPU run; 28 × 28 to 30 × 30\n for a better-resolved reconstruction; higher only with a large-VRAM GPU or a many-core CPU.\n- *\"Are there neighbours inside the mask?\"* For a pixelization the answer is *never* to mask\n their pixels out — that punches holes in the mesh and produces discontinuity systematics.\n Scale their noise instead (branch below).\n- *\"GPU or CPU?\"* Genuinely depends on your pixel scale, and the answer is counter-intuitive.\n Ask before assuming.\n\n## Branch — the hybrid model\n\nThe canonical composition. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py`.\n\n```python\n\"\"\"\nGalaxy Structure: Bulge Plus Pixelized Reconstruction\n=====================================================\n\nFit a galaxy whose light has two very different characters: a smooth central bulge, described by\na linear Sersic profile in six parameters, and asymmetric clumpy star formation, reconstructed\non a regularized rectangular mesh. The Sersic captures the smooth component interpretably; the\npixelization absorbs everything it cannot explain, and the reconstructed flux map is the\nmeasurement of the galaxy's irregular light.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the imaging, mask it, and apply pixelization over-sampling.\n- **Mesh Shape:** Fix the mesh dimensions before the model is composed.\n- **Model:** Compose the linear Sersic bulge plus the pixelization.\n- **Check:** Confirm the parameter count, evaluate one likelihood, and estimate VRAM.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPIXEL_SCALES = 0.1\nMASK_RADIUS = 2.0\n\n\"\"\"\n__Dataset__\n\nThe mask matters more than usual here. It defines the region the mesh is laid over, so a mask\nthat reaches well beyond the galaxy spends reconstruction pixels on empty sky, and one that\ntruncates the galaxy leaves its outer light unreconstructed\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe over-sampling argument changes too. A pixelization evaluates light on its *own* grid with\nits own over-sampling scheme, so the size is passed as `over_sample_size_pixelization`, not the\n`over_sample_size_lp` used for light profiles. Passing the wrong one silently leaves the\npixelization grid at its default.\n\"\"\"\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=PIXEL_SCALES,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\ndataset = dataset.apply_over_sampling(over_sample_size_pixelization=over_sample_size)\n\n\"\"\"\n__Mesh Shape__\n\nThe mesh dimensions are **fixed before the fit and cannot be a free parameter**. This is not a\nstylistic restriction: JAX compiles the likelihood against statically shaped arrays, and the\nmesh shape sets those shapes. A rectangular mesh uses the same number of pixels in y and x.\n\"\"\"\nmesh_pixels_yx = 20\nmesh_shape = (mesh_pixels_yx, mesh_pixels_yx)\n\n\"\"\"\n__Model__\n\n`ag.Pixelization` pairs a `mesh` — where the reconstruction pixels sit — with a `regularization`\nscheme — the prior that keeps the solution smooth. It is attached to the galaxy as a component\nalongside the light profiles, and the analysis knows to route it through the inversion\n(`PyAutoGalaxy:autogalaxy/galaxy/galaxy.py`).\n\nThe mesh itself contributes **zero** free parameters; the reconstruction's 400 flux values are\nsolved, not sampled. `ag.reg.GaussianKernel` contributes two (`coefficient`, `scale`). The bulge\nis `ag.lp_linear.Sersic` rather than `ag.lp.Sersic` deliberately: its `intensity` is then solved\nby the *same* inversion that solves the mesh amplitudes, which removes the degeneracy between\n\"bright bulge, faint reconstruction\" and \"faint bulge, bright reconstruction\" that a sampled\nintensity would create.\n\"\"\"\npixelization = af.Model(\n ag.Pixelization,\n mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n regularization=ag.reg.GaussianKernel,\n)\n\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n pixelization=pixelization,\n)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\nThree cheap checks, each catching a different class of mistake: the parameter count catches a\nmodel error, one likelihood evaluation catches an incompatibility between model, dataset and\nanalysis, and `print_vram_use` catches the resource error that otherwise appears as an\nout-of-memory failure mid-compile. Pixelizations use far more VRAM than profile-only models —\naround 0.05 GB per batched likelihood for 400 reconstruction pixels — which is why the\nworkspace uses a lower `n_batch` for these fits than for any other.\n\"\"\"\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\nlog_likelihood = analysis.log_likelihood_function(\n instance=model.instance_from_prior_medians()\n)\nprint(f\"log evidence at prior medians: {float(log_likelihood):.2f}\")\n```\n\n**N = 8**: the Sersic's centre (2), `ell_comps` (2), `effective_radius`, `sersic_index`, plus the\nregularization's `coefficient` and `scale`. Eight parameters, with 400 reconstruction pixels\nsolved. That is dramatically more parsimonious than stacking parametric profiles until every\nclump is described — a 20-plus-parameter approach that would still fail on genuinely irregular\nsubstructure.\n\nExtending the smooth side is exactly as you would expect — add components as further attributes\non the galaxy, keeping them linear so their intensities join the same inversion:\n\n```python\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n disk=ag.lp_linear.Exponential,\n pixelization=pixelization,\n)\n```\n\n## Branch — choosing a mesh and a regularization scheme\n\nThese are the two decisions that make or break a reconstruction, and the parameter cost is\nalmost entirely in the regularization.\n\n**Meshes** (`ag.mesh`, from `PyAutoArray:autoarray/inversion/mesh/`). All contribute zero free\nparameters, all take `shape=(y, x)`:\n\n| Mesh | Where the pixels go | Use when |\n|---|---|---|\n| `RectangularUniform` | a uniform grid over the masked region | you want the simplest, most predictable behaviour |\n| `RectangularBilinearAdaptDensity` | a rectangular grid whose spacing follows the density of image pixels mapping to it, via a rank CDF | **the default** — concentrates resolution where the data is, and the fast CPU path |\n| `RectangularBilinearAdaptImage` | adapts to the image's own brightness distribution | the irregular light is strongly concentrated |\n| `RectangularRTUAdaptDensity` / `RectangularRTUAdaptImage` | the same two adaptations through a kernel CDF | GPU, JAX gradient samplers and the interferometer sparse path — the only rectangular adaptive meshes with usable gradients |\n\n`Delaunay`, `KNearestNeighbor` and `KNNBarycentric` also exist for irregular tessellations. Start\nwith `RectangularBilinearAdaptDensity`; it is what every workspace example uses, and the\nrectangular meshes are what the fixed-`mesh_shape` JAX path is built around. (The unqualified\n`RectangularAdaptDensity` / `RectangularAdaptImage` names were split into the `Bilinear` and\n`RTU` families in PyAutoArray 2026.8.23.1 and no longer resolve.)\n\n**Regularization** (`ag.reg`, from `PyAutoArray:autoarray/inversion/regularization/`) is where\nthe free parameters are, and where the physics of \"how smooth should this be?\" lives:\n\n| Scheme | Free params | What it assumes |\n|---|---|---|\n| `ag.reg.Constant` | 1 (`coefficient`) | one smoothing strength everywhere — the simplest, and the right first try |\n| `ag.reg.GaussianKernel` | 2 (`coefficient`, `scale`) | smoothing with a Gaussian correlation length you also fit |\n| `ag.reg.MaternKernel` | 3 (`coefficient`, `scale`, `nu`) | as above, with the roughness `nu` free too |\n\nVerified counts, not guesses. `Constant` penalises the difference between neighbouring pixels\ndirectly; the kernel schemes impose a correlation *length*, which is physically closer to what a\ngalaxy's light does and generally reconstructs faint extended structure better at the cost of\none or two parameters. `ag.reg.Adapt` and its variants scale the smoothing with the\nreconstruction's own brightness — more flexible again, and requiring `adapt_images` on the\nanalysis, which is a step beyond this skill; ask if you want it.\n\nA practical route: fit once with `ag.reg.Constant`, look at the reconstruction. Over-smoothed\n(the clumps blurred into one blob) or over-fitted (isolated single-pixel spikes) both show up\nimmediately, and if `Constant` cannot get both the bright clumps and the faint envelope right at\none strength, that is the signal to move to `GaussianKernel`. Full discussion in\n[`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\n### The positive-only solver\n\nEvery pixelized reconstruction uses a **positive-only** linear solver: no mesh pixel may\nreconstruct negative flux. This is not a numerical nicety. A signed solver lets the\nreconstruction manufacture negative pixels that cancel positive ones to over-fit the data, and\nthat failure mode is a well-known systematic in the literature — many published methods allow\nit. Enforcing non-negativity efficiently needs bespoke linear algebra, which is why this is\nworth stating rather than assuming. You do not need to switch it on; it is the behaviour you get.\n(The one place in this workspace where you *must* disable it is a shapelet basis, which needs\nsigned amplitudes by construction — see [`ag_basis_profiles`](./ag_basis_profiles.md).)\n\n## Branch — contaminating neighbours: scale, never mask\n\nThe general advice for a neighbour inside the mask is to mask its pixels out. **For a\npixelization that advice is wrong.** Removing image pixels entirely removes their mapping into\nthe mesh, punching a hole in the reconstruction and producing discontinuities that show up as\nunexplained systematics.\n\nInstead, keep the pixels in the fit and make them contribute nothing: scale their data to zero\nand their noise to an enormous value, so the likelihood is indifferent to them while the mesh\nstays continuous. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py`.\n\n```python\n\"\"\"\n__Noise Scaling__\n\n`mask_extra_galaxies.fits` marks the contaminated pixels. It is loaded with `invert=True`\nbecause in this file `True` means \"scale this pixel\", the opposite of a modelling mask's\nconvention — getting this backwards scales the galaxy instead of the neighbour, so check the\nsubplot afterwards. `apply_noise_scaling` then zeroes those data values and inflates their\nnoise, driving their signal-to-noise to effectively zero without removing them from the mesh's\nmapping (`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nOrder matters: scale first, then apply the modelling mask.\n\"\"\"\nmask_extra_galaxies = ag.Mask2D.from_fits(\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n pixel_scales=PIXEL_SCALES,\n invert=True,\n)\n\ndataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=PIXEL_SCALES,\n centre=(0.0, 0.0),\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=\"scripts/scratch/my_galaxy/\",\n output_filename=\"noise_scaled\",\n output_format=\"png\",\n)\n```\n\nThe scaled pixels go to a noise value of order 1e8 — visibly so on the signal-to-noise panel of\nthe subplot, which is how you confirm you scaled the right region. Drawing that mask\ninteractively is `autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask_extra_galaxies.py`;\nthe modelling alternative, and when to prefer it, is\n[`ag_light_model_extras`](./ag_light_model_extras.md) and\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch — reading the reconstruction out\n\nThe reconstruction is the science product, and it lives on the `Inversion`. You can get there\nfrom a completed fit or from a single direct `ag.FitImaging` — the latter is the fast way to\nlearn the objects, and is what\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` does.\n\n```python\n\"\"\"\n__Reconstruction__\n\n`inversion.linear_obj_list` holds the linear objects the fit solved. For a hybrid model that is\none `LightProfileLinearObjFuncList` per linear light profile plus one `Mapper` for the\npixelization; with a non-linear `ag.lp.Sersic` bulge the `Mapper` is the only entry. The\n`Mapper` is the object that maps image pixels onto mesh pixels, and it is mesh-specific\n(`PyAutoArray:autoarray/inversion/mappers/`).\n\nThe reconstruction is a 1D array of one flux per mesh pixel, and the (y, x) arcsecond\ncoordinates of those pixels are `mapper.mesh_geometry.mesh_grid`. Pair them by index — they are\nthe same length and the same order — and you have the flux map.\n\"\"\"\ninversion = fit.inversion\n\nmapper = inversion.linear_obj_list[0]\n\nreconstruction = inversion.reconstruction\nmesh_grid = mapper.mesh_geometry.mesh_grid\n\nprint(f\"{len(reconstruction)} mesh pixels reconstructed\")\nprint(f\"coordinates shape: {mesh_grid.shape}\")\n\n\"\"\"\nThe reconstruction's own uncertainties, and its projection back onto the image, are also on the\ninversion. `mapped_reconstructed_operated_data` contains **only** the pixelized component — any\nparametric light profile in the model is excluded — which is exactly the quantity you want when\nasking how much light is in the irregular component.\n\"\"\"\nprint(inversion.reconstruction_noise_map)\nprint(inversion.mapped_reconstructed_operated_data.native.shape)\n```\n\nA caution on the `Mapper`'s grid attributes: `mapper.image_plane_mesh_grid` is `None` for a\nrectangular mesh, so do not reach for it. `mapper.mesh_geometry.mesh_grid` is the mesh pixel\ncentres (verified on the released stack), and `mapper.image_plane_data_grid` is the centre of\nevery masked *image* pixel. Some of the `Mapper`'s attribute names carry a plane-based prefix\ninherited from the shared inversion library that also serves a multi-plane use case; in\nPyAutoGalaxy there is only the one plane, so `mesh_geometry.mesh_grid` is both the clearer name\nand the one to use.\n\n### The evidence terms\n\nThe inversion's figure of merit is a Bayesian evidence, and its components are individually\nreadable — which is how you diagnose whether regularization is doing too much or too little:\n\n```python\nprint(f\"regularization term = {inversion.regularization_term}\")\nprint(f\"log det regularization = {inversion.log_det_regularization_matrix_term}\")\nprint(f\"log det curvature + reg = {inversion.log_det_curvature_reg_matrix_term}\")\n```\n\nThe `regularization_term` measures how non-smooth the solution is; the two log-determinant\nterms are the complexity penalty that stops a 400-pixel model winning by over-fitting. The\nmatrices themselves (`curvature_matrix`, `regularization_matrix`, `curvature_reg_matrix`) are\nthere too. The derivation is in HowToGalaxy chapter 3 and the papers it cites\n(arXiv:1708.07377, arXiv:astro-ph/0601493).\n\n### Diagnostic plots\n\n`aplt.subplot_fit_imaging` includes the reconstruction on the mesh alongside the usual data /\nmodel / residual panels, and is the first thing to look at. For the inversion's own internals\nthere are dedicated functions, which live in the shared inversion library rather than on `aplt`\nand so are imported explicitly — from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/plot.py`:\n\n```python\nfrom autoarray.inversion.plot.inversion_plots import subplot_of_mapper\nfrom autoarray.inversion.plot.mapper_plots import plot_mapper, subplot_image_and_mapper\n\nPLOT_DIR = \"scripts/scratch/my_galaxy/pixelization/\"\n\naplt.subplot_fit_imaging(fit=fit, output_path=PLOT_DIR, output_format=\"png\")\n\nsubplot_of_mapper(\n inversion=inversion, mapper_index=0, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nsubplot_image_and_mapper(\n mapper=mapper, image=dataset.data, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nprint(f\"Saved to: {Path(PLOT_DIR).resolve()}\")\n```\n\n`subplot_of_mapper` is the comprehensive diagnostic — reconstructed image, reconstruction, its\nnoise map and the regularization weights in one figure — and `mapper_index` selects which linear\nobject when there are several. `subplot_image_and_mapper` shows the data beside the mesh, which\nis how you check the mesh covers the structure you care about. Note that none of these three are\nexposed on the `aplt` module — `dir(aplt)` does not list them, so the explicit imports above are\nthe only route and writing them as `aplt.`-prefixed calls raises `AttributeError`. Quote the\nabsolute path back to the user and offer to open it.\n\n## Branch — exporting the reconstruction for downstream science\n\nA reconstruction that only exists inside a PyAutoGalaxy object is hard to share and hard to\nanalyse with other tools. Write it out as coordinates plus values and it becomes ordinary\ntabular data. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py`.\n\n```python\n\"\"\"\n__Export__\n\nFour columns — y, x, reconstruction, noise — is everything needed to rebuild, plot or analyse\nthe galaxy's irregular light without PyAutoGalaxy installed. A completed model-fit also writes\nthis file into its own `image/` folder automatically; glob for `*reconstruction_0.csv` there\nrather than hard-coding the stem, which carries a prefix from the shared inversion library.\n\"\"\"\nimport csv\n\nCSV_PATH = Path(\"scripts/scratch/my_galaxy/reconstruction.csv\")\nCSV_PATH.parent.mkdir(parents=True, exist_ok=True)\n\nwith CSV_PATH.open(\"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([\"y\", \"x\", \"reconstruction\", \"noise_map\"])\n for (y, x), value, sigma in zip(\n mesh_grid, inversion.reconstruction, inversion.reconstruction_noise_map\n ):\n writer.writerow([y, x, value, sigma])\n\nprint(f\"Reconstruction written to: {CSV_PATH.resolve()}\")\n```\n\nReloading needs nothing but the standard library, and from there the mesh is ordinary scattered\ndata. Two things the workspace does with it: a Delaunay triangulation via `scipy.spatial` for\nplotting on the mesh's own geometry, and interpolation onto a regular grid via\n`scipy.interpolate.griddata` for any tool that wants an image:\n\n```python\nimport numpy as np\nfrom scipy.interpolate import griddata\n\nwith CSV_PATH.open() as f:\n reader = csv.reader(f)\n header = next(reader) # ['y', 'x', 'reconstruction', 'noise_map']\n loaded = {key: [] for key in header}\n for row in reader:\n for key, value in zip(header, row):\n loaded[key].append(float(value))\n\npoints = np.stack((np.array(loaded[\"x\"]), np.array(loaded[\"y\"])), axis=-1)\n\ninterpolation_grid = ag.Grid2D.from_extent(\n extent=(-1.0, 1.0, -1.0, 1.0), shape_native=(201, 201)\n)\n\ninterpolated = griddata(\n points=points, values=np.array(loaded[\"reconstruction\"]), xi=interpolation_grid\n)\n```\n\nPick the `extent` to cover the reconstruction without over-resolving it — the mesh has a few\nhundred pixels, so interpolating to 201 × 201 is presentation, not information.\n\n## Branch — run time, VRAM, and the GPU-versus-CPU choice\n\nThis is the branch that decides whether your fit takes twenty minutes or three hours, and the\nanswer is not \"use the GPU\".\n\nPixelized inversions do linear algebra on very large, very **sparse** matrices. JAX has no sparse\nsupport and must work densely, which scales badly; the CPU implementation exploits the sparsity\nfully via `numba`. So the trade runs against pixel scale:\n\n- **Low resolution (`pixel_scales > 0.05`, e.g. Euclid)** — fewer sparse operations, modest VRAM.\n **GPU with JAX is usually fastest.**\n- **High resolution (`pixel_scales <= 0.03`, e.g. HST or JWST)** — the linear algebra is\n sparsity-dominated. **CPU with `numba` and many cores can beat a powerful GPU.**\n\nVRAM is the hard constraint on the GPU side. JAX must hold the whole batched likelihood in GPU\nmemory, and a pixelization needs far more than a profile model: around 0.05 GB per batched\nlikelihood at 400 reconstruction pixels, and more than 1 GB — occasionally more than 10 GB — at\nhigh resolution with a fine mesh. Two consequences: keep `n_batch` low (the workspace uses 20 for\npixelizations against 50 elsewhere), and run\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nbefore committing. It takes 20–30 seconds and it is the difference between knowing your limit\nand discovering it as an out-of-memory error mid-compile. If VRAM is exceeded the run time does\nnot degrade gracefully — it goes from under ten minutes to three hours or more.\n\nRough scaling with resolution, from the workspace's own measurements at a 20 × 20 mesh with VRAM\nunder control: ~10 minutes at 0.1\"/pixel, ~30 minutes at 0.05\", ~1 hour at 0.03\". Benchmark both\npaths for your own data and hardware rather than trusting either default; the search-side\nsettings are [`ag_configure_search`](./ag_configure_search.md) and\n[`../wiki/core/api/searches.md`](../wiki/core/api/searches.md).\n\n## Combine — where this hands off\n\n- **Try a basis first** → [`ag_basis_profiles`](./ag_basis_profiles.md). An MGE is four\n parameters and minutes, not hours, and it genuinely resolves the shape-mismatch case a\n pixelization is often reached for by mistake.\n- **Pick and configure the search** → [`ag_configure_search`](./ag_configure_search.md), with\n `n_batch` lowered for VRAM.\n- **Run the fit** → [`ag_run_search`](./ag_run_search.md); `image/fit.png` in the output folder\n refreshes on the fly and shows the reconstruction as it converges, which is worth watching for\n a fit this long.\n- **Plot and inspect** → [`ag_plot_fit`](./ag_plot_fit.md), plus the `subplot_of_mapper`\n diagnostics above.\n- **Load a completed fit programmatically** → [`ag_load_results`](./ag_load_results.md).\n- **Over-smoothed, over-fitted or unphysical reconstruction** →\n [`ag_debug_fit_failure`](./ag_debug_fit_failure.md). The pixelization-specific causes are a\n regularization scheme too rigid for the structure, a mask that punched holes via hard masking\n where noise scaling was needed, over-sampling passed as `over_sample_size_lp` instead of\n `over_sample_size_pixelization`, and VRAM exhaustion masquerading as a hung fit.\n- **Contaminating neighbours modelled rather than scaled** →\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- **Make the fit robust and fast by starting simple** → the search-chaining skill\n (`ag_chain_searches`). This is the biggest available win for a pixelization: fit a parametric\n model first, pass its bulge as priors, and let the expensive model start from a sensible place.\n The workspace recommends it explicitly.\n- **A non-parametric shape measurement instead of a reconstruction** →\n [`ag_ellipse_fitting`](./ag_ellipse_fitting.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording the mesh and its\nshape, the regularization scheme and why, the mask radius, the hardware path, and what the\nreconstruction showed — with a pixelization the choices *are* the result, and none of them are\nrecoverable from the output folder alone.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Bayesian regularization](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb):\n why a model with hundreds of free flux values does not simply over-fit, derived from scratch;\n `tutorial_6_model_fit` then runs the full fit.\n- **General reference** — [RTD: Pixelization API](https://pyautogalaxy.readthedocs.io/en/latest/api/pixelization.html):\n every mesh, regularization scheme and the objects that combine them.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n the hybrid fit end to end, with the run-time, VRAM and GPU-versus-CPU discussion in full.\n\n## Agent procedural checklist\n\n1. Look at the residual map of a parametric or basis fit first. Shape-following residuals mean\n `ag_basis_profiles`; discrete off-centre lumps mean a pixelization. Do not skip this.\n2. Confirm the structure is resolved — at coarse pixel scales a pixelization reconstructs noise.\n3. Always pair the pixelization with a linear light profile for the smooth component; never let\n the mesh reconstruct the bulge.\n4. Fix `mesh_shape` before composing the model; it cannot be a free parameter.\n5. Pass over-sampling as `over_sample_size_pixelization`, not `over_sample_size_lp`.\n6. Start with `RectangularBilinearAdaptDensity` + `ag.reg.Constant`; move to `GaussianKernel` only when\n one smoothing strength demonstrably cannot serve both the bright and faint structure.\n7. Scale contaminant noise (`apply_noise_scaling`, `invert=True`) — never hard-mask pixels inside\n a pixelization fit — and check the signal-to-noise panel afterwards.\n8. `print(model.info)`, evaluate one likelihood, then `print_vram_use` before any GPU run; keep\n `n_batch` low.\n9. Read the reconstruction via `inversion.reconstruction` +\n `mapper.mesh_geometry.mesh_grid`; export to CSV for anything downstream.\n10. Save the script to `scripts/`, quote every plot's absolute path and offer to open it, then\n offer the `wiki/project/` entry recording mesh, regularization and hardware choices.\n" - } - }, - "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file diff --git a/scripts/chapter_3_pixelizations/README.md b/scripts/chapter_3_pixelizations/README.md index 8e4fd2c..d45eaf7 100644 --- a/scripts/chapter_3_pixelizations/README.md +++ b/scripts/chapter_3_pixelizations/README.md @@ -1,17 +1,25 @@ -In chapter 3, we use **Pixelizations** to reconstruct the light of complex galaxies on pixelized grids. +Look at a resolved galaxy image. Its broad light distribution may follow a smooth bulge and disc, while smaller regions contain bright star-forming knots, off-centre clumps or irregular extensions. A model can capture the overall galaxy yet leave these features clearly visible in the residual image. -**Colab** links to every tutorial are included. +In Chapter 2, we introduced linear light profiles and multi-Gaussian expansions (MGEs). Combining Gaussians of different widths gives us a more flexible radial brightness distribution than a single Sérsic profile. Gaussian groups with different ellipticities and orientations can also describe changes in flattening and isophotal twists. Fixed widths and linearly solved intensities provide this flexibility without introducing a large number of non-linear parameters. -# Files +Our worked example nevertheless imposed a particular geometry: the Gaussians within each galaxy’s group shared a common centre and elliptical shape. Adding more Gaussians improves our control over the brightness distribution around that centre, but does not create independently positioned knots or several components with distinct centres. + +We could introduce offset Gaussian groups. The limitation is not that MGEs cannot represent multiple centres, but that increasingly complicated galaxies require us to choose and fit an increasingly elaborate arrangement of components. + +Suppose the MGE reproduces the smooth galaxy light but leaves compact, structured residuals. These may indicate that the model needs more freedom to describe local features. They are not automatically evidence for additional galaxy components: an inaccurate PSF, background estimate, contaminating object or other data-treatment error can also leave structured residuals. -- [Tutorial 1: Pixelizations](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb) — Creating a pixel-grid to reconstruct a galaxy's light. +In this chapter, we introduce pixelized reconstruction as another way to describe the galaxy’s light. We infer brightness values across a mesh without assigning a separate analytic centre and shape to every feature. The predicted image includes telescope blurring, so the reconstruction is an inferred description of the galaxy rather than simply a copy of the observed pixels. -- [Tutorial 2: Mappers](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_3_pixelizations/tutorial_2_mappers.ipynb) — How a pixelization maps its pixels to image-pixels. +This builds on the linear profiles of Chapter 2. Instead of solving for Gaussian intensities, we solve for the mesh brightness values. Their extra freedom can describe irregular structure, but can also fit noise. Regularization supplies a prior that controls variations between neighbouring brightness values. -- [Tutorial 3: Inversions](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb) — Inverting the mappings to reconstruct the galaxy's light. +The reconstruction still depends on modelling choices, including the mesh, its resolution, regularization and the treatment of the data. We will learn to inspect how those choices affect both the reconstructed galaxy and the image residuals. + +MGE and other analytic profiles remain useful for describing and measuring smooth galaxy components. Pixelizations complement them when more complicated structure needs to be represented, including in models that combine analytic components with a pixelized reconstruction. + +# Files -- [Tutorial 4: Bayesian Regularization](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb) — Smoothing the reconstruction within a Bayesian framework. +- [Tutorial 1: Pixelizations](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb) — Meshes, indexed mappings, inversions and telescope blurring. -- [Tutorial 5: Bayesian Formalism](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb) — The linear algebra and Bayesian evidence equations behind pixelized galaxy reconstruction. +- [Tutorial 2: Bayesian Regularization](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_2_bayesian_regularization.ipynb) — Interpolation, smoothness priors, evidence and resolution experiments. -- [Tutorial 6: Model Fit](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_3_pixelizations/tutorial_6_model_fit.ipynb) — An example modeling pipeline which uses an inversion. +- [Tutorial 3: Model Fit](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_model_fit.ipynb) — An MGE fit followed by a combined MGE and pixelized model. diff --git a/scripts/chapter_3_pixelizations/introduction b/scripts/chapter_3_pixelizations/introduction index fc990be..953e1d7 100755 --- a/scripts/chapter_3_pixelizations/introduction +++ b/scripts/chapter_3_pixelizations/introduction @@ -1,25 +1,17 @@ -So, we've learnt how to model galaxies with light profiles, and how search chaining (introduced at the end of -chapter 2, tutorials 9-10) lets us fit galaxies made of multiple components in stages. +Look at a resolved galaxy image. Its broad light distribution may follow a smooth bulge and disc, while smaller regions contain bright star-forming knots, off-centre clumps or irregular extensions. A model can capture the overall galaxy yet leave these features clearly visible in the residual image. -However, we saw a pretty huge barrier when trying to fit very complex galaxies: they require an unwieldy number -of non-linear parameters. The non-linear parameter space becomes very complex, and even a well crafted chain of -searches may not fix the problem. +In Chapter 2, we introduced linear light profiles and multi-Gaussian expansions (MGEs). Combining Gaussians of different widths gives us a more flexible radial brightness distribution than a single Sérsic profile. Gaussian groups with different ellipticities and orientations can also describe changes in flattening and isophotal twists. Fixed widths and linearly solved intensities provide this flexibility without introducing a large number of non-linear parameters. -In this chapter, we'll learn about pixelizations and inversions. These tools allow us to reconstruct components of a -galaxy using a pixel-grid. This makes no assumption about the galaxy's morphology, breaking the simplifying assumptions -inherent to analytic light profiles (e.g. symmetry). +Our worked example nevertheless imposed a particular geometry: the Gaussians within each galaxy’s group shared a common centre and elliptical shape. Adding more Gaussians improves our control over the brightness distribution around that centre, but does not create independently positioned knots or several components with distinct centres. -Remarkably, pixel grids use just a couple of non-linear parameters, meaning the 20+ non-linear parameters we required -to fit complex galaxy structures before are going to be reduced to just 2 or 3! +We could introduce offset Gaussian groups. The limitation is not that MGEs cannot represent multiple centres, but that increasingly complicated galaxies require us to choose and fit an increasingly elaborate arrangement of components. -By combining these fits with parametric models, we are therefore able to fit certain structures (e.g. a bulge and disk) -whilst using these non-parametric pixelizations to fit other components that may otherwise degrade the fit. +Suppose the MGE reproduces the smooth galaxy light but leaves compact, structured residuals. These may indicate that the model needs more freedom to describe local features. They are not automatically evidence for additional galaxy components: an inaccurate PSF, background estimate, contaminating object or other data-treatment error can also leave structured residuals. -In particular, you'll learn how we: +In this chapter, we introduce pixelized reconstruction as another way to describe the galaxy’s light. We infer brightness values across a mesh without assigning a separate analytic centre and shape to every feature. The predicted image includes telescope blurring, so the reconstruction is an inferred description of the galaxy rather than simply a copy of the observed pixels. -1) Pixelize a galaxy's image into a set of pixels that define mappings to image pixels. -2) Invert this pixelization to fit the galaxy and thus reconstruct its light. -3) Apply a smoothness prior on the galaxy reconstruction, called 'regularization', to ensure the solution is physical. -4) Apply this prior in a Bayesian framework to objectively quantify the galaxy reconstruction's log likelihood. -5) Write down the linear algebra and Bayesian evidence equations that underpin all of the above. -6) Use these features in a PyAutoGalaxy modeling pipeline. +This builds on the linear profiles of Chapter 2. Instead of solving for Gaussian intensities, we solve for the mesh brightness values. Their extra freedom can describe irregular structure, but can also fit noise. Regularization supplies a prior that controls variations between neighbouring brightness values. + +The reconstruction still depends on modelling choices, including the mesh, its resolution, regularization and the treatment of the data. We will learn to inspect how those choices affect both the reconstructed galaxy and the image residuals. + +MGE and other analytic profiles remain useful for describing and measuring smooth galaxy components. Pixelizations complement them when more complicated structure needs to be represented, including in models that combine analytic components with a pixelized reconstruction. diff --git a/scripts/chapter_3_pixelizations/tutorial_1_pixelizations.py b/scripts/chapter_3_pixelizations/tutorial_1_pixelizations.py index ee26688..5f8bbdf 100644 --- a/scripts/chapter_3_pixelizations/tutorial_1_pixelizations.py +++ b/scripts/chapter_3_pixelizations/tutorial_1_pixelizations.py @@ -1,142 +1,239 @@ """ -Tutorial 1: Pixelizations -========================= +Tutorial 1: Pixelizations, Mappers and Inversions +================================================= -In the previous chapters, we used light profiles to model the light of a galaxy, where the light profile was an -analytic description of how the luminosity varies as a function of radius. +Look at a resolved galaxy image. Its broad light distribution may follow a smooth bulge and disc, while smaller regions contain bright star-forming knots, off-centre clumps or irregular extensions. A model can capture the overall galaxy yet leave these features clearly visible in the residual image. -In this chapter, we are instead going to reconstruct the galaxy's light on a pixel-grid, and in this tutorial we will -learn how to create a pixelization in **PyAutoGalaxy**. +In Chapter 2, we introduced linear light profiles and multi-Gaussian expansions (MGEs). Combining Gaussians of different widths gives us a more flexible radial brightness distribution than a single Sérsic profile. Gaussian groups with different ellipticities and orientations can also describe changes in flattening and isophotal twists. Fixed widths and linearly solved intensities provide this flexibility without introducing a large number of non-linear parameters. -__Contents__ +Our worked example nevertheless imposed a particular geometry: the Gaussians within each galaxy’s group shared a common centre and elliptical shape. Adding more Gaussians improves our control over the brightness distribution around that centre, but does not create independently positioned knots or several components with distinct centres. -- **Initial Setup:** Create a grid for illustration. -- **Mesh:** Set up a rectangular mesh for the pixelization. -- **Wrap Up:** Summary of pixelization concepts. -""" +We could introduce offset Gaussian groups. The limitation is not that MGEs cannot represent multiple centres, but that increasingly complicated galaxies require us to choose and fit an increasingly elaborate arrangement of components. -# from autogalaxy import setup_notebook; setup_notebook() +Suppose the MGE reproduces the smooth galaxy light but leaves compact, structured residuals. These may indicate that the model needs more freedom to describe local features. They are not automatically evidence for additional galaxy components: an inaccurate PSF, background estimate, contaminating object or other data-treatment error can also leave structured residuals. -import autogalaxy as ag -import autogalaxy.plot as aplt -from autoarray.inversion.plot.mapper_plots import plot_mapper +In this chapter, we introduce pixelized reconstruction as another way to describe the galaxy’s light. We infer brightness values across a mesh without assigning a separate analytic centre and shape to every feature. The predicted image includes telescope blurring, so the reconstruction is an inferred description of the galaxy rather than simply a copy of the observed pixels. -""" -__Initial Setup__ +This builds on the linear profiles of Chapter 2. Instead of solving for Gaussian intensities, we solve for the mesh brightness values. Their extra freedom can describe irregular structure, but can also fit noise. Regularization supplies a prior that controls variations between neighbouring brightness values. -Lets setup a grid. -""" -grid = ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.05) +The reconstruction still depends on modelling choices, including the mesh, its resolution, regularization and the treatment of the data. We will learn to inspect how those choices affect both the reconstructed galaxy and the image residuals. -""" -__Mesh__ +MGE and other analytic profiles remain useful for describing and measuring smooth galaxy components. Pixelizations complement them when more complicated structure needs to be represented, including in models that combine analytic components with a pixelized reconstruction. -Next, lets set up a `Mesh` using the `mesh` module. The mesh represents the pixel-grid used by the pixelization -to reconstruct the galaxy. +We will build the connection between image coordinates, mesh indexes, reconstructed brightnesses and the model +image. Our worked dataset is deliberately a simple smooth bulge and disc: it makes these ingredients easy to see +before applying them to more complicated galaxy structure. -There are multiple `Mesh`'s available in **PyAutoGalaxy**. For now, we'll keep it simple and use a rectangular -grid, whose `shape` defines its $(y,x)$ dimensions. We will make it the same shape as the 2D grid. +__Contents__ -The `RectangularBilinearAdaptDensity` mesh adapts its pixels to the density of the masked image-plane -grid via the ray-guided transformed uniform (RTU) grid formulation of Enzi et al. (2026) -(https://arxiv.org/abs/2606.30620), which should be cited in published work using this mesh. -Note that whereas that paper pairs the RTU grid with a Gaussian-process prior, **PyAutoGalaxy** -instead uses its own regularization schemes, introduced later in this chapter. +- **The image and its coordinates:** Load and mask the data. +- **A brightness mesh:** Distinguish image indexes from mesh indexes. +- **Following the mappings:** Highlight which image pixels receive each mesh contribution. +- **An inversion:** Infer brightnesses, accounting for noise and telescope blurring. +- **A model image:** Inspect the reconstruction and residuals separately. +- **Using FitImaging:** Put these ingredients into a galaxy model. """ -mesh = ag.mesh.RectangularBilinearAdaptDensity(shape=(100, 100)) """ -We now pass the mesh to a `Pixelization`. +__The image and its coordinates__ + +The simulator supplies a Sérsic bulge and exponential disc. The circular mask selects the image pixels used in the +fit. We use one sample per image pixel for the indexed illustrations; accurate scientific modelling should also +check image integration. Each unmasked pixel has a position and a flattened index. These indexes describe the data, +not the separate mesh we are about to construct. """ -pixelization = ag.Pixelization(mesh=mesh) +from pathlib import Path +import subprocess +import sys +import numpy as np +import autogalaxy as ag +import autogalaxy.plot as aplt +import autoarray.plot as aaplt + +dataset_path = Path("dataset") / "imaging" / "simple" +if ag.util.dataset.should_simulate(str(dataset_path)): + subprocess.run([sys.executable, "scripts/simulators/simple.py"], check=True) +dataset = ag.Imaging.from_fits( + data_path=dataset_path / "data.fits", + noise_map_path=dataset_path / "noise_map.fits", + psf_path=dataset_path / "psf.fits", + pixel_scales=0.1, +) +mask = ag.Mask2D.circular( + shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.0 +) +dataset = dataset.apply_mask(mask=mask) +dataset = dataset.apply_over_sampling(over_sample_size_pixelization=1) +# Keep the smoke-test mesh smaller than its deliberately capped image. +mesh_pixels = min(25, min(dataset.shape_native) // 2) +mesh_shape = (mesh_pixels, mesh_pixels) +aplt.subplot_imaging_dataset(dataset=dataset) """ -By itself, a pixelization does not tell us much. It has no grid of $(y,x)$ coordinates, no image, and no information -about the galaxy we are fitting. +__A brightness mesh__ + +Our rectangular mesh covers the observed galaxy. There is no ray tracing: image coordinates and reconstructed +coordinates refer to the same sky. The shared mapper API nevertheless calls its reconstruction coordinates +`source_plane_data_grid` and `source_plane_mesh_grid`. + +`RectangularUniform` places brightness values at regularly spaced points. An image coordinate usually falls between +four mesh points, so bilinear interpolation combines their values with position-dependent weights. An image pixel +falling inside a rectangular cell does not simply take all its brightness from one mesh point. -This information comes when we use the pixelization to create a `Mapper`, which we perform below using the grid -that we created above. +Let's select small groups of image pixels near two different positions. Coordinate-based selection keeps this +illustration meaningful even when a quick smoke run uses a smaller dataset. """ + +image_grid = dataset.grids.pixelization +image_coordinates = np.asarray(image_grid) +indexes = [ + np.argsort(np.sum((image_coordinates - position) ** 2, axis=1))[:5].tolist() + for position in [(0.0, 0.5), (0.0, -0.5)] +] +aaplt.plot_grid( + grid=image_grid, indexes=indexes, title="Selected Image-Pixel Coordinates" +) +mesh = ag.mesh.RectangularUniform(shape=mesh_shape) interpolator = mesh.interpolator_from( - source_plane_data_grid=grid, source_plane_mesh_grid=None + source_plane_data_grid=image_grid, source_plane_mesh_grid=None ) +mapper = ag.Mapper( + interpolator=interpolator, regularization=ag.reg.Constant(coefficient=1.0) +) +image_index = indexes[0][0] +weights = np.asarray(mapper.mapping_matrix[image_index]) +mesh_indexes = np.flatnonzero(np.abs(weights) > 1.0e-12) +aaplt.plot_grid( + grid=mapper.source_plane_mesh_grid, + indexes=[mesh_indexes.tolist()], + title=f"Mesh Points Contributing to Image Pixel {image_index}", +) +print("Image position:", image_coordinates[image_index]) +for mesh_index in mesh_indexes: + print( + f"Mesh index {mesh_index}: position={np.asarray(mapper.source_plane_mesh_grid[mesh_index])}, weight={weights[mesh_index]:.4f}" + ) -mapper = ag.Mapper(interpolator=interpolator) - -""" -This `Mapper` is a `RectangularMapper` -- every `Mesh` and `Pixelization` generates its own mapper. """ -print(type(mapper)) +__Following the mappings__ +An image-pixel index and mesh index refer to different things. The mapper stores the relationship between them. +We can follow it in the opposite direction: select mesh points and find the image pixels receiving a contribution. + +Matching colours identify the selected mesh groups and their associated image regions. These are interpolation +contributions, rather than a strict claim that every image coordinate lies inside a coloured cell. Nearby mesh +values can contribute to the same image pixel; that overlap is part of interpolation. + +First inspect one mesh point near the centre, then compare a pair of nearby points with an offset point. Try moving +the offset position and watch which image pixels change colour. """ -By plotting our mapper, we now see our `Pixelization`. Its a fairly boring grid of rectangular pixels. -""" -plot_mapper( + +mesh_coordinates = np.asarray(mapper.source_plane_mesh_grid) +central_index = int(np.argmin(np.sum(mesh_coordinates**2, axis=1))) +pix_indexes = [[central_index]] +mappings = mapper.mappings_from(pix_indexes=pix_indexes) +aaplt.subplot_image_and_mapper( + mapper=mapper, + image=dataset.data, + regions=mappings, + region_labels=[str(central_index)], + mesh_grid=mapper.source_plane_mesh_grid, +) +nearby_indexes = np.argsort( + np.sum((mesh_coordinates - mesh_coordinates[central_index]) ** 2, axis=1) +)[:2].tolist() +offset_index = int( + np.argmin(np.sum((mesh_coordinates - np.array([0.3, 0.3])) ** 2, axis=1)) +) +pix_indexes = [nearby_indexes, [offset_index]] +mappings = mapper.mappings_from(pix_indexes=pix_indexes) +aaplt.subplot_image_and_mapper( mapper=mapper, - title="Fairly Boring Grid2D of RectangularBilinearAdaptDensity Pixels", + image=dataset.data, + regions=mappings, + region_labels=[str(group) for group in pix_indexes], + mesh_grid=mapper.source_plane_mesh_grid, ) """ -However, the `Mapper` does contain lots of interesting information about our `Pixelization`, for example its -pixelization_grid tells us where the pixel centers are located. -""" -print("RectangularBilinearAdaptDensity Grid2D Pixel Centre 1:") -print(mapper.source_plane_mesh_grid[0]) -print("RectangularBilinearAdaptDensity Grid2D Pixel Centre 2:") -print(mapper.source_plane_mesh_grid[1]) -print("RectangularBilinearAdaptDensity Grid2D Pixel Centre 3:") -print(mapper.source_plane_mesh_grid[2]) -print("etc.") +__An inversion__ +The mapper tells us how brightness would contribute to the image, but has not yet determined those brightnesses. +An inversion combines the mappings with the observed data, noise and PSF to infer the mesh values together. +Like the Gaussian intensities in Chapter 2, these values enter the predicted image linearly. Linear algebra handles +this large set of brightnesses without giving a non-linear search a free parameter for every mesh point. + +We also supplied `Constant` regularization with coefficient `1.0`. This smoothness prior discourages unsupported +variations between neighbours. The next tutorial explores why it is needed and how to choose its strength. + +Here there is only one mapper, so entry `j` in the reconstruction belongs to mesh index `j`. These values are jointly +inferred: interpolation and telescope blurring couple their effects on the image, while regularization couples +neighbouring brightnesses. They are not independent measurements of the selected coloured regions. """ -We can plot these centre on our grid, to make it look slightly less boring! -""" -plot_mapper( + +inversion = ag.Inversion(dataset=dataset, linear_obj_list=[mapper]) +reconstruction = np.asarray(inversion.reconstruction) +for group in pix_indexes: + for mesh_index in group: + print( + f"Mesh index {mesh_index}: reconstructed brightness={reconstruction[mesh_index]:.6g}" + ) +aaplt.plot_mapper( mapper=mapper, + solution_vector=reconstruction, mesh_grid=mapper.source_plane_mesh_grid, - title="Rectangular Grid With Pixel Centres", + regions=[mapping.source_contours for mapping in mappings], + region_labels=[str(group) for group in pix_indexes], + title="Reconstructed Galaxy and Selected Mesh Indexes", ) """ -The `Mapper` also has the grid that we passed when we set it up. Lets check they`re the same. -""" -print("Source Grid2D Pixel 1") -print(grid[0]) -print(mapper.source_plane_data_grid[0]) -print("Source Grid2D Pixel 2") -print(grid[1]) -print(mapper.source_plane_data_grid[1]) -print("etc.") +__A model image__ +The brightness reconstruction lives on the mesh. Mapping it onto the image grid and convolving with the PSF produces +the model image that we compare to the observations. Telescope blurring is already included in the inversion's solve; +it is not an extra correction applied after fitting an unblurred model to blurred data. + +The next figures distinguish the unblurred prediction, blurred model and residuals. A compact reconstructed feature +can be less distinct in the observed image because the PSF spreads its light. Inspect coherent residuals as well as +the reconstruction: a plausible-looking galaxy does not establish that the model explains the data. """ -We can over-lay this grid on the figure, which is starting to look a bit less boring now! -""" -plot_mapper( - mapper=mapper, - mesh_grid=mapper.source_plane_data_grid, - title="Even less Boring Grid2D of RectangularBilinearAdaptDensity Pixels", -) -plot_mapper( - mapper=mapper, - mesh_grid=mapper.source_plane_data_grid, - title="Zoomed Grid2D of RectangularBilinearAdaptDensity Pixels", +image_before_blurring = inversion.mapped_reconstructed_data +model_image = inversion.mapped_reconstructed_operated_data +residual_map = dataset.data - model_image +aplt.plot_array( + array=image_before_blurring, title="Reconstructed Image Before Telescope Blurring" +) +aplt.plot_array(array=model_image, title="Model Image Including Telescope Blurring") +aplt.plot_array(array=residual_map, title="Residuals: Data Minus Model") +aplt.plot_array( + array=residual_map / dataset.noise_map, title="Residuals Divided by the Noise" ) """ -Finally, the mapper`s `mesh_grid` has lots of information about the pixelization, for example, the arc-second -size and dimensions. +__Using FitImaging__ + +We exposed the mapper and inversion to understand what they do. In everyday modelling, put a `Pixelization` in a +`Galaxy` and let `FitImaging` construct these ingredients. This evaluates a specified model; it is not a non-linear +search. The reconstruction still depends on the mesh, resolution, regularization and data treatment. + +**🤖 Ask AI:** Why is a reconstructed brightness on the mesh different from a measured image-pixel value, even though +we are modelling a directly observed galaxy without lensing? """ -print(mapper.source_plane_mesh_grid.geometry.shape_native_scaled) -print(mapper.source_plane_mesh_grid.geometry.scaled_maxima) -print(mapper.source_plane_mesh_grid.geometry.scaled_minima) + +pixelization = ag.Pixelization( + mesh=ag.mesh.RectangularUniform(shape=mesh_shape), + regularization=ag.reg.Constant(coefficient=1.0), +) +galaxy = ag.Galaxy(redshift=0.5, pixelization=pixelization) +fit = ag.FitImaging(dataset=dataset, galaxies=ag.Galaxies(galaxies=[galaxy])) +aplt.subplot_fit_imaging(fit=fit) """ __Wrap Up__ -This was a relatively gentle overview of pixelizations, but one that was hopefully easy to follow. Think about the -following questions before moving on to the next tutorial: - - 1) The rectangular pixelization`s edges are aligned with the most exterior coordinates of the grid it was created - from. This is intentional, why do you think this is? +A mesh supplies brightness values, a mapper connects them to image coordinates, and an inversion infers them while +accounting for noise, telescope blurring and regularization. Next we investigate that regularization: a close image +fit alone does not tell us whether the inferred structure is trustworthy. """ diff --git a/scripts/chapter_3_pixelizations/tutorial_2_bayesian_regularization.py b/scripts/chapter_3_pixelizations/tutorial_2_bayesian_regularization.py new file mode 100644 index 0000000..d4be4f1 --- /dev/null +++ b/scripts/chapter_3_pixelizations/tutorial_2_bayesian_regularization.py @@ -0,0 +1,577 @@ +""" +Tutorial 2: Bayesian Regularization +================================== + +__Contents__ + +- Interpolation and our starting reconstruction. +- Reducing and increasing regularization. +- Bayesian evidence and a coefficient experiment. +- Inspecting the preferred reconstruction. +- Linear brightnesses and non-linear model choices. +- Comparing mesh resolutions. +""" + +""" +__Interpolation and Bayesian regularization__ + +So far, we have: + +- Used pixelizations and mappers to connect mesh points to image pixels. +- Used an inversion to reconstruct the galaxy’s brightness. +- Mapped that reconstruction back into the image, including telescope blurring, to compare it with the data. + +Our explanation of how an inversion works has deliberately left some things unexplained. In particular, you will have +noticed the regularization input that we passed when creating our pixelization. We used a coefficient of `1.0`, but have +not established why that value should give an appropriate reconstruction. + +This tutorial explores what regularization does and why we need it. We will change its strength, inspect the resulting +galaxy reconstructions, and see why obtaining a close fit to the image is not enough on its own. + +First, we will revisit interpolation. It is easy to confuse interpolation with smoothing, because both affect the +appearance of the reconstructed galaxy. Understanding the distinction will help us interpret the experiments that +follow. + +We use the same smooth bulge and disc dataset as tutorial 1. The mesh and data treatment remain fixed, so the first +experiments isolate our regularization choices.""" +from pathlib import Path +import subprocess +import sys +import numpy as np +import autogalaxy as ag +import autogalaxy.plot as aplt +import autoarray.plot as aaplt + +dataset_path = Path("dataset") / "imaging" / "simple" +if ag.util.dataset.should_simulate(str(dataset_path)): + subprocess.run([sys.executable, "scripts/simulators/simple.py"], check=True) +dataset = ag.Imaging.from_fits( + data_path=dataset_path / "data.fits", + noise_map_path=dataset_path / "noise_map.fits", + psf_path=dataset_path / "psf.fits", + pixel_scales=0.1, +) +mask = ag.Mask2D.circular( + shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.0 +) +dataset = dataset.apply_mask(mask=mask) +dataset = dataset.apply_over_sampling(over_sample_size_pixelization=1) +# Keep the smoke-test mesh smaller than its deliberately capped image. +mesh_pixels = min(25, min(dataset.shape_native) // 2) +mesh_shape = (mesh_pixels, mesh_pixels) +aplt.subplot_imaging_dataset(dataset=dataset) + +""" +The single sample per image pixel keeps the indexed mapping example straightforward. For scientific modelling, we would also check that our image sampling is sufficiently accurate. + +__Interpolation and our starting reconstruction__ + +Let’s look at our reconstruction from the previous tutorial in more detail. + +The `RectangularUniform` mesh describes the galaxy using brightness values at regularly spaced points. An image +coordinate generally falls between these points. Its predicted brightness is obtained by combining the four surrounding +values, with weights determined by its position. This is bilinear interpolation. + +Interpolation tells us how to calculate brightness between mesh points, but it does not tell us what those mesh values +should be. Four neighbouring values could be similar, or one could be much brighter than the others. Both can be +interpolated. In the second case, however, the brightness changes much more sharply across the galaxy. + +Regularization influences the brightness values we infer, discouraging variations that are not sufficiently supported by +the data. Interpolation then determines how those values contribute between mesh points. + +We are going to evaluate several reconstructions, so the function below keeps their common setup in one place. Only the +regularization coefficient changes.""" +mesh_shape = (mesh_pixels, mesh_pixels) + + +def fit_with_coefficient(coefficient): + pixelization = ag.Pixelization( + mesh=ag.mesh.RectangularUniform(shape=mesh_shape), + regularization=ag.reg.Constant(coefficient=coefficient), + ) + + galaxy = ag.Galaxy( + redshift=0.5, + pixelization=pixelization, + ) + + galaxies = ag.Galaxies(galaxies=[galaxy]) + + return ag.FitImaging(dataset=dataset, galaxies=galaxies) + + +fit = fit_with_coefficient(coefficient=1.0) + +aplt.subplot_fit_imaging(fit=fit) + +""" +Here is the interpolation calculation for one image pixel. As in tutorial 1, the mapper supplies the contributing mesh indexes and their weights. This time, we also have reconstructed brightness values, so we can see how the contributions combine. +""" +mapper = fit.inversion.cls_list_from(ag.Mapper)[0] +reconstruction = np.asarray(fit.inversion.reconstruction) + +# Select an image pixel near the right-hand side of the galaxy. +image_coordinates = np.asarray(mapper.image_plane_data_grid) +image_index = int( + np.argmin(np.sum((image_coordinates - np.array([0.0, 0.5])) ** 2, axis=1)) +) + +weights = np.asarray(mapper.mapping_matrix[image_index]) +mesh_indexes = np.flatnonzero(np.abs(weights) > 1.0e-12) + +for mesh_index in mesh_indexes: + brightness = reconstruction[mesh_index] + weight = weights[mesh_index] + print( + f"Mesh index {mesh_index}: " + f"brightness={brightness:.5g}, weight={weight:.5g}, " + f"contribution={brightness * weight:.5g}" + ) + +print( + "Combined brightness before telescope blurring:", + float(np.dot(weights, reconstruction)), +) + +""" +This is the image prediction before the PSF redistributes light between image pixels. We are inspecting a small part of the calculation, not replacing the inversion’s treatment of telescope blurring. + +__Reducing regularization__ + +Our starting reconstruction uses a regularization coefficient of `1.0`. Let’s reduce it substantially and examine what +changes. + +We use `0.01` rather than exactly zero, retaining a small smoothness penalty. Keep the mesh and data unchanged: we want +to isolate the effect of weakening regularization.""" +weak_regularization_fit = fit_with_coefficient(coefficient=0.01) + +aplt.subplot_fit_imaging(fit=weak_regularization_fit) + +""" +To understand this comparison, we need to look more closely at what regularization actually does. + +When the inversion reconstructs the galaxy, it does not only seek brightness values that reproduce the image. With +`Constant` regularization, it also compares neighbouring brightness values on the rectangular galaxy mesh. Interior mesh +points have four immediate neighbours. Large differences between their brightnesses contribute a larger penalty. + +You can think of this as applying a **smoothness prior** to the reconstructed galaxy. It expresses a preference for +neighbouring regions to have similar brightness, unless the image provides enough evidence for them to differ. + +The penalty depends on squared differences, so positive and negative differences cannot cancel. The coefficient controls +its strength. Reducing that coefficient makes a given amount of variation less costly; increasing it makes the same +variation more costly. + +In the language of linear algebra, this prior contributes a regularization matrix to the system the inversion solves. We +do not need to construct that matrix ourselves to understand its effect. + +Without sufficient regularization, the inversion has greater freedom to fit fluctuations in the observed image, +including noise. Some of those fluctuations can be explained by adding irregular structure to the galaxy. The image fit +may improve even though the inferred galaxy becomes less faithful to the galaxy that produced the data. + +Inspect the weakly regularized reconstruction for isolated bright values or rapid changes between neighbouring points. +Also look at its faint regions, where the image provides less information about the galaxy. + +A few extreme values can dominate the colour scale. We can compare both reconstructions using the starting +reconstruction’s brightness range to see the remaining structure more clearly.""" +galaxy_vmax = float(np.max(np.asarray(fit.inversion.reconstruction))) + +for label, current_fit in [ + ("Starting Reconstruction", fit), + ("Weak Regularization", weak_regularization_fit), +]: + current_mapper = current_fit.inversion.cls_list_from(ag.Mapper)[0] + + aaplt.plot_mapper( + mapper=current_mapper, + solution_vector=current_fit.inversion.reconstruction, + vmin=0.0, + vmax=galaxy_vmax, + zoom_to_brightest=False, + title=label, + ) + +""" +Values above this plotting limit share the highest colour, so use these figures alongside the original plots rather than treating them as the full brightness range. + +The important point is that recovering recognizable galaxy structure does not mean every reconstructed feature is +reliable. Genuine structure and noise-fitting can appear in the same reconstruction. + +__Increasing regularization__ + +Now let’s move in the other direction and use a much larger coefficient. + +With stronger regularization, the inversion pays a greater penalty for differences between neighbouring brightnesses. +This discourages the sharp variations that can fit noise. However, the real galaxy also contains brightness variations: +compact components, bright centres and the changes between those regions and their surroundings. + +Regularization cannot identify which variations are genuine simply by examining the galaxy. The image fit and the prior +must work together. If we make the smoothness preference too strong, the reconstruction can lose genuine structure +because reproducing it carries too large a penalty.""" +strong_regularization_fit = fit_with_coefficient(coefficient=100.0) + +strong_mapper = strong_regularization_fit.inversion.cls_list_from(ag.Mapper)[0] + +aaplt.plot_mapper( + mapper=strong_mapper, + solution_vector=strong_regularization_fit.inversion.reconstruction, + vmin=0.0, + vmax=galaxy_vmax, + zoom_to_brightest=False, + title="Strong Regularization", +) + +aplt.subplot_fit_imaging(fit=strong_regularization_fit) + +""" +Compare the bright components with the starting reconstruction. Look for features becoming flatter or merging together, then inspect the corresponding regions of the image residuals. + +This illustrates the difficulty in choosing a coefficient. Too little smoothing can introduce structure that explains +noise. Too much can remove structure needed to explain the galaxy. Neither the smoothest galaxy nor the closest possible +image fit is automatically the reconstruction we want. + +We can quantify image agreement using chi-squared: the sum of squared residuals divided by their noise variances.""" +fit_comparisons = [ + ("Weak", 0.01, weak_regularization_fit), + ("Starting", 1.0, fit), + ("Strong", 100.0, strong_regularization_fit), +] + +for label, coefficient, current_fit in fit_comparisons: + normalized_residuals = np.asarray( + (dataset.data - current_fit.model_data) / dataset.noise_map + ) + + chi_squared = float(np.sum(normalized_residuals**2)) + print(f"{label}: coefficient={coefficient:g}, chi-squared={chi_squared:.3f}") + +""" +A lower chi-squared means closer agreement with the image under the assumed noise map. It does not distinguish fitting genuine structure from fitting noise. This is why choosing the coefficient solely by image agreement would favour giving the galaxy too much freedom. + +**🤖 Ask AI:** Why might a weakly regularized reconstruction have a lower chi-squared but a less trustworthy galaxy than +a more strongly regularized reconstruction? + +__Bayesian evidence__ + +For inversions, we therefore need more than image agreement to choose an appropriate level of regularization. + +We use the **Bayesian evidence**, which accounts for both the fit to the image and the galaxy prior. It helps us compare +reconstructions that have different amounts of freedom, rather than simply choosing whichever one follows the observed +pixel values most closely. + +There are two useful parts to this intuition. + +First, the reconstruction must explain the image. If strong regularization prevents it from reproducing genuine galaxy +structure, the resulting residuals count against that choice. Preferring a smooth galaxy is not useful if that galaxy +cannot explain the observed galaxy. + +Second, allowing a more flexible galaxy comes at a cost. Weak regularization permits many more patterns of brightness +across neighbouring mesh points. Some of that extra freedom may be needed to describe the galaxy, but some may only help +reproduce the particular noise fluctuations in this image. + +Evidence weighs the improvement in fit against the freedom allowed by the prior. An improvement must be sufficient to +justify that additional flexibility. + +This is also why complexity is not simply the number of mesh points. Our three examples have exactly the same mesh. +Stronger regularization ties neighbouring brightnesses together more closely, reducing their freedom to vary +independently. We can therefore change the effective flexibility of the reconstruction without changing the number of +mesh points. + +Let’s compare the evidence values returned by `FitImaging`.""" +log_evidences = [] + +for label, coefficient, current_fit in fit_comparisons: + log_evidence = float(current_fit.log_evidence) + log_evidences.append(log_evidence) + + print(f"{label}: coefficient={coefficient:g}, " f"log evidence={log_evidence:.3f}") + +best_index = int(np.argmax(log_evidences)) +best_label, best_coefficient, _ = fit_comparisons[best_index] + +print( + f"\nHighest evidence among these examples: " + f"{best_label}, coefficient={best_coefficient:g}" +) + +""" +Compare this ranking with the galaxy plots and the chi-squared values. The highest evidence need not belong to the reconstruction with the lowest chi-squared, because image agreement is only part of the comparison. + +We still need to inspect the residuals ourselves. Evidence does not explicitly examine their spatial pattern or +guarantee that a preferred model is correct. Structured residuals can reveal shortcomings in the galaxy, PSF or other +assumptions that this three-coefficient comparison does not address. + +For now, we have compared only three choices. The starting value of `1.0` has no special status, and the best of these +three is not necessarily the best coefficient overall. Next, we will explore a broader range and see how this choice +fits into the wider modelling process. + + +__Exploring the regularization coefficient__ + +We have compared weak, moderate and strong regularization, but those three values were chosen to illustrate different +behaviours. They do not tell us where the evidence reaches its highest value. + +Let’s explore the coefficient more systematically. We will keep the mesh resolution, mask and noise map fixed, and +reconstruct the galaxy for a sequence of coefficients. + +Regularization coefficients can span several orders of magnitude, so we use logarithmically spaced values. This gives us +comparable coverage between `0.01` and `0.1`, between `0.1` and `1.0`, and so on. + +Every point in this experiment requires a new galaxy reconstruction. We are not taking one reconstructed galaxy and +smoothing it by different amounts afterwards. The coefficient changes the problem that the inversion solves.""" +import matplotlib.pyplot as plt + +coefficient_grid = np.logspace(-2, 2, 13) + +# Reuse the three reconstructions already calculated. +known_fits = { + 0.01: weak_regularization_fit, + 1.0: fit, + 100.0: strong_regularization_fit, +} + +evidence_grid = [] + +for coefficient in coefficient_grid: + coefficient = float(coefficient) + + if coefficient in known_fits: + current_fit = known_fits[coefficient] + else: + current_fit = fit_with_coefficient(coefficient=coefficient) + + evidence_grid.append(float(current_fit.log_evidence)) + +evidence_grid = np.asarray(evidence_grid) + +if not np.all(np.isfinite(evidence_grid)): + raise ValueError( + "Some evidence values are not finite. Inspect those fits before comparing." + ) + +fig, ax = plt.subplots() +ax.semilogx( + coefficient_grid, + evidence_grid - np.max(evidence_grid), + marker="o", +) +ax.set_xlabel("Regularization coefficient") +ax.set_ylabel("Log evidence relative to the highest sampled value") +ax.set_title("Choosing the Strength of Regularization") +plt.show() + +""" +Look for the part of the curve where the evidence is highest. Moving towards weaker regularization gives the galaxy more freedom; moving towards stronger regularization increasingly restricts its variations. + +We may find a clear peak, a broad region with similar evidence, or a highest value at one end of the range. These +outcomes mean different things. A boundary maximum tells us that this experiment has not bracketed the preferred +coefficient—we should extend the range before claiming to have located it. + +The plotted points are also discrete samples. Even an interior maximum only identifies the best coefficient we have +tried so far. + +__Inspecting the preferred reconstruction__ + +Let’s inspect the reconstruction with the highest evidence in our sampled range. + +It is tempting to treat the highest number as the end of the analysis. However, we should connect that number back to +the galaxy and image. We want to understand what this choice preserves, what it smooths away, and what the resulting +model still fails to explain. + +Compare it with the weakly and strongly regularized examples. In particular, examine the bright central regions and the +fainter outer light. Then look at the image residuals near those components.""" +best_index = int(np.argmax(evidence_grid)) +preferred_coefficient = float(coefficient_grid[best_index]) + +if preferred_coefficient in known_fits: + preferred_fit = known_fits[preferred_coefficient] +else: + preferred_fit = fit_with_coefficient(coefficient=preferred_coefficient) + +print("Preferred sampled coefficient:", preferred_coefficient) + +if best_index in (0, len(coefficient_grid) - 1): + print( + "The highest evidence lies at the boundary. " + "Extend the coefficient range before interpreting this as a peak." + ) + +preferred_mapper = preferred_fit.inversion.cls_list_from(ag.Mapper)[0] + +aaplt.plot_mapper( + mapper=preferred_mapper, + solution_vector=preferred_fit.inversion.reconstruction, + zoom_to_brightest=False, + title="Galaxy at the Preferred Sampled Coefficient", +) + +aplt.subplot_fit_imaging(fit=preferred_fit) + +""" +A preferred coefficient does not establish that every visible feature in the galaxy is real. The reconstruction remains conditional on the galaxy mesh, noise map and telescope blurring. + +Nor does a good-looking galaxy excuse coherent residuals in the image. The galaxy and residual plots provide +complementary information: one shows what we inferred, while the other shows what that inference leaves unexplained. + +**🤖 Ask AI:** If the evidence prefers a particular regularization coefficient but the residuals still follow the shape +of the galaxy, what modelling assumptions should I investigate next? + +__What is linear, and what requires a search?__ + +Before going further, let’s separate two parts of the calculation that are easy to confuse. + +For each coefficient we supplied, the inversion solved for the galaxy brightnesses. We did not give a non-linear search +hundreds of independent galaxy brightness parameters and ask it to explore their possible combinations. Instead, the +galaxy enters the predicted image linearly, allowing these brightnesses to be solved together using linear algebra. + +Regularization is included in that solve. The galaxy is not first reconstructed without a prior and then smoothed +afterwards. The inferred brightnesses already reflect the balance between fitting the image and satisfying the +smoothness prior. + +Choosing the regularization coefficient is a different problem. We supplied several coefficients, performed an inversion +for each, and compared their evidence values. Our loop is a simple grid search over one quantity. + +We can see the difference in scale directly:""" +mesh_brightnesses = np.asarray(preferred_fit.inversion.reconstruction) + +print("Number of galaxy mesh values:", preferred_mapper.pixels) +print("Number of reconstructed entries:", mesh_brightnesses.size) +print("Number of coefficients evaluated:", coefficient_grid.size) + +""" +The reconstruction contains an entry for each galaxy mesh point in this single-mapper example. Some values may be constrained to zero at the mesh boundary, and regularization couples neighbouring values, so the number of entries is not the number of independently constrained galaxy features. + +During galaxy modelling, a search can also change the geometry of accompanying analytic profiles. For each proposal, +we calculate their contribution and solve again for the linear brightnesses, including the pixelization. + +The sequence is therefore: + +1. Propose the non-linear parameters, including the regularization coefficient and any analytic-profile geometry. +2. Construct the corresponding image model and mappings. +3. Solve for the linear brightnesses. +4. Evaluate the fit, accounting for the reconstruction prior. + +This makes pixelizations practical: the search explores non-linear choices while the inversion handles the many +brightness values. + +__Mesh resolution and regularization belong together__ + +We have held the galaxy mesh at `(25, 25)` (a smaller mesh in capped smoke runs). The preferred coefficient we found +belongs to that choice of mesh. + +Changing the mesh changes the locations and number of galaxy brightness values, their neighbours, and how they +contribute to the image. The same numerical coefficient therefore need not give an equivalent amount of smoothing on +another mesh. + +This matters when testing resolution. If we increase the number of mesh points but keep the coefficient fixed, any +change in the reconstruction reflects both the new resolution and its interaction with the prior. We cannot assume that +we have made a fair comparison of the best reconstructions available at each resolution. + +Let’s repeat the coefficient experiment for `(15, 15)` and `(35, 35)`, alongside our existing `(25, 25)` results. The +same comparison uses smaller meshes when the dataset is capped for a smoke run. We extend our helper so the mesh shape +is an explicit input.""" + + +def fit_with_coefficient(coefficient, mesh_shape=mesh_shape): + pixelization = ag.Pixelization( + mesh=ag.mesh.RectangularUniform(shape=mesh_shape), + regularization=ag.reg.Constant(coefficient=coefficient), + ) + + galaxy = ag.Galaxy( + redshift=0.5, + pixelization=pixelization, + ) + + galaxies = ag.Galaxies(galaxies=[galaxy]) + + return ag.FitImaging(dataset=dataset, galaxies=galaxies) + + +evidence_by_shape = {mesh_shape: evidence_grid} + +comparison_sizes = [max(4, mesh_pixels - 10), min(35, min(dataset.shape_native) - 4)] +for size in comparison_sizes: + shape = (size, size) + values = [] + + for coefficient in coefficient_grid: + current_fit = fit_with_coefficient( + coefficient=float(coefficient), + mesh_shape=shape, + ) + values.append(float(current_fit.log_evidence)) + + evidence_by_shape[shape] = np.asarray(values) + +if not all(np.all(np.isfinite(values)) for values in evidence_by_shape.values()): + raise ValueError("Inspect non-finite evidence values before comparing meshes.") + +reference_evidence = max(float(np.max(values)) for values in evidence_by_shape.values()) + +fig, ax = plt.subplots() + +for shape, values in sorted(evidence_by_shape.items()): + ax.semilogx( + coefficient_grid, + values - reference_evidence, + marker="o", + label=f"{shape[0]} × {shape[1]}", + ) + +ax.set_xlabel("Regularization coefficient") +ax.set_ylabel("Log evidence relative to the highest sampled value") +ax.set_title("Mesh Resolution and Regularization") +ax.legend() +plt.show() + +""" +This experiment performs 26 additional reconstructions, so it takes longer than our earlier three-way comparison. + +Look at both the locations and heights of the curves’ maxima. The preferred coefficient may shift as the mesh changes. A +finer mesh may help describe galaxy structure, but adding points does not guarantee a higher evidence. + +All three curves use the same image pixels and noise model. We also subtract one common reference evidence, preserving +differences between the meshes. Subtracting each curve’s own maximum would hide those differences. + +As before, a boundary maximum means that the coefficient range needs extending. These are controlled resolution checks, +not a demonstration that mesh dimensions should become free parameters in every galaxy-model search. + +__Wrap Up__ + +We can now give the regularization input a more meaningful interpretation. + +The galaxy mesh supplies brightness values that can vary to explain the image. Interpolation defines the brightness +between those values. Regularization places a prior on their variation, discouraging unnecessary differences between +neighbours. + +Too little regularization can allow the reconstruction to explain noise through spurious galaxy structure. Too much can +suppress real structure and leave it visible in the image residuals. Evidence helps compare these choices by accounting +for both image agreement and the freedom allowed by the galaxy prior. + +We also saw that the coefficient is not a universal setting. Its appropriate value depends on the dataset, mesh and +regularization scheme. A value that works for one reconstruction should not simply be carried into another analysis +without checking it. + +For a final comparison, print the preferred sampled coefficient for each mesh:""" +for shape, values in sorted(evidence_by_shape.items()): + index = int(np.argmax(values)) + coefficient = float(coefficient_grid[index]) + boundary = index in (0, len(coefficient_grid) - 1) + + print( + f"Mesh {shape}: coefficient={coefficient:.4g}, " + f"log evidence={values[index]:.3f}" + + (" — boundary maximum; extend the range" if boundary else "") + ) + +# Retain the original mesh's preferred fit for subsequent inspection. +fit = preferred_fit + +""" +Throughout this tutorial, we evaluated reconstructions of a specified galaxy dataset. In the next tutorial, we use +a non-linear search and combine an MGE with a pixelization through search chaining. + +For readers who want the underlying equations, the workspace's [pixelization likelihood guide](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/pixelization/likelihood_function.py) +follows the mapping, blurring, regularization and evidence calculations step by step. That derivation complements +the experiments here; it is not required to continue using pixelizations. +""" diff --git a/scripts/chapter_3_pixelizations/tutorial_2_mappers.py b/scripts/chapter_3_pixelizations/tutorial_2_mappers.py deleted file mode 100644 index 00848a0..0000000 --- a/scripts/chapter_3_pixelizations/tutorial_2_mappers.py +++ /dev/null @@ -1,197 +0,0 @@ -""" -Tutorial 2: Mappers -=================== - -In the previous tutorial, we used a pixelization to create a `Mapper`. However, it was not clear what a `Mapper` -does, why it was called a mapper and whether it was mapping anything at all! - -Therefore, in this tutorial, we'll cover mappers in more detail. - -__Contents__ - -- **Initial Setup:** Load the dataset for illustration. -- **Dataset Auto-Simulation:** Automatically simulate the dataset if it does not already exist. -- **Mappers:** Understand how mappers map image-plane pixels to pixelization pixels. -- **Mask:** Apply a mask and see how it affects the mapper. -- **Wrap Up:** Summary of mapper concepts. -""" - -# from autogalaxy import setup_notebook; setup_notebook() - -from pathlib import Path -import numpy as np -import autogalaxy as ag -import autogalaxy.plot as aplt -import autoarray.plot as aaplt - -""" -__Initial Setup__ - -we'll use galaxy data, where: - - - The galaxy's bulge is an `Sersic`. - - The galaxy's disk is an `Exponential`. -""" -dataset_name = "simple" -dataset_path = Path("dataset") / "imaging" / dataset_name - -""" -__Dataset Auto-Simulation__ - -If the dataset does not already exist on your system, it will be created by running the corresponding -simulator script. This ensures that all example scripts can be run without manually simulating data first. -""" -if ag.util.dataset.should_simulate(str(dataset_path)): - import subprocess - import sys - - subprocess.run( - [sys.executable, "scripts/simulators/simple.py"], - check=True, - ) - -dataset = ag.Imaging.from_fits( - data_path=dataset_path / "data.fits", - noise_map_path=dataset_path / "noise_map.fits", - psf_path=dataset_path / "psf.fits", - pixel_scales=0.1, -) - -""" -Now, lets set up our `Grid2D` (using the image above). -""" -grid = ag.Grid2D.uniform( - shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales -) - -""" -__Mappers__ - -We now setup a `Pixelization` and use it to create a `Mapper` via the image's grid, just like we did in -the previous tutorial. - -We will make its pixelization resolution half that of the grid above. -""" -mesh = ag.mesh.RectangularBilinearAdaptDensity( - shape=(dataset.shape_native[0] / 2, dataset.shape_native[1] / 2) -) - -pixelization = ag.Pixelization(mesh=mesh) - -interpolator = mesh.interpolator_from( - source_plane_data_grid=grid, source_plane_mesh_grid=None -) - -mapper = ag.Mapper(interpolator=interpolator) - -""" -We now plot the `Mapper` alongside the image we used to generate the grid: the image on the left, and on the right the -rectangular mesh the image-pixel coordinates land on. -""" -aaplt.subplot_image_and_mapper(mapper=mapper, image=dataset.data) - - -""" -That shows us the two grids, but not the thing which links them. A mapper's actual job is to record, for every -pixelization pixel, which image-pixels fall inside it -- and we can ask it for exactly that. - -`mapper.mappings_from` takes a list of pixelization-pixel index *groups* and returns one `Mapping` per group. Each -`Mapping` carries `source_contours` (the outline of the pixelization cell(s) in the group) and `image_contours` (the -outlines of the connected regions of image-pixels which map into it). Both are polygons in arc-seconds, so -`subplot_image_and_mapper` can draw them in matched colours: the cell on the right, the image-pixels it owns on the -left. - -Lets map the pixelization pixels at the centre of the mesh to the image. The mesh above adapts its resolution to the -galaxy's light, so its central cells are far smaller than its outer ones -- a single central cell would be a speck on -the figure. We therefore take the 25 cells closest to the mesh centre as one group, which draws as one visible patch. -""" -mesh_grid = np.asarray(mapper.source_plane_mesh_grid) - -distances = np.hypot(mesh_grid[:, 0], mesh_grid[:, 1]) - -pix_indexes = [np.argsort(distances)[:25]] - -mappings = mapper.mappings_from(pix_indexes=pix_indexes) - -aaplt.subplot_image_and_mapper(mapper=mapper, image=dataset.data, regions=mappings) - -""" -On the right, a red patch of the pixelization. On the left, the same red marks the image-pixels which map into it, -sitting exactly on the galaxy's bright centre. The colour is the statement: these image-pixels and those cells are the -same thing, seen from the two sides of the mapper. - -Notice that the image-plane patch is a little wider than the cells strictly contain. This is because the pairing is -not one-to-one: a bilinear interpolation scheme is used, so an image-pixel which lands just outside a cell is still -paired with it, with a weight. - -Okay, so I think we can agree, mapper's map things! More specifically, they map pixelization pixels to multiple pixels -in the observed image of a galaxy. - -__Mask__ - -Finally, lets repeat the steps that we performed above, but now using a masked image. By applying a `Mask2D`, the -mapper only maps image-pixels that are not removed by the mask. This removes the (many) image pixels at the edge of the -image, where the galaxy is not present. - -Lets just have a quick look at these edges pixels: - -Lets use an circular `Mask2D`, which will capture the central galaxy light and clumps. -""" -mask = ag.Mask2D.circular( - shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.0 -) - -dataset = dataset.apply_mask(mask=mask) -aplt.plot_array(array=dataset.data, title="Data") - -""" -We can now use the masked grid to create a new `Mapper` (using the same rectangular pixelization as before). -""" -interpolator = mesh.interpolator_from( - source_plane_data_grid=dataset.grids.pixelization, source_plane_mesh_grid=None -) -mapper = ag.Mapper(interpolator=interpolator) - -""" -Lets plot it. -""" -aaplt.subplot_image_and_mapper(mapper=mapper, image=dataset.data) - -""" -First, we can see a red circle of dots in both the image and pixelization, showing where the edge of the mask -maps to in the pixelization. - -Now lets show that when we draw pixelization pixels, they still appear in the same place in the image. We take the 100 -cells closest to the mesh centre and split them into four groups of 25, working outwards, so each group is drawn in -its own colour. -""" -mesh_grid = np.asarray(mapper.source_plane_mesh_grid) - -distances = np.hypot(mesh_grid[:, 0], mesh_grid[:, 1]) - -order = np.argsort(distances) - -pix_indexes = [order[index * 25 : (index + 1) * 25] for index in range(4)] - -mappings = mapper.mappings_from(pix_indexes=pix_indexes) - -aaplt.subplot_image_and_mapper(mapper=mapper, image=dataset.data, regions=mappings) - -""" -Four groups, four colours, and each colour appears in exactly one place in the image -- unlike a strong lens, where -the same source region appears in several images, an unlensed galaxy maps one-to-one. Groups which are neighbours in -the pixelization own image-pixels which are neighbours in the image, so the colours nest outwards from the galaxy's -centre in both panels. - -The mask has not moved anything: it has only removed the image-pixels outside it, so the cells beyond the mask's edge -now own nothing at all. - -__Wrap Up__ - -In this tutorial, we learnt about mappers, and we used them to understand how the image and pixelization map to one -another. Your exercises are: - - 1) Think about how this could help us actually model galaxies. We have said we're going to reconstruct our galaxies - on the pixel-grid. So, how does knowing how each pixel maps to the image actually help us? If you`ve not got - any bright ideas, then worry not, that's exactly what we're going to cover in the next tutorial. -""" diff --git a/scripts/chapter_3_pixelizations/tutorial_3_inversions.py b/scripts/chapter_3_pixelizations/tutorial_3_inversions.py deleted file mode 100644 index 2304430..0000000 --- a/scripts/chapter_3_pixelizations/tutorial_3_inversions.py +++ /dev/null @@ -1,233 +0,0 @@ -""" -Tutorial 3: Inversions -====================== - -In the previous two tutorials, we introduced: - - - `Pixelization`'s: which place a pixel-grid over the image data. - - `Mappers`'s: which describe how each pixelization pixel maps to one or more image pixels. - -However, none of this has actually helped us fit galaxy data or reconstruct the galaxy. This is the subject -of this tutorial, where the process of reconstructing the galaxy's light on the pixelization is called an `Inversion`. - -__Contents__ - -- **Initial Setup:** Load the dataset for illustration. -- **Dataset Auto-Simulation:** Automatically simulate the dataset if it does not already exist. -- **Pixelization:** Create a pixelization and perform an inversion to reconstruct the galaxy. -- **Positive Only Solver:** Ensure the reconstruction has only positive intensity values. -- **Detailed Explanation:** Where the linear algebra behind inversions is derived in full. -- **Wrap Up:** Summary of inversion concepts. -""" - -# from autogalaxy import setup_notebook; setup_notebook() - -from pathlib import Path -import autogalaxy as ag -import autogalaxy.plot as aplt -import autoarray.plot as aaplt - -""" -__Initial Setup__ - -we'll use the same galaxy data as the previous tutorial, where: - - - The galaxy's bulge is an `Sersic`. - - The galaxy's disk is an `Exponential`. -""" -dataset_name = "simple" -dataset_path = Path("dataset") / "imaging" / dataset_name - -""" -__Dataset Auto-Simulation__ - -If the dataset does not already exist on your system, it will be created by running the corresponding -simulator script. This ensures that all example scripts can be run without manually simulating data first. -""" -if ag.util.dataset.should_simulate(str(dataset_path)): - import subprocess - import sys - - subprocess.run( - [sys.executable, "scripts/simulators/simple.py"], - check=True, - ) - -dataset = ag.Imaging.from_fits( - data_path=dataset_path / "data.fits", - noise_map_path=dataset_path / "noise_map.fits", - psf_path=dataset_path / "psf.fits", - pixel_scales=0.1, -) - -""" -Lets create a circular mask which contains the galaxy's emission: -""" -mask = ag.Mask2D.circular( - shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.0 -) - -""" -We now create the masked imaging, as we did in the previous tutorial. -""" -dataset = dataset.apply_mask(mask=mask) - -aplt.plot_array(array=dataset.data, title="Data") - -""" -we again use the rectangular pixelization to create the mapper. - -(Ignore the regularization input below for now, we will cover this in the next tutorial). -""" -mesh = ag.mesh.RectangularBilinearAdaptDensity(shape=(25, 25)) - -pixelization = ag.Pixelization(mesh=mesh) - -interpolator = mesh.interpolator_from( - source_plane_data_grid=dataset.grids.pixelization, - source_plane_mesh_grid=None, -) - -mapper = ag.Mapper( - interpolator=interpolator, - regularization=ag.reg.Constant(coefficient=1.0), -) - -aaplt.subplot_image_and_mapper(mapper=mapper, image=dataset.data) - -""" -__Pixelization__ - -Finally, we can now use the `Mapper` to reconstruct the galaxy via an `Inversion`. I'll explain how this works in a -second, but lets just go ahead and create the inversion first. -""" -inversion = ag.Inversion(dataset=dataset, linear_obj_list=[mapper]) - -""" -The inversion has reconstructed the galaxy's light on the rectangular pixel grid, which is called the -`reconstruction`. - -This reconstruction can be mapped back to the same resolution as the image to produce the `mapped_reconstructed_operated_data`. -""" -print(inversion.reconstruction) -print(inversion.mapped_reconstructed_operated_data) - -""" -Both of these can be plotted using `subplot_of_mapper`. - -It is possible for an inversion to have multiple `Mapper`'s, therefore for certain figures we specify the index -of the mapper we wish to plot. In this case, because we only have one mapper we specify the index 0. -""" -aplt.plot_array( - array=inversion.mapped_reconstructed_operated_data, title="Reconstruction" -) -aaplt.subplot_of_mapper(inversion=inversion, mapper_index=0) - -""" -There we have it, we have successfully reconstructed the galaxy using a rectangular pixel-grid, capturing the -structure of its light without assuming an analytic form for it. - -Pretty great, huh? If you fitted this galaxy via search chaining at the end of chapter 2 (tutorials 9-10), you'll -remember how much effort a good model image took. With an inversion, we can do this with ease and without having to -perform model-fitting with 20+ parameters for the galaxy's light! - -We will now briefly discuss how an inversion actually works, however the explanation given in this tutorial will be -overly-simplified. (The full linear algebra -- the mapping matrices, the linear solve and the equations behind -them -- is derived step-by-step in tutorial 5.) To be good at modeling you do not need to understand the details of -how an inversion works, you simply need to be able to use an inversion to model a galaxy. - -To begin, lets consider some random mappings between our mapper`s pixelization pixels and the image. - -`mapper.mappings_from` returns one `Mapping` per group of pixelization pixels, which we pass straight to -`subplot_image_and_mapper` as `regions=`. Each mapping is drawn in its own colour: the pixelization cell on the right, -and the image-pixels which map into it on the left. Tutorial 2 covers this in detail. -""" -pix_indexes = [[min(index, mapper.pixels - 1)] for index in [445, 285, 313, 132, 211]] - -mappings = mapper.mappings_from(pix_indexes=pix_indexes) - -aaplt.subplot_image_and_mapper(mapper=mapper, image=dataset.data, regions=mappings) - -""" -These mappings are known before the inversion reconstructs the galaxy, which means before this inversion is performed -we know two key pieces of information: - - 1) The mappings between every pixelization pixel and a set of image-pixels. - 2) The flux values in every observed image-pixel, which are the values we want to fit successfully. - -It turns out that with these two pieces of information we can linearly solve for the set of pixelization pixel fluxes -that best-fit (e.g. maximize the log likelihood) our observed image. Essentially, we set up the mappings between -pixelization and image pixels as a large matrix and solve for the pixelization pixel fluxes in an analogous fashion to -how you would solve a set of simultaneous linear equations. This process is called a `linear inversion`. - -There are three more things about a linear inversion that are worth knowing: - - 1) When performing fits using light profiles, we discussed how a `model_image` was generated by convolving the light - profile images with the data's PSF. A similar blurring operation is incorporated into the inversion, such that it - reconstructs a galaxy (and therefore image) which fully accounts for the telescope optics and effect of the PSF. - - 2) You may be familiar with image sub-gridding, which splits each image-pixel into a sub-pixel (if you are not - familiar then feel free to checkout the optional **HowToGalaxy** tutorial on sub-gridding. If a sub-grid is used, it is - the mapping between every sub-pixel -pixel that is computed and used to perform the inversion. This prevents - aliasing effects degrading the image reconstruction. By default **PyAutoGalaxy** uses sub-gridding of degree 4x4. - - 3) The inversion`s solution is regularized. But wait, that`s what we'll cover in the next tutorial! - -Finally, let me show you how easy it is to fit an image with an `Inversion` using a `FitImaging` object. Instead of -giving the galaxy a light profile, we simply pass it a `Pixelization` and regularization, and pass it to a -galaxies. -""" -pixelization = ag.Pixelization( - mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=(25, 25)), - regularization=ag.reg.Constant(coefficient=1.0), -) - -galaxy = ag.Galaxy(redshift=1.0, pixelization=pixelization) - -galaxies = ag.Galaxies(galaxies=[galaxy]) - -""" -Then, like before, we pass the imaging and galaxies `FitImaging` object. - -We see some pretty good looking residuals, albeit there is faint flux leftover. We will consider how we can address -this in the next tutorial. - -We can use the `subplot_of_galaxies` method to specifically visualize the inversion and plot the reconstruction. -""" -fit = ag.FitImaging(dataset=dataset, galaxies=galaxies) - -aplt.subplot_fit_imaging(fit=fit) - -""" -__Positive Only Solver__ - -All pixelized galaxy reconstructions use a positive-only solver, meaning that every pixelization pixel is only -allowed to reconstruct positive flux values. This ensures that the reconstruction is physical and that we don't -reconstruct negative flux values that don't exist in the real galaxy (a common unphysical systematic in methods -without this constraint). - -It may be surprising to hear that this is a feature worth pointing out, but it turns out setting up the linear algebra -to enforce positive reconstructions is difficult to make efficient. A lot of development time went into making this -possible, where a bespoke fast non-negative linear solver was developed to achieve this. - -Other methods in the literature often do not use a positive only solver, and therefore suffer from these -unphysical solutions, which can degrade the results of galaxy models in general. - -__Detailed Explanation__ - -The linear algebra sketched above -- setting up the mappings as a matrix and solving for the pixelization pixel -fluxes -- is derived in full in tutorial 5 of this chapter, where we build every matrix by hand and perform the -solve ourselves. The file `autogalaxy_workspace/*/imaging/features/pixelization/likelihood_function.ipynb` gives a -further visual step-by-step guide of the process alongside equations and references to literature on the subject. - -__Wrap Up__ - -And, we're done, here are a few questions to get you thinking about inversions: - - 1) The inversion provides the maximum log likelihood solution to the observed image. Is there a problem with seeking - the highest likelihood solution? Is there a risk that we're going to fit other things in the image than just the - galaxy? What happens if you reduce the `coefficient` of the regularization object above to zero? - - 2) The exterior pixels in the rectangular pixel-grid have no image-pixels in them. However, they are still given a - reconstructed flux. Given these pixels do not map to the data, where is this value coming from? -""" diff --git a/scripts/chapter_3_pixelizations/tutorial_3_model_fit.py b/scripts/chapter_3_pixelizations/tutorial_3_model_fit.py new file mode 100644 index 0000000..9e4e310 --- /dev/null +++ b/scripts/chapter_3_pixelizations/tutorial_3_model_fit.py @@ -0,0 +1,212 @@ +""" +Tutorial 3: Model Fit +===================== + +A pixelization can describe a galaxy without assigning an analytic centre and shape to every visible feature. +However, analytic profiles remain useful when we want to describe its smooth components. In this tutorial we combine +an MGE with a pixelization and use search chaining to put the smooth light model in place first. + +This is a continuation of Chapter 2's linear profiles. Gaussian widths are fixed, Gaussian intensities are solved +linearly, and the search explores their shared geometry. The second fit adds mesh brightnesses and searches for the +regularization coefficient. We actually perform both fits, so the second model inherits a fitted MGE. + +Our smooth bulge-and-disc simulation is a controlled starting point. A pixelization need not reveal new clumps in +such data: inspect whether it captures genuine residual structure or merely compensates for modelling choices. +For irregular observed galaxies, the same procedure offers extra spatial freedom without choosing a separate +analytic profile for every knot. + +__Contents__ + +- **Dataset:** Load, mask and oversample the image. +- **Search 1:** Fit the smooth galaxy light with an MGE. +- **Search 2:** Add a regularized pixelization using the fitted MGE geometry. +- **Search 3:** Refine the MGE geometry together with the pixelization. +- **Interpretation:** Inspect both the residuals and the component decomposition. +""" + +from pathlib import Path +import subprocess +import sys +import numpy as np +import autogalaxy as ag +import autogalaxy.plot as aplt +import autoarray.plot as aaplt + +dataset_path = Path("dataset") / "imaging" / "simple" +if ag.util.dataset.should_simulate(str(dataset_path)): + subprocess.run([sys.executable, "scripts/simulators/simple.py"], check=True) +dataset = ag.Imaging.from_fits( + data_path=dataset_path / "data.fits", + noise_map_path=dataset_path / "noise_map.fits", + psf_path=dataset_path / "psf.fits", + pixel_scales=0.1, +) +mask = ag.Mask2D.circular( + shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.0 +) +dataset = dataset.apply_mask(mask=mask) +dataset = dataset.apply_over_sampling(over_sample_size_pixelization=1) +# Keep the smoke-test mesh smaller than its deliberately capped image. +mesh_pixels = min(25, min(dataset.shape_native) // 2) +mesh_shape = (mesh_pixels, mesh_pixels) +aplt.subplot_imaging_dataset(dataset=dataset) + +import autofit as af + +over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from( + grid=dataset.grid, + sub_size_list=[8, 4, 2], + radial_list=[0.3, 0.6], + centre_list=[(0.0, 0.0)], +) +dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) + +""" +__Search 1: Fit the MGE__ + +An MGE combines Gaussians with fixed widths and linearly solved intensities. We use two Gaussian groups so that the +smooth model can describe light with different flattenings and orientations. Each group's Gaussians share their +elliptical shape; their centre is fixed at the known simulation centre in this example. For real data, the centre +should be inferred or justified independently. + +The search therefore adjusts the shapes of these groups rather than a separate intensity and width for every +Gaussian. The helper below sets up those shared parameters. Look at `model_1.info` to inspect the resulting model. +This first fit supplies a useful starting description, not a guarantee that every smooth or compact feature has +been assigned to the correct physical component. +""" + +mge = ag.model_util.mge_model_from( + mask_radius=2.0, + total_gaussians=20, + gaussian_per_basis=2, + centre_fixed=(0.0, 0.0), + sigma_min=0.01, +) +model_1 = af.Collection( + galaxies=af.Collection(galaxy=af.Model(ag.Galaxy, redshift=0.5, bulge=mge)) +) +print(model_1.info) +search_1 = af.Nautilus( + path_prefix=Path("howtogalaxy") / "chapter_3", + name="mge_search_1", + unique_tag="simple", + n_live=100, + n_batch=50, +) +result_1 = search_1.fit( + model=model_1, analysis=ag.AnalysisImaging(dataset=dataset, use_jax=True) +) +aplt.subplot_fit_imaging(fit=result_1.max_log_likelihood_fit) + +""" +__Search 2: Add the pixelization__ + +Inspect the MGE residuals before adding freedom. Compact coherent residuals might need a more flexible brightness +description, but PSF or background errors can also leave structure. A pixelization can absorb those errors too; +a better-looking fit does not identify their cause. + +We now hold the MGE geometry at `result_1.instance` and add a rectangular brightness mesh. The mesh shape is fixed +before the search; JAX needs this array shape to remain static. The regularization coefficient is inferred, and the +mesh brightnesses are solved linearly for every proposal. + +Using `.instance` makes this fit simpler because it does not need to rediscover the smooth galaxy geometry. The +MGE's linear Gaussian intensities are still solved together with the pixelized brightnesses. We are fitting one +combined image model, not subtracting a noisy observed image and pretending that subtraction is exact. +""" + +pixelization = af.Model( + ag.Pixelization, + mesh=ag.mesh.RectangularUniform(shape=mesh_shape), + regularization=af.Model(ag.reg.Constant), +) +pixelization.regularization.coefficient = af.LogUniformPrior( + lower_limit=0.01, upper_limit=100.0 +) +model_2 = af.Collection( + galaxies=af.Collection( + galaxy=af.Model( + ag.Galaxy, + redshift=0.5, + bulge=result_1.instance.galaxies.galaxy.bulge, + pixelization=pixelization, + ) + ) +) +search_2 = af.Nautilus( + path_prefix=Path("howtogalaxy") / "chapter_3", + name="mge_pixelization_search_2", + unique_tag="simple", + n_live=50, + n_batch=50, +) +result_2 = search_2.fit( + model=model_2, analysis=ag.AnalysisImaging(dataset=dataset, use_jax=True) +) +fit_2 = result_2.max_log_likelihood_fit +aplt.subplot_fit_imaging(fit=fit_2) +mapper_2 = fit_2.inversion.cls_list_from(ag.Mapper)[0] +aaplt.plot_mapper( + mapper=mapper_2, + solution_vector=fit_2.inversion.reconstruction_dict[mapper_2], + title="Pixelized Component Alongside the MGE", +) + +""" +__Search 3: Refine both components__ + +Fixing geometry helped us get started, but its uncertainty should not disappear from a final scientific analysis. +Using `result_1.model` returns the MGE geometry to the search with priors informed by the first fit. We also pass the +regularization model from the second fit. Their linear intensities continue to be solved for each proposal. + +Search chaining is a practical way to initialize this combined model. Priors passed between searches should be +checked: if an initial analytic fit was inadequate, it can provide an overconfident starting point. In that case, +widen the relevant priors and investigate the competing solutions. +""" + +model_3 = af.Collection( + galaxies=af.Collection( + galaxy=af.Model( + ag.Galaxy, + redshift=0.5, + bulge=result_1.model.galaxies.galaxy.bulge, + pixelization=result_2.model.galaxies.galaxy.pixelization, + ) + ) +) +search_3 = af.Nautilus( + path_prefix=Path("howtogalaxy") / "chapter_3", + name="mge_pixelization_search_3", + unique_tag="simple", + n_live=100, + n_batch=50, +) +result_3 = search_3.fit( + model=model_3, analysis=ag.AnalysisImaging(dataset=dataset, use_jax=True) +) +fit_3 = result_3.max_log_likelihood_fit +aplt.subplot_fit_imaging(fit=fit_3) +mapper_3 = fit_3.inversion.cls_list_from(ag.Mapper)[0] +aaplt.plot_mapper( + mapper=mapper_3, + solution_vector=fit_3.inversion.reconstruction_dict[mapper_3], + title="Pixelized Component After Joint Geometry Refinement", +) + +""" +__Wrap Up__ + +The MGE describes smooth light while the mesh gives the combined model more spatial freedom. Their decomposition +is not automatically unique: a pixelization can represent some light that an MGE could also explain. Regularization, +mesh resolution and analytic-model choices affect which component receives it. + +Inspect the residuals, the pixelized component and the inferred MGE geometry together. A small residual map does not +guarantee unbiased component measurements. Check that scientific conclusions remain stable under reasonable mesh, +regularization and prior changes, and use the posterior samples when reporting uncertainty. + +**🤖 Ask AI:** Why can the total galaxy image be well constrained while the division of its light between an MGE and +a pixelization remains uncertain? + +This chapter has connected pixelized brightnesses to the linear intensities from Chapter 2, followed their mappings +into the image, explored regularization, and performed a chained model fit. MGE remains a useful modelling tool; +pixelization adds another way to represent galaxy structure when analytic components alone become cumbersome. +""" diff --git a/scripts/chapter_3_pixelizations/tutorial_4_bayesian_regularization.py b/scripts/chapter_3_pixelizations/tutorial_4_bayesian_regularization.py deleted file mode 100644 index e0c1e4a..0000000 --- a/scripts/chapter_3_pixelizations/tutorial_4_bayesian_regularization.py +++ /dev/null @@ -1,304 +0,0 @@ -""" -Tutorial 4: Bayesian Regularization -=================================== - -So far, we have: - - - Used pixelizations and mappers to map pixelization pixels to image-pixels and visa versa. - - Successfully used an inversion to reconstruct a galaxy. - - Seen that this reconstruction provides a good fit of the observed image, providing a high likelihood solution. - -The explanation of *how* an inversion works has so far been overly simplified. You'll have noted the regularization -inputs which we have not so far discussed. This will be the topic of this tutorial, and where inversions become more -conceptually challenging! - -__Contents__ - -- **Initial Setup:** Load the dataset for illustration. -- **Dataset Auto-Simulation:** Automatically simulate the dataset if it does not already exist. -- **Convenience Function:** A helper function for performing inversions. -- **Pixelization:** Perform inversions with different regularization coefficients. -- **Regularization:** Understand how regularization smooths the reconstruction. -- **Bayesian Evidence:** Use the Bayesian evidence to objectively choose the regularization coefficient. -- **Non-Linear and Linear:** Discussion of how regularization interacts with the non-linear search. -- **Detailed Description:** In-depth explanation of how the Bayesian evidence penalizes overfitting. -- **Wrap Up:** Summary of Bayesian regularization concepts. -""" - -# from autogalaxy import setup_notebook; setup_notebook() - -from pathlib import Path -import autogalaxy as ag -import autogalaxy.plot as aplt -from autoarray.inversion.plot.inversion_plots import subplot_of_mapper - -""" -__Initial Setup__ - -we'll use the same galaxy data as the previous tutorial, where: - - - The galaxy's bulge is an `Sersic`. - - The galaxy's disk is an `Exponential`. -""" -dataset_name = "simple" -dataset_path = Path("dataset") / "imaging" / dataset_name - -""" -__Dataset Auto-Simulation__ - -If the dataset does not already exist on your system, it will be created by running the corresponding -simulator script. This ensures that all example scripts can be run without manually simulating data first. -""" -if ag.util.dataset.should_simulate(str(dataset_path)): - import subprocess - import sys - - subprocess.run( - [sys.executable, "scripts/simulators/simple.py"], - check=True, - ) - -dataset = ag.Imaging.from_fits( - data_path=dataset_path / "data.fits", - noise_map_path=dataset_path / "noise_map.fits", - psf_path=dataset_path / "psf.fits", - pixel_scales=0.1, -) - -""" -__Convenience Function__ - -we're going to perform a lot of fits using an `Inversion` this tutorial. This would create a lot of code, so to keep -things tidy, I've setup this function which handles it all for us. -""" - - -def perform_fit_with_galaxy(dataset, galaxy): - mask = ag.Mask2D.circular( - shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.0 - ) - - dataset = dataset.apply_mask(mask=mask) - - galaxies = ag.Galaxies(galaxies=[galaxy]) - - return ag.FitImaging(dataset=dataset, galaxies=galaxies) - - -""" -__Pixelization__ - -Okay, so lets look at our fit from the previous tutorial in more detail. -""" -# `PYAUTO_SMALL_DATASETS=1` (the CI smoke harness) caps the data to a 16 x 16 image, where a -# 50 x 50 mesh reconstructs 2500 source pixels from a few dozen image pixels. The mesh is -# capped alongside the data; a normal full-resolution run keeps the 50 x 50 grid described above. -mesh_shape = ( - ag.util.dataset.SMALL_DATASETS_SHAPE_NATIVE - if dataset.shape_native == ag.util.dataset.SMALL_DATASETS_SHAPE_NATIVE - else (50, 50) -) - -pixelization = ag.Pixelization( - mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape), - regularization=ag.reg.Constant(coefficient=1.0), -) - -galaxy = ag.Galaxy(redshift=1.0, pixelization=pixelization) - -fit = perform_fit_with_galaxy(dataset=dataset, galaxy=galaxy) - -aplt.subplot_fit_imaging(fit=fit) -subplot_of_mapper(inversion=fit.inversion, mapper_index=0) - -""" -__Regularization__ - -The galaxy reconstruction looks pretty good! - -However, the high quality of this solution was possible because I chose a `coefficient` for the regularization input of -1.0. If we reduce this `coefficient` to 0.01, the galaxy reconstruction goes *very* weird. -""" -pixelization = ag.Pixelization( - mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape), - regularization=ag.reg.Constant(coefficient=0.01), -) - -galaxy = ag.Galaxy(redshift=1.0, pixelization=pixelization) - -no_regularization_fit = perform_fit_with_galaxy(dataset=dataset, galaxy=galaxy) - -aplt.subplot_fit_imaging(fit=no_regularization_fit) -subplot_of_mapper(inversion=no_regularization_fit.inversion, mapper_index=0) - -""" -So, what is happening here? Why does reducing the `coefficient` do this to our reconstruction? First, we need -to understand what regularization actually does! - -When the inversion reconstructs the galaxy, it does not *only* compute the set of pixelization pixel fluxes that -best-fit the image. It also regularizes this solution, whereby it goes to every pixel on the rectangular grid -and computes the difference between the reconstructed flux values of every pixel with its 4 neighboring pixels. -If the difference in flux is large the solution is penalized, reducing its log likelihood. You can think of this as -us applying a 'smoothness prior' on the reconstructed galaxy's light. - -This smoothing adds a 'penalty term' to the log likelihood of an inversion which is the summed difference between the -reconstructed fluxes of every pixelization pixel pair multiplied by the `coefficient`. By setting the regularization -coefficient to zero, we set this penalty term to zero, meaning that regularization is completely omitted. - -Why do we need to regularize our solution? We just saw why, if we do not apply this smoothness prior to the galaxy -reconstruction, we `over-fit` the image and reconstruct a noisy galaxy with lots of extraneous features. This is what -the aliasing chequer-board effect is caused by. If the inversions's sole aim is to maximize the log likelihood, it can -do this by fitting *everything* accurately, including the noise. - -Over-fitting is why regularization is necessary. Solutions like this will completely ruin our attempts to model a -galaxy. By smoothing our galaxy reconstruction we ensure it does not over fit noise in the image. - -So, what happens if we apply a high value for the regularization coefficient? -""" -pixelization = ag.Pixelization( - mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape), - regularization=ag.reg.Constant(coefficient=100.0), -) - -galaxy = ag.Galaxy(redshift=1.0, pixelization=pixelization) - -high_regularization_fit = perform_fit_with_galaxy(dataset=dataset, galaxy=galaxy) - -aplt.subplot_fit_imaging(fit=high_regularization_fit) -subplot_of_mapper(inversion=high_regularization_fit.inversion, mapper_index=0) - -""" -The figure above shows that we completely remove over-fitting. However, we now fit the image data more poorly, -due to the much higher level of smoothing. - -So, we now understand what regularization is and why it is necessary. There is one nagging question that remains, how -do I choose the regularization coefficient value? We can not use the log likelihood, as decreasing the regularization -coefficient will always increase the log likelihood, because less smoothing allows the reconstruction to fit -the data better. -""" -print("Likelihood Without Regularization:") -print(no_regularization_fit.log_likelihood_with_regularization) -print("Likelihood With Normal Regularization:") -print(fit.log_likelihood_with_regularization) -print("Likelihood With High Regularization:") -print(high_regularization_fit.log_likelihood_with_regularization) - -""" -__Bayesian Evidence__ - -For inversions, we therefore need a different goodness-of-fit measure to choose the appropriate level of regularization. - -For this, we invoke the `Bayesian Evidence`, which quantifies the goodness of the fit as follows: - - - It requires that the residuals of the fit are consistent with Gaussian noise (which is the type of noise expected - in the imaging data). If this Gaussian pattern is not visible in the residuals, the noise must have been over-fitted - by the inversion. The Bayesian evidence will therefore decrease. If the image is fitted poorly due to over smoothing, - the residuals will again not appear Gaussian either, again producing a decrease in the Bayesian evidence value. - - - There can be many solutions which fit the data to the noise level, without over-fitting. To determine the best - solutions from these solutions, the Bayesian evidence therefore also quantifies the complexity of the galaxy - reconstruction. If an inversion requires many pixels and a low level of regularization to achieve a good fit, the - Bayesian evidence will decrease. The evidence penalizes solutions which are complex, which, in a Bayesian sense, are - less probable (you may want to look up `Occam`s Razor`). - -The Bayesian evidence therefore ensures we only invoke a more complex galaxy reconstruction when the data absolutely -necessitates it. - -(This tutorial describes the Bayesian evidence in words; tutorial 5 writes it down as an equation, deriving each of -its terms via the linear algebra of the inversion.) - -Lets take a look at the Bayesian evidence of the fits that we performed above, which is accessible from a `FitImaging` -object via the `log_evidence` property: -""" -print("Bayesian Evidence Without Regularization:") -print(no_regularization_fit.log_evidence) -print("Bayesian Evidence With Normal Regularization:") -print(fit.log_evidence) -print("Bayesian Evidence With High Regularization:") -print(high_regularization_fit.log_evidence) - -""" -As expected, the solution that we could see `by-eye` was the best solution corresponds to the highest log evidence -solution. - -__Non-Linear and Linear__ - -Before we end, lets consider which aspects of an inversion are linear and which are non-linear. - -The linear part of the inversion is the step that solves for the reconstructed pixelization pixel fluxes, including -accounting for the smoothing via regularization. We do not have to perform a non-linear search to determine the pixel -fluxes or compute the Bayesian evidence discussed above. - -However, determining the regularization `coefficient` that maximizes the Bayesian log evidence is a non-linear problem -that requires a non-linear search. The Bayesian evidence also depends on the grid resolution, which means the -pixel-grid's `shape` parameter may also now become dimensions of non linear parameter space (albeit it is common -practise for us to simply use the resolution of the image data, or a multiple of this). - -Nevertheless, these total only 3 non-linear parameters, far fewer than the 20+ that are required when modeling such a -complex galaxy using light profiles for every individual clump! - -Here are a few questions for you to think about. - - 1) We maximize the log evidence by using simpler galaxy reconstructions. Therefore, decreasing the pixel-grid - size should provide a higher log_evidence, provided it still has sufficiently high resolution to fit the image well - (and provided that the regularization coefficient is set to an appropriate value). Can you increase the log evidence - from the value above by changing these parameters, I've set you up with a code to do so below. -""" -pixelization = ag.Pixelization( - mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape), - regularization=ag.reg.Constant(coefficient=1.0), -) - -galaxy = ag.Galaxy(redshift=1.0, pixelization=pixelization) - -fit = perform_fit_with_galaxy(dataset=dataset, galaxy=galaxy) - -print("Previous Bayesian Evidence:") -print(3988.0716851250163) -print("New Bayesian Evidence:") -print(fit.log_evidence) - -aplt.subplot_fit_imaging(fit=fit) - -""" -__Detailed Description__ - -Below, I provide a more detailed discussion of the Bayesian evidence. It is not paramount that you understand this to -use **PyAutoGalaxy**, but I recommend you give it a read to get an intuition for how the evidence works. - -The Bayesian log evidence quantifies the following 3 aspects of a fit to galaxy imaging data: - -1) *The quality of the image reconstruction:* The galaxy reconstruction is a linear inversion which uses the observed - values in the image-data to fit it and reconstruct the galaxy. It is in principle able to perfectly reconstruct the - image regardless of the image’s noise or the accuracy of the model (e.g. at infinite resolution without - regularization). The problem is therefore ‘ill-posed’ and this is why regularization is necessary. - - However, this raises the question of what constitutes a ‘good’ solution? The Bayesian evidence defines this by - assuming that the image data consists of independent Gaussian noise in every image pixel. A ‘good’ solution is one - whose chi-squared residuals are consistent with Gaussian noise, producing a reduced chi-squared near 1.0 .Solutions - which give a reduced chi squared below 1 are penalized for being overly complex and fitting the image’s noise, whereas - solutions with a reduced chi-squared above are penalized for not invoking a more complex galaxy model when the data it - is necessary to fit the data bettter. In both circumstances, these penalties reduce the inferred Bayesian evidence! - -2) *The complexity of the galaxy reconstruction:* The log evidence estimates the number of pixelization pixels that are used - to reconstruct the image, after accounting for their correlation with one another due to regularization. Solutions that - require fewer correlated galaxy pixels increase the Bayesian evidence. Thus, simpler and less complex galaxy - reconstructions are favoured. - -3) *The signal-to-noise (S/N) of the image that is fitted:* The Bayesian evidence favours models which fit higher S/N - realizations of the observed data (where the S/N is determined using the image-pixel variances, e.g. the noise-map). Up - to now, all **PyAutoGalaxy** fits assumed fixed variances, meaning that this aspect of the Bayeisan evidence has no impact - on the inferred evidence values. - - The premise is that whilst increasing the variances of image pixels lowers their S/N values and therefore also - decreases the log evidence, doing so may produce a net increase in log evidence. This occurs when the chi-squared - values of the image pixels whose variances are increased were initially very high (e.g. they were fit poorly by the - model). - -__Wrap Up__ - -In summary, the log evidence is maximized for solutions which most accurately reconstruct the highest S/N realization of -the observed image, without over-fitting its noise and using the fewest correlated pixelization pixels. By employing -this framework throughout, **PyAutoGalaxy** objectively determines the final model following the principles of Bayesian -analysis and Occam’s Razor. -""" diff --git a/scripts/chapter_3_pixelizations/tutorial_5_bayesian_formalism.py b/scripts/chapter_3_pixelizations/tutorial_5_bayesian_formalism.py deleted file mode 100644 index 0f79c5a..0000000 --- a/scripts/chapter_3_pixelizations/tutorial_5_bayesian_formalism.py +++ /dev/null @@ -1,620 +0,0 @@ -""" -Tutorial 5: Bayesian Formalism -============================== - -In tutorials 1 to 4, we built an intuition for how pixelized galaxy reconstruction works: pixelizations place a -pixel-grid over the galaxy's image, mappers pair pixelization pixels with image-pixels, inversions solve for the -pixel fluxes that best fit the data, and regularization smooths the solution within a Bayesian framework. - -This tutorial collects the linear algebra behind all of that in one place. The hands-on tutorials built intuition, -and now we write down the equations. We will construct, step-by-step and in code, every matrix and vector the -inversion uses, solve for the galaxy reconstruction ourselves and compute the Bayesian evidence by hand, comparing -our answer at the end to the `FitImaging` object which performs this calculation internally. - -None of this is required to *use* **PyAutoGalaxy** for galaxy modeling. However, if you publish results which use a -pixelization, this is the calculation your paper's likelihood function section will describe, and understanding it -removes any sense that the galaxy reconstruction is a "black box". - -The formalism follows Warren & Dye 2003 (https://arxiv.org/abs/astro-ph/0302587), hereafter WD03, with the data -vector notation of Nightingale & Dye 2015 (https://arxiv.org/abs/1412.7436), hereafter N15. These papers derived -the method for reconstructing gravitationally lensed sources, but the linear algebra is identical for a galaxy's -own light -- the only lensing-specific step (ray tracing image-pixel coordinates to a source-plane) is simply -absent, with the mesh laid directly over the galaxy's image. The Bayesian evidence was derived by Suyu et al. 2006 -(https://arxiv.org/abs/astro-ph/0601493) and translated to **PyAutoGalaxy** notation in Dye et al. 2008 -(https://arxiv.org/abs/0804.4002). - -__Contents__ - -- **Initial Setup:** Load the dataset the previous tutorials fitted. -- **Dataset Auto-Simulation:** Automatically simulate the dataset if it does not already exist. -- **Mask:** Mask the data so the likelihood is evaluated only where the galaxy's light is. -- **Over Sampling:** Disable over sampling so the algebra stays simple. -- **Mesh Shape:** Fix the rectangular mesh's shape and note why edge pixels are zeroed. -- **Galaxy:** Create the galaxy whose pixelization pairs the mesh with `Constant` regularization. -- **Image Grid:** The masked image-pixel coordinates the mesh is laid over -- no ray tracing occurs. -- **Mesh Pixel Centres:** Overlay the rectangular mesh over the masked image grid. -- **Interpolation:** Pair every image-pixel with mesh pixels via bilinear interpolation. -- **Mapper:** Package the interpolation into a `Mapper` describing all image-to-mesh mappings. -- **Mapping Matrix:** Express the mappings as the 2D matrix $f$. -- **Blurred Mapping Matrix:** Convolve every column of $f$ with the imaging PSF. -- **Data Vector (D):** Compute the data vector $D$ from the blurred mapping matrix, data and noise-map. -- **Curvature Matrix (F):** Compute the curvature matrix $F$. -- **Unregularized Solve:** Solve $s = F^{-1} D$ and see the over-fitted mess this produces. -- **Regularization Matrix (H):** Compute the regularization matrix $H$ encoding the smoothness prior. -- **Galaxy Reconstruction (s):** Solve the regularized system $s = [F + H]^{-1} D$. -- **Image Reconstruction:** Map the reconstruction back to image resolution via the blurred mapping matrix. -- **Likelihood Function:** The five terms which combine into the log evidence. -- **Chi Squared:** The goodness-of-fit of the reconstructed image to the data. -- **Regularization Term:** The penalty $s^{T} H s$ applied by the smoothness prior. -- **Complexity Terms:** The log determinant terms which penalize complex galaxy reconstructions. -- **Noise Normalization Term:** The Gaussian noise normalization. -- **Log Evidence:** Combine all five terms into the log evidence. -- **Fit:** Compare our by-hand log evidence to the `FitImaging` object's internal calculation. -- **Wrap Up:** Summary and next steps. -""" - -# from autogalaxy import setup_notebook; setup_notebook() - -import matplotlib.pyplot as plt -import numpy as np -from pathlib import Path - -import autogalaxy as ag -import autogalaxy.plot as aplt -from autoarray.inversion.plot.mapper_plots import plot_mapper - -""" -__Initial Setup__ - -we'll use the same galaxy data as the previous tutorials, where: - - - The galaxy's bulge is an `Sersic`. - - The galaxy's disk is an `Exponential`. - -For simplicity, the model in this tutorial is a pixelization only, with no light profiles: the mesh absorbs the -bulge and disk together. In WD03's notation this means the light profile model image $b_{j}$ is zero everywhere. If -light profiles are included in the galaxy model, their PSF-convolved image is computed first and subtracted from -the data before the steps below -- nothing else about the formalism changes. -""" -dataset_name = "simple" -dataset_path = Path("dataset") / "imaging" / dataset_name - -""" -__Dataset Auto-Simulation__ - -If the dataset does not already exist on your system, it will be created by running the corresponding -simulator script. This ensures that all example scripts can be run without manually simulating data first. -""" -if ag.util.dataset.should_simulate(str(dataset_path)): - import subprocess - import sys - - subprocess.run( - [sys.executable, "scripts/simulators/simple.py"], - check=True, - ) - -dataset = ag.Imaging.from_fits( - data_path=dataset_path / "data.fits", - noise_map_path=dataset_path / "noise_map.fits", - psf_path=dataset_path / "psf.fits", - pixel_scales=0.1, -) - -aplt.subplot_imaging_dataset(dataset=dataset) - -""" -__Mask__ - -The likelihood is only evaluated within a mask, which we define as the same 2.0" circle used in the previous -tutorials, containing all of the galaxy's light. -""" -mask = ag.Mask2D.circular( - shape_native=dataset.shape_native, - pixel_scales=dataset.pixel_scales, - radius=2.0, -) - -masked_dataset = dataset.apply_mask(mask=mask) - -aplt.subplot_imaging_dataset(dataset=masked_dataset) - -""" -__Over Sampling__ - -Over sampling splits every image pixel into a sub-grid of sub-pixels, each of which is paired with mesh pixels -individually. It improves accuracy, but it also multiplies the number of rows in every matrix below by the number -of sub-pixels. - -To keep the algebra as easy to follow as possible, we disable over sampling by setting both sub-grid sizes to 1, so -each image pixel is represented by the single coordinate at its centre. -""" -masked_dataset = masked_dataset.apply_over_sampling( - over_sample_size_lp=1, - over_sample_size_pixelization=1, -) - -""" -__Mesh Shape__ - -The `mesh_shape` defines the number of pixels in the rectangular mesh used to reconstruct the galaxy, set below -to 20 x 20 = 400 mesh pixels. - -We use the `RectangularUniform` mesh, where all rectangular mesh pixels have the same size, rather than the -`RectangularBilinearAdaptDensity` mesh used in the previous tutorials. The uniform mesh keeps the geometry simple, and every -equation below applies unchanged to the adaptive meshes -- only the mesh pixel centres move. - -By default, mesh pixels at the edge of the mesh are forced to solutions of zero flux by the linear algebra solver. -This prevents unphysical solutions where the mesh edge lights up to fit residuals, and does not change any of the -formalism below. -""" -mesh_pixels_yx = 20 -mesh_shape = (mesh_pixels_yx, mesh_pixels_yx) - -""" -__Galaxy__ - -We create the galaxy whose `Pixelization` pairs the `RectangularUniform` mesh with `Constant` regularization (whose -role appears later, when we reach the matrix $H$). - -The galaxy has no light profiles -- the mesh alone will reconstruct its bulge and disk. -""" -pixelization = ag.Pixelization( - mesh=ag.mesh.RectangularUniform(shape=mesh_shape), - regularization=ag.reg.Constant(coefficient=1.0), -) - -galaxy = ag.Galaxy(redshift=0.5, pixelization=pixelization) - -""" -__Image Grid__ - -In the lensing version of this formalism (see **PyAutoLens**), every image-pixel coordinate is first ray-traced to -a source-plane, and the mesh is laid over the traced coordinates. For a galaxy there is no lensing, so this step -simply does not exist: the mesh is laid directly over the galaxy's own image, and the grid the inversion uses is -the grid of masked image-pixel centres itself. - -This grid is `masked_dataset.grids.pixelization`, with one coordinate at the centre of every masked image pixel -(because we disabled over sampling above). - -(The `Mapper` attributes below carry `source_plane_` prefixes because **PyAutoGalaxy** and **PyAutoLens** share one -inversion implementation. For a galaxy, the "source plane" is just the image plane the galaxy lives in.) -""" -aplt.plot_grid(grid=masked_dataset.grids.pixelization, title="Masked Image Grid") - -""" -__Mesh Pixel Centres__ - -To reconstruct the galaxy on a `RectangularUniform` mesh, we need the centres of its rectangular mesh pixels. - -We compute these by overlaying a uniform rectangular grid over the masked image grid, sized so the mesh fully -contains the masked region without wasted edge pixels beyond it. -""" -from autoarray.inversion.mesh.mesh.rectangular_rtu_adapt_density import ( - overlay_grid_from, -) - -mesh_grid = overlay_grid_from( - shape_native=mesh_shape, grid=masked_dataset.grids.pixelization -) - -""" -__Interpolation__ - -We now combine the two grids to create an `Interpolator`, which describes how every image-pixel coordinate maps to -the rectangular mesh pixels. - -For a rectangular mesh the scheme is bilinear interpolation: every image pixel maps to the rectangular pixel it -lands in *and* its three nearest neighbours, with weights set by how close the coordinate is to each pixel centre. -Interpolation is what lets the mesh reconstruct smooth galaxy morphologies. We can print the mappings and weights -of the first image pixel to confirm it pairs with four mesh pixels. -""" -interpolator = pixelization.mesh.interpolator_from( - source_plane_data_grid=masked_dataset.grids.pixelization, - source_plane_mesh_grid=mesh_grid, -) - -print(interpolator.mappings[0]) -print(interpolator.weights[0]) - -""" -__Mapper__ - -The interpolator creates a `Mapper`, the object tutorials 1 and 2 introduced. It packages up the mapping between -every image pixel and every rectangular mesh pixel. - -The key attribute is `pix_indexes_for_sub_slim_index`, mapping every image-pixel index (`sub_slim_index`) to the -mesh-pixel indexes (`pix_indexes`) it interpolates onto, alongside the number of mappings per image pixel and -their interpolation weights. -""" -mapper = ag.Mapper(interpolator=interpolator) - -pix_indexes_for_sub_slim_index = mapper.pix_indexes_for_sub_slim_index - -print(pix_indexes_for_sub_slim_index[0:9]) -print(mapper.pix_sizes_for_sub_slim_index[0:9]) -print(mapper.pix_weights_for_sub_slim_index[0:9]) - -""" -__Mapping Matrix__ - -The `mapping_matrix` expresses these image-pixel to mesh-pixel mappings as a single 2D matrix, with -dimensions `(total_image_pixels, total_mesh_pixels)`. - -Each column is the "image" of one mesh pixel: entries are the interpolation weights for image pixels which map to -that mesh pixel and zero everywhere else. -""" -mapping_matrix = ag.util.mapper.mapping_matrix_from( - pix_indexes_for_sub_slim_index=pix_indexes_for_sub_slim_index, - pix_size_for_sub_slim_index=mapper.pix_sizes_for_sub_slim_index, - pix_weights_for_sub_slim_index=mapper.pix_weights_for_sub_slim_index, - pixels=mapper.pixels, - total_mask_pixels=mapper.source_plane_data_grid.mask.pixels_in_mask, - slim_index_for_sub_slim_index=mapper.slim_index_for_sub_slim_index, - sub_fraction=mapper.over_sampler.sub_fraction, -) - -plt.imshow(mapping_matrix, aspect=(mapping_matrix.shape[1] / mapping_matrix.shape[0])) -plt.show() -plt.close() - -""" -Because each column is an image of zeros and interpolation weights, we can plot any column as a 2D image showing -all image pixels its mesh pixel maps to. For a mesh pixel near the mesh centre, these image pixels sit at the -centre of the galaxy, where its bulge is brightest. -""" -central_mesh_pixel = (mesh_shape[0] // 2) * mesh_shape[1] + mesh_shape[1] // 2 - -array_2d = ag.Array2D( - values=mapping_matrix[:, central_mesh_pixel], mask=masked_dataset.mask -) - -aplt.plot_array(array=array_2d, title="Image of Central Mesh Pixel") - -""" -__Blurred Mapping Matrix__ - -The imaging data is blurred by the telescope's PSF, so the model must be too. Since each column of the mapping -matrix is an image, we simply convolve each column with the PSF via 2D convolution. - -This produces the `blurred_mapping_matrix`, with the same dimensions `(total_image_pixels, total_mesh_pixels)`. - -In WD03 this matrix is denoted $f_{ij}$, where $i$ runs over all $I$ mesh pixels and $j$ over all $J$ image -pixels. For example: - - - $f_{0, 2} = 0.3$ indicates that image-pixel $2$ maps to mesh-pixel $0$ with a weight of $0.3$ after PSF - convolution. - - $f_{4, 8} = 0$ indicates that image-pixel $8$ does not map to mesh-pixel $4$, even after PSF convolution. - -(The indexing of the code's `mapping_matrix` is transposed relative to WD03's $f$: image pixels are the first index -in the code, but the second index in the equations.) - -PSF blurring has an important consequence: it correlates neighbouring columns, so the images of nearby mesh pixels -now overlap far more than the interpolation alone produced. -""" -blurred_mapping_matrix = masked_dataset.psf.convolved_mapping_matrix_from( - mapping_matrix=mapping_matrix, mask=masked_dataset.mask -) - -plt.imshow( - blurred_mapping_matrix, - aspect=(blurred_mapping_matrix.shape[1] / blurred_mapping_matrix.shape[0]), -) -plt.colorbar() -plt.show() -plt.close() - -r""" -__Data Vector (D)__ - -We now pose the reconstruction as a linear inversion, converting the blurred mapping matrix, data and noise-map -into two objects: the data vector $D$ and the curvature matrix $F$. - -The data vector has dimensions `(total_mesh_pixels,)` and is given by (WD03 / N15): - - $\vec{D}_{i} = \sum_{j=1}^{J} f_{ij} (d_{j} - b_{j}) / \sigma_{j}^2 \, \, .$ - -Where: - - - $d_{j}$ are the image-pixel data values. - - $b_{j}$ are the model images of any light profiles in the galaxy model (zero here, because our model is a - pixelization only). - - $\sigma_{j}^2$ are the statistical uncertainties of each image pixel. - -Each entry of $D$ is therefore the noise-weighted overlap between one mesh pixel's blurred image and the data: -it measures how much evidence the data provides for flux in that mesh pixel, with the PSF fully accounted for. -""" -data_vector = ag.util.inversion_imaging.data_vector_via_blurred_mapping_matrix_from( - blurred_mapping_matrix=blurred_mapping_matrix, - image=np.array(masked_dataset.data), - noise_map=np.array(masked_dataset.noise_map), -) - -plt.imshow( - data_vector.reshape(data_vector.shape[0], 1), aspect=10.0 / data_vector.shape[0] -) -plt.colorbar() -plt.show() -plt.close() - -r""" -__Curvature Matrix (F)__ - -The curvature matrix has dimensions `(total_mesh_pixels, total_mesh_pixels)` and is given by (WD03): - - ${F}_{ik} = \sum_{j=1}^{J} f_{ij} f_{kj} / \sigma_{j}^2 \, \, .$ - -Every entry of $F$ is the noise-weighted overlap between the blurred images of two mesh pixels: $F_{ik}$ sums the -product of columns $i$ and $k$ of $f$ over all image pixels. For $F_{ik}$ to be non-zero, mesh pixels $i$ and $k$ -must share at least one image pixel, which happens for neighbouring pixels via interpolation and for pixels -further apart via PSF blurring. - -$F$ describes how degenerate pairs of mesh pixels are with one another: two mesh pixels whose blurred images -overlap heavily can trade flux between themselves whilst fitting the data almost equally well. -""" -curvature_matrix = ag.util.inversion.curvature_matrix_via_mapping_matrix_from( - mapping_matrix=blurred_mapping_matrix, noise_map=masked_dataset.noise_map -) - -plt.imshow(curvature_matrix) -plt.colorbar() -plt.show() -plt.close() - -r""" -__Unregularized Solve__ - -The inversion seeks the mesh-pixel fluxes $s$ (a vector with one entry per mesh pixel) that minimize the -chi-squared: - - $\chi^2 = \sum_{j=1}^{J} \bigg[ \frac{(\sum_{i=1}^{I} s_{i} f_{ij}) + b_{j} - d_{j}}{\sigma_{j}} \bigg]^2$ - -Setting the derivative of $\chi^2$ with respect to each $s_{i}$ to zero gives the linear system whose solution is -(equation 5 of WD03): - - $s = F^{-1} D$ - -We can solve this directly with NumPy. (Without regularization the curvature matrix is often singular, so the loop -below adds a tiny value to its diagonal to avoid a `LinAlgError` -- it is a numerical crutch, not part of the -formalism.) -""" -for i in range(curvature_matrix.shape[0]): - curvature_matrix[i, i] += 1e-8 - -reconstruction = np.linalg.solve(curvature_matrix, data_vector) - -plot_mapper(mapper=mapper, solution_vector=reconstruction) - -r""" -The reconstructed mesh-pixel fluxes are a noisy, unsmooth mess -- exactly the over-fitting we saw in tutorial 4 -when we lowered the regularization coefficient towards zero. The linear inversion is fitting the noise in the -data, because this system of equations is ill-posed: we need a smoothness prior. - -__Regularization Matrix (H)__ - -Regularization adds a linear regularization term $G_{L}$ to the merit function we minimize (equation 11 of WD03): - - $G = \chi^2 + \lambda \, G_{L}$ - -where $\lambda$ is the `regularization_coefficient` controlling the degree of smoothing. The `Constant` scheme uses -gradient regularization (equation 14 of WD03): - - $G_{L} = \sum_{i}^{I} \sum_{n=1}^{N} [s_{i} - s_{i, n}]^2$ - -In words: for every mesh pixel, compare its flux with each of its $N$ neighbours $n$, and penalize solutions where -the differences are large. This is precisely the "smoothness prior" of tutorial 4, now written as an equation. - -To fold this into the linear algebra we define the regularization matrix $H$, with -dimensions `(total_mesh_pixels, total_mesh_pixels)` (equation 13 of WD03): - - $H_{ik} = \frac{1}{2} \frac{\partial^{2} G_{L}}{\partial s_{i} \partial s_{k}}$ - -$H$ has the coefficient $\lambda$ folded into it. Its non-zero off-diagonal entries mark pairs of mesh pixels -which are neighbours and therefore regularized with one another; most entries are zero because most mesh pixels -are not neighbours. -""" -regularization_matrix = ag.util.regularization.constant_regularization_matrix_from( - coefficient=galaxy.pixelization.regularization.coefficient, - neighbors=mapper.neighbors, - neighbors_sizes=mapper.neighbors.sizes, -) - -plt.imshow(regularization_matrix) -plt.colorbar() -plt.show() -plt.close() - -""" -__Galaxy Reconstruction (s)__ - -$H$ enters the linear system as follows (equation 12 of WD03): - - $s = [F + H]^{-1} D$ - -We add the two matrices and solve again. The diagonal jitter used above is no longer needed, because $H$ makes the -system well-posed. -""" -curvature_reg_matrix = np.add(curvature_matrix, regularization_matrix) - -reconstruction = np.linalg.solve(curvature_reg_matrix, data_vector) - -plot_mapper(mapper=mapper, solution_vector=reconstruction) - -""" -The reconstructed fluxes are now smooth and physical: regularization has suppressed the noisy solution and the -reconstruction actually looks like the galaxy's bulge and disk, without over-fitting the noise. - -__Image Reconstruction__ - -Using the reconstructed mesh-pixel fluxes, we map the reconstruction back to image resolution via the blurred -mapping matrix (so the reconstructed image includes PSF blurring) to produce the model image of the galaxy. -""" -mapped_reconstructed_data = ( - ag.util.inversion.mapped_reconstructed_data_via_mapping_matrix_from( - mapping_matrix=blurred_mapping_matrix, reconstruction=reconstruction - ) -) - -mapped_reconstructed_data = ag.Array2D( - values=mapped_reconstructed_data, mask=masked_dataset.mask -) - -aplt.plot_array(array=mapped_reconstructed_data, title="Reconstructed Image") - -r""" -__Likelihood Function__ - -We now quantify the goodness-of-fit of the galaxy reconstruction, computing the quantity tutorial 4 called the -Bayesian evidence. The log evidence consists of five terms: - - $-2 \, \mathrm{ln} \, \epsilon = \chi^2 + s^{T} H s + \mathrm{ln} \, [ \mathrm{det} (F + H) ] - \mathrm{ln} \, [ \mathrm{det} (H) ] + \sum_{j=1}^{J} \mathrm{ln} \, [2 \pi (\sigma_{j})^2 ] \, .$ - -This expression was first derived by Suyu et al. 2006 (https://arxiv.org/abs/astro-ph/0601493), equation (19), and -is given in **PyAutoGalaxy** notation by Dye et al. 2008 (https://arxiv.org/abs/0804.4002), equation (5). - -We now compute each term in turn. - -__Chi Squared__ - -The first term is the $\chi^2$ statistic from the merit function above, computed as: - - - `model_data` = the reconstructed image of the galaxy (plus any light profile model images, zero here). - - `residual_map` = (`data` - `model_data`) - - `normalized_residual_map` = (`data` - `model_data`) / `noise_map` - - `chi_squared_map` = (`normalized_residual_map`) ** 2.0 - - `chi_squared` = sum(`chi_squared_map`) - -High chi-squared values indicate image pixels the reconstruction fits poorly, lowering the likelihood. -""" -model_image = mapped_reconstructed_data - -residual_map = masked_dataset.data - model_image -normalized_residual_map = residual_map / masked_dataset.noise_map -chi_squared_map = normalized_residual_map**2.0 - -chi_squared = np.sum(chi_squared_map) - -print(chi_squared) - -r""" -__Regularization Term__ - -The second term, $s^{T} H s$, is the $\lambda \, G_{L}$ regularization penalty evaluated at the solution: the -summed difference in flux between all neighbouring mesh pixels, weighted by the regularization coefficient (which -is already folded into $H$). - -Less smooth solutions have larger values of this term and therefore lower likelihoods. -""" -regularization_term = np.matmul( - reconstruction.T, np.matmul(regularization_matrix, reconstruction) -) - -print(regularization_term) - -r""" -__Complexity Terms__ - -Up to this point, nothing has justified our choice of `regularization_coefficient=1.0`. We cannot choose it using -the two terms above, because increasing the coefficient smooths the solution more, which *both* worsens the -chi-squared *and* (for a fixed solution) raises the regularization penalty. Optimizing those two terms alone would -drive the coefficient to zero and put us right back at the over-fitted mess. - -The two log determinant terms, $\mathrm{ln} \, [ \mathrm{det} (F + H) ]$ and $- \mathrm{ln} \, [ \mathrm{det} (H) ]$, -fix this. Together they measure how *complex* the galaxy reconstruction is -- roughly, how many effective degrees -of freedom the mesh uses after regularization correlates its pixels -- and penalize more complex solutions. -Lowering the regularization coefficient frees the mesh to use more of its flexibility, increasing this complexity -penalty. - -These terms therefore counteract the chi-squared and regularization terms, so the highest evidence goes to -solutions which fit the data well with the *simplest* galaxy reconstruction. This is the Occam's razor behaviour -that tutorial 4 demonstrated empirically. -""" -log_curvature_reg_matrix_term = np.linalg.slogdet(curvature_reg_matrix)[1] -log_regularization_matrix_term = np.linalg.slogdet(regularization_matrix)[1] - -print(log_curvature_reg_matrix_term) -print(log_regularization_matrix_term) - -""" -__Noise Normalization Term__ - -The likelihood function assumes the imaging data consists of independent Gaussian noise in every image pixel, and -the final term is the normalization of those Gaussians: the sum of the log of every noise-map value squared. - -Because the noise-map is fixed, this term is constant throughout galaxy modeling and has no impact on the model -we infer -- it simply normalizes the likelihood. -""" -noise_normalization = float(np.sum(np.log(2 * np.pi * masked_dataset.noise_map**2.0))) - -print(noise_normalization) - -""" -__Log Evidence__ - -We can now combine the five terms into the log evidence of the galaxy reconstruction. -""" -log_evidence = float( - -0.5 - * ( - chi_squared - + regularization_term - + log_curvature_reg_matrix_term - - log_regularization_matrix_term - + noise_normalization - ) -) - -print(log_evidence) - -""" -__Fit__ - -Everything above is what the `FitImaging` object does internally when it fits a galaxy with a pixelization. We can -see this by performing the fit and comparing its `log_evidence` to ours. - -The two values do not agree exactly, because the real fit improves on our simplified solve in two ways mentioned -along the way: it uses the positive-only solver (tutorial 3), which forbids the negative mesh-pixel fluxes our -unconstrained `np.linalg.solve` permits, and it zeroes the pixels at the edge of the mesh. Our unconstrained solve -exploits that extra (unphysical) freedom to push its chi-squared lower than the real solver allows, which is why -our by-hand log evidence comes out somewhat higher. Neither constraint changes the formalism -- the same $f$, $D$, -$F$ and $H$ feed a solver with extra conditions on $s$. -""" -galaxies = ag.Galaxies(galaxies=[galaxy]) - -fit = ag.FitImaging(dataset=masked_dataset, galaxies=galaxies) - -print(fit.log_evidence) - -aplt.subplot_fit_imaging(fit=fit) - -""" -__Wrap Up__ - -We have walked through the complete linear algebra of a pixelized galaxy reconstruction: - - - The `mapping_matrix` and PSF-blurred mapping matrix $f$, whose columns are the blurred images of each - mesh pixel. - - - The data vector $D$ and curvature matrix $F$, the noise-weighted overlaps of those images with the data and with - each other. - - - The regularization matrix $H$, which encodes the smoothness prior, and the linear solve $s = [F + H]^{-1} D$ for - the galaxy reconstruction. - - - The five terms of the Suyu et al. 2006 log evidence -- chi-squared, the regularization penalty, the two log - determinant complexity terms and the noise normalization -- and their Bayesian interpretation as an Occam's - razor which favours the simplest galaxy reconstruction the data allows. - -During galaxy modeling, this whole calculation is one likelihood evaluation: the non-linear search varies the -model's parameters (for example the mesh resolution, the regularization coefficient, or the light profiles fitted -alongside the mesh), and each sample triggers the full solve and evidence computation above. - -Two simplifications are worth remembering: real fits use over sampling (each image pixel contributes several -sub-pixel rows to $f$) and **PyAutoGalaxy** uses a positive-only solver for $s$ rather than the unconstrained -`np.linalg.solve` used here (see tutorial 3). The workspace -guide `autogalaxy_workspace/*/imaging/features/pixelization/likelihood_function.ipynb` repeats this walk-through -with additional visualization of every step, including how light profiles combine with the mesh. - -In the next tutorial, we return to hands-on territory and use pixelizations in an actual model-fit, combining light -profiles and an inversion via search chaining. -""" diff --git a/scripts/chapter_3_pixelizations/tutorial_6_model_fit.py b/scripts/chapter_3_pixelizations/tutorial_6_model_fit.py deleted file mode 100644 index adb1a22..0000000 --- a/scripts/chapter_3_pixelizations/tutorial_6_model_fit.py +++ /dev/null @@ -1,256 +0,0 @@ -""" -Tutorial 6: Model Fit -===================== - -In the previous tutorials we used an inversion to reconstruct a complex galaxy. However, from the perspective of -a scientific analysis, it is not clear how useful this was. When we fit a galaxy with light profiles, we learn about -its brightness (`intensity`), size (`effective_radius`), compactness (`sersic_index`), etc. - -What did we learn about the galaxy we reconstructed? Not a lot, perhaps. - -Inversions are most useful when combined with light profiles. For the complex galaxy we have used throughout this -chapter, we can fit it with light profiles to quantify the properties of its `bulge` and `disk` components, whilst -simultaneously fitting any residual structure with the inversion so as to ensure it does not impact the fit. - -To illustrate modeling using an inversion, this tutorial therefore revisits the complex galaxy model-fit that we -performed via search chaining at the end of chapter 2 (tutorials 9-10). This time, as you have probably guessed, we -will fit part of the galaxy using an inversion. - -We will use search chaining to do this, first fitting the main galaxy components with light profiles, thereby -initializing the bulge and disk components. In the later searches we will switch to an `Inversion`. - -__Contents__ - -- **Initial Setup:** Load the galaxy dataset and apply a mask. -- **Dataset Auto-Simulation:** Automatically simulate the dataset if it does not already exist. -- **Model + Search + Analysis + Model-Fit (Search 1):** Fit light profiles to the main galaxy components. -- **Mesh Shape:** Discussion of how mesh shape affects the inversion. -- **Model + Search + Analysis + Model-Fit (Search 2):** Fit with a pixelization for residual structure. -- **Model + Search (Search 3):** Final simultaneous fit of light profiles and pixelization. -- **Wrap Up:** Summary of combining light profiles with pixelizations via search chaining. -""" - -# from autogalaxy import setup_notebook; setup_notebook() - -from pathlib import Path -import autofit as af -import autogalaxy as ag -import autogalaxy.plot as aplt - -""" -__Initial Setup__ - -we'll use the same galaxy data as the previous tutorials, where: - - - The galaxy's bulge is an `Sersic`. - - The galaxy's disk is an `Exponential`. -""" -dataset_name = "simple" -dataset_path = Path("dataset") / "imaging" / dataset_name - -""" -__Dataset Auto-Simulation__ - -If the dataset does not already exist on your system, it will be created by running the corresponding -simulator script. This ensures that all example scripts can be run without manually simulating data first. -""" -if ag.util.dataset.should_simulate(str(dataset_path)): - import subprocess - import sys - - subprocess.run( - [sys.executable, "scripts/simulators/simple.py"], - check=True, - ) - -dataset = ag.Imaging.from_fits( - data_path=dataset_path / "data.fits", - noise_map_path=dataset_path / "noise_map.fits", - psf_path=dataset_path / "psf.fits", - pixel_scales=0.1, -) - -mask = ag.Mask2D.circular( - shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.0 -) - - -dataset = dataset.apply_mask(mask=mask) - -over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from( - grid=dataset.grid, - sub_size_list=[8, 4, 2], - radial_list=[0.3, 0.6], - centre_list=[(0.0, 0.0)], -) - -dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) - -aplt.subplot_imaging_dataset(dataset=dataset) - - -""" -__Model + Search + Analysis + Model-Fit (Search 1)__ - -Search 1 we fit a model where: - - - The galaxy's bulge is an `Sersic` with fixed centre [5 parameters]. - - - The galaxy's disk is an `Exponential` with fixed centre [4 parameters]. - -The number of free parameters and therefore the dimensionality of non-linear parameter space is N=9. -""" -bulge = af.Model(ag.lp.Sersic) -disk = af.Model(ag.lp.Exponential) - -bulge.centre_0 = 0.0 -bulge.centre_1 = 0.0 -disk.centre_0 = 0.0 -disk.centre_1 = 0.0 - -galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk) - -model_1 = af.Collection(galaxies=af.Collection(galaxy=galaxy)) - -search_1 = af.Nautilus( - path_prefix=Path("howtogalaxy", "chapter_3"), - name="search[1]", - unique_tag=dataset_name, - n_live=100, - n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2. -) - -analysis_1 = ag.AnalysisImaging(dataset=dataset, use_jax=True) - -result_1 = search_1.fit(model=model_1, analysis=analysis_1) - -""" -__Mesh Shape__ - -The `mesh_shape` parameter defines the number of pixels used by the rectangular mesh to reconstruct the galaxy, -set below to 28 x 28. - -The `mesh_shape` must be fixed before modeling and cannot be a free parameter of the model, because JAX uses the -mesh shape to define static shaped arrays which use the mesh to reconstruct the galaxy. For a rectangular -mesh, the same number of pixels must be used in the y and x directions. -""" -mesh_pixels_yx = 28 -mesh_shape = (mesh_pixels_yx, mesh_pixels_yx) - -""" -__Model + Search + Analysis + Model-Fit (Search 2)__ - -We use the results of search 1 to create the model fitted in search 2, where: - - - The galaxy's bulge is an `Sersic` [0 parameters: parameters fixed from search 1]. - - - The galaxy's disk is an `Exponential` [0 parameters: parameters fixed from search 1]. - - - Residual galaxy structure is reconstructed using a `RectangularBilinearAdaptDensity` mesh with a fixed 28 x 28 - shape [0 parameters]. - - - This pixelization is regularized using a `GaussianKernel` scheme [2 parameters]. - -The number of free parameters and therefore the dimensionality of non-linear parameter space is N=2. - -This search allows us to very efficiently set up the regularization scheme's parameters, before refitting the -galaxy's bulge and disk alongside the inversion in search 3. -""" -pixelization = af.Model( - ag.Pixelization, - mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape), - regularization=ag.reg.GaussianKernel, -) - -galaxy = af.Model( - ag.Galaxy, - redshift=0.5, - bulge=result_1.instance.galaxies.galaxy.bulge, - disk=result_1.instance.galaxies.galaxy.disk, - pixelization=pixelization, -) - -model_2 = af.Collection(galaxies=af.Collection(galaxy=galaxy)) - -search_2 = af.Nautilus( - path_prefix=Path("howtogalaxy", "chapter_3"), - name="search[2]", - unique_tag=dataset_name, - n_live=50, - n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2. -) - -analysis_2 = ag.AnalysisImaging( - dataset=dataset, - settings=ag.Settings(use_border_relocator=True), - use_jax=True, -) - -result_2 = search_2.fit(model=model_2, analysis=analysis_2) - -""" -__Model + Search (Search 3)__ - -We use the results of searches 1 and 2 to create the model fitted in search 3, where: - - - The galaxy's bulge is an `Sersic` [7 parameters: priors initialized from search 1]. - - - The galaxy's disk is an `Sersic` [7 parameters: priors initialized from search 1]. - - - Residual galaxy structure uses a `RectangularBilinearAdaptDensity` mesh with a fixed 28 x 28 shape [0 parameters]. - - - This pixelization is regularized using a `GaussianKernel` scheme [2 parameters]. - -The number of free parameters and therefore the dimensionality of non-linear parameter space is N=16. - -This search allows us to refit the bulge and disk components with an inversion that takes care of any residual -structure the light profiles do not capture. -""" -bulge = af.Model(ag.lp.Sersic) -bulge.ell_comps = result_1.model.galaxies.galaxy.bulge.ell_comps -bulge.intensity = result_1.model.galaxies.galaxy.bulge.intensity -bulge.effective_radius = result_1.model.galaxies.galaxy.bulge.effective_radius -bulge.sersic_index = result_1.model.galaxies.galaxy.bulge.sersic_index - -disk = af.Model(ag.lp.Sersic) -disk.ell_comps = result_1.model.galaxies.galaxy.disk.ell_comps -disk.intensity = result_1.model.galaxies.galaxy.disk.intensity -disk.effective_radius = result_1.model.galaxies.galaxy.disk.effective_radius - -pixelization = af.Model( - ag.Pixelization, - mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape), - regularization=ag.reg.GaussianKernel, -) - -galaxy = af.Model( - ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk, pixelization=pixelization -) - -model_3 = af.Collection(galaxies=af.Collection(galaxy=galaxy)) - -search_3 = af.Nautilus( - path_prefix=Path("howtogalaxy", "chapter_3"), - name="search[3]", - unique_tag=dataset_name, - n_live=100, - n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2. -) - -analysis_3 = ag.AnalysisImaging(dataset=dataset, use_jax=True) - -result_3 = search_3.fit(model=model_3, analysis=analysis_3) - -""" -__Wrap Up__ - -And with that, we now have a pipeline to model galaxies using an inversion! - -This concludes the pixelizations chapter. You now have every tool this chapter set out to teach: pixelizations and -mappers (tutorials 1-2), inversions (tutorial 3), Bayesian regularization and the evidence (tutorials 4-5), and a -search-chained pipeline which combines light profiles with an inversion (this tutorial). - -In chapter 4, we scale up from a single galaxy to the busier fields real imaging surveys deliver: datasets with -extra galaxies near the main galaxy, blended multi-galaxy systems modeled simultaneously, and cluster fields with -many member galaxies. -""" diff --git a/workspace_index.json b/workspace_index.json index bf93e4f..04dc1b1 100644 --- a/workspace_index.json +++ b/workspace_index.json @@ -283,117 +283,49 @@ }, { "contents": [ - "Initial Setup", - "Mesh", - "Wrap Up" + "The image and its coordinates", + "A brightness mesh", + "Following the mappings", + "An inversion", + "A model image", + "Using FitImaging" ], "cross_refs": [], "notebook": "notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb", "path": "scripts/chapter_3_pixelizations/tutorial_1_pixelizations.py", - "summary": "In the previous chapters, we used light profiles to model the light of a galaxy, where the light profile was an analytic description of how the luminosity varies as a function of radius.", - "title": "Tutorial 1: Pixelizations" - }, - { - "contents": [ - "Initial Setup", - "Dataset Auto-Simulation", - "Mappers", - "Mask", - "Wrap Up" - ], - "cross_refs": [], - "notebook": "notebooks/chapter_3_pixelizations/tutorial_2_mappers.ipynb", - "path": "scripts/chapter_3_pixelizations/tutorial_2_mappers.py", - "summary": "In the previous tutorial, we used a pixelization to create a `Mapper`. However, it was not clear what a `Mapper` does, why it was called a mapper and whether it was mapping anything at all!", - "title": "Tutorial 2: Mappers" - }, - { - "contents": [ - "Initial Setup", - "Dataset Auto-Simulation", - "Pixelization", - "Positive Only Solver", - "Detailed Explanation", - "Wrap Up" - ], - "cross_refs": [ - "/imaging/features/pixelization/likelihood_function.ipynb" - ], - "notebook": "notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb", - "path": "scripts/chapter_3_pixelizations/tutorial_3_inversions.py", - "summary": "In the previous two tutorials, we introduced:", - "title": "Tutorial 3: Inversions" + "summary": "Look at a resolved galaxy image. Its broad light distribution may follow a smooth bulge and disc, while smaller regions contain bright star-forming knots, off-centre clumps or irregular extensions. A model can capture the overall galaxy yet leave these features clearly visible in the residual image.", + "title": "Tutorial 1: Pixelizations, Mappers and Inversions" }, { "contents": [ - "Initial Setup", - "Dataset Auto-Simulation", - "Convenience Function", - "Pixelization", - "Regularization", - "Bayesian Evidence", - "Non-Linear and Linear", - "Detailed Description", - "Wrap Up" - ], - "cross_refs": [], - "notebook": "notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb", - "path": "scripts/chapter_3_pixelizations/tutorial_4_bayesian_regularization.py", - "summary": "So far, we have:", - "title": "Tutorial 4: Bayesian Regularization" - }, - { - "contents": [ - "Initial Setup", - "Dataset Auto-Simulation", - "Mask", - "Over Sampling", - "Mesh Shape", - "Galaxy", - "Image Grid", - "Mesh Pixel Centres", - "Interpolation", - "Mapper", - "Mapping Matrix", - "Blurred Mapping Matrix", - "Data Vector (D)", - "Curvature Matrix (F)", - "Unregularized Solve", - "Regularization Matrix (H)", - "Galaxy Reconstruction (s)", - "Image Reconstruction", - "Likelihood Function", - "Chi Squared", - "Regularization Term", - "Complexity Terms", - "Noise Normalization Term", - "Log Evidence", - "Fit", - "Wrap Up" + "Interpolation and our starting reconstruction.", + "Reducing and increasing regularization.", + "Bayesian evidence and a coefficient experiment.", + "Inspecting the preferred reconstruction.", + "Linear brightnesses and non-linear model choices.", + "Comparing mesh resolutions." ], "cross_refs": [ - "/imaging/features/pixelization/likelihood_function.ipynb" + "//github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/pixelization/likelihood_function.py" ], - "notebook": "notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb", - "path": "scripts/chapter_3_pixelizations/tutorial_5_bayesian_formalism.py", - "summary": "In tutorials 1 to 4, we built an intuition for how pixelized galaxy reconstruction works: pixelizations place a pixel-grid over the galaxy's image, mappers pair pixelization pixels with image-pixels, inversions solve for the pixel fluxes that best fit the data, and regularization smooths the solution within a Bayesian framework.", - "title": "Tutorial 5: Bayesian Formalism" + "notebook": "notebooks/chapter_3_pixelizations/tutorial_2_bayesian_regularization.ipynb", + "path": "scripts/chapter_3_pixelizations/tutorial_2_bayesian_regularization.py", + "summary": "(no summary in script docstring)", + "title": "Tutorial 2: Bayesian Regularization" }, { "contents": [ - "Initial Setup", - "Dataset Auto-Simulation", - "Model + Search + Analysis + Model-Fit (Search 1)", - "Mesh Shape", - "Model + Search + Analysis + Model-Fit (Search 2)", - "Model + Search (Search 3)", - "Wrap Up" + "Dataset", + "Search 1", + "Search 2", + "Search 3", + "Interpretation" ], "cross_refs": [], - "notebook": "notebooks/chapter_3_pixelizations/tutorial_6_model_fit.ipynb", - "path": "scripts/chapter_3_pixelizations/tutorial_6_model_fit.py", - "summary": "In the previous tutorials we used an inversion to reconstruct a complex galaxy. However, from the perspective of a scientific analysis, it is not clear how useful this was. When we fit a galaxy with light profiles, we learn about its brightness (`intensity`), size (`effective_radius`), compactness (`sersic_index`), etc.", - "title": "Tutorial 6: Model Fit" + "notebook": "notebooks/chapter_3_pixelizations/tutorial_3_model_fit.ipynb", + "path": "scripts/chapter_3_pixelizations/tutorial_3_model_fit.py", + "summary": "A pixelization can describe a galaxy without assigning an analytic centre and shape to every visible feature. However, analytic profiles remain useful when we want to describe its smooth components. In this tutorial we combine an MGE with a pixelization and use search chaining to put the smooth light model in place first.", + "title": "Tutorial 3: Model Fit" }, { "contents": [