diff --git a/AGENTS.md b/AGENTS.md index ebd02a7..a8874c5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,11 +9,12 @@ instructions for this repo. - `scripts/` — Runnable Python tutorial scripts: - `chapter_1_introduction/` — Grids, light profiles, galaxies, data, fitting - - `chapter_2_modeling/` — Non-linear searches, Bayesian inference, galaxy modeling - - `chapter_3_pixelizations/` — Pixelized reconstruction, inversions, regularization, the Bayesian - formalism + - `chapter_2_modeling/` — Non-linear searches, practicalities, difficult fits, linear profiles, + data and likelihoods, component-based search chaining + - `chapter_3_pixelizations/` — Pixelized reconstruction, mappings, inversions, evidence-guided + regularization, fit problems, adaptive reconstruction and combined analytic/pixelized fits - `chapter_4_scaling_up_galaxies/` — Extra galaxies, blended multi-galaxy systems, cluster fields - - `chapter_optional/` — Alternative searches and advanced topics + - `chapter_optional/` — Alternative searches, runtime and historical prior passing - `simulators/` — Simulator scripts that generate the tutorial datasets at runtime - `notebooks/` — Jupyter versions, generated from `scripts/` (do not edit directly) - `config/` — PyAutoGalaxy configuration YAML diff --git a/README.md b/README.md index b21dbbf..bf1ea0f 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # HowToGalaxy -[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/start_here.ipynb) +[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/start_here.ipynb) -[Start Here on Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/start_here.ipynb) | +[Start Here on Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/start_here.ipynb) | [Installation Guide](https://pyautogalaxy.readthedocs.io/en/latest/installation/overview.html) | [PyAutoGalaxy readthedocs](https://pyautogalaxy.readthedocs.io/en/latest/index.html) | [Browse Chapter 1 With Images](markdown/README.md) | @@ -31,8 +31,8 @@ more appropriate — they are concise and assume the concepts taught in **HowToG profiles, galaxies, simulated imaging data, and fitting. - `chapter_2_modeling` — Bayesian inference, non-linear searches, and how to fit a galaxy model to CCD imaging data with **PyAutoGalaxy**, ending with search chaining and automated pipelines. -- `chapter_3_pixelizations` — Pixelized reconstructions (inversions) for galaxies with irregular - morphologies, including the Bayesian formalism underpinning them. +- `chapter_3_pixelizations` — Pixelized reconstructions for galaxies with irregular morphologies, choosing + regularization using Bayesian evidence, fit problems and adaptive reconstruction. - `chapter_4_scaling_up_galaxies` — Scaling galaxy modeling up beyond a single galaxy: extra galaxies, blended multi-galaxy systems, and cluster fields. - `chapter_optional` — Optional tutorials on alternative non-linear searches and other advanced topics. @@ -78,15 +78,15 @@ output figures inline. Nothing runs and nothing installs — you just read it. T skimming a tutorial before running it, or for reading on a phone. Markdown pages currently exist only for the chapter 1 tutorials listed with a `markdown` link below; every other tutorial is Colab-only. -**[Start Here](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/start_here.ipynb)** — a one-page overview of the whole series. +**[Start Here](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/start_here.ipynb)** — a one-page overview of the whole series. - **[Chapter 1: Introduction](scripts/chapter_1_introduction/README.md)** — Grids, light profiles, galaxies, simulated imaging data, and fitting. - - Tutorial 0: Visualization — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_1_introduction/tutorial_0_visualization.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_0_visualization.md)) - - Tutorial 1: Grids and Galaxies — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_1_grids_and_galaxies.md)) - - Tutorial 2: Data — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_1_introduction/tutorial_2_data.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_2_data.md)) - - Tutorial 3: Fitting — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_1_introduction/tutorial_3_fitting.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_3_fitting.md)) - - Tutorial 4: Methods — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_1_introduction/tutorial_4_methods.ipynb)) - - Tutorial 5: Summary — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_1_introduction/tutorial_5_summary.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_5_summary.md)) + - Tutorial 0: Visualization — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_0_visualization.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_0_visualization.md)) + - Tutorial 1: Grids and Galaxies — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_1_grids_and_galaxies.md)) + - Tutorial 2: Data — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_2_data.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_2_data.md)) + - Tutorial 3: Fitting — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_3_fitting.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_3_fitting.md)) + - Tutorial 4: Methods — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_4_methods.ipynb)) + - Tutorial 5: Summary — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_5_summary.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_5_summary.md)) - **[Chapter 2: Modeling](scripts/chapter_2_modeling/README.md)** — Practical galaxy models, data and likelihoods, linear profiles and search chaining. - Tutorial 1: Non-linear Search — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb)) - Tutorial 2: Practicalities — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb)) @@ -103,9 +103,9 @@ for the chapter 1 tutorials listed with a `markdown` link below; every other tut - Tutorial 5: Model Fit — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_5_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.11.1.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.11.1.1/notebooks/chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy.ipynb)) - - Tutorial 3: Cluster — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_4_scaling_up_galaxies/tutorial_3_cluster.ipynb)) + - Tutorial 1: Extra Galaxies — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/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/main/notebooks/chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy.ipynb)) + - Tutorial 3: Cluster — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_4_scaling_up_galaxies/tutorial_3_cluster.ipynb)) - **[Optional Tutorials](scripts/chapter_optional/)** — Alternative non-linear searches and advanced topics. - Alternative Searches — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_optional/tutorial_searches.ipynb)) - Need for Speed — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_optional/tutorial_need_for_speed.ipynb)) diff --git a/llms.txt b/llms.txt index c434517..46bc30e 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 — practicalities, difficult fits, linear profiles, data and likelihoods, and component-based search chaining. -- **Chapter 3 — Pixelizations** → [scripts/chapter_3_pixelizations/](scripts/chapter_3_pixelizations/): Reconstructing galaxy structure on a mesh — indexed mappings, inversions, Bayesian regularization, fit problems, adaptive reconstruction and combined MGE/pixelization search chaining. +- **Chapter 3 — Pixelizations** → [scripts/chapter_3_pixelizations/](scripts/chapter_3_pixelizations/): Reconstructing galaxy structure on a mesh — indexed mappings, inversions, evidence-guided regularization, fit problems, adaptive reconstruction and combined analytic/pixelized fits. - **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… @@ -40,6 +40,7 @@ real analysis?" below). - **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_5_model_fit.py](scripts/chapter_3_pixelizations/tutorial_5_model_fit.py). +- **How do I choose the regularization strength?** → [tutorial_2_bayesian_regularization.py](scripts/chapter_3_pixelizations/tutorial_2_bayesian_regularization.py): Compare log evidences and inspect how mesh resolution affects the preferred coefficient. - **Why does a regularized reconstruction still leave residuals?** → [tutorial_3_fit_problems.py](scripts/chapter_3_pixelizations/tutorial_3_fit_problems.py): Mesh resolution, concentrated light and the limits of smoothing. - **How can the mesh and smoothing follow galaxy brightness?** → [tutorial_4_adaptive_reconstruction.py](scripts/chapter_3_pixelizations/tutorial_4_adaptive_reconstruction.py): Hilbert sampling and adaptive regularization, compared using log evidence. diff --git a/notebooks/README.md b/notebooks/README.md index e54ca64..c22eaa6 100644 --- a/notebooks/README.md +++ b/notebooks/README.md @@ -4,9 +4,10 @@ The `HowToGalaxy` folder contains **HowToGalaxy** lectures, which teach a new us - `chapter_1_introduction`: An introduction to galaxy morphology and structure using **PyAutoGalaxy**. - `chapter_2_modeling`: How to model galaxies, with data, models, Analysis objects and searches. -- `chapter_3_pixelizations`: How to perform pixelized reconstructions of a galaxy. +- `chapter_3_pixelizations`: Reconstruct complex galaxy light, choose regularization using Bayesian + evidence, diagnose fit problems and adapt the mesh and smoothing. - `chapter_4_scaling_up_galaxies`: How to scale up modeling to multiple galaxies, from blended pairs to cluster fields. -- `chapter_optional`: Optional tutorials. +- `chapter_optional`: Alternative searches, runtime and historical prior passing. - `simulators`: Scripts used to simulate the galaxy datasets fitted throughout the **HowToGalaxy** lectures. # Full Explanation @@ -95,15 +96,15 @@ fit CCD imaging data of a galaxy with a model. At the end, you'll understand: **Using an inversion to perform a pixelized morphology reconstruction** -In chapter 3, we'll learn how to reconstruct the morphological features of a galaxy using a pixel-grid, ensuring -that we can fit an accurate model to galaxies with complex and irregular morphologies. You'll learn how to: +In chapter 3, we'll reconstruct complex galaxy light using a pixel-grid, compare reconstructions using Bayesian +evidence, and investigate where the mesh and smoothing limit the fit. You'll learn how to: -1. Pixelize a galaxy reconstruction into pixels. -2. Perform a linear inversion using this pixelization to reconstruct the galaxy's light. -3. Apply a smoothness prior on the galaxy reconstruction, called regularization. -4. Apply smoothing within a Bayesian framework to objectively quantify the reconstruction's complexity. -5. Write down the linear algebra and Bayesian evidence equations that underpin the whole framework. -6. Use these features to fit a model via non-linear searches. +1. Connect reconstruction mesh points to image pixels through mappings. +2. Solve for the galaxy's brightness using a linear inversion. +3. Apply regularization and compare log evidences to choose its strength. +4. Diagnose compact-galaxy fit problems that remain after choosing the regularization coefficient. +5. Combine Delaunay meshes, Hilbert brightness adaptation and adaptive Split regularization. +6. Fit a smooth analytic light component alongside a pixelization. # OVERVIEW OF CHAPTER 4 (Advanced) diff --git a/notebooks/chapter_1_introduction/README.md b/notebooks/chapter_1_introduction/README.md index 49f18ad..54173cc 100644 --- a/notebooks/chapter_1_introduction/README.md +++ b/notebooks/chapter_1_introduction/README.md @@ -4,14 +4,14 @@ In chapter 1, we introduce you to galaxies, the light they emit and the core **P # Files -- [Tutorial 0: Visualization](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_1_introduction/tutorial_0_visualization.ipynb) — Setting up **PyAutoGalaxy**'s visualization library. +- [Tutorial 0: Visualization](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_0_visualization.ipynb) — Setting up **PyAutoGalaxy**'s visualization library. -- [Tutorial 1: Grids And Galaxies](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb) — How grids of (y,x) coordinates are used to create images of galaxies that ultimately quantify their morphology. +- [Tutorial 1: Grids And Galaxies](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb) — How grids of (y,x) coordinates are used to create images of galaxies that ultimately quantify their morphology. -- [Tutorial 2: Data](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_1_introduction/tutorial_2_data.ipynb) — Simulating and inspecting telescope imaging data of a galaxy, for example from the Hubble Space Telescope. +- [Tutorial 2: Data](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_2_data.ipynb) — Simulating and inspecting telescope imaging data of a galaxy, for example from the Hubble Space Telescope. -- [Tutorial 3: Fitting](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_1_introduction/tutorial_3_fitting.ipynb) — How to fit imaging data of a galaxy and quantify whether a fit is good or bad. +- [Tutorial 3: Fitting](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_3_fitting.ipynb) — How to fit imaging data of a galaxy and quantify whether a fit is good or bad. -- [Tutorial 4: Methods](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_1_introduction/tutorial_4_methods.ipynb) — An overview of the different methods used to fit galaxies with. +- [Tutorial 4: Methods](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_4_methods.ipynb) — An overview of the different methods used to fit galaxies with. -- [Tutorial 5: Summary](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_1_introduction/tutorial_5_summary.ipynb) — A summary of the chapter. +- [Tutorial 5: Summary](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_5_summary.ipynb) — A summary of the chapter. diff --git a/notebooks/chapter_2_modeling/tutorial_3_why_modeling_is_hard.ipynb b/notebooks/chapter_2_modeling/tutorial_3_why_modeling_is_hard.ipynb index fc8a0c4..6c741a3 100644 --- a/notebooks/chapter_2_modeling/tutorial_3_why_modeling_is_hard.ipynb +++ b/notebooks/chapter_2_modeling/tutorial_3_why_modeling_is_hard.ipynb @@ -584,7 +584,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_2_modeling/tutorial_3_why_modeling_is_hard.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_run_search\n\n---\nname: ag_run_search\ndescription: Run the fit — take a composed model, an analysis and a configured search and drive `search.fit(model=model, analysis=analysis)` to completion, then read what it wrote. Covers the output-folder anatomy and the on-the-fly announcement, the unique-identifier resume behaviour and when it silently reuses a stale fit, `iterations_per_quick_update` and `live_visual_update`, JAX/GPU acceleration and when it actually pays, VRAM checks before a long GPU run, the `PYAUTO_TEST_MODE` smoke levels, and the `if __name__ == \"__main__\"` parallelisation fix. Use once `ag_build_imaging_model` and `ag_configure_search` have produced `model`, `analysis` and `search` objects, or when a fit is running and the user wants to know what to watch. Not for composing the model or choosing the search (those two skills), not for interpreting the finished posterior (`ag_load_results`), and not for diagnosing a fit that ran but converged somewhere unphysical (`ag_debug_fit_failure`).\n---\n\n# Running the fit\n\nThis is the moment the inference actually happens. Everything before it was preparation:\na `model` says which morphological parameters are free and what priors they carry, an\n`analysis` binds that model to one dataset and knows how to turn a parameter vector into a\nlog likelihood, and a `search` knows how to explore the parameter space. One call joins\nthem:\n\n```python\nresult = search.fit(model=model, analysis=analysis)\n```\n\nStatistically, that call is sampling (or optimising) the posterior\n$P(\\theta | d) \\propto \\mathcal{L}(d | \\theta) P(\\theta)$, where the likelihood is the\nGaussian-noise chi-squared of the PSF-convolved model image against the data — walked\nline by line in `autogalaxy_workspace:scripts/imaging/likelihood_function.py`. Scientifically,\nit is where a Sersic index, an effective radius or a bulge-to-total ratio stops being a guess\nand becomes a measurement with errors. What this skill adds is everything *around* the call:\nhow to watch it, how long to expect, how to make it fast, and how to prove the script works\nbefore committing hours to it.\n\nTwo wiki pages carry the background this skill assumes. Read\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md) for\nwhat each sampler does and how run time scales with the model, and\n[`wiki/core/api/analysis_objects.md`](../wiki/core/api/analysis_objects.md) for what the\nreturned `Result` contains.\n\n## Ask\n\nThree questions, and the answers change the branch:\n\n- *\"Do you already have `model`, `analysis` and `search`?\"* If not, route to\n [`ag_build_imaging_model`](./ag_build_imaging_model.md) and\n [`ag_configure_search`](./ag_configure_search.md) first. A fit assembled from a\n half-remembered model is the most expensive mistake available here.\n- *\"Smoke test first, or straight to the production run?\"* Almost always smoke test first —\n it takes seconds and answers \"does this script execute end to end?\", which is a different\n question from \"is this galaxy's Sersic index 3.2?\". The smoke branch is below.\n- *\"How long can this run, and on what?\"* A `MultiStartProdigy` fit is minutes; a `Nautilus`\n fit of a smooth model is tens of minutes on a GPU and can be hours on a CPU; a pixelised\n fit can be far longer. That answer decides foreground vs background, laptop vs cluster,\n and whether `live_visual_update` is worth switching on.\n\nIf the data is real observational imaging, the inspection gate in\n[`../AGENTS.md`](../AGENTS.md) applies before you get here at all — contaminants and mask\nextent are settled in [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md), not\nretrospectively.\n\n## Branch — the production run\n\nThe deliverable is one script in `scripts/` the user can re-run and edit. Adapted from\n`autogalaxy_workspace:scripts/imaging/start_here.py` (the fit and result sections) and\n`autogalaxy_workspace:scripts/imaging/modeling.py` (the Nautilus configuration and the VRAM\ncheck):\n\n```python\n\"\"\"\nGalaxy Structure: Run the Fit\n=============================\n\nFit a galaxy's surface-brightness profile to CCD imaging: load and mask the data, compose a\nlinear Sersic bulge, and sample the posterior with Nautilus so the inferred effective radius\nand Sersic index come with errors.\n\n__Contents__\n\n- **Imports:** JAX environment first, then the standard trio.\n- **Dataset:** Load imaging, mask it, and apply adaptive over-sampling.\n- **Model:** Compose the galaxy's light profile.\n- **Search:** Configure Nautilus and its update cadence.\n- **Analysis:** Bind the model to the data and choose the JAX backend.\n- **Model-Fit:** Run the search and announce the output folder.\n- **Result:** Read the best-fit model back.\n\"\"\"\nfrom autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\n\"\"\"\n__Dataset__\n\nGalaxy modeling needs three ingredients: the image in CCD counts, a per-pixel RMS noise-map,\nand the PSF. The PSF is forward-modelled rather than divided out, which is what separates a\ngenuinely compact bulge from a seeing-broadened one. `pixel_scales` converts pixels to\narcseconds and must match the instrument (`ag.Imaging.from_fits`,\n`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe mask sets which pixels enter the likelihood, and its radius is a science choice, not a\ndefault: truncate the outer isophotes and the effective radius and Sersic index are biased\ndirectly. Over-sampling evaluates the light profile several times per pixel where the\ngradient is steep, which matters most in the central few tenths of an arcsecond\n(`ag.util.over_sample.over_sample_size_via_radial_bins_from`).\n\"\"\"\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"\"\nMASK_RADIUS = 2.5\n\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n pixel_scales=0.1,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\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)\n\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n\n\"\"\"\n__Model__\n\nA linear `Sersic` bulge: the `intensity` is solved by linear inversion each iteration rather\nthan sampled, so the search explores one fewer dimension per component for free\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Linear Light Profiles__`).\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\n\n\"\"\"\n__Search__\n\n`Nautilus` is nested sampling: it returns the full posterior — every parameter's density,\nits errors, and the correlations between them. `n_live` trades accuracy against run time and\n200 covers the vast majority of galaxy models. `unique_tag` is conventionally the dataset\nname, which is what keeps the same model fitted to different data in different folders\n(`PyAutoFit:autofit/non_linear/search/nest/nautilus/search.py`).\n\"\"\"\nsearch = af.Nautilus(\n path_prefix=Path(\"imaging\"),\n name=\"sersic\",\n unique_tag=\"\",\n n_live=200,\n iterations_per_quick_update=10000,\n live_visual_update=False,\n)\n\n\"\"\"\n__Analysis__\n\n`ag.AnalysisImaging` defines the `log_likelihood_function` the search calls, and defaults to\n`use_jax=True` when JAX is installed (`PyAutoGalaxy:autogalaxy/imaging/model/analysis.py`).\n\"\"\"\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\n\"\"\"\n__Model-Fit__\n\nResults are written to the output folder on the fly, from the best model found so far, so the\nfolder is worth opening the moment the search starts.\n\"\"\"\nprint(f\"Output folder: {search.paths.output_path.resolve()}\")\n\nresult = search.fit(model=model, analysis=analysis)\n\n\"\"\"\n__Result__\n\"\"\"\nprint(result.info)\nprint(result.max_log_likelihood_instance)\n```\n\nRun it with writable caches if the default locations are not writable — a sandbox, CI, or an\ninstall imported from a Windows mount under WSL\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)):\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\n`search.fit` itself is `PyAutoFit:autofit/non_linear/search/abstract_search.py`.\n\n## Branch — what the output folder contains, and when to look\n\n**Announce the folder at launch, not at the end.** Quote\n`search.paths.output_path.resolve()` once the fit is running and say plainly that\n`model.results` and `image/fit.png` refresh as the search goes — there is nothing to wait\nfor. Users new to the stack sit watching a silent terminal because nobody told them.\n\nThe annotated tree of `files/`, `image/`, `model.info`, `model.results`, `search.summary`\nand the `` folder is `__Output Folder Layout__` in\n[`autogalaxy_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/modeling.py);\nthe same section appears in the `interferometer`, `multi_dataset`, `multi_galaxy` and\n`cluster` `modeling.py` scripts. Link it rather than copying the tree into the conversation,\nwhere it would rot. The condensed version is also in\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n\"The output folder\".\n\nName what to open first, in this order:\n\n1. `model.results` — the human-readable fit summary, parameters with errors.\n2. `image/fit.png` — data, model image, residuals and chi-squared map in one figure.\n3. `search.log` — tail it if you want to watch progress from a terminal.\n\nDepth follows [`_style.md`](./_style.md) \"Adaptive depth\": for a newcomer, or in teacher\nmode, walk all three. For a returning user, quoting the path is enough.\n\n## Branch — resuming, and the trap inside it\n\n`` is derived from the model, the search settings and the dataset identifier, so\nre-running an identical configuration **resumes** the existing fit rather than restarting it\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Unique Identifier__`). That is a\nfeature — an interrupted overnight run picks up where it stopped.\n\nIt is also the sharpest edge in the workflow. **The identifier does not hash the pixel\nvalues of your data.** Swap `data.fits` for a different galaxy, keep the model, the search\nand the `unique_tag` identical, and the next run finds a completed fit at the same path and\nreturns it — silently, in seconds, with the previous galaxy's parameters. If the data\nchanges, change the `unique_tag`. If you are unsure whether a result is stale, delete the\n`` folder and re-run rather than reasoning about it.\n\nTest mode namespaces its output separately: any active `PYAUTO_TEST_MODE` level inserts a\n`test_mode` segment straight after the output root, so a smoke run lands in\n`output/test_mode//...` and cannot short-circuit a later real fit\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## Branch — the update cadence and the live view\n\nTwo settings control what you see while the fit runs, both on the search\n(`PyAutoFit:autofit/non_linear/search/abstract_search.py`):\n\n- **`iterations_per_quick_update`** — how often the current best model is visualised and\n written to disk. The unit depends on the search: likelihood evaluations for `Nautilus`\n (hence the large `10000` in `modeling.py`), gradient steps for `MultiStartProdigy` (hence\n the much smaller `50` in `start_here.py`). Each update costs roughly ten seconds, so too\n low a value and output dominates the run time; too high and you cannot see progress. If\n the log is constantly reporting that it is outputting results, raise it.\n- **`live_visual_update`** — additionally push the quick-update image to a live surface: a\n matplotlib window that refreshes in a plain script, or a self-updating cell in Jupyter and\n Colab. The `fit.png` disk write happens either way. Leave it `False` on anything headless\n — an HPC node, a background process, CI.\n\nIf the search configuration already records the choice, don't re-ask; that decision belongs\nto [`ag_configure_search`](./ag_configure_search.md).\n\n## Branch — JAX, GPUs, and when the acceleration pays\n\nImaging fits run through JAX by default. Installing the extra (`pip install autogalaxy[jax]`)\nis all that is required: `ag.AnalysisImaging` then defaults to `use_jax=True`, and the search\ndriver wraps the likelihood in `jax.vmap(jax.jit(...))` so a whole batch of parameter vectors\nevaluates in one call. You will see a one-time log line as the JIT compile starts; every\nevaluation after that re-uses the compiled trace. This is described in\n`autogalaxy_workspace:scripts/guides/using_jax.py` `__Auto-Enabled Modeling__`, and if JAX is\nabsent the analysis warns once and falls back to NumPy.\n\n**When it pays.** The gain scales with how much array work each likelihood evaluation does,\nso it is largest for big masks, fine over-sampling, many-component bases and pixelised\nreconstructions, and smallest for a tiny mask with one smooth profile. GPU gains dwarf CPU\ngains: `autogalaxy_workspace:scripts/imaging/modeling.py` `__JAX__` quotes roughly ten\nminutes on a GPU against an hour on a CPU for its example, with a CPU still gaining from\nmultithreading. Gradient-based searches like `MultiStartProdigy` are not merely faster under\nJAX — they are only possible with it, because JAX is what supplies the likelihood's\nderivatives and evaluates all the parallel starts in one batched call\n(`autogalaxy_workspace:scripts/imaging/start_here.py` `__Multi Start Gradient Optimization__`).\n\n**Check VRAM before a long GPU run.** A JAX fit must fit inside the GPU's memory, and it\nfails at JIT-compile time or on the first likelihood call if it does not:\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py` `__VRAM Use__`. It takes\ntwenty or thirty seconds, so comment it out once you know your model's footprint. Batch size\nis the lever: larger batches cut wall-clock time and raise VRAM, smaller batches the reverse.\nA smooth-profile fit on a modest dataset is tens of megabytes; a pixelised reconstruction on\nhigh-resolution data can exceed ten gigabytes.\n\n**Turn JAX off to debug.** `ag.AnalysisImaging(dataset=dataset, use_jax=False)`, or\n`PYAUTO_DISABLE_JAX=1` to force it globally without editing code. NumPy stack traces are far\neasier to read, and you can drop a debugger or a `print` into code JAX would otherwise\ncompile. That is the first lever to pull when deciding whether a failure is a JAX problem at\nall — see [`ag_debug_fit_failure`](./ag_debug_fit_failure.md).\n\nFor running on a cluster — SLURM array jobs, one galaxy per task, the CPU and GPU batch\nscripts, and `number_of_cores` read from `SLURM_CPUS_PER_TASK` — read\n[`../wiki/core/operations/hpc.md`](../wiki/core/operations/hpc.md) for the concepts and\n[`../wiki/core/operations/hpc_infrastructure.md`](../wiki/core/operations/hpc_infrastructure.md)\nfor the `hpc/` templates and `sync` CLI this repo ships; the upstream ground truth behind both\nis `autogalaxy_workspace:scripts/guides/hpc/example_cpu_and_gpu.py`. The Python modeling code\nis identical for a GPU run; only the batch script changes.\n\n## Branch — the smoke test, before you spend hours\n\nEvery script gets one fast structural run before a real one. `PYAUTO_TEST_MODE` has four\nlevels ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)), and the\nchoice between them matters more than it looks:\n\n```bash\n# Level 1 — sampler runs with minimal iterations. A real (tiny) search: writes\n# model.results, image/fit.png and a samples.csv you can load back.\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n\n# Level 2 — sampler bypassed, likelihood called exactly once. The fastest proof that\n# the model composes and the likelihood evaluates.\nPYAUTO_TEST_MODE=2 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\n**Level 2 does not write the fit products.** A level-2 run returns a `Result`, proving the\nwiring, but leaves no `model.results` and no `image/fit.png` behind — so if the next thing\nyou want to do is plot or load the fit, use level 1. Level 3 skips the likelihood call as\nwell, which is only useful for checking that a script's non-fitting scaffolding runs.\n\n**The parameter values from any test-mode run are meaningless.** The sampler was truncated or\nmocked. Never quote a structural parameter measured in test mode; say explicitly that the\nnumber is a wiring check.\n\nFor the fastest possible loop, combine test mode with the dataset and output short-circuits:\n\n```bash\nPYAUTO_TEST_MODE=2 PYAUTO_SKIP_FIT_OUTPUT=1 PYAUTO_SKIP_VISUALIZATION=1 \\\n PYAUTO_SMALL_DATASETS=1 PYAUTO_FAST_PLOTS=1 python scripts/run_fit.py\n```\n\n`PYAUTO_SMALL_DATASETS=1` caps every array, mask and grid to 16 × 16 pixels — so delete any\npreviously simulated `dataset/` when you toggle it, or a full-resolution dataset on disk will\nbe reused and mismatch the capped grids.\n\n## Branch — the error that appears the moment the search starts\n\nOn some combinations of operating system and Python version, a script raises as soon as the\nsearch begins, from Python's process spawning rather than from anything about your model. The\nfix is to wrap the whole fit in a function and call it under a main guard:\n\n```python\ndef fit():\n from autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\n import autofit as af\n import autogalaxy as ag\n\n # ... dataset, model, search, analysis as above ...\n result = search.fit(model=model, analysis=analysis)\n\n\nif __name__ == \"__main__\":\n fit()\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/modeling/bug_fix.py`, which is the same\n`modeling.py` fit with this one structural change. It works for every dataset type, so adopt\nit for any modeling script that hits the error. If parallelisation still will not work after\nthe fix, that script points at the project's support channel.\n\n## Combine\n\n- [`ag_plot_fit`](./ag_plot_fit.md) — render the fit yourself, at whatever scaling and\n cropping the science needs, rather than reading the auto-generated `image/fit.png`.\n- [`ag_load_results`](./ag_load_results.md) — pull the posterior, the best-fit galaxies and\n the derived quantities back into Python, in-session or from disk later.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) — the fit finished but the residuals or\n the parameters are wrong.\n- [`ag_configure_search`](./ag_configure_search.md) — the fit is too slow, or the sampler is\n the wrong one for the model.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) — build a controlled dataset with known\n truth and fit that first, which is the cleanest way to separate a model problem from a\n data problem.\n\nWhen the script and its fit are worth keeping, offer (default-yes) to record the run in a\ndated `wiki/project/YYYY-MM-DD-.md` entry: the science question, what was inferred and\nwith what search, and the output path — per [`_style.md`](./_style.md) property #5.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Practicalities](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running a fit — output structure, reviewing results as they appear,\n and managing run times.\n- **General reference** — [RTD: New user guide](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n the decision tree for which fit to run first, by system scale and dataset type.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit, with the JAX and quick-update sections this skill\n mirrors.\n\n## Agent procedural checklist\n\n1. Confirm `model`, `analysis` and `search` exist; if not, route to the model-building and\n search-configuration skills.\n2. On real observational data, confirm the inspection gate has been satisfied.\n3. Write the script to `scripts/` in the generated-script style; never leave it inline only.\n4. Validate it with `PYAUTO_TEST_MODE=1` (level 2 if you only need the likelihood proved),\n with the cache variables set if the environment needs them.\n5. Launch the production run; **quote the absolute output path immediately** and say results\n refresh on the fly.\n6. Name `model.results` and `image/fit.png` as the first two things to open.\n7. If the data changed but the model did not, confirm the `unique_tag` changed too.\n8. On a GPU, run the VRAM check before a long fit.\n9. On completion, hand off to the results-loading or fit-plotting skill rather than\n interpreting the numbers inline.\n10. Offer the `wiki/project/` entry.\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_2_modeling/tutorial_3_why_modeling_is_hard.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_debug_fit_failure\n\n---\nname: ag_debug_fit_failure\ndescription: Triage a galaxy fit that crashed, stalled, or finished with residuals and parameters you do not believe. Works through a failure taxonomy — bad environment, bad data, bad model, bad priors, bad search settings, or a stale result that was never re-run — and gives the probes that separate them: hand-evaluating the likelihood at prior medians, checking the mask extent and over-sampling scheme, reading the normalised-residual and chi-squared maps, walking the likelihood step by step, forcing the NumPy path to get a readable stack trace, and the `PYAUTO_TEST_MODE` short-circuit loop for fast iteration. Also covers the two silent failures: a resumed fit whose identifier ignored the data, and a cached result mistaken for a new one. Use when a fit raises, hangs, returns nonsense, or converges somewhere unphysical. Not for the first composition of a model (`ag_build_imaging_model`), not for routine result inspection (`ag_load_results`), and not for an environment that will not import at all (`ag_setup_environment`).\n---\n\n# When the fit goes wrong\n\nA galaxy fit fails in a small number of characteristic ways, and the debugging cost is\ndominated by mis-attribution: hours spent widening priors when the mask was truncating the\nouter isophotes, or rebuilding a model when the script was quietly resuming a cached result\nfrom last week. So the first move is never a fix — it is to establish *which kind* of failure\nthis is.\n\nThe discipline that makes that possible is cheap probes before expensive ones. A single\nlikelihood evaluation costs a fraction of a second and tells you whether the model and data\ncan talk to each other at all. A `PYAUTO_TEST_MODE=2` run costs seconds and proves the whole\nscript executes. Only after those pass is it worth spending an hour of sampling to find out\nwhether the *inference* is the problem.\n\n## Ask\n\nGet the symptom precisely, because the taxonomy branches on it:\n\n- *\"Did it raise, hang, or complete?\"* A raise has a traceback to read. A hang is usually\n parallelisation, a JIT compile you mistook for a stall, or an update cadence writing output\n constantly. A completed fit that looks wrong is the hardest case and needs the residuals.\n- *\"What makes you say it is wrong?\"* Coherent residuals, an unphysical parameter, an error\n bar that is implausibly tight or implausibly wide, or the number simply disagreeing with the\n literature — each points somewhere different.\n- *\"Simulated data or real observations?\"* On simulated data you know the truth, which makes\n everything below faster. If the user has real data and no simulated control, running one is\n often the fastest path to an answer ([`ag_simulate_dataset`](./ag_simulate_dataset.md)).\n- *\"Has this exact script run before?\"* This decides whether the stale-result trap is in play.\n\n## The taxonomy\n\nSix categories, ordered by how cheap they are to rule out:\n\n| Category | Tell | First probe |\n|---|---|---|\n| **Stale output** | The fit \"finished\" implausibly fast, or the result is identical after you changed something | Delete the `` folder and re-run |\n| **Environment** | An import error, a numba or matplotlib cache error, a parallelisation error the moment the search starts | `--check-install`, the cache variables, the main guard |\n| **Bad data** | Residuals dominated by one blob, or a suspiciously large chi-squared everywhere | Plot the dataset; check the noise-map and the mask |\n| **Bad model** | Coherent, structured residuals with a physical shape | Read the residual pattern; add or change a component |\n| **Bad priors** | The best fit sits on a prior boundary, or the search never moves off its start | `model.info`; hand-evaluate the likelihood |\n| **Bad search settings** | Wide posteriors, a low log evidence, different runs disagreeing, no errors at all | `search.summary`; raise `n_live`, or change search |\n\nThe rest of this skill is one branch per category.\n\n## Branch — stale output, the silent one\n\nRule this out first, every time, because it is invisible and it invalidates everything else you\nwould conclude.\n\nA fit's output folder is `output/////`, and\n`` is derived from the model, the search settings and the dataset identifier. An\nidentical configuration therefore **resumes** rather than restarting\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Unique Identifier__`). That is a\nfeature for an interrupted overnight run and a trap the rest of the time, because **the\nidentifier does not hash the pixel values of your data**. Swap `data.fits` for a different\ngalaxy while keeping the model, search and `unique_tag` the same, and the next run finds a\ncompleted fit at the same path and hands it back — in seconds, with the previous galaxy's\nparameters, and no warning that anything is wrong.\n\nThe symptoms: a fit that completes far faster than it should; a result that does not change\nafter you deliberately changed the data; `model.results` timestamps older than the run you\njust launched.\n\n```bash\n# Prove it rather than reasoning about it.\nrm -rf output////\n```\n\nThen re-run. If the answer changes, that was the bug. Going forward, change the `unique_tag`\nwhenever the data changes — that is what it is for.\n\nThe related trap: test-mode output. Any active `PYAUTO_TEST_MODE` level inserts a `test_mode`\nsegment straight after the output root, precisely so a smoke run cannot short-circuit a later\nreal fit ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)). If you\nfind yourself inspecting a result whose path contains `test_mode`, stop: every parameter in it\nis a wiring check. Also delete any simulated `dataset/` when you toggle\n`PYAUTO_SMALL_DATASETS`, or a full-resolution dataset on disk gets reused against capped grids\nand produces shape errors that look like library bugs.\n\n## Branch — environment and the errors that fire at launch\n\nIf the stack itself is the problem, nothing downstream is diagnostic. Confirm the install\nfirst:\n\n```bash\npython autoassistant/audit_skill_apis.py --check-install\n```\n\nExit `0` is ready; `2` means the packages are absent from *this* interpreter; `3` means they\nwere found but an import raised. Repairing it is\n[`ag_setup_environment`](./ag_setup_environment.md), with the routes in\n[`wiki/core/operations/installation.md`](../wiki/core/operations/installation.md).\n\nThree failures that are environment, not science:\n\n- **A numba or matplotlib cache error** buried in a long trace — the libraries cannot write\n their caches. Fix with `NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib`\n ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n- **An error the instant the search starts**, from Python's process spawning rather than from\n your model. Wrap the fit in a function under a main guard, exactly as\n `autogalaxy_workspace:scripts/guides/modeling/bug_fix.py` does — it is the same\n `modeling.py` fit with this one structural change:\n\n ```python\n def fit():\n from autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\n import autofit as af\n import autogalaxy as ag\n\n # ... dataset, mask, over-sampling, model, search, analysis ...\n result = search.fit(model=model, analysis=analysis)\n\n\n if __name__ == \"__main__\":\n fit()\n ```\n\n It applies to every dataset type, so adopt it for any modeling script that hits the error.\n That script also names the project's support channel if the fix is not enough.\n- **A stale API symbol** — an `AttributeError` on a PyAuto\\* name recalled from an older\n release. Do not guess a replacement; check it:\n\n ```bash\n python autoassistant/audit_skill_apis.py --file scripts/run_fit.py\n ```\n\n [`ag_audit_skill_apis`](./ag_audit_skill_apis.md) owns that check and its bypass.\n\n### Is it a JAX problem?\n\nThe single most useful lever, because it splits the space in two:\n\n```python\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=False)\n```\n\nor, without editing code, `PYAUTO_DISABLE_JAX=1` to force the NumPy path on every analysis\n(`autogalaxy_workspace:scripts/guides/using_jax.py` `__Disabling JAX__`). NumPy stack traces\nare far easier to read than compiled ones, and you can drop a debugger or a `print` into code\nJAX would otherwise compile away. If the failure disappears on NumPy, it is a JAX problem; if\nit survives, JAX was never involved and you have halved the search space.\n\nTwo JAX-specific failure shapes worth recognising:\n\n- **An out-of-memory error at compile time or on the first likelihood call** on a GPU. Check\n the footprint before a long run:\n `analysis.print_vram_use(model=model, batch_size=search.batch_size)`\n (`autogalaxy_workspace:scripts/imaging/modeling.py` `__VRAM Use__`), and lower the batch\n size if it is close to the card's limit.\n- **A long pause at the start that looks like a hang.** The first evaluation compiles the\n likelihood and its gradient; every step after that re-uses the compiled result. The log\n line announcing the compile is the tell\n (`autogalaxy_workspace:scripts/imaging/start_here.py` `__JAX__`). A persistent compilation\n cache means this is paid once per machine, not once per process\n ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## Branch — bad data\n\nPlot the dataset before you plot anything else. On real observations this is not optional —\nthe inspection gate in [`../AGENTS.md`](../AGENTS.md) requires it before a fit is even\ncomposed, and a fit that skipped it is a prime suspect.\n\n```python\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=PLOT_DIR,\n output_filename=\"dataset\",\n output_format=\"png\",\n)\n```\n\nFour things to check, in order:\n\n1. **Contaminants.** A neighbouring galaxy, a foreground star or a reduction artefact inside\n the mask contributes to the likelihood and biases every parameter. The fix is to scale its\n noise rather than cut the pixels out — `dataset.apply_noise_scaling(mask=mask_extra_galaxies)`\n keeps the pixels in the fit but makes them contribute negligibly, which avoids the\n discontinuities that removing pixels creates\n (`autogalaxy_workspace:scripts/imaging/modeling.py` `__Extra Galaxies Noise Scaling__`).\n Alternatively shrink the circular mask so the contaminant falls outside it. Concept:\n [`wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md);\n the tooling is [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md).\n2. **The mask extent.** Too small and it truncates the outer isophotes, which biases the\n effective radius and the Sersic index directly — the classic cause of a \"wrong\" Sersic\n index. Too large and it drags sky and neighbours in, slowing the fit for no information.\n [`wiki/core/concepts/grids_and_masks.md`](../wiki/core/concepts/grids_and_masks.md)\n \"Choosing the radius is a science decision\".\n3. **The noise-map.** If it is underestimated, chi-squared is uniformly too large and the\n posterior is spuriously tight; if overestimated, the reverse. A residual map that is\n featureless but scaled wrong across the whole image points here rather than at the model.\n4. **`pixel_scales`.** Wrong by a factor and every angular quantity is wrong by that factor,\n while the fit looks perfectly healthy. Check it against the instrument.\n\n## Branch — bad model\n\nThis is what coherent residuals mean. Rebuild the fit and read the maps:\n\n```python\nfit = result.max_log_likelihood_fit # or ag.FitImaging(dataset=dataset, galaxies=galaxies)\n\nprint(f\"chi_squared = {fit.chi_squared}\")\nprint(f\"log_likelihood = {fit.log_likelihood}\")\nprint(f\"figure_of_merit = {fit.figure_of_merit}\")\n\naplt.plot_array(\n array=fit.normalized_residual_map,\n title=\"Normalized Residual Map\",\n symmetric=True,\n output_path=PLOT_DIR,\n output_filename=\"normalized_residual_map\",\n output_format=\"png\",\n)\naplt.plot_array(\n array=fit.chi_squared_map,\n title=\"Chi-Squared Map\",\n output_path=PLOT_DIR,\n output_filename=\"chi_squared_map\",\n output_format=\"png\",\n)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Fit Figures__`. Read the\n**normalised** residuals first: they are the only map calibrated against the noise, so they\nanswer *significance* rather than *magnitude*. Scatter within roughly ±3 is consistent with\nnoise; coherent structure outside that is a model failure however faint it looks.\n\nTwo quick numerical summaries worth printing alongside the figures — chi-squared per unmasked\npixel (order unity for a good fit), and the fraction of pixels beyond 3σ (a few per cent for a\ngood fit, tens of per cent for a badly wrong model).\n\nThe residual patterns and what each implies are tabulated in\n[`ag_plot_fit`](./ag_plot_fit.md) \"The inspection discipline\". The model responses:\n\n- **Ring at one radius** → the radial profile is too rigid. One Sersic where a bulge plus a\n disk is needed, or a Sersic index that was fixed. Free it, or add the second component.\n- **Four-lobed alternating pattern** → the ellipticity or position angle is wrong, or the\n isophotes twist with radius. [`wiki/core/concepts/ellipse_fitting_and_multipoles.md`](../wiki/core/concepts/ellipse_fitting_and_multipoles.md).\n- **Central excess** → coarse over-sampling, or a nuclear component the model lacks. Check the\n over-sampling scheme before adding physics (below).\n- **Clumpy, asymmetric structure no smooth profile can absorb** → this is where a\n many-component basis or a pixelised reconstruction earns its keep:\n [`wiki/core/concepts/linear_light_profiles_and_mge.md`](../wiki/core/concepts/linear_light_profiles_and_mge.md),\n [`wiki/core/concepts/shapelets.md`](../wiki/core/concepts/shapelets.md),\n [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n- **A uniform offset across the whole image** → an unmodelled sky background:\n [`wiki/core/concepts/sky_background_and_operated_profiles.md`](../wiki/core/concepts/sky_background_and_operated_profiles.md).\n\n**Check the over-sampling before blaming the physics.** A steep central profile evaluated once\nper pixel is systematically wrong at the centre, and the symptom is exactly the residual a\nmissing nuclear component would leave:\n\n```python\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_lp=over_sample_size)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py` `__Over Sampling__`. Re-plot\nthe dataset subplot afterwards — its lower panels show the scheme that was actually applied,\nso you can confirm it rather than assume it. The full treatment, including why the outer bins\nnever drop to a single sub-pixel, is\n[`wiki/core/concepts/grids_and_masks.md`](../wiki/core/concepts/grids_and_masks.md)\n\"Over-sampling\", with the runnable guide at\n`autogalaxy_workspace:scripts/guides/advanced/over_sampling.py`.\n\nAdding complexity is [`ag_build_imaging_model`](./ag_build_imaging_model.md). Do it one\ncomponent at a time and re-fit: a model that gained three components at once tells you nothing\nabout which one mattered.\n\n## Branch — bad priors, and hand-evaluating the likelihood\n\nThe most direct probe in the whole stack. A model and an analysis are enough — no search, no\nwaiting:\n\n```python\ninstance = model.instance_from_prior_medians()\nlog_likelihood = analysis.log_likelihood_function(instance=instance)\n\nprint(f\"log likelihood at prior medians = {log_likelihood}\")\n```\n\nFrom [`wiki/core/api/analysis_objects.md`](../wiki/core/api/analysis_objects.md) \"Evaluating\nthe likelihood by hand\". `log_likelihood_function(instance)` is the single contract between a\nmodel and data, so what it returns is diagnostic on its own:\n\n- **It raises.** The failure is in the forward model or the data shapes, not in the inference.\n Force `use_jax=False` first for a readable trace, then walk the likelihood step by step\n (next branch).\n- **It returns `nan` or `-inf`.** Something in the model is degenerate at those parameter\n values — a zero or negative size, a profile whose centre sits outside the mask, a noise-map\n with zeros.\n- **It returns a finite but wildly bad value, and the fit's best likelihood is barely better.**\n The search never found anything, which usually means the priors do not contain the answer.\n- **It returns something close to the fit's best value.** The priors are fine and the search\n is doing its job; look elsewhere.\n\nThen compare against a known-good instance. On simulated data you have the truth, so evaluate\nthe likelihood there: if the true model scores much better than anything the search found, the\npriors or the search settings are at fault, not the model. This is the cleanest experiment\navailable, and it is the reason to keep a simulated control alongside real data\n([`ag_simulate_dataset`](./ag_simulate_dataset.md)).\n\nRead the priors themselves rather than recalling them:\n\n```python\nprint(model.info)\n```\n\nThree specific things to look for. **A best-fit parameter sitting on a prior boundary** means\nthe prior is truncating the posterior — the answer may be outside it entirely. **A prior far\nwider than physically sensible** wastes the search's effort and invites multi-modality. And\n**a prior narrowed to make a search behave** is a scientific choice, not a convenience: it\nchanges the posterior and therefore the answer. If you want to steer where a search *starts*\nwithout changing the posterior, that is a start point, and only the MCMC and optimisation\nsearches accept one — nested samplers draw from the prior by construction\n([`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n\"Priors and start points\"). Defaults come from configuration\n([`wiki/core/api/configuration.md`](../wiki/core/api/configuration.md)), and overriding them\nper parameter is [`ag_build_imaging_model`](./ag_build_imaging_model.md).\n\nAlso confirm the galaxy is near the coordinate origin. The default priors assume a centre near\n(0.0\", 0.0\"); a galaxy several arcseconds off-centre needs either re-centred data or\nexplicitly overridden centre priors (`autogalaxy_workspace:scripts/imaging/modeling.py`\n`__Coordinates__`).\n\n## Branch — walking the likelihood step by step\n\nWhen the hand evaluation raises or returns something inexplicable, the step-by-step\nwalkthrough is the ground truth. `autogalaxy_workspace:scripts/imaging/likelihood_function.py`\ncomputes a galaxy model's log likelihood one NumPy operation at a time — the elliptical\ncoordinate transform, each light profile's image, the sum into a galaxy image, the blurring\ngrid and PSF convolution, then:\n\n```\nmodel_data = convolved_image_2d\nresidual_map = data - model_data\nnormalized_residual_map = residual_map / noise_map\nchi_squared_map = normalized_residual_map ** 2\nchi_squared = sum(chi_squared_map)\nnoise_normalization = sum(log(2 * pi * noise_map ** 2))\nfigure_of_merit = -0.5 * (chi_squared + noise_normalization)\n```\n\nand finishes by showing that `ag.FitImaging(dataset=dataset, galaxies=galaxies).figure_of_merit`\nreproduces the same number. Running it against your own dataset localises the failure to one\nstep, which is far faster than reading a compiled trace.\n\nThere are matching walkthroughs for the features whose likelihood is genuinely different, and\nthe difference is where their failures live:\n`autogalaxy_workspace:scripts/imaging/features/linear_light_profiles/likelihood_function.py`\n(the mapping matrix, data vector, curvature matrix and the positive-only reconstruction),\n`.../multi_gaussian_expansion/likelihood_function.py` (the same for a Gaussian basis), and\n`.../pixelization/likelihood_function.py` (the regularisation matrix and the Bayesian\ncomplexity terms). If a fit with linear profiles or a pixelisation fails where a standard\nprofile fit succeeds, the extra linear-algebra steps in those scripts are the place to look.\n\nA real fit does not run that NumPy code — it runs the same calculation compiled. To probe the\ncompiled path exactly as a search drives it, `autogalaxy_workspace:scripts/guides/using_jax.py`\n`__Custom Likelihood Functions__` shows the `Fitness` route, and explains why batching a vector\nof parameters is a stricter test than one concrete call: a single call can quietly succeed on\ncode where NumPy is leaking through, and then break as soon as the search batches.\n\n## Branch — bad search settings\n\nThe model and data are fine; the sampler did not do its job. Read the search's own report\nfirst: `search.summary` in the output folder, plus `result.samples.log_evidence` and the\nposterior widths.\n\n- **Posteriors far wider than the data should allow, or a low log evidence** → too few live\n points for the model's dimensionality. `n_live=200` covers most galaxy models; raise it for\n a complex one ([`wiki/core/api/searches.md`](../wiki/core/api/searches.md)).\n- **No errors at all** → the fit used a gradient optimiser, which is maximum-a-posteriori and\n returns one model. Re-run with `Nautilus` if the science needs uncertainties\n (`autogalaxy_workspace:scripts/imaging/start_here.py` `__Posterior__`).\n- **Two runs of the same configuration disagreeing** → a multi-modal parameter space with a\n search that is finding different modes. Either raise `n_live`, or start simple and chain into\n the complex model with the simple fit's posterior as priors\n ([`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n \"Search chaining\"; the runnable version is\n `autogalaxy_workspace:scripts/guides/modeling/chaining.py`).\n- **Run time far longer than expected** → total cost is (likelihood evaluation time) ×\n (number of evaluations), and dimensionality dominates. A many-Gaussian expansion with six\n free parameters routinely beats a multi-component decomposition with thirteen, despite the\n slower per-evaluation cost. [`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n \"Run-time estimation\".\n- **The log constantly reporting that it is outputting results** → `iterations_per_quick_update`\n is too low and visualisation is eating the run. Raise it\n ([`ag_run_search`](./ag_run_search.md)).\n\nChoosing and tuning the search is [`ag_configure_search`](./ag_configure_search.md).\n\n## Branch — the fast iteration loop\n\nWhile you are changing a script's structure, do not pay for inference. `PYAUTO_TEST_MODE` has\nfour levels ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)):\n\n```bash\n# Level 2 — sampler bypassed, likelihood called exactly once. The fastest proof that the\n# model composes, the shapes agree and the likelihood evaluates.\nPYAUTO_TEST_MODE=2 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n\n# Level 1 — a real but minimal search. Slower, and the only level that writes model.results,\n# image/fit.png and a loadable samples.csv.\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\nLevel 2 does **not** write the fit products, which is worth knowing before you go looking for\n`image/fit.png` after a level-2 run. Level 3 skips the likelihood as well, so it only checks\nthe non-fitting scaffolding. `PYAUTO_SKIP_CHECKS=1` is available when a smoke run trips a\nruntime validation on data too small to be sane — never set it for a real fit, since those\nchecks are what stop a silently degenerate inversion. And **never quote a parameter measured\nin test mode**: the sampler was truncated or mocked, so the numbers are wiring evidence, not\nmeasurements.\n\nThe loop that works: level 2 until the script runs clean → level 1 until the products look\nsane → one full run on a small mask or a simulated dataset → the production fit.\n\n## Branch — when nothing above explains it\n\nTwo escalations, in order.\n\n**Reduce to a control.** Simulate a dataset from a model you choose, fit it with that same\nmodel, and confirm you recover the truth\n([`ag_simulate_dataset`](./ag_simulate_dataset.md)). If the control fails, the problem is in\nthe code or the setup. If the control succeeds, the problem is in the real data or its\npreparation — and you have narrowed it to a half of the space you could not distinguish\nbefore. This is the single highest-value move in this skill and it is under-used.\n\n**Check the library, not yourself.** If a symbol does not resolve or an idiom that reads\ncorrectly does not work, run the audit — a construction can be retired while every token in it\nstill imports:\n\n```bash\npython autoassistant/audit_skill_apis.py --scope scripts\npython autoassistant/audit_skill_apis.py --lint-idioms\n```\n\n[`ag_audit_skill_apis`](./ag_audit_skill_apis.md) owns both. Only after those come back clean\nis \"this might be a library bug\" a reasonable hypothesis — at which point\n[`contribute-upstream`](./contribute-upstream.md) is the route to filing it with a minimal\nreproduction.\n\n## Combine\n\n- [`ag_plot_fit`](./ag_plot_fit.md) — the residual-pattern table this skill's model branch\n routes through, and the figures that make a diagnosis visible.\n- [`ag_build_imaging_model`](./ag_build_imaging_model.md) — acting on a \"bad model\" or \"bad\n priors\" verdict.\n- [`ag_configure_search`](./ag_configure_search.md) — acting on a \"bad search settings\"\n verdict.\n- [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md) — acting on a \"bad data\" verdict:\n masks, noise scaling, contaminant handling.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) — the control experiment.\n- [`ag_setup_environment`](./ag_setup_environment.md) — the install will not import at all.\n- [`ag_run_search`](./ag_run_search.md) — re-launching once the cause is fixed.\n\nRecord the diagnosis, not just the fix. Offer (default-yes) a dated\n`wiki/project/YYYY-MM-DD-.md` entry naming the symptom, the probe that localised it, and\nwhat changed — per [`_style.md`](./_style.md) property #5. A debugging session that is not\nwritten down gets repeated.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Why modeling is hard](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_3_why_modeling_is_hard.ipynb):\n why searches fail on galaxy models, what a local maximum looks like in practice, and how\n model complexity and prior choice interact.\n- **General reference** — [RTD: Likelihood function](https://pyautogalaxy.readthedocs.io/en/latest/general/likelihood_function.html):\n the likelihood the library evaluates, and pointers into the step-by-step walkthroughs.\n- **Experienced PyAutoGalaxy user** — [workspace: guides/modeling/bug_fix.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/guides/modeling/bug_fix.py):\n the main-guard fix for the parallelisation error, as a complete runnable fit.\n\n## Agent procedural checklist\n\n1. Get the symptom: raised, hung, or completed-but-wrong; and what makes it wrong.\n2. Rule out stale output first — check timestamps, then `rm -rf` the `` folder and\n re-run. Check for a `test_mode` path segment.\n3. Confirm the environment with `--check-install`; apply the cache variables and the main guard\n if either applies.\n4. Toggle `use_jax=False` (or `PYAUTO_DISABLE_JAX=1`) to split JAX from non-JAX failures and\n get a readable trace.\n5. Plot the dataset: contaminants, mask extent, noise-map, `pixel_scales`.\n6. Hand-evaluate `analysis.log_likelihood_function(instance=model.instance_from_prior_medians())`\n before running any search.\n7. Read `model.info` for boundary-hugging and over-wide priors; confirm the galaxy is near the\n origin.\n8. Rebuild the fit and read the **normalised residual** map, then the chi-squared map; check\n the over-sampling scheme before adding physics.\n9. Read `search.summary` and the log evidence for search-settings failures.\n10. Iterate with `PYAUTO_TEST_MODE=2`, then `=1`; never quote a test-mode parameter.\n11. If unresolved, build a simulated control and fit it; run the symbol and idiom audits before\n suspecting a library bug.\n12. Offer the `wiki/project/` entry recording symptom, probe and fix.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_2_modeling/tutorial_4_linear_profiles.ipynb b/notebooks/chapter_2_modeling/tutorial_4_linear_profiles.ipynb index 23512f3..8e067b2 100644 --- a/notebooks/chapter_2_modeling/tutorial_4_linear_profiles.ipynb +++ b/notebooks/chapter_2_modeling/tutorial_4_linear_profiles.ipynb @@ -494,7 +494,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_2_modeling/tutorial_4_linear_profiles.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_debug_fit_failure\n\n---\nname: ag_debug_fit_failure\ndescription: Triage a galaxy fit that crashed, stalled, or finished with residuals and parameters you do not believe. Works through a failure taxonomy \u2014 bad environment, bad data, bad model, bad priors, bad search settings, or a stale result that was never re-run \u2014 and gives the probes that separate them: hand-evaluating the likelihood at prior medians, checking the mask extent and over-sampling scheme, reading the normalised-residual and chi-squared maps, walking the likelihood step by step, forcing the NumPy path to get a readable stack trace, and the `PYAUTO_TEST_MODE` short-circuit loop for fast iteration. Also covers the two silent failures: a resumed fit whose identifier ignored the data, and a cached result mistaken for a new one. Use when a fit raises, hangs, returns nonsense, or converges somewhere unphysical. Not for the first composition of a model (`ag_build_imaging_model`), not for routine result inspection (`ag_load_results`), and not for an environment that will not import at all (`ag_setup_environment`).\n---\n\n# When the fit goes wrong\n\nA galaxy fit fails in a small number of characteristic ways, and the debugging cost is\ndominated by mis-attribution: hours spent widening priors when the mask was truncating the\nouter isophotes, or rebuilding a model when the script was quietly resuming a cached result\nfrom last week. So the first move is never a fix \u2014 it is to establish *which kind* of failure\nthis is.\n\nThe discipline that makes that possible is cheap probes before expensive ones. A single\nlikelihood evaluation costs a fraction of a second and tells you whether the model and data\ncan talk to each other at all. A `PYAUTO_TEST_MODE=2` run costs seconds and proves the whole\nscript executes. Only after those pass is it worth spending an hour of sampling to find out\nwhether the *inference* is the problem.\n\n## Ask\n\nGet the symptom precisely, because the taxonomy branches on it:\n\n- *\"Did it raise, hang, or complete?\"* A raise has a traceback to read. A hang is usually\n parallelisation, a JIT compile you mistook for a stall, or an update cadence writing output\n constantly. A completed fit that looks wrong is the hardest case and needs the residuals.\n- *\"What makes you say it is wrong?\"* Coherent residuals, an unphysical parameter, an error\n bar that is implausibly tight or implausibly wide, or the number simply disagreeing with the\n literature \u2014 each points somewhere different.\n- *\"Simulated data or real observations?\"* On simulated data you know the truth, which makes\n everything below faster. If the user has real data and no simulated control, running one is\n often the fastest path to an answer ([`ag_simulate_dataset`](./ag_simulate_dataset.md)).\n- *\"Has this exact script run before?\"* This decides whether the stale-result trap is in play.\n\n## The taxonomy\n\nSix categories, ordered by how cheap they are to rule out:\n\n| Category | Tell | First probe |\n|---|---|---|\n| **Stale output** | The fit \"finished\" implausibly fast, or the result is identical after you changed something | Delete the `` folder and re-run |\n| **Environment** | An import error, a numba or matplotlib cache error, a parallelisation error the moment the search starts | `--check-install`, the cache variables, the main guard |\n| **Bad data** | Residuals dominated by one blob, or a suspiciously large chi-squared everywhere | Plot the dataset; check the noise-map and the mask |\n| **Bad model** | Coherent, structured residuals with a physical shape | Read the residual pattern; add or change a component |\n| **Bad priors** | The best fit sits on a prior boundary, or the search never moves off its start | `model.info`; hand-evaluate the likelihood |\n| **Bad search settings** | Wide posteriors, a low log evidence, different runs disagreeing, no errors at all | `search.summary`; raise `n_live`, or change search |\n\nThe rest of this skill is one branch per category.\n\n## Branch \u2014 stale output, the silent one\n\nRule this out first, every time, because it is invisible and it invalidates everything else you\nwould conclude.\n\nA fit's output folder is `output/////`, and\n`` is derived from the model, the search settings and the dataset identifier. An\nidentical configuration therefore **resumes** rather than restarting\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Unique Identifier__`). That is a\nfeature for an interrupted overnight run and a trap the rest of the time, because **the\nidentifier does not hash the pixel values of your data**. Swap `data.fits` for a different\ngalaxy while keeping the model, search and `unique_tag` the same, and the next run finds a\ncompleted fit at the same path and hands it back \u2014 in seconds, with the previous galaxy's\nparameters, and no warning that anything is wrong.\n\nThe symptoms: a fit that completes far faster than it should; a result that does not change\nafter you deliberately changed the data; `model.results` timestamps older than the run you\njust launched.\n\n```bash\n# Prove it rather than reasoning about it.\nrm -rf output////\n```\n\nThen re-run. If the answer changes, that was the bug. Going forward, change the `unique_tag`\nwhenever the data changes \u2014 that is what it is for.\n\nThe related trap: test-mode output. Any active `PYAUTO_TEST_MODE` level inserts a `test_mode`\nsegment straight after the output root, precisely so a smoke run cannot short-circuit a later\nreal fit ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)). If you\nfind yourself inspecting a result whose path contains `test_mode`, stop: every parameter in it\nis a wiring check. Also delete any simulated `dataset/` when you toggle\n`PYAUTO_SMALL_DATASETS`, or a full-resolution dataset on disk gets reused against capped grids\nand produces shape errors that look like library bugs.\n\n## Branch \u2014 environment and the errors that fire at launch\n\nIf the stack itself is the problem, nothing downstream is diagnostic. Confirm the install\nfirst:\n\n```bash\npython autoassistant/audit_skill_apis.py --check-install\n```\n\nExit `0` is ready; `2` means the packages are absent from *this* interpreter; `3` means they\nwere found but an import raised. Repairing it is\n[`ag_setup_environment`](./ag_setup_environment.md), with the routes in\n[`wiki/core/operations/installation.md`](../wiki/core/operations/installation.md).\n\nThree failures that are environment, not science:\n\n- **A numba or matplotlib cache error** buried in a long trace \u2014 the libraries cannot write\n their caches. Fix with `NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib`\n ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n- **An error the instant the search starts**, from Python's process spawning rather than from\n your model. Wrap the fit in a function under a main guard, exactly as\n `autogalaxy_workspace:scripts/guides/modeling/bug_fix.py` does \u2014 it is the same\n `modeling.py` fit with this one structural change:\n\n ```python\n def fit():\n from autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\n import autofit as af\n import autogalaxy as ag\n\n # ... dataset, mask, over-sampling, model, search, analysis ...\n result = search.fit(model=model, analysis=analysis)\n\n\n if __name__ == \"__main__\":\n fit()\n ```\n\n It applies to every dataset type, so adopt it for any modeling script that hits the error.\n That script also names the project's support channel if the fix is not enough.\n- **A stale API symbol** \u2014 an `AttributeError` on a PyAuto\\* name recalled from an older\n release. Do not guess a replacement; check it:\n\n ```bash\n python autoassistant/audit_skill_apis.py --file scripts/run_fit.py\n ```\n\n [`ag_audit_skill_apis`](./ag_audit_skill_apis.md) owns that check and its bypass.\n\n### Is it a JAX problem?\n\nThe single most useful lever, because it splits the space in two:\n\n```python\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=False)\n```\n\nor, without editing code, `PYAUTO_DISABLE_JAX=1` to force the NumPy path on every analysis\n(`autogalaxy_workspace:scripts/guides/using_jax.py` `__Disabling JAX__`). NumPy stack traces\nare far easier to read than compiled ones, and you can drop a debugger or a `print` into code\nJAX would otherwise compile away. If the failure disappears on NumPy, it is a JAX problem; if\nit survives, JAX was never involved and you have halved the search space.\n\nTwo JAX-specific failure shapes worth recognising:\n\n- **An out-of-memory error at compile time or on the first likelihood call** on a GPU. Check\n the footprint before a long run:\n `analysis.print_vram_use(model=model, batch_size=search.batch_size)`\n (`autogalaxy_workspace:scripts/imaging/modeling.py` `__VRAM Use__`), and lower the batch\n size if it is close to the card's limit.\n- **A long pause at the start that looks like a hang.** The first evaluation compiles the\n likelihood and its gradient; every step after that re-uses the compiled result. The log\n line announcing the compile is the tell\n (`autogalaxy_workspace:scripts/imaging/start_here.py` `__JAX__`). A persistent compilation\n cache means this is paid once per machine, not once per process\n ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## Branch \u2014 bad data\n\nPlot the dataset before you plot anything else. On real observations this is not optional \u2014\nthe inspection gate in [`../AGENTS.md`](../AGENTS.md) requires it before a fit is even\ncomposed, and a fit that skipped it is a prime suspect.\n\n```python\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=PLOT_DIR,\n output_filename=\"dataset\",\n output_format=\"png\",\n)\n```\n\nFour things to check, in order:\n\n1. **Contaminants.** A neighbouring galaxy, a foreground star or a reduction artefact inside\n the mask contributes to the likelihood and biases every parameter. The fix is to scale its\n noise rather than cut the pixels out \u2014 `dataset.apply_noise_scaling(mask=mask_extra_galaxies)`\n keeps the pixels in the fit but makes them contribute negligibly, which avoids the\n discontinuities that removing pixels creates\n (`autogalaxy_workspace:scripts/imaging/modeling.py` `__Extra Galaxies Noise Scaling__`).\n Alternatively shrink the circular mask so the contaminant falls outside it. Concept:\n [`wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md);\n the tooling is [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md).\n2. **The mask extent.** Too small and it truncates the outer isophotes, which biases the\n effective radius and the Sersic index directly \u2014 the classic cause of a \"wrong\" Sersic\n index. Too large and it drags sky and neighbours in, slowing the fit for no information.\n [`wiki/core/concepts/grids_and_masks.md`](../wiki/core/concepts/grids_and_masks.md)\n \"Choosing the radius is a science decision\".\n3. **The noise-map.** If it is underestimated, chi-squared is uniformly too large and the\n posterior is spuriously tight; if overestimated, the reverse. A residual map that is\n featureless but scaled wrong across the whole image points here rather than at the model.\n4. **`pixel_scales`.** Wrong by a factor and every angular quantity is wrong by that factor,\n while the fit looks perfectly healthy. Check it against the instrument.\n\n## Branch \u2014 bad model\n\nThis is what coherent residuals mean. Rebuild the fit and read the maps:\n\n```python\nfit = result.max_log_likelihood_fit # or ag.FitImaging(dataset=dataset, galaxies=galaxies)\n\nprint(f\"chi_squared = {fit.chi_squared}\")\nprint(f\"log_likelihood = {fit.log_likelihood}\")\nprint(f\"figure_of_merit = {fit.figure_of_merit}\")\n\naplt.plot_array(\n array=fit.normalized_residual_map,\n title=\"Normalized Residual Map\",\n symmetric=True,\n output_path=PLOT_DIR,\n output_filename=\"normalized_residual_map\",\n output_format=\"png\",\n)\naplt.plot_array(\n array=fit.chi_squared_map,\n title=\"Chi-Squared Map\",\n output_path=PLOT_DIR,\n output_filename=\"chi_squared_map\",\n output_format=\"png\",\n)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Fit Figures__`. Read the\n**normalised** residuals first: they are the only map calibrated against the noise, so they\nanswer *significance* rather than *magnitude*. Scatter within roughly \u00b13 is consistent with\nnoise; coherent structure outside that is a model failure however faint it looks.\n\nTwo quick numerical summaries worth printing alongside the figures \u2014 chi-squared per unmasked\npixel (order unity for a good fit), and the fraction of pixels beyond 3\u03c3 (a few per cent for a\ngood fit, tens of per cent for a badly wrong model).\n\nThe residual patterns and what each implies are tabulated in\n[`ag_plot_fit`](./ag_plot_fit.md) \"The inspection discipline\". The model responses:\n\n- **Ring at one radius** \u2192 the radial profile is too rigid. One Sersic where a bulge plus a\n disk is needed, or a Sersic index that was fixed. Free it, or add the second component.\n- **Four-lobed alternating pattern** \u2192 the ellipticity or position angle is wrong, or the\n isophotes twist with radius. [`wiki/core/concepts/ellipse_fitting_and_multipoles.md`](../wiki/core/concepts/ellipse_fitting_and_multipoles.md).\n- **Central excess** \u2192 coarse over-sampling, or a nuclear component the model lacks. Check the\n over-sampling scheme before adding physics (below).\n- **Clumpy, asymmetric structure no smooth profile can absorb** \u2192 this is where a\n many-component basis or a pixelised reconstruction earns its keep:\n [`wiki/core/concepts/linear_light_profiles_and_mge.md`](../wiki/core/concepts/linear_light_profiles_and_mge.md),\n [`wiki/core/concepts/shapelets.md`](../wiki/core/concepts/shapelets.md),\n [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n- **A uniform offset across the whole image** \u2192 an unmodelled sky background:\n [`wiki/core/concepts/sky_background_and_operated_profiles.md`](../wiki/core/concepts/sky_background_and_operated_profiles.md).\n\n**Check the over-sampling before blaming the physics.** A steep central profile evaluated once\nper pixel is systematically wrong at the centre, and the symptom is exactly the residual a\nmissing nuclear component would leave:\n\n```python\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_lp=over_sample_size)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py` `__Over Sampling__`. Re-plot\nthe dataset subplot afterwards \u2014 its lower panels show the scheme that was actually applied,\nso you can confirm it rather than assume it. The full treatment, including why the outer bins\nnever drop to a single sub-pixel, is\n[`wiki/core/concepts/grids_and_masks.md`](../wiki/core/concepts/grids_and_masks.md)\n\"Over-sampling\", with the runnable guide at\n`autogalaxy_workspace:scripts/guides/advanced/over_sampling.py`.\n\nAdding complexity is [`ag_build_imaging_model`](./ag_build_imaging_model.md). Do it one\ncomponent at a time and re-fit: a model that gained three components at once tells you nothing\nabout which one mattered.\n\n## Branch \u2014 bad priors, and hand-evaluating the likelihood\n\nThe most direct probe in the whole stack. A model and an analysis are enough \u2014 no search, no\nwaiting:\n\n```python\ninstance = model.instance_from_prior_medians()\nlog_likelihood = analysis.log_likelihood_function(instance=instance)\n\nprint(f\"log likelihood at prior medians = {log_likelihood}\")\n```\n\nFrom [`wiki/core/api/analysis_objects.md`](../wiki/core/api/analysis_objects.md) \"Evaluating\nthe likelihood by hand\". `log_likelihood_function(instance)` is the single contract between a\nmodel and data, so what it returns is diagnostic on its own:\n\n- **It raises.** The failure is in the forward model or the data shapes, not in the inference.\n Force `use_jax=False` first for a readable trace, then walk the likelihood step by step\n (next branch).\n- **It returns `nan` or `-inf`.** Something in the model is degenerate at those parameter\n values \u2014 a zero or negative size, a profile whose centre sits outside the mask, a noise-map\n with zeros.\n- **It returns a finite but wildly bad value, and the fit's best likelihood is barely better.**\n The search never found anything, which usually means the priors do not contain the answer.\n- **It returns something close to the fit's best value.** The priors are fine and the search\n is doing its job; look elsewhere.\n\nThen compare against a known-good instance. On simulated data you have the truth, so evaluate\nthe likelihood there: if the true model scores much better than anything the search found, the\npriors or the search settings are at fault, not the model. This is the cleanest experiment\navailable, and it is the reason to keep a simulated control alongside real data\n([`ag_simulate_dataset`](./ag_simulate_dataset.md)).\n\nRead the priors themselves rather than recalling them:\n\n```python\nprint(model.info)\n```\n\nThree specific things to look for. **A best-fit parameter sitting on a prior boundary** means\nthe prior is truncating the posterior \u2014 the answer may be outside it entirely. **A prior far\nwider than physically sensible** wastes the search's effort and invites multi-modality. And\n**a prior narrowed to make a search behave** is a scientific choice, not a convenience: it\nchanges the posterior and therefore the answer. If you want to steer where a search *starts*\nwithout changing the posterior, that is a start point, and only the MCMC and optimisation\nsearches accept one \u2014 nested samplers draw from the prior by construction\n([`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n\"Priors and start points\"). Defaults come from configuration\n([`wiki/core/api/configuration.md`](../wiki/core/api/configuration.md)), and overriding them\nper parameter is [`ag_build_imaging_model`](./ag_build_imaging_model.md).\n\nAlso confirm the galaxy is near the coordinate origin. The default priors assume a centre near\n(0.0\", 0.0\"); a galaxy several arcseconds off-centre needs either re-centred data or\nexplicitly overridden centre priors (`autogalaxy_workspace:scripts/imaging/modeling.py`\n`__Coordinates__`).\n\n## Branch \u2014 walking the likelihood step by step\n\nWhen the hand evaluation raises or returns something inexplicable, the step-by-step\nwalkthrough is the ground truth. `autogalaxy_workspace:scripts/imaging/likelihood_function.py`\ncomputes a galaxy model's log likelihood one NumPy operation at a time \u2014 the elliptical\ncoordinate transform, each light profile's image, the sum into a galaxy image, the blurring\ngrid and PSF convolution, then:\n\n```\nmodel_data = convolved_image_2d\nresidual_map = data - model_data\nnormalized_residual_map = residual_map / noise_map\nchi_squared_map = normalized_residual_map ** 2\nchi_squared = sum(chi_squared_map)\nnoise_normalization = sum(log(2 * pi * noise_map ** 2))\nfigure_of_merit = -0.5 * (chi_squared + noise_normalization)\n```\n\nand finishes by showing that `ag.FitImaging(dataset=dataset, galaxies=galaxies).figure_of_merit`\nreproduces the same number. Running it against your own dataset localises the failure to one\nstep, which is far faster than reading a compiled trace.\n\nThere are matching walkthroughs for the features whose likelihood is genuinely different, and\nthe difference is where their failures live:\n`autogalaxy_workspace:scripts/imaging/features/linear_light_profiles/likelihood_function.py`\n(the mapping matrix, data vector, curvature matrix and the positive-only reconstruction),\n`.../multi_gaussian_expansion/likelihood_function.py` (the same for a Gaussian basis), and\n`.../pixelization/likelihood_function.py` (the regularisation matrix and the Bayesian\ncomplexity terms). If a fit with linear profiles or a pixelisation fails where a standard\nprofile fit succeeds, the extra linear-algebra steps in those scripts are the place to look.\n\nA real fit does not run that NumPy code \u2014 it runs the same calculation compiled. To probe the\ncompiled path exactly as a search drives it, `autogalaxy_workspace:scripts/guides/using_jax.py`\n`__Custom Likelihood Functions__` shows the `Fitness` route, and explains why batching a vector\nof parameters is a stricter test than one concrete call: a single call can quietly succeed on\ncode where NumPy is leaking through, and then break as soon as the search batches.\n\n## Branch \u2014 bad search settings\n\nThe model and data are fine; the sampler did not do its job. Read the search's own report\nfirst: `search.summary` in the output folder, plus `result.samples.log_evidence` and the\nposterior widths.\n\n- **Posteriors far wider than the data should allow, or a low log evidence** \u2192 too few live\n points for the model's dimensionality. `n_live=200` covers most galaxy models; raise it for\n a complex one ([`wiki/core/api/searches.md`](../wiki/core/api/searches.md)).\n- **No errors at all** \u2192 the fit used a gradient optimiser, which is maximum-a-posteriori and\n returns one model. Re-run with `Nautilus` if the science needs uncertainties\n (`autogalaxy_workspace:scripts/imaging/start_here.py` `__Posterior__`).\n- **Two runs of the same configuration disagreeing** \u2192 a multi-modal parameter space with a\n search that is finding different modes. Either raise `n_live`, or start simple and chain into\n the complex model with the simple fit's posterior as priors\n ([`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n \"Search chaining\"; the runnable version is\n `autogalaxy_workspace:scripts/guides/modeling/chaining.py`).\n- **Run time far longer than expected** \u2192 total cost is (likelihood evaluation time) \u00d7\n (number of evaluations), and dimensionality dominates. A many-Gaussian expansion with six\n free parameters routinely beats a multi-component decomposition with thirteen, despite the\n slower per-evaluation cost. [`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n \"Run-time estimation\".\n- **The log constantly reporting that it is outputting results** \u2192 `iterations_per_quick_update`\n is too low and visualisation is eating the run. Raise it\n ([`ag_run_search`](./ag_run_search.md)).\n\nChoosing and tuning the search is [`ag_configure_search`](./ag_configure_search.md).\n\n## Branch \u2014 the fast iteration loop\n\nWhile you are changing a script's structure, do not pay for inference. `PYAUTO_TEST_MODE` has\nfour levels ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)):\n\n```bash\n# Level 2 \u2014 sampler bypassed, likelihood called exactly once. The fastest proof that the\n# model composes, the shapes agree and the likelihood evaluates.\nPYAUTO_TEST_MODE=2 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n\n# Level 1 \u2014 a real but minimal search. Slower, and the only level that writes model.results,\n# image/fit.png and a loadable samples.csv.\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\nLevel 2 does **not** write the fit products, which is worth knowing before you go looking for\n`image/fit.png` after a level-2 run. Level 3 skips the likelihood as well, so it only checks\nthe non-fitting scaffolding. `PYAUTO_SKIP_CHECKS=1` is available when a smoke run trips a\nruntime validation on data too small to be sane \u2014 never set it for a real fit, since those\nchecks are what stop a silently degenerate inversion. And **never quote a parameter measured\nin test mode**: the sampler was truncated or mocked, so the numbers are wiring evidence, not\nmeasurements.\n\nThe loop that works: level 2 until the script runs clean \u2192 level 1 until the products look\nsane \u2192 one full run on a small mask or a simulated dataset \u2192 the production fit.\n\n## Branch \u2014 when nothing above explains it\n\nTwo escalations, in order.\n\n**Reduce to a control.** Simulate a dataset from a model you choose, fit it with that same\nmodel, and confirm you recover the truth\n([`ag_simulate_dataset`](./ag_simulate_dataset.md)). If the control fails, the problem is in\nthe code or the setup. If the control succeeds, the problem is in the real data or its\npreparation \u2014 and you have narrowed it to a half of the space you could not distinguish\nbefore. This is the single highest-value move in this skill and it is under-used.\n\n**Check the library, not yourself.** If a symbol does not resolve or an idiom that reads\ncorrectly does not work, run the audit \u2014 a construction can be retired while every token in it\nstill imports:\n\n```bash\npython autoassistant/audit_skill_apis.py --scope scripts\npython autoassistant/audit_skill_apis.py --lint-idioms\n```\n\n[`ag_audit_skill_apis`](./ag_audit_skill_apis.md) owns both. Only after those come back clean\nis \"this might be a library bug\" a reasonable hypothesis \u2014 at which point\n[`contribute-upstream`](./contribute-upstream.md) is the route to filing it with a minimal\nreproduction.\n\n## Combine\n\n- [`ag_plot_fit`](./ag_plot_fit.md) \u2014 the residual-pattern table this skill's model branch\n routes through, and the figures that make a diagnosis visible.\n- [`ag_build_imaging_model`](./ag_build_imaging_model.md) \u2014 acting on a \"bad model\" or \"bad\n priors\" verdict.\n- [`ag_configure_search`](./ag_configure_search.md) \u2014 acting on a \"bad search settings\"\n verdict.\n- [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md) \u2014 acting on a \"bad data\" verdict:\n masks, noise scaling, contaminant handling.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) \u2014 the control experiment.\n- [`ag_setup_environment`](./ag_setup_environment.md) \u2014 the install will not import at all.\n- [`ag_run_search`](./ag_run_search.md) \u2014 re-launching once the cause is fixed.\n\nRecord the diagnosis, not just the fix. Offer (default-yes) a dated\n`wiki/project/YYYY-MM-DD-.md` entry naming the symptom, the probe that localised it, and\nwhat changed \u2014 per [`_style.md`](./_style.md) property #5. A debugging session that is not\nwritten down gets repeated.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [HowToGalaxy: Dealing with failure](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_4_dealing_with_failure.ipynb):\n why searches fail on galaxy models, what a local maximum looks like in practice, and how\n model complexity and prior choice interact.\n- **General reference** \u2014 [RTD: Likelihood function](https://pyautogalaxy.readthedocs.io/en/latest/general/likelihood_function.html):\n the likelihood the library evaluates, and pointers into the step-by-step walkthroughs.\n- **Experienced PyAutoGalaxy user** \u2014 [workspace: guides/modeling/bug_fix.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/guides/modeling/bug_fix.py):\n the main-guard fix for the parallelisation error, as a complete runnable fit.\n\n## Agent procedural checklist\n\n1. Get the symptom: raised, hung, or completed-but-wrong; and what makes it wrong.\n2. Rule out stale output first \u2014 check timestamps, then `rm -rf` the `` folder and\n re-run. Check for a `test_mode` path segment.\n3. Confirm the environment with `--check-install`; apply the cache variables and the main guard\n if either applies.\n4. Toggle `use_jax=False` (or `PYAUTO_DISABLE_JAX=1`) to split JAX from non-JAX failures and\n get a readable trace.\n5. Plot the dataset: contaminants, mask extent, noise-map, `pixel_scales`.\n6. Hand-evaluate `analysis.log_likelihood_function(instance=model.instance_from_prior_medians())`\n before running any search.\n7. Read `model.info` for boundary-hugging and over-wide priors; confirm the galaxy is near the\n origin.\n8. Rebuild the fit and read the **normalised residual** map, then the chi-squared map; check\n the over-sampling scheme before adding physics.\n9. Read `search.summary` and the log evidence for search-settings failures.\n10. Iterate with `PYAUTO_TEST_MODE=2`, then `=1`; never quote a test-mode parameter.\n11. If unresolved, build a simulated control and fit it; run the symbol and idiom audits before\n suspecting a library bug.\n12. Offer the `wiki/project/` entry recording symptom, probe and fix.\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_2_modeling/tutorial_4_linear_profiles.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_basis_profiles\n\n---\nname: ag_basis_profiles\ndescription: Fit a galaxy's morphology with a *basis* rather than one or two smooth profiles \u2014 linear light profiles (`ag.lp_linear`), a Multi-Gaussian Expansion, or a shapelet expansion \u2014 where every component's `intensity` is solved analytically by a linear inversion instead of sampled by the search. Covers why `ag.lp_linear` is the default for any bulge-disk decomposition, when an MGE beats a Sersic pair (isophotal twists, radially varying ellipticity, asymmetry), when shapelets beat an MGE, the positive-only versus signed linear solver and what a negative amplitude means physically, `ag.model_util.mge_model_from` and the hand-rolled `ag.lp_basis.Basis` idiom behind it, a compact MGE for an unresolved nucleus, and how to read solved intensities back out of a fit. Use when a Sersic or bulge-plus-disk model leaves structure in the residuals but the galaxy still has a well-defined centre. Not for pixelized reconstruction of genuinely irregular clumps (`ag_pixelization`), not for non-parametric isophote measurement (`ag_ellipse_fitting`), and not for the basics of composing an `af.Model` tree (`ag_build_imaging_model`).\n---\n\n# Fitting morphology with a basis\n\nA Sersic profile makes a strong claim: that the galaxy's isophotes are concentric, similar\nellipses with a single fixed axis ratio and position angle, and that its surface brightness\nfalls off as one power of radius. Real galaxies routinely violate all of that. Isophotes twist\nwith radius, the ellipticity varies from the bulge outwards, a bar or a spiral pattern breaks\nthe symmetry \u2014 and when a Sersic cannot represent those features it does not fail loudly. It\nabsorbs them, and returns an `effective_radius` and `sersic_index` biased by exactly the\nstructure it could not fit.\n\nA **basis** is the answer: instead of one profile with a shape, use tens of simple profiles\nwhose superposition can take almost any shape. The reason this is affordable \u2014 and the reason\nit is often *cheaper* than a Sersic pair \u2014 is statistical. Every basis component's `intensity`\nis a **linear** parameter: given the shapes and positions of the components, the amplitudes\nthat maximise the likelihood follow from solving a linear system, exactly, in one step. So they\nnever enter the non-linear search's parameter space at all. A 60-Gaussian MGE can have four\nfree parameters where a two-component linear Sersic decomposition has nine.\n\nThree tiers, same machinery, increasing flexibility:\n\n| Tier | What it is | Free parameters | Reach for it when |\n|---|---|---|---|\n| `ag.lp_linear.*` | ordinary profiles with `intensity` solved | 6 per Sersic, 3 per aligned Exponential | you want interpretable bulge/disk parameters \u2014 **the default** |\n| MGE (`ag.lp_basis.Basis` of `Gaussian`s) | 15\u2013100 Gaussians on a fixed log-spaced `sigma` ladder | 4 (one basis) to 6 (two) | isophotal twists, radial ellipticity variation, mild asymmetry |\n| shapelets | an orthonormal polar or Cartesian basis | 3 (spherical) to 5 (elliptical) | disky, star-forming morphology the MGE still smooths over |\n\nThe science this serves is the decomposition itself. A bulge-plus-disk fit measures the\nbulge-to-total light ratio, the two components' sizes and the bulge's concentration \u2014 the\nquantities that place a galaxy on the mass\u2013size relation and separate a classical spheroid from\na pseudo-bulge. A basis fit measures something the parametric fit cannot: how the shape of the\nlight changes with radius. Both concepts are in\n[`../wiki/core/concepts/linear_light_profiles_and_mge.md`](../wiki/core/concepts/linear_light_profiles_and_mge.md)\nand [`../wiki/core/concepts/shapelets.md`](../wiki/core/concepts/shapelets.md); the catalogue of\nwhich variant lives in which module is\n[`../wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md).\n\nThis skill assumes you already have a masked, over-sampled dataset and know how to build an\n`af.Model` tree \u2014 that is [`ag_build_imaging_model`](./ag_build_imaging_model.md), whose MGE\nbranch is the one-paragraph version of what follows.\n\n## Ask\n\n- *\"Do you need the Sersic parameters, or the best fit?\"* This is the real fork. If your science\n is a bulge-to-total ratio, an effective radius, a Sersic index \u2014 a number you will put in a\n table next to other people's \u2014 stay with `ag.lp_linear` Sersic-family profiles, because an\n MGE does not hand you those numbers. If your science is the light distribution itself, or you\n need the residuals flat before you can trust anything else, go to a basis.\n- *\"What does the residual map look like after a single Sersic?\"* Structured residuals that\n follow the isophotes (a four-lobed or twisted pattern) say the *shape* is wrong \u2014 an MGE\n fixes that. Residuals in discrete off-centre lumps say the shape is fine but there is\n substructure \u2014 that is a pixelization ([`ag_pixelization`](./ag_pixelization.md)), not a basis.\n If you have not looked yet, look first; it is one plot and it decides the branch.\n- *\"Does the galaxy have a single well-defined centre?\"* Every basis in this skill shares one\n centre across all its components. A merger, or a galaxy with a bright companion overlapping\n it, breaks that assumption \u2014 handle the companion first with\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- *\"Is there a compact nuclear source?\"* An AGN or a nuclear starburst is a separate component,\n and there is a purpose-built compact MGE for it (branch four below).\n\n## Branch \u2014 linear light profiles, the default for any decomposition\n\nStart here even when you expect to end up with a basis. This is the same bulge-plus-disk model\n`ag_build_imaging_model` composes, and the point of this branch is what happens to `intensity`.\n\n```python\n\"\"\"\nGalaxy Structure: Linear Bulge-Disk Decomposition\n=================================================\n\nDecompose a galaxy's light into a Sersic bulge and an Exponential disk using *linear* light\nprofiles, whose `intensity` parameters are solved analytically by a linear inversion inside\nevery likelihood evaluation rather than sampled by the non-linear search. The ratio of the two\nsolved intensities, integrated, is the bulge-to-total light ratio.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the masked, over-sampled imaging dataset.\n- **Model:** Compose the linear bulge and disk, with their centres paired.\n- **Check:** Confirm the parameter count and evaluate one likelihood.\n- **Intensities:** Read the solved intensities back out of a completed fit.\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 = 3.0\n\n\"\"\"\n__Dataset__\n\nLoaded from FITS, masked to a radius chosen by inspecting the data, and over-sampled adaptively\nwhere the profile's intensity gradient is steep. All three decisions change the answer, so they\nare reproduced here rather than hidden\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\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_lp=over_sample_size)\n\n\"\"\"\n__Model__\n\nThe decomposition is identifiable because the two components are *asymmetric* in what they are\nallowed to be: the bulge's `sersic_index` is free, so the fit can find a concentrated spheroid\n(n ~ 4), while the `Exponential` disk has n fixed at 1 by construction. Two free Sersics on one\ngalaxy are largely degenerate and the fit will trade light between them.\n\n`ag.lp_linear` rather than `ag.lp` is the only change from a standard composition, and it is\nnot a small one: each profile's `intensity` leaves the search's parameter space and is instead\nsolved by a linear inversion that always returns the amplitudes maximising the likelihood given\nthe other parameters. Two dimensions vanish, and with them the strong degeneracies between\n`intensity` and `effective_radius` / `sersic_index` that a sampler finds hardest to map\n(`PyAutoGalaxy:autogalaxy/profiles/light/linear/sersic.py`).\n\n`bulge.centre = disk.centre` asserts the components are concentric \u2014 physically reasonable for\nmost galaxies, and worth two parameters.\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\ndisk = af.Model(ag.lp_linear.Exponential)\nbulge.centre = disk.centre\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\nThe likelihood at the prior medians costs one evaluation and proves the model, dataset and\nanalysis are mutually compatible. Pass `use_jax=False` while debugging \u2014 NumPy tracebacks are\nfar easier to read (`PyAutoGalaxy:autogalaxy/imaging/model/analysis.py`).\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 likelihood at prior medians: {float(log_likelihood):.2f}\")\n```\n\nN = 9: the bulge's centre (2), two `ell_comps` pairs (4), two `effective_radius` values and the\nbulge's `sersic_index` \u2014 with both intensities solved. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/linear_light_profiles/modeling.py`, which\nreduces `n_live` to 75 for exactly this reason: a simpler parameter space needs fewer live\npoints to map.\n\nThe cost is real but small. A linear likelihood evaluation is roughly three to five times\nslower than a standard one, because the inversion has to be solved every time. The workspace\nexample measures ~0.05 s against ~0.01 s on a low-resolution dataset. That is repaid by fewer\niterations and a more reliable posterior, and the trade tips further towards linear the more\nprofiles you add \u2014 which is what makes the next two branches possible at all.\n\n### The consequence: `intensity` is not in the model, so it is not in the results\n\nThis trips up everyone once. A linear profile has no `intensity` attribute to report, so\n`model.results` does not list one, and **a linear profile cannot be plotted directly** \u2014 there\nis no amplitude to evaluate. The intensities exist only after a fit, as the inversion's\nsolution. Three ways to get at them, all from\n`autogalaxy_workspace:scripts/imaging/features/linear_light_profiles/modeling.py`:\n\n```python\n\"\"\"\n__Intensities__\n\n`max_log_likelihood_galaxies` has already performed the inversion, so its profiles carry their\nsolved `intensity` values and can be evaluated and plotted like ordinary profiles. The\n`Fit` additionally exposes a dictionary keyed by the profile objects themselves, which is the\nunambiguous route when several components share a class\n(`PyAutoGalaxy:autogalaxy/imaging/fit_imaging.py`).\n\"\"\"\ngalaxies = result.max_log_likelihood_galaxies\n\nprint(f\"bulge intensity = {galaxies[0].bulge.intensity}\")\n\nfit = result.max_log_likelihood_fit\n\nprint(fit.linear_light_profile_intensity_dict[fit.galaxies[0].bulge])\nprint(fit.linear_light_profile_intensity_dict[fit.galaxies[0].disk])\n\ngalaxies_ordinary = fit.model_obj_linear_light_profiles_to_light_profiles\n\naplt.subplot_galaxies(\n galaxies=galaxies_ordinary,\n grid=dataset.grid,\n output_path=\"scripts/scratch/my_galaxy/\",\n auto_filename=\"decomposition\",\n output_format=\"png\",\n)\n```\n\n`model_obj_linear_light_profiles_to_light_profiles` returns the same galaxies with every linear\nprofile replaced by its ordinary equivalent at the solved amplitude \u2014 that is the object to\nhand to any plotting or derived-quantity call. `fit.inversion.linear_obj_list` holds one\n`LightProfileLinearObjFuncList` per linear component (or per `Basis`), which is where the\nbookkeeping lives when you need to be certain which amplitude belongs to which profile.\n\nIntegrating those amplitudes over the two profiles is what gives you the bulge-to-total ratio;\nthe machinery for luminosities and magnitudes is\n[`../wiki/core/concepts/cosmology_and_units.md`](../wiki/core/concepts/cosmology_and_units.md).\nAsk if you want the derived-quantity route spelled out.\n\n## Branch \u2014 a Multi-Gaussian Expansion, when the *shape* is wrong\n\nA Gaussian is a poor galaxy profile on its own and an excellent basis function in company:\nsum enough of them at fixed, logarithmically spaced widths and you can build any monotonic\nradial profile, and \u2014 if you let separate groups of them carry separate ellipticities \u2014 an\nisophote shape that changes with radius. That last property is the one a Sersic cannot have at\nany parameter count, and it is why an MGE is the workspace's recommended default model.\n\nThe composition is long, so the library ships a helper:\n\n```python\n\"\"\"\n__Model__\n\nAn MGE bulge: 20 linear Gaussians sharing one centre and one ellipticity, with every `sigma`\nfixed on a logarithmic ladder running from below the pixel scale out to `mask_radius`, and\nevery intensity solved by the inversion. `mask_radius` sets the outer end of that ladder, so\npass the radius you actually masked at \u2014 a ladder that stops short of the data leaves the\nouter isophotes unrepresented (`PyAutoGalaxy:autogalaxy/analysis/model_util.py`).\n\"\"\"\nbulge = ag.model_util.mge_model_from(\n mask_radius=MASK_RADIUS,\n total_gaussians=20,\n centre_prior_is_uniform=True,\n)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n```\n\n**N = 4** \u2014 a shared centre and a shared `ell_comps`. Twenty Gaussians, four dimensions, more\nmorphological freedom than a Sersic's six. Adapted from\n`autogalaxy_workspace:scripts/imaging/start_here.py`, where the MGE is the recommended default.\n\nThe full signature is\n`mge_model_from(mask_radius, total_gaussians=30, gaussian_per_basis=1,\ncentre_prior_is_uniform=True, centre=(0.0, 0.0), centre_fixed=None, centre_per_basis=False,\ncentre_sigma=0.3, ell_comps_prior_is_uniform=False, ell_comps_uniform_width=0.2,\nell_comps_sigma=0.3, use_spherical=False)`. The arguments worth knowing:\n\n- **`gaussian_per_basis=2`** splits the ladder into two bases with *independent* ellipticities.\n N goes 4 \u2192 6 and you buy the ability to fit an isophotal twist: an inner group and an outer\n group free to be differently elongated and differently oriented. This is the single most\n useful knob here, and the reason to prefer an MGE over a Sersic pair for an early-type galaxy.\n- **`centre_fixed=(y, x)`** pins the centre entirely, dropping two more parameters. Used for\n contaminating neighbours ([`ag_light_model_extras`](./ag_light_model_extras.md)).\n- **`use_spherical=True`** drops the ellipticity \u2014 for a genuinely round system, or as a\n deliberately rigid comparison model.\n- **`total_gaussians`** buys radial resolution, not shape freedom. 15 is enough for a smooth\n profile; 60 for a well-resolved one; beyond that you are mostly paying for likelihood\n evaluations. Cost scales with the count, because every Gaussian's image must be computed and\n PSF-convolved: the workspace measures ~0.5 s per evaluation for 60 Gaussians, against ~0.01 s\n for a standard Sersic. VRAM rises too \u2014 10\u201350 MB per batched likelihood at 60 Gaussians, so\n check `analysis.print_vram_use(model=model, batch_size=search.batch_size)` before a GPU run\n with hundreds of components.\n\nThat run time is why the overall comparison is not obvious, and the workspace is honest about\nit: the MGE's likelihood is much slower, but its parameter space is so much simpler \u2014 and\ncrucially contains *no parameter that scales the galaxy's size* \u2014 that the search converges far\nfaster. Net, it usually wins, and it fits better.\n\n### The hand-rolled `Basis`, and why you might want it\n\nThe helper is a convenience over one explicit idiom. Compose it yourself when you need\nsomething the arguments do not offer \u2014 a bespoke `sigma` range, a third basis, per-basis\npriors. From `autogalaxy_workspace:scripts/imaging/features/multi_gaussian_expansion/modeling.py`:\n\n```python\n\"\"\"\n__Model__\n\nTwo groups of 30 Gaussians. Within a group every Gaussian shares the centre and ellipticity of\nthe first, and every `sigma` is *fixed* to a value on a log10 ladder spanning a tenth of the\npixel scale to the mask radius. `ag.lp_basis.Basis` then groups the whole list into one model\ncomponent the galaxy can hold (`PyAutoGalaxy:autogalaxy/profiles/basis.py`).\n\nThe lower end matters: anchoring it to the pixel scale stops the basis spending Gaussians on\nscales the data cannot resolve. `mge_model_from` exposes this as `sigma_min` (default `1e-4`,\nwhich reproduces the historical ladder exactly).\n\"\"\"\nimport numpy as np\n\ntotal_gaussians = 30\ngaussian_per_basis = 2\n\nlog10_sigma_list = np.linspace(\n np.log10(dataset.pixel_scales[0] / 10.0), np.log10(MASK_RADIUS), total_gaussians\n)\n\ncentre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\ncentre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n\nbulge_gaussian_list = []\n\nfor _ in range(gaussian_per_basis):\n\n gaussian_list = af.Collection(\n af.Model(ag.lp_linear.Gaussian) for _ in range(total_gaussians)\n )\n\n for i, gaussian in enumerate(gaussian_list):\n gaussian.centre.centre_0 = centre_0 # one shared y centre\n gaussian.centre.centre_1 = centre_1 # one shared x centre\n gaussian.ell_comps = gaussian_list[0].ell_comps # shared within this basis\n gaussian.sigma = 10 ** log10_sigma_list[i] # fixed, not sampled\n\n bulge_gaussian_list += gaussian_list\n\nbulge = af.Model(ag.lp_basis.Basis, profile_list=bulge_gaussian_list)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n```\n\nN = 6. `print(model.info)` prints all sixty Gaussians and looks alarming; almost every\nparameter shown is fixed. Trust `model.total_free_parameters`, not the length of the printout.\n\nTwo details that are load-bearing. Assigning `gaussian.sigma = ` **fixes** it \u2014 the\nwhole scheme depends on the widths not being sampled, because a free `sigma` reintroduces the\nsize-scaling degeneracy the MGE exists to remove. And sharing `ell_comps` *within* a basis but\nnot *between* bases is precisely what makes the twist fittable.\n\nThe `Basis` constructor also accepts a `regularization` argument that penalises non-smooth\namplitude solutions. Treat it as research-only: the positive-only solver below already fixes\nthe pathology it was introduced for, and no production analysis uses it \u2014 the workspace moved\nthat branch out of the user-facing script deliberately.\n\n## Branch \u2014 a compact MGE for an unresolved nucleus\n\nAn AGN or nuclear starburst is not the extended stellar light, and forcing one basis to cover\nboth makes the fit choose between them. Model it as a second, deliberately compact basis: the\nsame construction with the `sigma` ladder capped at about twice the pixel scale, so the\ncomponent cannot be broader than a PSF-convolved point source.\n\n```python\n\"\"\"\n__Model__\n\nThe galaxy's light becomes the sum of a diffuse stellar `bulge` MGE and a compact `point` MGE.\nThe point basis is 10 linear Gaussians sharing one centre and ellipticity with `sigma` values\nlog-spaced from `sigma_min` (default 0.01\") to twice the pixel scale \u2014 compact relative to the\nresolution of the data, which is what makes it read as a point source rather than a small galaxy\n(`PyAutoGalaxy:autogalaxy/analysis/model_util.py`).\n\"\"\"\npoint = ag.model_util.mge_point_model_from(\n pixel_scales=PIXEL_SCALES,\n total_gaussians=10,\n centre=(0.0, 0.0),\n)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, point=point)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/features/multi_gaussian_expansion/modeling.py`,\nwhose `__Point Source__` section builds the same basis line by line first if you want to see\ninside the helper. Four extra parameters on top of the bulge MGE.\n\nThere is a genuinely different approach to the same problem \u2014 an **operated** light profile,\nwhich is assumed to be already PSF-convolved and so bypasses the convolution entirely. Which\nto pick, and why a compact model source is so sensitive to sub-pixel placement, is\n[`ag_light_model_extras`](./ag_light_model_extras.md) and\n[`../wiki/core/concepts/sky_background_and_operated_profiles.md`](../wiki/core/concepts/sky_background_and_operated_profiles.md).\n\n## Branch \u2014 shapelets, and the price of a signed solver\n\nShapelets are an orthonormal basis of Gauss\u2013Hermite (Cartesian) or Gauss\u2013Laguerre (polar)\nfunctions on a single scale `beta`, introduced for exactly this problem\n(Refregier 2003, arXiv:astro-ph/0105178). Because the basis is complete, it can represent\nmorphology an MGE smooths over \u2014 the disky, star-forming structure the workspace cites them\nfor. But completeness has a price, and it is a physical one.\n\n**Shapelets require negative amplitudes.** The higher-order basis functions oscillate in sign,\nand reproducing an arbitrary shape means combining them with signed coefficients. Every other\nbranch in this skill uses a positive-only linear solver, because a negative surface brightness\nis not a thing a galaxy has. Shapelets cannot: you must pass\n`ag.Settings(use_positive_only_solver=False)`, and the reconstructed light *will* contain\nnegative flux \u2014 verified, not assumed. That is not a numerical wrinkle to ignore; it is the\nmodel telling you it is a mathematical fit rather than a physical decomposition, and it is why\nthe workspace recommends trying an MGE alongside.\n\n```python\n\"\"\"\n__Model__\n\nA polar shapelet basis to order n = 5: 11 `ShapeletPolar` components whose `n` and `m` indices\nare fixed by construction, sharing one centre, one ellipticity and one scale `beta`. `beta` is\nthe only shape parameter \u2014 it sets the physical size the whole basis is expressed on, so its\nprior matters more here than any single amplitude\n(`PyAutoGalaxy:autogalaxy/profiles/light/linear/shapelets/polar.py`).\n\"\"\"\ntotal_n = 5\ntotal_m = sum(range(2, total_n + 1)) + 1\n\nshapelets_bulge_list = af.Collection(\n af.Model(ag.lp_linear.ShapeletPolar) for _ in range(total_n + total_m)\n)\n\nn_count = 1\nm_count = -1\n\nfor shapelet in shapelets_bulge_list:\n shapelet.n = n_count\n shapelet.m = m_count\n\n m_count += 2\n\n if m_count > n_count:\n n_count += 1\n m_count = -n_count\n\n shapelet.centre = shapelets_bulge_list[0].centre\n shapelet.ell_comps = shapelets_bulge_list[0].ell_comps\n shapelet.beta = shapelets_bulge_list[0].beta\n\nbulge = af.Model(ag.lp_basis.Basis, profile_list=shapelets_bulge_list)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\n\"\"\"\n__Analysis__\n\nThe signed solver is requested through `ag.Settings`, which is passed to the analysis rather\nthan to the model \u2014 it is a property of how the inversion is solved, not of what is being\nfitted (`PyAutoArray:autoarray/settings.py`).\n\"\"\"\nanalysis = ag.AnalysisImaging(\n dataset=dataset,\n settings=ag.Settings(use_positive_only_solver=False),\n use_jax=True,\n)\n```\n\n**N = 5**: centre (2), `ell_comps` (2), `beta` (1). Adapted from\n`autogalaxy_workspace:scripts/imaging/features/shapelets/modeling.py` \u2014 note that the workspace\nloop as written does *not* link `ell_comps` across the basis, which leaves each shapelet's\nellipticity free and inflates the model to N = 43 rather than the N = 3 its prose claims. The\nline `shapelet.ell_comps = shapelets_bulge_list[0].ell_comps` above is the fix; N = 3 is what\nyou get from the spherical variant `ag.lp_linear.ShapeletPolarSph`, which has no `ell_comps` at\nall. Check `model.total_free_parameters` rather than trusting a comment \u2014 including this one.\n\nPolar shapelets suit radially organised light, which is most galaxies.\n`ag.lp_linear.ShapeletCartesian` (indexed by `n_y`, `n_x` instead of `n`, `m`) and\n`ag.lp_linear.ShapeletExponential` are the other two families; the Cartesian basis is not\ngenerally recommended for galaxies. You can see what a basis actually looks like before fitting\nanything:\n\n```python\nshapelets = [\n ag.lp_linear.ShapeletCartesian(\n n_y=y, n_x=x, centre=(0.0, 0.0), ell_comps=(0.0, 0.0), beta=1.0\n )\n for x in range(5)\n for y in range(5)\n]\n\nbasis = ag.lp_basis.Basis(profile_list=shapelets)\n\naplt.subplot_basis_image(\n basis=basis,\n grid=ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.05),\n output_path=\"scripts/scratch/shapelet_basis/\",\n output_format=\"png\",\n)\n```\n\n`subplot_basis_image` renders every component of the basis on a grid, which is the fastest way\nto build intuition for what `beta` and the order limit are buying you. It takes `output_path` /\n`output_format` but **not** `output_filename` \u2014 give each variant its own directory\n([`../wiki/core/api/plotting.md`](../wiki/core/api/plotting.md) tabulates that split). Print the\nabsolute path and offer to open it.\n\nShapelets also cost about 0.37 s per likelihood evaluation for ~60 components in the workspace's\nmeasurement \u2014 slower than linear profiles, comparable to an MGE, and with more free parameters\nthan an MGE of similar flexibility. The workspace's own recommendation is to run both and\ncompare; the concept page\n[`../wiki/core/concepts/shapelets.md`](../wiki/core/concepts/shapelets.md) has the full\nwhen-to-use discussion.\n\n## Choosing between the three\n\nFit them in order and let the residuals decide, because each step is cheap given the last:\n\n1. **Single linear Sersic** \u2014 the reference every other fit is judged against, and the source of\n the size and concentration you will actually quote. Six parameters.\n2. **Linear bulge plus disk** \u2014 if the science is a bulge-to-total ratio, this *is* the answer;\n a basis will fit better and tell you less. Nine parameters.\n3. **MGE, `gaussian_per_basis=2`** \u2014 if the residuals show a twist or a radially varying\n ellipticity. Six parameters, better fit, less interpretable.\n4. **Shapelets** \u2014 if the MGE still leaves disky or asymmetric structure and you accept a signed\n solution. Five parameters.\n5. **Neither is enough** \u2014 the residuals sit in discrete off-centre lumps, and no basis with a\n single shared centre will absorb them. That is\n [`ag_pixelization`](./ag_pixelization.md).\n\nAn MGE and a shapelet basis can be compared by Bayesian evidence only with care, because they\nsolve different linear problems (positive-only versus signed). Compare them on the residual map\nand the chi-squared first, and ask if you want the evidence caveats spelled out.\n\n## Combine \u2014 where this hands off\n\n- **Pick a search** \u2192 [`ag_configure_search`](./ag_configure_search.md). Basis models want\n *fewer* live points than a parametric fit, not more \u2014 the workspace drops `n_live` to 75 for\n both linear profiles and the MGE \u2014 because the parameter space is simpler.\n- **Run it and read the output folder** \u2192 [`ag_run_search`](./ag_run_search.md).\n- **Plot the fit** \u2192 [`ag_plot_fit`](./ag_plot_fit.md), remembering that a linear profile has to\n go through `model_obj_linear_light_profiles_to_light_profiles` before it can be plotted.\n- **The basis fits worse than you expected, or the search stalls** \u2192\n [`ag_debug_fit_failure`](./ag_debug_fit_failure.md). The two failure modes specific to this\n skill are a `sigma` ladder that stops short of the mask radius, and a free `sigma` or `beta`\n reintroducing a size degeneracy.\n- **Structured residuals a basis cannot reach** \u2192 [`ag_pixelization`](./ag_pixelization.md).\n- **A neighbour overlapping the galaxy, a residual sky, or a nuclear point source** \u2192\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- **A non-parametric shape measurement instead of a model** \u2192\n [`ag_ellipse_fitting`](./ag_ellipse_fitting.md), which measures the isophotal twist directly\n rather than inferring it from a two-basis MGE.\n- **The same galaxy in several bands** \u2192 the multi-dataset skill (`ag_multi_dataset`). A basis\n across bands is where the factor graph earns its keep, since the shape can be shared while\n the amplitudes are solved per band.\n- **Chaining a parametric fit into a basis fit** \u2192 the search-chaining skill\n (`ag_chain_searches`); a Sersic fit's centre and ellipticity make excellent starting priors\n for an MGE.\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording which tier you\nused, `total_gaussians` / `gaussian_per_basis` or the shapelet order, the solver you chose, and\nwhat the residuals looked like at each step \u2014 the last is the evidence for the model choice and\nthe first thing a referee will ask for.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [HowToGalaxy: Linear profiles](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_4_linear_profiles.ipynb):\n builds up from a standard profile to a linear one to a basis, showing what the inversion\n actually solves at each step.\n- **General reference** \u2014 [RTD: Light profiles API](https://pyautogalaxy.readthedocs.io/en/latest/api/light.html):\n every standard, linear, operated and basis variant with its module and parameters.\n- **Experienced PyAutoGalaxy user** \u2014 [workspace: imaging/features/multi_gaussian_expansion/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/multi_gaussian_expansion/modeling.py):\n the MGE end to end, including the compact nuclear basis and the run-time and VRAM discussion.\n\n## Agent procedural checklist\n\n1. Ask whether the user needs interpretable Sersic parameters or the best achievable fit \u2014 that\n choice, not the API, picks the branch.\n2. Look at the residual map of a single linear Sersic first; structured-but-smooth residuals mean\n a basis, discrete lumps mean `ag_pixelization`.\n3. Default to `ag.lp_linear` for every parametric component; never use `ag.lp` in a model\n without a reason.\n4. For an MGE, pass the real `mask_radius`, and reach for `gaussian_per_basis=2` when the\n isophotes twist.\n5. For shapelets, pass `ag.Settings(use_positive_only_solver=False)` on the *analysis*, link\n `ell_comps` across the basis, and tell the user the reconstruction may contain negative flux.\n6. Always check `model.total_free_parameters` against what you intended \u2014 a basis's `model.info`\n is long and mostly fixed, and one unlinked parameter multiplies by the component count.\n7. Evaluate one likelihood before committing to a search; run `print_vram_use` before a GPU run\n with a large basis.\n8. Read intensities out via `max_log_likelihood_galaxies`,\n `fit.linear_light_profile_intensity_dict`, or\n `model_obj_linear_light_profiles_to_light_profiles` \u2014 never expect them in `model.results`.\n9. Save the script to `scripts/`, quote every plot's absolute path and offer to open it, then\n offer the `wiki/project/` entry.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_2_modeling/tutorial_5_data_and_likelihoods.ipynb b/notebooks/chapter_2_modeling/tutorial_5_data_and_likelihoods.ipynb index a285906..e51bd27 100644 --- a/notebooks/chapter_2_modeling/tutorial_5_data_and_likelihoods.ipynb +++ b/notebooks/chapter_2_modeling/tutorial_5_data_and_likelihoods.ipynb @@ -361,7 +361,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_2_modeling/tutorial_5_data_and_likelihoods.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_basis_profiles\n\n---\nname: ag_basis_profiles\ndescription: Fit a galaxy's morphology with a *basis* rather than one or two smooth profiles — linear light profiles (`ag.lp_linear`), a Multi-Gaussian Expansion, or a shapelet expansion — where every component's `intensity` is solved analytically by a linear inversion instead of sampled by the search. Covers why `ag.lp_linear` is the default for any bulge-disk decomposition, when an MGE beats a Sersic pair (isophotal twists, radially varying ellipticity, asymmetry), when shapelets beat an MGE, the positive-only versus signed linear solver and what a negative amplitude means physically, `ag.model_util.mge_model_from` and the hand-rolled `ag.lp_basis.Basis` idiom behind it, a compact MGE for an unresolved nucleus, and how to read solved intensities back out of a fit. Use when a Sersic or bulge-plus-disk model leaves structure in the residuals but the galaxy still has a well-defined centre. Not for pixelized reconstruction of genuinely irregular clumps (`ag_pixelization`), not for non-parametric isophote measurement (`ag_ellipse_fitting`), and not for the basics of composing an `af.Model` tree (`ag_build_imaging_model`).\n---\n\n# Fitting morphology with a basis\n\nA Sersic profile makes a strong claim: that the galaxy's isophotes are concentric, similar\nellipses with a single fixed axis ratio and position angle, and that its surface brightness\nfalls off as one power of radius. Real galaxies routinely violate all of that. Isophotes twist\nwith radius, the ellipticity varies from the bulge outwards, a bar or a spiral pattern breaks\nthe symmetry — and when a Sersic cannot represent those features it does not fail loudly. It\nabsorbs them, and returns an `effective_radius` and `sersic_index` biased by exactly the\nstructure it could not fit.\n\nA **basis** is the answer: instead of one profile with a shape, use tens of simple profiles\nwhose superposition can take almost any shape. The reason this is affordable — and the reason\nit is often *cheaper* than a Sersic pair — is statistical. Every basis component's `intensity`\nis a **linear** parameter: given the shapes and positions of the components, the amplitudes\nthat maximise the likelihood follow from solving a linear system, exactly, in one step. So they\nnever enter the non-linear search's parameter space at all. A 60-Gaussian MGE can have four\nfree parameters where a two-component linear Sersic decomposition has nine.\n\nThree tiers, same machinery, increasing flexibility:\n\n| Tier | What it is | Free parameters | Reach for it when |\n|---|---|---|---|\n| `ag.lp_linear.*` | ordinary profiles with `intensity` solved | 6 per Sersic, 3 per aligned Exponential | you want interpretable bulge/disk parameters — **the default** |\n| MGE (`ag.lp_basis.Basis` of `Gaussian`s) | 15–100 Gaussians on a fixed log-spaced `sigma` ladder | 4 (one basis) to 6 (two) | isophotal twists, radial ellipticity variation, mild asymmetry |\n| shapelets | an orthonormal polar or Cartesian basis | 3 (spherical) to 5 (elliptical) | disky, star-forming morphology the MGE still smooths over |\n\nThe science this serves is the decomposition itself. A bulge-plus-disk fit measures the\nbulge-to-total light ratio, the two components' sizes and the bulge's concentration — the\nquantities that place a galaxy on the mass–size relation and separate a classical spheroid from\na pseudo-bulge. A basis fit measures something the parametric fit cannot: how the shape of the\nlight changes with radius. Both concepts are in\n[`../wiki/core/concepts/linear_light_profiles_and_mge.md`](../wiki/core/concepts/linear_light_profiles_and_mge.md)\nand [`../wiki/core/concepts/shapelets.md`](../wiki/core/concepts/shapelets.md); the catalogue of\nwhich variant lives in which module is\n[`../wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md).\n\nThis skill assumes you already have a masked, over-sampled dataset and know how to build an\n`af.Model` tree — that is [`ag_build_imaging_model`](./ag_build_imaging_model.md), whose MGE\nbranch is the one-paragraph version of what follows.\n\n## Ask\n\n- *\"Do you need the Sersic parameters, or the best fit?\"* This is the real fork. If your science\n is a bulge-to-total ratio, an effective radius, a Sersic index — a number you will put in a\n table next to other people's — stay with `ag.lp_linear` Sersic-family profiles, because an\n MGE does not hand you those numbers. If your science is the light distribution itself, or you\n need the residuals flat before you can trust anything else, go to a basis.\n- *\"What does the residual map look like after a single Sersic?\"* Structured residuals that\n follow the isophotes (a four-lobed or twisted pattern) say the *shape* is wrong — an MGE\n fixes that. Residuals in discrete off-centre lumps say the shape is fine but there is\n substructure — that is a pixelization ([`ag_pixelization`](./ag_pixelization.md)), not a basis.\n If you have not looked yet, look first; it is one plot and it decides the branch.\n- *\"Does the galaxy have a single well-defined centre?\"* Every basis in this skill shares one\n centre across all its components. A merger, or a galaxy with a bright companion overlapping\n it, breaks that assumption — handle the companion first with\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- *\"Is there a compact nuclear source?\"* An AGN or a nuclear starburst is a separate component,\n and there is a purpose-built compact MGE for it (branch four below).\n\n## Branch — linear light profiles, the default for any decomposition\n\nStart here even when you expect to end up with a basis. This is the same bulge-plus-disk model\n`ag_build_imaging_model` composes, and the point of this branch is what happens to `intensity`.\n\n```python\n\"\"\"\nGalaxy Structure: Linear Bulge-Disk Decomposition\n=================================================\n\nDecompose a galaxy's light into a Sersic bulge and an Exponential disk using *linear* light\nprofiles, whose `intensity` parameters are solved analytically by a linear inversion inside\nevery likelihood evaluation rather than sampled by the non-linear search. The ratio of the two\nsolved intensities, integrated, is the bulge-to-total light ratio.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the masked, over-sampled imaging dataset.\n- **Model:** Compose the linear bulge and disk, with their centres paired.\n- **Check:** Confirm the parameter count and evaluate one likelihood.\n- **Intensities:** Read the solved intensities back out of a completed fit.\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 = 3.0\n\n\"\"\"\n__Dataset__\n\nLoaded from FITS, masked to a radius chosen by inspecting the data, and over-sampled adaptively\nwhere the profile's intensity gradient is steep. All three decisions change the answer, so they\nare reproduced here rather than hidden\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\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_lp=over_sample_size)\n\n\"\"\"\n__Model__\n\nThe decomposition is identifiable because the two components are *asymmetric* in what they are\nallowed to be: the bulge's `sersic_index` is free, so the fit can find a concentrated spheroid\n(n ~ 4), while the `Exponential` disk has n fixed at 1 by construction. Two free Sersics on one\ngalaxy are largely degenerate and the fit will trade light between them.\n\n`ag.lp_linear` rather than `ag.lp` is the only change from a standard composition, and it is\nnot a small one: each profile's `intensity` leaves the search's parameter space and is instead\nsolved by a linear inversion that always returns the amplitudes maximising the likelihood given\nthe other parameters. Two dimensions vanish, and with them the strong degeneracies between\n`intensity` and `effective_radius` / `sersic_index` that a sampler finds hardest to map\n(`PyAutoGalaxy:autogalaxy/profiles/light/linear/sersic.py`).\n\n`bulge.centre = disk.centre` asserts the components are concentric — physically reasonable for\nmost galaxies, and worth two parameters.\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\ndisk = af.Model(ag.lp_linear.Exponential)\nbulge.centre = disk.centre\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\nThe likelihood at the prior medians costs one evaluation and proves the model, dataset and\nanalysis are mutually compatible. Pass `use_jax=False` while debugging — NumPy tracebacks are\nfar easier to read (`PyAutoGalaxy:autogalaxy/imaging/model/analysis.py`).\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 likelihood at prior medians: {float(log_likelihood):.2f}\")\n```\n\nN = 9: the bulge's centre (2), two `ell_comps` pairs (4), two `effective_radius` values and the\nbulge's `sersic_index` — with both intensities solved. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/linear_light_profiles/modeling.py`, which\nreduces `n_live` to 75 for exactly this reason: a simpler parameter space needs fewer live\npoints to map.\n\nThe cost is real but small. A linear likelihood evaluation is roughly three to five times\nslower than a standard one, because the inversion has to be solved every time. The workspace\nexample measures ~0.05 s against ~0.01 s on a low-resolution dataset. That is repaid by fewer\niterations and a more reliable posterior, and the trade tips further towards linear the more\nprofiles you add — which is what makes the next two branches possible at all.\n\n### The consequence: `intensity` is not in the model, so it is not in the results\n\nThis trips up everyone once. A linear profile has no `intensity` attribute to report, so\n`model.results` does not list one, and **a linear profile cannot be plotted directly** — there\nis no amplitude to evaluate. The intensities exist only after a fit, as the inversion's\nsolution. Three ways to get at them, all from\n`autogalaxy_workspace:scripts/imaging/features/linear_light_profiles/modeling.py`:\n\n```python\n\"\"\"\n__Intensities__\n\n`max_log_likelihood_galaxies` has already performed the inversion, so its profiles carry their\nsolved `intensity` values and can be evaluated and plotted like ordinary profiles. The\n`Fit` additionally exposes a dictionary keyed by the profile objects themselves, which is the\nunambiguous route when several components share a class\n(`PyAutoGalaxy:autogalaxy/imaging/fit_imaging.py`).\n\"\"\"\ngalaxies = result.max_log_likelihood_galaxies\n\nprint(f\"bulge intensity = {galaxies[0].bulge.intensity}\")\n\nfit = result.max_log_likelihood_fit\n\nprint(fit.linear_light_profile_intensity_dict[fit.galaxies[0].bulge])\nprint(fit.linear_light_profile_intensity_dict[fit.galaxies[0].disk])\n\ngalaxies_ordinary = fit.model_obj_linear_light_profiles_to_light_profiles\n\naplt.subplot_galaxies(\n galaxies=galaxies_ordinary,\n grid=dataset.grid,\n output_path=\"scripts/scratch/my_galaxy/\",\n auto_filename=\"decomposition\",\n output_format=\"png\",\n)\n```\n\n`model_obj_linear_light_profiles_to_light_profiles` returns the same galaxies with every linear\nprofile replaced by its ordinary equivalent at the solved amplitude — that is the object to\nhand to any plotting or derived-quantity call. `fit.inversion.linear_obj_list` holds one\n`LightProfileLinearObjFuncList` per linear component (or per `Basis`), which is where the\nbookkeeping lives when you need to be certain which amplitude belongs to which profile.\n\nIntegrating those amplitudes over the two profiles is what gives you the bulge-to-total ratio;\nthe machinery for luminosities and magnitudes is\n[`../wiki/core/concepts/cosmology_and_units.md`](../wiki/core/concepts/cosmology_and_units.md).\nAsk if you want the derived-quantity route spelled out.\n\n## Branch — a Multi-Gaussian Expansion, when the *shape* is wrong\n\nA Gaussian is a poor galaxy profile on its own and an excellent basis function in company:\nsum enough of them at fixed, logarithmically spaced widths and you can build any monotonic\nradial profile, and — if you let separate groups of them carry separate ellipticities — an\nisophote shape that changes with radius. That last property is the one a Sersic cannot have at\nany parameter count, and it is why an MGE is the workspace's recommended default model.\n\nThe composition is long, so the library ships a helper:\n\n```python\n\"\"\"\n__Model__\n\nAn MGE bulge: 20 linear Gaussians sharing one centre and one ellipticity, with every `sigma`\nfixed on a logarithmic ladder running from below the pixel scale out to `mask_radius`, and\nevery intensity solved by the inversion. `mask_radius` sets the outer end of that ladder, so\npass the radius you actually masked at — a ladder that stops short of the data leaves the\nouter isophotes unrepresented (`PyAutoGalaxy:autogalaxy/analysis/model_util.py`).\n\"\"\"\nbulge = ag.model_util.mge_model_from(\n mask_radius=MASK_RADIUS,\n total_gaussians=20,\n centre_prior_is_uniform=True,\n)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n```\n\n**N = 4** — a shared centre and a shared `ell_comps`. Twenty Gaussians, four dimensions, more\nmorphological freedom than a Sersic's six. Adapted from\n`autogalaxy_workspace:scripts/imaging/start_here.py`, where the MGE is the recommended default.\n\nThe full signature is\n`mge_model_from(mask_radius, total_gaussians=30, gaussian_per_basis=1,\ncentre_prior_is_uniform=True, centre=(0.0, 0.0), centre_fixed=None, centre_per_basis=False,\ncentre_sigma=0.3, ell_comps_prior_is_uniform=False, ell_comps_uniform_width=0.2,\nell_comps_sigma=0.3, use_spherical=False)`. The arguments worth knowing:\n\n- **`gaussian_per_basis=2`** splits the ladder into two bases with *independent* ellipticities.\n N goes 4 → 6 and you buy the ability to fit an isophotal twist: an inner group and an outer\n group free to be differently elongated and differently oriented. This is the single most\n useful knob here, and the reason to prefer an MGE over a Sersic pair for an early-type galaxy.\n- **`centre_fixed=(y, x)`** pins the centre entirely, dropping two more parameters. Used for\n contaminating neighbours ([`ag_light_model_extras`](./ag_light_model_extras.md)).\n- **`use_spherical=True`** drops the ellipticity — for a genuinely round system, or as a\n deliberately rigid comparison model.\n- **`total_gaussians`** buys radial resolution, not shape freedom. 15 is enough for a smooth\n profile; 60 for a well-resolved one; beyond that you are mostly paying for likelihood\n evaluations. Cost scales with the count, because every Gaussian's image must be computed and\n PSF-convolved: the workspace measures ~0.5 s per evaluation for 60 Gaussians, against ~0.01 s\n for a standard Sersic. VRAM rises too — 10–50 MB per batched likelihood at 60 Gaussians, so\n check `analysis.print_vram_use(model=model, batch_size=search.batch_size)` before a GPU run\n with hundreds of components.\n\nThat run time is why the overall comparison is not obvious, and the workspace is honest about\nit: the MGE's likelihood is much slower, but its parameter space is so much simpler — and\ncrucially contains *no parameter that scales the galaxy's size* — that the search converges far\nfaster. Net, it usually wins, and it fits better.\n\n### The hand-rolled `Basis`, and why you might want it\n\nThe helper is a convenience over one explicit idiom. Compose it yourself when you need\nsomething the arguments do not offer — a bespoke `sigma` range, a third basis, per-basis\npriors. From `autogalaxy_workspace:scripts/imaging/features/multi_gaussian_expansion/modeling.py`:\n\n```python\n\"\"\"\n__Model__\n\nTwo groups of 30 Gaussians. Within a group every Gaussian shares the centre and ellipticity of\nthe first, and every `sigma` is *fixed* to a value on a log10 ladder spanning a tenth of the\npixel scale to the mask radius. `ag.lp_basis.Basis` then groups the whole list into one model\ncomponent the galaxy can hold (`PyAutoGalaxy:autogalaxy/profiles/basis.py`).\n\nThe lower end matters: anchoring it to the pixel scale stops the basis spending Gaussians on\nscales the data cannot resolve. `mge_model_from` exposes this as `sigma_min` (default `1e-4`,\nwhich reproduces the historical ladder exactly).\n\"\"\"\nimport numpy as np\n\ntotal_gaussians = 30\ngaussian_per_basis = 2\n\nlog10_sigma_list = np.linspace(\n np.log10(dataset.pixel_scales[0] / 10.0), np.log10(MASK_RADIUS), total_gaussians\n)\n\ncentre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\ncentre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n\nbulge_gaussian_list = []\n\nfor _ in range(gaussian_per_basis):\n\n gaussian_list = af.Collection(\n af.Model(ag.lp_linear.Gaussian) for _ in range(total_gaussians)\n )\n\n for i, gaussian in enumerate(gaussian_list):\n gaussian.centre.centre_0 = centre_0 # one shared y centre\n gaussian.centre.centre_1 = centre_1 # one shared x centre\n gaussian.ell_comps = gaussian_list[0].ell_comps # shared within this basis\n gaussian.sigma = 10 ** log10_sigma_list[i] # fixed, not sampled\n\n bulge_gaussian_list += gaussian_list\n\nbulge = af.Model(ag.lp_basis.Basis, profile_list=bulge_gaussian_list)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n```\n\nN = 6. `print(model.info)` prints all sixty Gaussians and looks alarming; almost every\nparameter shown is fixed. Trust `model.total_free_parameters`, not the length of the printout.\n\nTwo details that are load-bearing. Assigning `gaussian.sigma = ` **fixes** it — the\nwhole scheme depends on the widths not being sampled, because a free `sigma` reintroduces the\nsize-scaling degeneracy the MGE exists to remove. And sharing `ell_comps` *within* a basis but\nnot *between* bases is precisely what makes the twist fittable.\n\nThe `Basis` constructor also accepts a `regularization` argument that penalises non-smooth\namplitude solutions. Treat it as research-only: the positive-only solver below already fixes\nthe pathology it was introduced for, and no production analysis uses it — the workspace moved\nthat branch out of the user-facing script deliberately.\n\n## Branch — a compact MGE for an unresolved nucleus\n\nAn AGN or nuclear starburst is not the extended stellar light, and forcing one basis to cover\nboth makes the fit choose between them. Model it as a second, deliberately compact basis: the\nsame construction with the `sigma` ladder capped at about twice the pixel scale, so the\ncomponent cannot be broader than a PSF-convolved point source.\n\n```python\n\"\"\"\n__Model__\n\nThe galaxy's light becomes the sum of a diffuse stellar `bulge` MGE and a compact `point` MGE.\nThe point basis is 10 linear Gaussians sharing one centre and ellipticity with `sigma` values\nlog-spaced from `sigma_min` (default 0.01\") to twice the pixel scale — compact relative to the\nresolution of the data, which is what makes it read as a point source rather than a small galaxy\n(`PyAutoGalaxy:autogalaxy/analysis/model_util.py`).\n\"\"\"\npoint = ag.model_util.mge_point_model_from(\n pixel_scales=PIXEL_SCALES,\n total_gaussians=10,\n centre=(0.0, 0.0),\n)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, point=point)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/features/multi_gaussian_expansion/modeling.py`,\nwhose `__Point Source__` section builds the same basis line by line first if you want to see\ninside the helper. Four extra parameters on top of the bulge MGE.\n\nThere is a genuinely different approach to the same problem — an **operated** light profile,\nwhich is assumed to be already PSF-convolved and so bypasses the convolution entirely. Which\nto pick, and why a compact model source is so sensitive to sub-pixel placement, is\n[`ag_light_model_extras`](./ag_light_model_extras.md) and\n[`../wiki/core/concepts/sky_background_and_operated_profiles.md`](../wiki/core/concepts/sky_background_and_operated_profiles.md).\n\n## Branch — shapelets, and the price of a signed solver\n\nShapelets are an orthonormal basis of Gauss–Hermite (Cartesian) or Gauss–Laguerre (polar)\nfunctions on a single scale `beta`, introduced for exactly this problem\n(Refregier 2003, arXiv:astro-ph/0105178). Because the basis is complete, it can represent\nmorphology an MGE smooths over — the disky, star-forming structure the workspace cites them\nfor. But completeness has a price, and it is a physical one.\n\n**Shapelets require negative amplitudes.** The higher-order basis functions oscillate in sign,\nand reproducing an arbitrary shape means combining them with signed coefficients. Every other\nbranch in this skill uses a positive-only linear solver, because a negative surface brightness\nis not a thing a galaxy has. Shapelets cannot: you must pass\n`ag.Settings(use_positive_only_solver=False)`, and the reconstructed light *will* contain\nnegative flux — verified, not assumed. That is not a numerical wrinkle to ignore; it is the\nmodel telling you it is a mathematical fit rather than a physical decomposition, and it is why\nthe workspace recommends trying an MGE alongside.\n\n```python\n\"\"\"\n__Model__\n\nA polar shapelet basis to order n = 5: 11 `ShapeletPolar` components whose `n` and `m` indices\nare fixed by construction, sharing one centre, one ellipticity and one scale `beta`. `beta` is\nthe only shape parameter — it sets the physical size the whole basis is expressed on, so its\nprior matters more here than any single amplitude\n(`PyAutoGalaxy:autogalaxy/profiles/light/linear/shapelets/polar.py`).\n\"\"\"\ntotal_n = 5\ntotal_m = sum(range(2, total_n + 1)) + 1\n\nshapelets_bulge_list = af.Collection(\n af.Model(ag.lp_linear.ShapeletPolar) for _ in range(total_n + total_m)\n)\n\nn_count = 1\nm_count = -1\n\nfor shapelet in shapelets_bulge_list:\n shapelet.n = n_count\n shapelet.m = m_count\n\n m_count += 2\n\n if m_count > n_count:\n n_count += 1\n m_count = -n_count\n\n shapelet.centre = shapelets_bulge_list[0].centre\n shapelet.ell_comps = shapelets_bulge_list[0].ell_comps\n shapelet.beta = shapelets_bulge_list[0].beta\n\nbulge = af.Model(ag.lp_basis.Basis, profile_list=shapelets_bulge_list)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\n\"\"\"\n__Analysis__\n\nThe signed solver is requested through `ag.Settings`, which is passed to the analysis rather\nthan to the model — it is a property of how the inversion is solved, not of what is being\nfitted (`PyAutoArray:autoarray/settings.py`).\n\"\"\"\nanalysis = ag.AnalysisImaging(\n dataset=dataset,\n settings=ag.Settings(use_positive_only_solver=False),\n use_jax=True,\n)\n```\n\n**N = 5**: centre (2), `ell_comps` (2), `beta` (1). Adapted from\n`autogalaxy_workspace:scripts/imaging/features/shapelets/modeling.py` — note that the workspace\nloop as written does *not* link `ell_comps` across the basis, which leaves each shapelet's\nellipticity free and inflates the model to N = 43 rather than the N = 3 its prose claims. The\nline `shapelet.ell_comps = shapelets_bulge_list[0].ell_comps` above is the fix; N = 3 is what\nyou get from the spherical variant `ag.lp_linear.ShapeletPolarSph`, which has no `ell_comps` at\nall. Check `model.total_free_parameters` rather than trusting a comment — including this one.\n\nPolar shapelets suit radially organised light, which is most galaxies.\n`ag.lp_linear.ShapeletCartesian` (indexed by `n_y`, `n_x` instead of `n`, `m`) and\n`ag.lp_linear.ShapeletExponential` are the other two families; the Cartesian basis is not\ngenerally recommended for galaxies. You can see what a basis actually looks like before fitting\nanything:\n\n```python\nshapelets = [\n ag.lp_linear.ShapeletCartesian(\n n_y=y, n_x=x, centre=(0.0, 0.0), ell_comps=(0.0, 0.0), beta=1.0\n )\n for x in range(5)\n for y in range(5)\n]\n\nbasis = ag.lp_basis.Basis(profile_list=shapelets)\n\naplt.subplot_basis_image(\n basis=basis,\n grid=ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.05),\n output_path=\"scripts/scratch/shapelet_basis/\",\n output_format=\"png\",\n)\n```\n\n`subplot_basis_image` renders every component of the basis on a grid, which is the fastest way\nto build intuition for what `beta` and the order limit are buying you. It takes `output_path` /\n`output_format` but **not** `output_filename` — give each variant its own directory\n([`../wiki/core/api/plotting.md`](../wiki/core/api/plotting.md) tabulates that split). Print the\nabsolute path and offer to open it.\n\nShapelets also cost about 0.37 s per likelihood evaluation for ~60 components in the workspace's\nmeasurement — slower than linear profiles, comparable to an MGE, and with more free parameters\nthan an MGE of similar flexibility. The workspace's own recommendation is to run both and\ncompare; the concept page\n[`../wiki/core/concepts/shapelets.md`](../wiki/core/concepts/shapelets.md) has the full\nwhen-to-use discussion.\n\n## Choosing between the three\n\nFit them in order and let the residuals decide, because each step is cheap given the last:\n\n1. **Single linear Sersic** — the reference every other fit is judged against, and the source of\n the size and concentration you will actually quote. Six parameters.\n2. **Linear bulge plus disk** — if the science is a bulge-to-total ratio, this *is* the answer;\n a basis will fit better and tell you less. Nine parameters.\n3. **MGE, `gaussian_per_basis=2`** — if the residuals show a twist or a radially varying\n ellipticity. Six parameters, better fit, less interpretable.\n4. **Shapelets** — if the MGE still leaves disky or asymmetric structure and you accept a signed\n solution. Five parameters.\n5. **Neither is enough** — the residuals sit in discrete off-centre lumps, and no basis with a\n single shared centre will absorb them. That is\n [`ag_pixelization`](./ag_pixelization.md).\n\nAn MGE and a shapelet basis can be compared by Bayesian evidence only with care, because they\nsolve different linear problems (positive-only versus signed). Compare them on the residual map\nand the chi-squared first, and ask if you want the evidence caveats spelled out.\n\n## Combine — where this hands off\n\n- **Pick a search** → [`ag_configure_search`](./ag_configure_search.md). Basis models want\n *fewer* live points than a parametric fit, not more — the workspace drops `n_live` to 75 for\n both linear profiles and the MGE — because the parameter space is simpler.\n- **Run it and read the output folder** → [`ag_run_search`](./ag_run_search.md).\n- **Plot the fit** → [`ag_plot_fit`](./ag_plot_fit.md), remembering that a linear profile has to\n go through `model_obj_linear_light_profiles_to_light_profiles` before it can be plotted.\n- **The basis fits worse than you expected, or the search stalls** →\n [`ag_debug_fit_failure`](./ag_debug_fit_failure.md). The two failure modes specific to this\n skill are a `sigma` ladder that stops short of the mask radius, and a free `sigma` or `beta`\n reintroducing a size degeneracy.\n- **Structured residuals a basis cannot reach** → [`ag_pixelization`](./ag_pixelization.md).\n- **A neighbour overlapping the galaxy, a residual sky, or a nuclear point source** →\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- **A non-parametric shape measurement instead of a model** →\n [`ag_ellipse_fitting`](./ag_ellipse_fitting.md), which measures the isophotal twist directly\n rather than inferring it from a two-basis MGE.\n- **The same galaxy in several bands** → the multi-dataset skill (`ag_multi_dataset`). A basis\n across bands is where the factor graph earns its keep, since the shape can be shared while\n the amplitudes are solved per band.\n- **Chaining a parametric fit into a basis fit** → the search-chaining skill\n (`ag_chain_searches`); a Sersic fit's centre and ellipticity make excellent starting priors\n for an MGE.\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording which tier you\nused, `total_gaussians` / `gaussian_per_basis` or the shapelet order, the solver you chose, and\nwhat the residuals looked like at each step — the last is the evidence for the model choice and\nthe first thing a referee will ask for.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Linear profiles](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_5_linear_profiles.ipynb):\n builds up from a standard profile to a linear one to a basis, showing what the inversion\n actually solves at each step.\n- **General reference** — [RTD: Light profiles API](https://pyautogalaxy.readthedocs.io/en/latest/api/light.html):\n every standard, linear, operated and basis variant with its module and parameters.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/features/multi_gaussian_expansion/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/multi_gaussian_expansion/modeling.py):\n the MGE end to end, including the compact nuclear basis and the run-time and VRAM discussion.\n\n## Agent procedural checklist\n\n1. Ask whether the user needs interpretable Sersic parameters or the best achievable fit — that\n choice, not the API, picks the branch.\n2. Look at the residual map of a single linear Sersic first; structured-but-smooth residuals mean\n a basis, discrete lumps mean `ag_pixelization`.\n3. Default to `ag.lp_linear` for every parametric component; never use `ag.lp` in a model\n without a reason.\n4. For an MGE, pass the real `mask_radius`, and reach for `gaussian_per_basis=2` when the\n isophotes twist.\n5. For shapelets, pass `ag.Settings(use_positive_only_solver=False)` on the *analysis*, link\n `ell_comps` across the basis, and tell the user the reconstruction may contain negative flux.\n6. Always check `model.total_free_parameters` against what you intended — a basis's `model.info`\n is long and mostly fixed, and one unlinked parameter multiplies by the component count.\n7. Evaluate one likelihood before committing to a search; run `print_vram_use` before a GPU run\n with a large basis.\n8. Read intensities out via `max_log_likelihood_galaxies`,\n `fit.linear_light_profile_intensity_dict`, or\n `model_obj_linear_light_profiles_to_light_profiles` — never expect them in `model.results`.\n9. Save the script to `scripts/`, quote every plot's absolute path and offer to open it, then\n offer the `wiki/project/` entry.\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_2_modeling/tutorial_5_data_and_likelihoods.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_prepare_imaging_data\n\n---\nname: ag_prepare_imaging_data\ndescription: Load a user's own CCD imaging of a galaxy from FITS into an `ag.Imaging` dataset and get it ready to fit — pixel scale, flux units, the RMS noise-map, the PSF, the mask extent, contaminating extra galaxies and foreground stars, over-sampling, and the optional `info.json` / centre sidecars. **This skill owns the real-data inspection gate**: the plot-and-settle procedure that must run before any model is composed or fitted on real observational data. Use whenever the user brings their own data (HST, JWST, Euclid, ground-based), whenever a dataset needs checking against PyAutoGalaxy's standards, or whenever a mask or contaminant decision is open. Not for simulating data (`ag_simulate_dataset`), not for composing the model itself (`ag_build_imaging_model`), and not for visibility-plane data.\n---\n\n# Preparing your own imaging data\n\nEverything downstream inherits the decisions made here. A noise-map that is a variance\nrather than an RMS makes every likelihood wrong by a constant power; a mask that truncates\nthe outer isophotes biases the effective radius and Sersic index directly; an unmodelled\nneighbour inside the mask pulls the fit toward a galaxy that isn't there. None of those\nthree announce themselves — the search converges, the residuals look plausible, and the\nnumber you publish is wrong. That is why this step is a gate rather than a formality.\n\nScientifically, the job is to hand the likelihood three things it can trust: an **image**\nin electrons per second, a **per-pixel RMS noise-map** in the same units, and a **PSF** to\nforward-convolve the model with. Statistically, the job is to define the *support* of the\nlikelihood — which pixels are in the sum — and to make sure every pixel inside it is\ndescribed by the model you are about to fit. The standards themselves come from\n`autogalaxy_workspace:scripts/imaging/data_preparation/start_here.py`; the API catalogue\nis [`../wiki/core/api/datasets.md`](../wiki/core/api/datasets.md).\n\n## The real-data gate — non-negotiable\n\n**Before composing or running any model-fit on real observational data**, plot it, show the\nuser the `dataset.png` path, and settle two things from that same look:\n\n**(a) Extra galaxies, foreground stars and artefacts.** These are the single largest source\nof fit bias. Decide, explicitly, which of the three strategies below applies to each one.\n\n**(b) The mask extent** — the radius and shape that captures the galaxy's emission out to\nwhere it meets the sky, without dragging in noise or contaminants. **Never leave the mask\nradius as a silent default on real data.** A mask that cuts inside the outer isophotes\nbiases `effective_radius` and `sersic_index`, so this is a science-critical choice, not a\ntidy-up.\n\n**If you cannot execute code in the current session** — a planning-only or read-only session,\na harness whose tools are restricted — **the gate is not waived**: ask the user to plot and inspect the data, and to confirm both\n(a) contaminants and (b) the mask extent, before you compose the fit. These are the\nquestions every real-data run must ask, on every harness.\n\n**Simulated data is exempt** — you know the truth, including where every component is, so\nthere is nothing to discover by looking. Everything else in this skill still applies to\nsimulated data as documentation of what a real run would need.\n\nThe gate is satisfied by looking, not by asserting. The first branch below is how you look.\n\n## Ask\n\n- *\"What instrument and filter, and what is the pixel scale?\"* — you cannot proceed without\n it, and it is the one number nothing in the data can tell you.\n- *\"Is the noise-map an RMS standard deviation per pixel, or a variance / weight map / HST\n WHT map?\"* — if they are not certain, treat it as unknown and convert; the likelihood\n assumes RMS.\n- *\"Are there neighbouring galaxies, foreground stars or reduction artefacts near the\n target?\"* — the (a) half of the gate.\n- *\"How far out do you care about the light — just the bright body, or the faint outer\n envelope?\"* — this is the (b) half of the gate phrased as a science question, which is\n how it should be decided.\n\n## Branch — look at it first\n\nLoad the three ingredients and plot them. Nothing else happens until this figure has been\nseen.\n\n```python\n\"\"\"\nData Inspection: ()\n=============================================\n\nLoad a galaxy's CCD imaging from FITS and inspect it before any model is composed. This\nscript exists to satisfy the real-data inspection gate: the image, noise-map, PSF and\nsignal-to-noise map are plotted so that two science-critical decisions can be made from\nevidence rather than defaults — which contaminating objects are present, and how far out\nthe mask should extend.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the image, noise-map and PSF from FITS with the correct pixel scale.\n- **Standards Check:** Verify the PSF is odd-sized and normalised, and report the S/N.\n- **Plot:** Write the dataset subplot to disk for inspection.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPLOT_DIR = Path(\"scripts\") / \"scratch\" / \"my_galaxy\"\n\n\"\"\"\n__Dataset__\n\nThree ingredients are needed for galaxy modeling: the image in electrons per second, a\nper-pixel RMS noise-map in the same units, and the PSF describing the blurring imposed by\nthe telescope optics. The PSF is *forward-convolved* onto the model rather than divided out\nof the data, which is what lets a fit distinguish a genuinely compact bulge from a\nseeing-broadened one.\n\n`pixel_scales` converts pixels to arcseconds and must be correct for your instrument —\nHST/ACS ~0.05\", JWST/NIRCam ~0.03-0.06\", Euclid VIS 0.1\" and NISP 0.2\", ground-based\n0.2-0.3\". Nothing in the FITS data can correct a wrong value for you; every inferred size\nscales with it. Loading is handled by `ag.Imaging.from_fits`\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\"\"\"\nPIXEL_SCALES = 0.1\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\n\"\"\"\n__Standards Check__\n\nTwo properties of the PSF are cheap to check and expensive to get wrong. An **even-sized**\nkernel shifts the convolved model by half a pixel, which propagates straight into the\ninferred centre; and a kernel that does not **sum to unity** does not conserve flux, which\ncorrupts any magnitude or luminosity derived from the fit. The signal-to-noise peak is a\nsanity check on the noise-map: a galaxy usually peaks somewhere around 10-300, and a value\norders of magnitude away from that is a sign the noise-map is in the wrong units or is a\nvariance rather than an RMS.\n\"\"\"\npsf_shape = dataset.psf.kernel.shape_native\n\nprint(f\"PSF shape: {psf_shape}, odd: {all(s % 2 == 1 for s in psf_shape)}\")\nprint(f\"PSF sum: {float(dataset.psf.kernel.sum()):.6f} (should be 1.0)\")\nprint(f\"peak signal-to-noise: {float(dataset.signal_to_noise_map.max()):.1f}\")\n\n\"\"\"\n__Plot__\n\nThe subplot shows the image, noise-map, PSF and signal-to-noise map together, which is\nexactly the set needed to answer the two gate questions: what contaminating objects are\npresent, and how far out the galaxy's emission extends before it meets the sky.\n\"\"\"\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=PLOT_DIR,\n output_filename=\"dataset\",\n output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThen **quote the absolute path of `dataset.png` back to the user and offer to open it**\n(`xdg-open` on Linux, `open` on macOS, `explorer.exe` or `wslview` from WSL) — one offer,\nnot repeated nagging. Ask the two gate questions against that specific figure, naming what\nyou can see in it. \"There's a compact object about 2\" north-east of the centre — is that a\nneighbour or part of the galaxy?\" is a useful question; \"are there any contaminants?\" in the\nabstract is not.\n\n## Branch — the three standards, and how to fix a violation\n\n`autogalaxy_workspace:scripts/imaging/data_preparation/start_here.py` is the checklist; the\nper-ingredient tools are in `examples/data.py`, `examples/noise_map.py` and\n`examples/psf.py` beside it.\n\n**The image.** Flux in **electrons per second**, galaxy near the centre, cut down to a\npostage stamp. The units matter because default priors on light-profile `intensity` assume\nthem, and because magnitudes are computed from them. Conversions both ways are in the\npreprocess module (`PyAutoArray:autoarray/dataset/preprocess.py`):\n\n```python\nexposure_time_map = ag.Array2D.full(\n fill_value=1000.0,\n shape_native=data.shape_native,\n pixel_scales=data.pixel_scales,\n)\n\ndata_counts = ag.preprocess.array_eps_to_counts(\n array_eps=data, exposure_time_map=exposure_time_map\n)\ndata_eps = ag.preprocess.array_counts_to_eps(\n array_counts=data_counts, exposure_time_map=exposure_time_map\n)\n```\n\nADUs need the gain as well — `ag.preprocess.array_eps_to_adus(array_eps=data, gain=4.0,\nexposure_time_map=exposure_time_map)` and `array_adus_to_eps` back. If your reduction\nproduced a real per-pixel exposure-time map, load it with `ag.Array2D.from_fits` instead of\nthe flat `full` above; a flat map is a good approximation for many HST observations and not\nfor all. Trim an oversized stamp with\n`ag.preprocess.array_with_new_shape(array=data, new_shape=(80, 80))`, which crops centred.\nBackground subtraction is better done by your reduction pipeline, but\n`background_sky_level_via_edges_from` and `background_noise_map_via_edges_from` exist for\nwhen it wasn't — and modelling the residual sky as a free parameter is often the better\nanswer anyway (see the sky-background note in\n[`ag_build_imaging_model`](./ag_build_imaging_model.md)).\n\n**The noise-map.** RMS standard deviation per pixel, in electrons per second, **including**\nthe Poisson contribution from the galaxy's own counts as well as background sky. This is the\none to be most careful about: reduction pipelines frequently drop the Poisson term, and a\nnoise-map that is a variance, an inverse variance, or an HST WHT map will produce a fit that\nconverges confidently to the wrong answer. The preprocess module has a converter for each\ncommon input form — `noise_map_via_weight_map_from`,\n`noise_map_via_inverse_noise_map_from`,\n`noise_map_via_data_eps_and_exposure_time_map_from`,\n`noise_map_via_data_eps_exposure_time_map_and_background_noise_map_from`,\n`noise_map_via_data_eps_exposure_time_map_and_background_variances_from` and\n`poisson_noise_via_data_eps_from`. If you cannot determine which form you have, the\ninstrument handbook is the authority; guessing here is not recoverable later.\n\n**The PSF.** Odd dimensions, normalised to unity, centred, and roughly 11×11 to 21×21\npixels. Larger kernels (51×51) work but slow every likelihood evaluation, since convolution\nruns on every model image. Load with normalisation applied:\n\n```python\npsf = ag.Convolver.from_fits(\n file_path=DATASET_PATH / \"psf.fits\",\n hdu=0,\n pixel_scales=PIXEL_SCALES,\n normalize=True,\n)\n```\n\n`ag.Imaging.from_fits` normalises the PSF internally anyway, so this is belt-and-braces. An\neven-sized kernel is a genuine problem rather than a warning:\n`ag.preprocess.kernel_with_odd_dimensions_from` will interpolate one for you, but it *is*\nan interpolation and the right fix is to re-derive the PSF at odd size in your reduction.\nResize with `ag.preprocess.array_with_new_shape(array=psf.kernel, new_shape=(21, 21))`.\n\n## Branch — (a) contaminants: three strategies, one decision per object\n\nFor each neighbouring galaxy, foreground star or artefact you identified in the figure,\nchoose one:\n\n**1. Scale its noise (the default).** Keep the pixels in the fit but blow their noise-map\nvalues up so they contribute negligibly to the likelihood. Preferred over deleting pixels\nbecause it leaves the pixel grid intact — which matters a great deal later if you move to a\npixelised reconstruction, where removed pixels create discontinuities.\n\n```python\nmask_extra_galaxies = ag.Mask2D.from_fits(\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n pixel_scales=dataset.pixel_scales,\n invert=True, # `True` marks the pixels whose noise is scaled.\n)\n\ndataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies)\n\naplt.subplot_imaging_dataset(\n dataset=dataset, output_path=PLOT_DIR, output_filename=\"dataset_scaled\",\n output_format=\"png\",\n)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py`. Note `invert=True`: the\nFITS convention here marks the *scaled* region as `True`. Build the mask as a union of\ncircles when you know the positions, following\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/mask_extra_galaxies.py`:\n\n```python\nimport numpy as np\n\nextra_galaxies_mask = np.zeros(data.shape_native, dtype=bool)\n\nfor centre, radius in [((1.0, 3.5), 1.5), ((-2.0, -3.5), 2.4)]:\n circle = ag.Mask2D.circular(\n shape_native=data.shape_native,\n pixel_scales=data.pixel_scales,\n centre=centre,\n radius=radius,\n invert=True,\n )\n extra_galaxies_mask = np.logical_or(extra_galaxies_mask, circle.native)\n\nmask = ag.Mask2D(mask=extra_galaxies_mask, pixel_scales=data.pixel_scales)\n\naplt.fits_array(\n array=mask, file_path=DATASET_PATH / \"mask_extra_galaxies.fits\", overwrite=True\n)\n```\n\nFor irregular shapes there is a spray-paint GUI at\n`autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask_extra_galaxies.py`, and the\nsame `ag.Scribbler`-based tool appears inline at the foot of\n`autogalaxy_workspace:scripts/imaging/start_here.py`. Point the user at it rather than\nhand-deriving centres when the contaminant is a messy blend.\n\n**2. Shrink the mask so it falls outside.** The simplest option, and the right one when the\ncontaminant sits comfortably beyond the galaxy's emission. It costs you nothing except the\nsky annulus you gave up — but check it does not also cut into the outer isophotes, because\nthen you have traded a known bias for a worse one.\n\n**3. Model it as an extra galaxy.** Give it its own light profile with a fixed centre. This\nis the choice when its light genuinely overlaps the target's, so neither masking nor scaling\ncan separate them without also removing signal you need. That is a *model* decision, so it\nbelongs to [`ag_build_imaging_model`](./ag_build_imaging_model.md); what you produce here is\nthe list of centres it will consume:\n\n```python\nextra_galaxies_centres = ag.Grid2DIrregular(values=[(1.0, 3.5), (-2.0, -3.5)])\n\naplt.plot_array(\n array=data,\n title=\"Data\",\n positions=[np.array(extra_galaxies_centres)],\n output_path=PLOT_DIR,\n output_filename=\"data_with_extra_galaxies\",\n output_format=\"png\",\n)\n\nag.output_to_json(\n obj=extra_galaxies_centres,\n file_path=DATASET_PATH / \"extra_galaxies_centres.json\",\n)\n```\n\nAdapted from\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/extra_galaxies_centres.py`.\nAlways plot the centres over the image before saving them — an off-by-a-sign (y,x) ordering\nis obvious in a figure and invisible in a JSON file. There is a click-to-select GUI at\n`autogalaxy_workspace:scripts/imaging/data_preparation/gui/extra_galaxies_centres.py` which\nsnaps to the brightest pixel in a 5×5 box.\n\nThe physics of choosing between the three, and what noise scaling does to the likelihood,\nis\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch — (b) the mask extent\n\nThe mask defines which pixels enter the likelihood. Choose its radius from the figure, and\nsay out loud what you chose and why:\n\n```python\nMASK_RADIUS = 2.5\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\n\ndataset = dataset.apply_mask(mask=mask)\n\naplt.subplot_imaging_dataset(\n dataset=dataset, output_path=PLOT_DIR, output_filename=\"dataset_masked\",\n output_format=\"png\",\n)\n```\n\nTwo failure directions, and they are not symmetric. **Too small** truncates the outer\nisophotes and biases `effective_radius` and `sersic_index` — a real, systematic error in\nyour science result. **Too large** drags in sky-dominated pixels: it slows the fit and adds\nlittle information, but it does not bias the answer, and it keeps honest sky pixels that\nconstrain a background level. When in doubt, err large and re-plot; the cost is run time,\nnot correctness.\n\nCircular is the default and usually right for a single galaxy. Non-circular shapes exist\nwhen the geometry calls for it — `ag.Mask2D.circular_annular(inner_radius=..., outer_radius=...)`\nto exclude a saturated core, `ag.Mask2D.elliptical(major_axis_radius=..., axis_ratio=...,\nangle=...)` and `ag.Mask2D.elliptical_annular(...)` for a strongly inclined disk. All four\nare shown in\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/mask.py`, and\n`autogalaxy_workspace:scripts/guides/modeling/customize.py` covers applying a custom mask to\na fit. A mask drawn by hand in the GUI\n(`autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask.py`) is written to\n`mask.fits` and loaded back with `ag.Mask2D.from_fits`; for a genuinely irregular footprint,\n`autogalaxy_workspace:scripts/imaging/data_preparation/manual/mask_irregular.py` is the\nmanual route.\n\nWhy the radius is a science decision rather than a default, and what the slim/native\ndistinction means once a mask is applied, is\n[`../wiki/core/concepts/grids_and_masks.md`](../wiki/core/concepts/grids_and_masks.md).\n\n## Branch — over-sampling\n\nA Sersic profile's intensity varies steeply across a single central pixel, so evaluating it\nonce at the pixel centre under-counts the flux. Over-sampling evaluates the profile on a\nfiner sub-grid and averages, and it changes the inferred parameters — this is accuracy, not\ncosmetics. Do it adaptively: high in the centre where the gradient is steep, low in the\noutskirts where it is flat and the cost would be wasted.\n\n```python\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)\n\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py`. That reads as 8×8\nsub-sampling inside 0.3\", 4×4 between 0.3\" and 0.6\", and 2×2 beyond — note the list ends at\n2, never 1, so even the outskirts keep a floor. `centre_list` takes **every** bright\ncentre, so if you are modelling an extra galaxy rather than masking it, add its centre here\ntoo; a companion evaluated at 2×2 while the target gets 8×8 is a quiet accuracy loss. A\nplain integer (`over_sample_size_lp=4`) applies uniform over-sampling when you want\nsimplicity over tuning. The `_lp` suffix names the grid used for **l**ight-**p**rofile\nevaluation, which is a different grid from a pixelisation's.\n\n## Branch — the optional sidecars\n\nNone of these are required to fit; all of them make the result easier to interpret later.\n\n**`info.json`** — auxiliary numbers that travel with the dataset: redshift, velocity\ndispersion, a stellar mass from the literature, a previous paper's measurement. Passed to\n`search.fit(model=model, analysis=analysis, info=info)`, it is stored with the fit and can\nbe read back by the aggregator, which is what makes a population-scale comparison against\nexternal measurements possible.\n\n```python\nimport json\n\ninfo = {\"redshift\": 0.5, \"velocity_dispersion\": 250.0, \"stellar_mass\": 1e11}\n\nwith open(DATASET_PATH / \"info.json\", \"w+\") as f:\n json.dump(info, f, indent=4)\n```\n\nAdapted from\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/info.py`.\n\n**`light_centre.json`** — the galaxy's light centre as an `ag.Grid2DIrregular`, saved with\n`ag.output_to_json`, for use as a fixed value in the model. Fixing the centre removes two\nfree parameters and rules out solutions where the model centre wanders somewhere\nunphysical; it is the standard rescue when a search will not converge. Grounded in\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/light_centre.py`,\nwith a click-to-select GUI at\n`autogalaxy_workspace:scripts/imaging/data_preparation/gui/light_centre.py`.\n\nThe on-disk layout these files belong to is documented in\n[`../wiki/core/operations/dataset.md`](../wiki/core/operations/dataset.md), grounded on the\nbundled dataset and `autogalaxy_workspace:scripts/imaging/data_preparation/start_here.py`\n(the workspace simulates its imaging datasets on first run rather than committing them).\n\n## Combine — where this hands off\n\n- **The gate is satisfied and the dataset is loaded, masked and over-sampled** →\n [`ag_build_imaging_model`](./ag_build_imaging_model.md). Tell it what you decided about\n contaminants and the mask; it will ask otherwise.\n- **You want to rehearse the whole loop before touching real data** →\n [`ag_simulate_dataset`](./ag_simulate_dataset.md), which builds a dataset in exactly this\n format with known truth.\n- **A contaminant needs modelling rather than masking** → the model skill's extra-galaxies\n branch, fed by the `extra_galaxies_centres.json` you wrote above.\n- **The data looks wrong in a way you can't place** → the environment skill\n ([`ag_setup_environment`](./ag_setup_environment.md)) if it is the *plot* misbehaving, or\n the fit-debugging skill (`ag_debug_fit_failure`) once a fit has actually run.\n\nOffer (default-yes) to record the session as a dated\n`wiki/project/YYYY-MM-DD-.md` entry — the mask radius you chose and *why*, and what\nyou did about each contaminant, are exactly the decisions you will want justified when you\nwrite the paper.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Data](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_2_data.ipynb):\n what a CCD image, a noise-map and a PSF actually are, and why the PSF is convolved onto\n the model rather than divided out of the data. Its companion,\n [Data and likelihoods](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_5_data_and_likelihoods.ipynb),\n explains masking, contamination and how data choices change the likelihood.\n- **General reference** — [RTD: New user guide](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n routes by system scale and dataset type, and is the page to hand someone deciding how\n their data should be organised before they load it.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/data_preparation/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/data_preparation/start_here.py):\n the standards checklist with the per-ingredient example scripts and GUIs beneath it.\n\n## Agent procedural checklist\n\n1. Establish the pixel scale and the noise-map's definition before writing code.\n2. Load the three ingredients, plot the dataset subplot, **print and quote its absolute\n path**, and offer to open it once.\n3. Run the gate against that figure: settle (a) every contaminant and (b) the mask extent\n *with the user*. On a harness that cannot plot, ask the user to do both — never waive it.\n4. Check the three standards: eps units, RMS-with-Poisson noise-map, odd normalised PSF.\n Convert rather than assume.\n5. Apply, in order: noise scaling for contaminants → the mask → adaptive over-sampling\n (with every bright centre in `centre_list`).\n6. Write the sidecars the model will need (`extra_galaxies_centres.json`,\n `light_centre.json`, `info.json`) and plot any centres over the image before saving.\n7. Save the script to `scripts/`, hand off to `ag_build_imaging_model`, and offer the\n `wiki/project/` entry recording the mask and contaminant decisions.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_2_modeling/tutorial_6_search_chaining.ipynb b/notebooks/chapter_2_modeling/tutorial_6_search_chaining.ipynb index dba7df5..088a80c 100644 --- a/notebooks/chapter_2_modeling/tutorial_6_search_chaining.ipynb +++ b/notebooks/chapter_2_modeling/tutorial_6_search_chaining.ipynb @@ -411,7 +411,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_2_modeling/tutorial_6_search_chaining.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_prepare_imaging_data\n\n---\nname: ag_prepare_imaging_data\ndescription: Load a user's own CCD imaging of a galaxy from FITS into an `ag.Imaging` dataset and get it ready to fit — pixel scale, flux units, the RMS noise-map, the PSF, the mask extent, contaminating extra galaxies and foreground stars, over-sampling, and the optional `info.json` / centre sidecars. **This skill owns the real-data inspection gate**: the plot-and-settle procedure that must run before any model is composed or fitted on real observational data. Use whenever the user brings their own data (HST, JWST, Euclid, ground-based), whenever a dataset needs checking against PyAutoGalaxy's standards, or whenever a mask or contaminant decision is open. Not for simulating data (`ag_simulate_dataset`), not for composing the model itself (`ag_build_imaging_model`), and not for visibility-plane data.\n---\n\n# Preparing your own imaging data\n\nEverything downstream inherits the decisions made here. A noise-map that is a variance\nrather than an RMS makes every likelihood wrong by a constant power; a mask that truncates\nthe outer isophotes biases the effective radius and Sersic index directly; an unmodelled\nneighbour inside the mask pulls the fit toward a galaxy that isn't there. None of those\nthree announce themselves — the search converges, the residuals look plausible, and the\nnumber you publish is wrong. That is why this step is a gate rather than a formality.\n\nScientifically, the job is to hand the likelihood three things it can trust: an **image**\nin electrons per second, a **per-pixel RMS noise-map** in the same units, and a **PSF** to\nforward-convolve the model with. Statistically, the job is to define the *support* of the\nlikelihood — which pixels are in the sum — and to make sure every pixel inside it is\ndescribed by the model you are about to fit. The standards themselves come from\n`autogalaxy_workspace:scripts/imaging/data_preparation/start_here.py`; the API catalogue\nis [`../wiki/core/api/datasets.md`](../wiki/core/api/datasets.md).\n\n## The real-data gate — non-negotiable\n\n**Before composing or running any model-fit on real observational data**, plot it, show the\nuser the `dataset.png` path, and settle two things from that same look:\n\n**(a) Extra galaxies, foreground stars and artefacts.** These are the single largest source\nof fit bias. Decide, explicitly, which of the three strategies below applies to each one.\n\n**(b) The mask extent** — the radius and shape that captures the galaxy's emission out to\nwhere it meets the sky, without dragging in noise or contaminants. **Never leave the mask\nradius as a silent default on real data.** A mask that cuts inside the outer isophotes\nbiases `effective_radius` and `sersic_index`, so this is a science-critical choice, not a\ntidy-up.\n\n**If you cannot execute code in the current session** — a planning-only or read-only session,\na harness whose tools are restricted — **the gate is not waived**: ask the user to plot and inspect the data, and to confirm both\n(a) contaminants and (b) the mask extent, before you compose the fit. These are the\nquestions every real-data run must ask, on every harness.\n\n**Simulated data is exempt** — you know the truth, including where every component is, so\nthere is nothing to discover by looking. Everything else in this skill still applies to\nsimulated data as documentation of what a real run would need.\n\nThe gate is satisfied by looking, not by asserting. The first branch below is how you look.\n\n## Ask\n\n- *\"What instrument and filter, and what is the pixel scale?\"* — you cannot proceed without\n it, and it is the one number nothing in the data can tell you.\n- *\"Is the noise-map an RMS standard deviation per pixel, or a variance / weight map / HST\n WHT map?\"* — if they are not certain, treat it as unknown and convert; the likelihood\n assumes RMS.\n- *\"Are there neighbouring galaxies, foreground stars or reduction artefacts near the\n target?\"* — the (a) half of the gate.\n- *\"How far out do you care about the light — just the bright body, or the faint outer\n envelope?\"* — this is the (b) half of the gate phrased as a science question, which is\n how it should be decided.\n\n## Branch — look at it first\n\nLoad the three ingredients and plot them. Nothing else happens until this figure has been\nseen.\n\n```python\n\"\"\"\nData Inspection: ()\n=============================================\n\nLoad a galaxy's CCD imaging from FITS and inspect it before any model is composed. This\nscript exists to satisfy the real-data inspection gate: the image, noise-map, PSF and\nsignal-to-noise map are plotted so that two science-critical decisions can be made from\nevidence rather than defaults — which contaminating objects are present, and how far out\nthe mask should extend.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the image, noise-map and PSF from FITS with the correct pixel scale.\n- **Standards Check:** Verify the PSF is odd-sized and normalised, and report the S/N.\n- **Plot:** Write the dataset subplot to disk for inspection.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPLOT_DIR = Path(\"scripts\") / \"scratch\" / \"my_galaxy\"\n\n\"\"\"\n__Dataset__\n\nThree ingredients are needed for galaxy modeling: the image in electrons per second, a\nper-pixel RMS noise-map in the same units, and the PSF describing the blurring imposed by\nthe telescope optics. The PSF is *forward-convolved* onto the model rather than divided out\nof the data, which is what lets a fit distinguish a genuinely compact bulge from a\nseeing-broadened one.\n\n`pixel_scales` converts pixels to arcseconds and must be correct for your instrument —\nHST/ACS ~0.05\", JWST/NIRCam ~0.03-0.06\", Euclid VIS 0.1\" and NISP 0.2\", ground-based\n0.2-0.3\". Nothing in the FITS data can correct a wrong value for you; every inferred size\nscales with it. Loading is handled by `ag.Imaging.from_fits`\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\"\"\"\nPIXEL_SCALES = 0.1\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\n\"\"\"\n__Standards Check__\n\nTwo properties of the PSF are cheap to check and expensive to get wrong. An **even-sized**\nkernel shifts the convolved model by half a pixel, which propagates straight into the\ninferred centre; and a kernel that does not **sum to unity** does not conserve flux, which\ncorrupts any magnitude or luminosity derived from the fit. The signal-to-noise peak is a\nsanity check on the noise-map: a galaxy usually peaks somewhere around 10-300, and a value\norders of magnitude away from that is a sign the noise-map is in the wrong units or is a\nvariance rather than an RMS.\n\"\"\"\npsf_shape = dataset.psf.kernel.shape_native\n\nprint(f\"PSF shape: {psf_shape}, odd: {all(s % 2 == 1 for s in psf_shape)}\")\nprint(f\"PSF sum: {float(dataset.psf.kernel.sum()):.6f} (should be 1.0)\")\nprint(f\"peak signal-to-noise: {float(dataset.signal_to_noise_map.max()):.1f}\")\n\n\"\"\"\n__Plot__\n\nThe subplot shows the image, noise-map, PSF and signal-to-noise map together, which is\nexactly the set needed to answer the two gate questions: what contaminating objects are\npresent, and how far out the galaxy's emission extends before it meets the sky.\n\"\"\"\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=PLOT_DIR,\n output_filename=\"dataset\",\n output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThen **quote the absolute path of `dataset.png` back to the user and offer to open it**\n(`xdg-open` on Linux, `open` on macOS, `explorer.exe` or `wslview` from WSL) — one offer,\nnot repeated nagging. Ask the two gate questions against that specific figure, naming what\nyou can see in it. \"There's a compact object about 2\" north-east of the centre — is that a\nneighbour or part of the galaxy?\" is a useful question; \"are there any contaminants?\" in the\nabstract is not.\n\n## Branch — the three standards, and how to fix a violation\n\n`autogalaxy_workspace:scripts/imaging/data_preparation/start_here.py` is the checklist; the\nper-ingredient tools are in `examples/data.py`, `examples/noise_map.py` and\n`examples/psf.py` beside it.\n\n**The image.** Flux in **electrons per second**, galaxy near the centre, cut down to a\npostage stamp. The units matter because default priors on light-profile `intensity` assume\nthem, and because magnitudes are computed from them. Conversions both ways are in the\npreprocess module (`PyAutoArray:autoarray/dataset/preprocess.py`):\n\n```python\nexposure_time_map = ag.Array2D.full(\n fill_value=1000.0,\n shape_native=data.shape_native,\n pixel_scales=data.pixel_scales,\n)\n\ndata_counts = ag.preprocess.array_eps_to_counts(\n array_eps=data, exposure_time_map=exposure_time_map\n)\ndata_eps = ag.preprocess.array_counts_to_eps(\n array_counts=data_counts, exposure_time_map=exposure_time_map\n)\n```\n\nADUs need the gain as well — `ag.preprocess.array_eps_to_adus(array_eps=data, gain=4.0,\nexposure_time_map=exposure_time_map)` and `array_adus_to_eps` back. If your reduction\nproduced a real per-pixel exposure-time map, load it with `ag.Array2D.from_fits` instead of\nthe flat `full` above; a flat map is a good approximation for many HST observations and not\nfor all. Trim an oversized stamp with\n`ag.preprocess.array_with_new_shape(array=data, new_shape=(80, 80))`, which crops centred.\nBackground subtraction is better done by your reduction pipeline, but\n`background_sky_level_via_edges_from` and `background_noise_map_via_edges_from` exist for\nwhen it wasn't — and modelling the residual sky as a free parameter is often the better\nanswer anyway (see the sky-background note in\n[`ag_build_imaging_model`](./ag_build_imaging_model.md)).\n\n**The noise-map.** RMS standard deviation per pixel, in electrons per second, **including**\nthe Poisson contribution from the galaxy's own counts as well as background sky. This is the\none to be most careful about: reduction pipelines frequently drop the Poisson term, and a\nnoise-map that is a variance, an inverse variance, or an HST WHT map will produce a fit that\nconverges confidently to the wrong answer. The preprocess module has a converter for each\ncommon input form — `noise_map_via_weight_map_from`,\n`noise_map_via_inverse_noise_map_from`,\n`noise_map_via_data_eps_and_exposure_time_map_from`,\n`noise_map_via_data_eps_exposure_time_map_and_background_noise_map_from`,\n`noise_map_via_data_eps_exposure_time_map_and_background_variances_from` and\n`poisson_noise_via_data_eps_from`. If you cannot determine which form you have, the\ninstrument handbook is the authority; guessing here is not recoverable later.\n\n**The PSF.** Odd dimensions, normalised to unity, centred, and roughly 11×11 to 21×21\npixels. Larger kernels (51×51) work but slow every likelihood evaluation, since convolution\nruns on every model image. Load with normalisation applied:\n\n```python\npsf = ag.Convolver.from_fits(\n file_path=DATASET_PATH / \"psf.fits\",\n hdu=0,\n pixel_scales=PIXEL_SCALES,\n normalize=True,\n)\n```\n\n`ag.Imaging.from_fits` normalises the PSF internally anyway, so this is belt-and-braces. An\neven-sized kernel is a genuine problem rather than a warning:\n`ag.preprocess.kernel_with_odd_dimensions_from` will interpolate one for you, but it *is*\nan interpolation and the right fix is to re-derive the PSF at odd size in your reduction.\nResize with `ag.preprocess.array_with_new_shape(array=psf.kernel, new_shape=(21, 21))`.\n\n## Branch — (a) contaminants: three strategies, one decision per object\n\nFor each neighbouring galaxy, foreground star or artefact you identified in the figure,\nchoose one:\n\n**1. Scale its noise (the default).** Keep the pixels in the fit but blow their noise-map\nvalues up so they contribute negligibly to the likelihood. Preferred over deleting pixels\nbecause it leaves the pixel grid intact — which matters a great deal later if you move to a\npixelised reconstruction, where removed pixels create discontinuities.\n\n```python\nmask_extra_galaxies = ag.Mask2D.from_fits(\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n pixel_scales=dataset.pixel_scales,\n invert=True, # `True` marks the pixels whose noise is scaled.\n)\n\ndataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies)\n\naplt.subplot_imaging_dataset(\n dataset=dataset, output_path=PLOT_DIR, output_filename=\"dataset_scaled\",\n output_format=\"png\",\n)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py`. Note `invert=True`: the\nFITS convention here marks the *scaled* region as `True`. Build the mask as a union of\ncircles when you know the positions, following\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/mask_extra_galaxies.py`:\n\n```python\nimport numpy as np\n\nextra_galaxies_mask = np.zeros(data.shape_native, dtype=bool)\n\nfor centre, radius in [((1.0, 3.5), 1.5), ((-2.0, -3.5), 2.4)]:\n circle = ag.Mask2D.circular(\n shape_native=data.shape_native,\n pixel_scales=data.pixel_scales,\n centre=centre,\n radius=radius,\n invert=True,\n )\n extra_galaxies_mask = np.logical_or(extra_galaxies_mask, circle.native)\n\nmask = ag.Mask2D(mask=extra_galaxies_mask, pixel_scales=data.pixel_scales)\n\naplt.fits_array(\n array=mask, file_path=DATASET_PATH / \"mask_extra_galaxies.fits\", overwrite=True\n)\n```\n\nFor irregular shapes there is a spray-paint GUI at\n`autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask_extra_galaxies.py`, and the\nsame `ag.Scribbler`-based tool appears inline at the foot of\n`autogalaxy_workspace:scripts/imaging/start_here.py`. Point the user at it rather than\nhand-deriving centres when the contaminant is a messy blend.\n\n**2. Shrink the mask so it falls outside.** The simplest option, and the right one when the\ncontaminant sits comfortably beyond the galaxy's emission. It costs you nothing except the\nsky annulus you gave up — but check it does not also cut into the outer isophotes, because\nthen you have traded a known bias for a worse one.\n\n**3. Model it as an extra galaxy.** Give it its own light profile with a fixed centre. This\nis the choice when its light genuinely overlaps the target's, so neither masking nor scaling\ncan separate them without also removing signal you need. That is a *model* decision, so it\nbelongs to [`ag_build_imaging_model`](./ag_build_imaging_model.md); what you produce here is\nthe list of centres it will consume:\n\n```python\nextra_galaxies_centres = ag.Grid2DIrregular(values=[(1.0, 3.5), (-2.0, -3.5)])\n\naplt.plot_array(\n array=data,\n title=\"Data\",\n positions=[np.array(extra_galaxies_centres)],\n output_path=PLOT_DIR,\n output_filename=\"data_with_extra_galaxies\",\n output_format=\"png\",\n)\n\nag.output_to_json(\n obj=extra_galaxies_centres,\n file_path=DATASET_PATH / \"extra_galaxies_centres.json\",\n)\n```\n\nAdapted from\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/extra_galaxies_centres.py`.\nAlways plot the centres over the image before saving them — an off-by-a-sign (y,x) ordering\nis obvious in a figure and invisible in a JSON file. There is a click-to-select GUI at\n`autogalaxy_workspace:scripts/imaging/data_preparation/gui/extra_galaxies_centres.py` which\nsnaps to the brightest pixel in a 5×5 box.\n\nThe physics of choosing between the three, and what noise scaling does to the likelihood,\nis\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch — (b) the mask extent\n\nThe mask defines which pixels enter the likelihood. Choose its radius from the figure, and\nsay out loud what you chose and why:\n\n```python\nMASK_RADIUS = 2.5\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\n\ndataset = dataset.apply_mask(mask=mask)\n\naplt.subplot_imaging_dataset(\n dataset=dataset, output_path=PLOT_DIR, output_filename=\"dataset_masked\",\n output_format=\"png\",\n)\n```\n\nTwo failure directions, and they are not symmetric. **Too small** truncates the outer\nisophotes and biases `effective_radius` and `sersic_index` — a real, systematic error in\nyour science result. **Too large** drags in sky-dominated pixels: it slows the fit and adds\nlittle information, but it does not bias the answer, and it keeps honest sky pixels that\nconstrain a background level. When in doubt, err large and re-plot; the cost is run time,\nnot correctness.\n\nCircular is the default and usually right for a single galaxy. Non-circular shapes exist\nwhen the geometry calls for it — `ag.Mask2D.circular_annular(inner_radius=..., outer_radius=...)`\nto exclude a saturated core, `ag.Mask2D.elliptical(major_axis_radius=..., axis_ratio=...,\nangle=...)` and `ag.Mask2D.elliptical_annular(...)` for a strongly inclined disk. All four\nare shown in\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/mask.py`, and\n`autogalaxy_workspace:scripts/guides/modeling/customize.py` covers applying a custom mask to\na fit. A mask drawn by hand in the GUI\n(`autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask.py`) is written to\n`mask.fits` and loaded back with `ag.Mask2D.from_fits`; for a genuinely irregular footprint,\n`autogalaxy_workspace:scripts/imaging/data_preparation/manual/mask_irregular.py` is the\nmanual route.\n\nWhy the radius is a science decision rather than a default, and what the slim/native\ndistinction means once a mask is applied, is\n[`../wiki/core/concepts/grids_and_masks.md`](../wiki/core/concepts/grids_and_masks.md).\n\n## Branch — over-sampling\n\nA Sersic profile's intensity varies steeply across a single central pixel, so evaluating it\nonce at the pixel centre under-counts the flux. Over-sampling evaluates the profile on a\nfiner sub-grid and averages, and it changes the inferred parameters — this is accuracy, not\ncosmetics. Do it adaptively: high in the centre where the gradient is steep, low in the\noutskirts where it is flat and the cost would be wasted.\n\n```python\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)\n\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py`. That reads as 8×8\nsub-sampling inside 0.3\", 4×4 between 0.3\" and 0.6\", and 2×2 beyond — note the list ends at\n2, never 1, so even the outskirts keep a floor. `centre_list` takes **every** bright\ncentre, so if you are modelling an extra galaxy rather than masking it, add its centre here\ntoo; a companion evaluated at 2×2 while the target gets 8×8 is a quiet accuracy loss. A\nplain integer (`over_sample_size_lp=4`) applies uniform over-sampling when you want\nsimplicity over tuning. The `_lp` suffix names the grid used for **l**ight-**p**rofile\nevaluation, which is a different grid from a pixelisation's.\n\n## Branch — the optional sidecars\n\nNone of these are required to fit; all of them make the result easier to interpret later.\n\n**`info.json`** — auxiliary numbers that travel with the dataset: redshift, velocity\ndispersion, a stellar mass from the literature, a previous paper's measurement. Passed to\n`search.fit(model=model, analysis=analysis, info=info)`, it is stored with the fit and can\nbe read back by the aggregator, which is what makes a population-scale comparison against\nexternal measurements possible.\n\n```python\nimport json\n\ninfo = {\"redshift\": 0.5, \"velocity_dispersion\": 250.0, \"stellar_mass\": 1e11}\n\nwith open(DATASET_PATH / \"info.json\", \"w+\") as f:\n json.dump(info, f, indent=4)\n```\n\nAdapted from\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/info.py`.\n\n**`light_centre.json`** — the galaxy's light centre as an `ag.Grid2DIrregular`, saved with\n`ag.output_to_json`, for use as a fixed value in the model. Fixing the centre removes two\nfree parameters and rules out solutions where the model centre wanders somewhere\nunphysical; it is the standard rescue when a search will not converge. Grounded in\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/light_centre.py`,\nwith a click-to-select GUI at\n`autogalaxy_workspace:scripts/imaging/data_preparation/gui/light_centre.py`.\n\nThe on-disk layout these files belong to is documented in\n[`../wiki/core/operations/dataset.md`](../wiki/core/operations/dataset.md), grounded on the\nbundled dataset and `autogalaxy_workspace:scripts/imaging/data_preparation/start_here.py`\n(the workspace simulates its imaging datasets on first run rather than committing them).\n\n## Combine — where this hands off\n\n- **The gate is satisfied and the dataset is loaded, masked and over-sampled** →\n [`ag_build_imaging_model`](./ag_build_imaging_model.md). Tell it what you decided about\n contaminants and the mask; it will ask otherwise.\n- **You want to rehearse the whole loop before touching real data** →\n [`ag_simulate_dataset`](./ag_simulate_dataset.md), which builds a dataset in exactly this\n format with known truth.\n- **A contaminant needs modelling rather than masking** → the model skill's extra-galaxies\n branch, fed by the `extra_galaxies_centres.json` you wrote above.\n- **The data looks wrong in a way you can't place** → the environment skill\n ([`ag_setup_environment`](./ag_setup_environment.md)) if it is the *plot* misbehaving, or\n the fit-debugging skill (`ag_debug_fit_failure`) once a fit has actually run.\n\nOffer (default-yes) to record the session as a dated\n`wiki/project/YYYY-MM-DD-.md` entry — the mask radius you chose and *why*, and what\nyou did about each contaminant, are exactly the decisions you will want justified when you\nwrite the paper.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Data](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_2_data.ipynb):\n what a CCD image, a noise-map and a PSF actually are, and why the PSF is convolved onto\n the model rather than divided out of the data. Its companion,\n [chapter 2 tutorial 6](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_6_masking.ipynb),\n is the masking lecture.\n- **General reference** — [RTD: New user guide](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n routes by system scale and dataset type, and is the page to hand someone deciding how\n their data should be organised before they load it.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/data_preparation/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/data_preparation/start_here.py):\n the standards checklist with the per-ingredient example scripts and GUIs beneath it.\n\n## Agent procedural checklist\n\n1. Establish the pixel scale and the noise-map's definition before writing code.\n2. Load the three ingredients, plot the dataset subplot, **print and quote its absolute\n path**, and offer to open it once.\n3. Run the gate against that figure: settle (a) every contaminant and (b) the mask extent\n *with the user*. On a harness that cannot plot, ask the user to do both — never waive it.\n4. Check the three standards: eps units, RMS-with-Poisson noise-map, odd normalised PSF.\n Convert rather than assume.\n5. Apply, in order: noise scaling for contaminants → the mask → adaptive over-sampling\n (with every bright centre in `centre_list`).\n6. Write the sidecars the model will need (`extra_galaxies_centres.json`,\n `light_centre.json`, `info.json`) and plot any centres over the image before saving.\n7. Save the script to `scripts/`, hand off to `ag_build_imaging_model`, and offer the\n `wiki/project/` entry recording the mask and contaminant decisions.\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_2_modeling/tutorial_6_search_chaining.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_chain_searches\n\n---\nname: ag_chain_searches\ndescription: Break one hard fit into a sequence of easier non-linear searches, using each result to initialize the next. Covers when chaining beats a single search and when it does not, passing a whole profile or galaxy with `result.model` (which preserves the original priors) versus narrowing them with `result.model_centred` and its absolute, relative and bounded variants, the `TruncatedGaussianPrior` those produce and where its sigma comes from in the `priors` config `width_modifier`, fixing a component with `result.instance` to remove its dimensions, and the output-path convention that keeps a chain's searches together. Use when a model is too complex for one search, when an early search should use cheap settings and a later one accurate ones, or when several galaxies must be added one at a time. Not for choosing a single search (`ag_configure_search`), not for driving one fit (`ag_run_search`), and not for combining several datasets (`ag_multi_dataset`).\n---\n\n# Chaining searches\n\nEvery other modelling skill in this workspace composes one model and hands it to one search.\nChaining is the alternative shape: split the problem into a sequence of searches, and use what\neach one learned to tell the next where to look.\n\nThe reason is statistical, not cosmetic. A non-linear search has to map a parameter space it knows\nnothing about, and the cost of doing that grows sharply with dimensionality while the risk of\nsettling in a local maximum grows with multi-modality. A galaxy model with a bulge, a disk, a sky\nlevel and two blended neighbours has both problems at once. Fit the bulge alone and the space is\nsmall, unimodal and mapped in minutes; then the disk only has to be added to a galaxy whose size\nand centre are already known. Each search in a chain solves a problem that is easy *because* of\nthe one before it.\n\nThree distinct benefits, and they are worth separating because they justify chaining in different\nsituations:\n\n- **Lower dimensionality per search.** Earlier searches fit simpler models with a parameter space\n that can be sampled properly, which reduces the chance of an incorrect local maximum in the\n final one.\n- **Cheap settings early, accurate settings late.** An early search only needs to find the high-\n likelihood region, so it can use a fast optimizer or a small `n_live`. Only the final search\n needs settings good enough to quantify errors.\n- **Cheap approximations early.** An early search can use a smaller mask, coarser over-sampling\n or a simplified component, and revert to the accurate-but-expensive settings at the end. The\n approximation costs some fidelity in the early result, which is fine when that result is only\n being used to place a prior.\n\nThis skill has **one** grounding script: `autogalaxy_workspace:scripts/guides/modeling/chaining.py`.\nIt is deliberately an API overview rather than a library of pipelines, and this skill is scoped to\nmatch it — the mechanics of prior passing, done honestly, rather than a catalogue of recipes that\ndo not exist upstream. The end of chapter 2 of the HowToGalaxy lecture series (tutorials 9-10) is where the pedagogy lives.\nRead [`../wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md) for\nhow run time scales with the model, which is the quantity chaining exists to manage.\n\n## Ask\n\n- *\"What makes this fit hard — too many parameters, or a search that keeps landing somewhere\n wrong?\"* Both are chaining's territory, but they suggest different splits: dimensionality\n suggests adding components one at a time, multi-modality suggests fixing the thing the search\n keeps getting wrong.\n- *\"What would you fit first if you had to pick one component?\"* Usually the brightest and\n simplest. If the user cannot name one, chaining may not be the right tool — see the branch on\n when not to chain.\n- *\"Is a single search actually failing, or just slow?\"* A slow-but-correct search is often better\n served by a faster sampler or JAX than by a chain, because a chain adds a whole class of\n failure: a wrong early result confidently narrowing a later prior.\n\n## Branch — the two-search chain\n\nThe deliverable is one script containing the whole chain, so it can be re-run end to end. Adapted\nfrom `autogalaxy_workspace:scripts/guides/modeling/chaining.py`.\n\n```python\n\"\"\"\nGalaxy Structure: Chained Searches\n=================================\n\nFit a galaxy's bulge alone, then add a disk with the bulge's parameters initialized from the\nfirst fit. Splitting the fit this way lets each search sample a parameter space it can actually\nmap, and makes the two-component decomposition a refinement of a known galaxy rather than a\nfourteen-dimensional search from broad priors.\n\n__Contents__\n\n- **Imports:** JAX environment first, then the standard trio.\n- **Dataset:** Load, mask and over-sample the imaging once, for every search.\n- **Paths:** One output prefix shared by every search in the chain.\n- **Model (Search 1):** A single linear Sersic bulge.\n- **Model-Fit (Search 1):** Fit it, cheaply.\n- **Model Chaining:** Pass the bulge into search 2 and add a disk.\n- **Model-Fit (Search 2):** Fit the two-component model with accurate settings.\n- **Result:** Read the final model back.\n\"\"\"\nfrom autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\n\"\"\"\n__Dataset__\n\nLoaded, masked and over-sampled once. Every search in the chain shares one `analysis`, which is\nwhat makes their likelihoods comparable — if search 2 used a different mask, its log likelihood\nwould not be on the same scale as search 1's, and the priors passed between them would refer to a\ndifferent dataset.\n\"\"\"\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"\"\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=0.1,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=3.0,\n)\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)\n\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\n\"\"\"\n__Paths__\n\nOne `path_prefix` for the whole chain, with each search distinguished only by `name`. This keeps\nevery stage of one chain in one directory tree, which matters when you come back to a fit and\nneed to see what search 1 actually inferred before trusting search 2.\n\"\"\"\npath_prefix = Path(\"imaging\") / \"chaining\" / \"\"\n\n\"\"\"\n__Model (Search 1)__\n\nThe bulge alone. A linear `Sersic` solves its own `intensity`, so this is a compact space the\nsearch can map quickly (`PyAutoGalaxy:autogalaxy/profiles/light/linear/sersic.py`).\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel_1 = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model_1.info)\n\n\"\"\"\n__Model-Fit (Search 1)__\n\nCheap settings on purpose: this search only has to find the high-likelihood region, not measure\nerrors. Inspect its result before relying on it — a chain built on a bad first search propagates\nthat error into every subsequent prior, with more confidence at every step.\n\"\"\"\nsearch_1 = af.Nautilus(\n path_prefix=path_prefix,\n name=\"search[1]__bulge\",\n unique_tag=\"\",\n n_live=100,\n)\n\nresult_1 = search_1.fit(model=model_1, analysis=analysis)\n\nprint(result_1.info)\n\n\"\"\"\n__Model Chaining__\n\n`result_1.model_centred` returns the search-1 model with every free parameter replaced by a\n`TruncatedGaussianPrior` centred on that parameter's median from search 1\n(`PyAutoFit:autofit/non_linear/result.py`,\n`PyAutoFit:autofit/mapper/prior/truncated_gaussian.py`). Search 2 therefore starts sampling in\nthe region search 1 found, rather than from broad priors.\n\nNote the attribute: `result_1.model` passes the component through with its **original** priors\nunchanged, which is useful when you want the structure of a previous model but not its\nconstraints. `model_centred` is the one that narrows.\n\"\"\"\nbulge = result_1.model_centred.galaxies.galaxy.bulge\ndisk = af.Model(ag.lp_linear.Exponential)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n\nmodel_2 = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model_2.info)\n\n\"\"\"\n__Model-Fit (Search 2)__\n\nThe accurate search. Read search 2's `model.info` in the output folder to confirm the priors\narrived as intended before trusting the result.\n\"\"\"\nsearch_2 = af.Nautilus(\n path_prefix=path_prefix,\n name=\"search[2]__bulge_disk\",\n unique_tag=\"\",\n n_live=150,\n)\n\nresult_2 = search_2.fit(model=model_2, analysis=analysis)\n\n\"\"\"\n__Result__\n\"\"\"\nprint(result_2.info)\n\nPLOT_DIR = Path(\"scripts\") / \"scratch\" / \"\" / \"chained\"\n\naplt.subplot_fit_imaging(\n fit=result_2.max_log_likelihood_fit,\n output_path=str(PLOT_DIR),\n output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nWhole components pass, not just single parameters: `result_1.model_centred.galaxies.galaxy.bulge`\ncarries every one of the bulge's parameters across in one expression, provided the component's\n*type* has not changed. A single parameter passes the same way —\n`galaxy.bulge.effective_radius = result_1.model_centred.galaxies.galaxy.bulge.effective_radius` —\nwhich is how you narrow some parameters and leave others broad.\n\n## Branch — `model`, `model_centred`, and `instance`\n\nThis is the part to get right, and the distinction is sharper than the workspace script's prose\nsuggests. Three attributes on a `Result`, three different things:\n\n**`result.model`** — the same model with the **same priors it had before**. On the released stack\nthis attribute preserves the priors rather than narrowing them\n(`PyAutoFit:autofit/non_linear/result.py`), so a component passed this way brings its structure\nacross but no information from the fit. That is occasionally exactly what you want — reuse the\ncomposition, refit from scratch — but it is *not* prior passing, and reading the workspace\nscript's older description of it as producing narrowed Gaussians will mislead you. Check what you\nactually got:\n\n```python\nprint(type(model_2.galaxies.galaxy.bulge.sersic_index).__name__)\n```\n\n**`result.model_centred`** — the narrowing one. Every free parameter becomes a\n`TruncatedGaussianPrior` whose `mean` is that parameter's median from the previous search and whose\n`sigma` comes from the parameter's `width_modifier` in the `priors` config. Three further variants\nlet you override that width:\n\n| Attribute | Prior produced | `sigma` |\n|---|---|---|\n| `result.model_centred` | `TruncatedGaussianPrior` | from the parameter's config `width_modifier` |\n| `result.model_centred_absolute(a=0.1)` | `TruncatedGaussianPrior` | exactly `a`, for every parameter |\n| `result.model_centred_relative(r=0.2)` | `TruncatedGaussianPrior` | `r × mean`, per parameter |\n| `result.model_centred_max_lh_bounded(b=0.3)` | `UniformPrior` | bounds at `mean ± b` |\n\n**`result.instance`** — the maximum-likelihood *values*, as fixed numbers. A component passed this\nway has no free parameters at all, so search 2's dimensionality drops by that component's\nparameter count. This is the lever for \"fit the bulge, freeze it, then fit the disk against a\nfixed bulge\", and it is much stronger medicine than a narrow prior: the later search cannot\nrevisit the frozen component even if the added component would have changed it.\n\n```python\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=result_1.instance.galaxies.galaxy.bulge, # fixed, contributes 0 parameters\n disk=af.Model(ag.lp_linear.Exponential),\n)\n```\n\nThe common three-stage pattern uses all of it: fit the bulge; fix it and fit the disk; then free\nboth from the second result's narrowed priors for a final search where everything moves together.\nFreezing permanently is a real bias risk, because a bulge fitted without a disk absorbs some of\nthe disk's light — so the third stage is not optional if the decomposition is the result you are\nquoting.\n\n## Branch — where `sigma` comes from, and its two traps\n\n`model_centred` reads each parameter's width from the `width_modifier` field of its entry in the\n`priors` config (`autogalaxy_assistant:config/priors/`, mapped in\n[`../wiki/core/api/configuration.md`](../wiki/core/api/configuration.md)). Two forms:\n\n- **Absolute** — `sigma` is the config value directly. For a linear `Sersic`, `sersic_index`\n carries `Absolute: 1.5`, each `centre` component `Absolute: 0.05`, and each `ell_comps`\n component `Absolute: 0.2`.\n- **Relative** — `sigma` is that fraction of the inferred value. `effective_radius` carries\n `Relative: 1.0`.\n\nThe reasoning behind which is which is worth understanding, because it tells you when to override.\nA relative width on a centre makes no sense: a galaxy centred near `(0.0, 0.0)` would get a sigma\nnear zero and the next search could not move it at all. An absolute width on an `intensity` makes\nno sense either, because intensity depends on units, exposure and brightness, so no single number\ngeneralises. Hence absolute centres and relative radii.\n\nTwo traps follow directly, and both are worth stating to a user before they hit them:\n\n**Relative widths break on parameters that can be negative or zero.**\n`model_centred_relative(r=...)` applies one relative width to *every* parameter, including\n`ell_comps`, whose median is legitimately near zero and often negative. That yields a negative\n`sigma` and raises rather than silently misbehaving — which is the good outcome, but it does mean\nthe blanket relative form is unusable on a general light-profile model. Use `model_centred`\n(per-parameter config widths), or `model_centred_absolute` where a single absolute width is\ndefensible for the parameters you are passing.\n\n**The bounded variant does not inherit the parameter's physical limits.**\n`model_centred_max_lh_bounded(b=...)` builds a `UniformPrior` at `mean ± b` regardless of the\nparameter's configured limits, so a `sersic_index` inferred near its ceiling of 5.0 can come back\nwith an upper limit above 5.0. Set the bound with the parameter's range in mind, or clamp the\nprior yourself afterwards.\n\nThe width you want is a genuine trade-off with no default that is right everywhere: wide enough\nthat a better nearby solution can still be found, narrow enough that the search is not doing\nsearch-1's work over again. The shipped `width_modifier` values are a considered balance rather\nthan a physical truth, and overriding them for one parameter you understand well is normal.\n\n## Branch — when chaining is the wrong tool\n\nChaining adds a failure mode that a single search does not have: **a wrong early result narrows a\nlater prior around the wrong place, and the later search never looks anywhere else.** The final\nposterior then looks tight and well-behaved and is simply wrong. Three situations where a single\nsearch is better:\n\n- **The single search works and is merely slow.** Reach for a faster sampler, a linear light\n profile, JAX or a GPU first ([`ag_configure_search`](./ag_configure_search.md),\n [`ag_run_search`](./ag_run_search.md)). Complexity you do not need is complexity that can be\n wrong.\n- **The early model is not a subset of the late one.** Prior passing assumes the parameter means\n something similar in both searches. Passing a `Sersic`'s parameters into an `Exponential`, or a\n parametric component's into a pixelised one, is either an error or meaningless.\n- **The parameter you fixed early is the one you are measuring.** If a bulge fitted without a disk\n is the number going in the paper, do not chain to a frozen bulge — chain to a narrowed one and\n let the final search move it.\n\nAlways inspect the intermediate result rather than trusting the chain. `result_1.info`, and\n`model.info` inside search 2's output folder, are the two things to read before believing the\nfinal number.\n\n## Branch — the practical mechanics\n\n**One analysis, reused.** Build the `ag.AnalysisImaging` once, before search 1, and pass the same\nobject to every search — unless you are deliberately changing the data between stages (a smaller\nmask early, the full one late), in which case say so explicitly, because the log likelihoods are\nthen not comparable across stages.\n\n**Naming.** One `path_prefix` for the chain, and `name=\"search[1]__\"` per stage. The bracket\nconvention is the workspace's and it sorts correctly; the `__` suffix is what makes an\noutput tree readable a month later.\n\n**`unique_tag`.** Keep it identical across the chain's searches, since it identifies the *dataset*.\nEach stage still lands in its own folder because `name` differs. And the identifier trap from\n[`ag_configure_search`](./ag_configure_search.md) applies to every stage: it does not hash your\ndata's pixel values, so if you swap datasets without changing `unique_tag`, every search in the\nchain silently returns the previous galaxy's result.\n\n**Smoke test the whole chain, not one search.** A chain's characteristic bug is a mis-typed\nattribute path in the passing expression, and that only fires at the second search:\n\n```bash\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/chained_fit.py\n```\n\nLevel 1 rather than level 2 here: level 1 runs a real (tiny) search at each stage, so a `Result`\nexists with samples for the next stage to pass from. Level 2 bypasses the sampler and leaves the\nchain nothing meaningful to narrow around. The levels are\n[`../wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md), and the priors a\ntest-mode chain produces are wiring evidence only — never quote them.\n\n## Combine\n\n- [`ag_configure_search`](./ag_configure_search.md) — cheap settings for early searches and\n accurate ones for the last; also the `unique_tag` semantics every stage inherits.\n- [`ag_run_search`](./ag_run_search.md) — driving each stage and reading its output folder.\n- [`ag_build_imaging_model`](./ag_build_imaging_model.md) — composing the models the chain steps\n between, including prior customisation by hand when you want to override a passed width.\n- [`ag_multi_galaxy_and_cluster`](./ag_multi_galaxy_and_cluster.md) — adding galaxies one at a\n time is the most common real use of chaining.\n- [`ag_multi_dataset`](./ag_multi_dataset.md) — its one-by-one branch is a chain across datasets\n rather than across model complexity.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) — when a single search lands somewhere\n unphysical, which is the diagnosis that most often leads here.\n- `ag_pixelization` — a smooth-profile fit chained into a pixelised one is a natural pairing,\n because the pixelisation wants a decent light model to start from.\n\nWhen a chain is worth keeping, offer (default-yes) to record it in a dated\n`wiki/project/YYYY-MM-DD-.md` entry: why the fit was split, what each stage fitted, what was\npassed as a narrowed prior versus fixed as an instance, and the shared output prefix — per\n[`_style.md`](./_style.md) property #5. The split and the passing decisions are the reasoning a\nreader will want, and they are invisible in the final `model.results`.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Search chaining](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_6_search_chaining.ipynb):\n fit a neighbouring galaxy first, then fix its geometry while refining the target.\n `chapter_optional/tutorial_prior_passing` explains historical prior narrowing, not a recommended next step;\n `chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy` applies the ideas to blended galaxies.\n- **General reference** — [RTD: Configs](https://pyautogalaxy.readthedocs.io/en/latest/general/configs.html):\n how the config files are laid out and looked up — the `priors` tree is where each parameter's\n `width_modifier` lives, and hence where a passed prior's `sigma` comes from.\n- **Experienced PyAutoGalaxy user** — [workspace: guides/modeling/chaining.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/guides/modeling/chaining.py):\n the API overview this skill is grounded in, with its own long discussion of absolute versus\n relative widths.\n\n## Agent procedural checklist\n\n1. Ask whether the single search is failing or merely slow; recommend a faster search before a\n chain when it is only slow.\n2. Choose the split with the user and say what each stage buys — dimensionality, settings, or a\n cheap approximation.\n3. Build the dataset and one `ag.AnalysisImaging` before search 1 and reuse it, or state\n explicitly why a stage uses different data.\n4. Write the whole chain into one script under one `path_prefix`, with `search[N]__` names.\n5. Use `result.model_centred` (or a `model_centred_*` variant) to narrow, `result.instance` to\n fix, and `result.model` only when you deliberately want the original priors back.\n6. Verify what you built: print the passed prior's type, and read `model.info` in the later\n search's output folder.\n7. Do not use `model_centred_relative` on a model containing `ell_comps` or a centre — it raises\n on a negative median.\n8. Inspect `result_1.info` before trusting anything downstream of it.\n9. If a component is frozen mid-chain, plan the final stage that frees it again before quoting its\n parameters.\n10. Validate the whole chain with `PYAUTO_TEST_MODE=1` (not 2 — the chain needs samples to pass).\n11. Offer the `wiki/project/` entry recording the split and the passing decisions.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_2_modeling/tutorial_7_summary.ipynb b/notebooks/chapter_2_modeling/tutorial_7_summary.ipynb index 7fe4f90..d385515 100644 --- a/notebooks/chapter_2_modeling/tutorial_7_summary.ipynb +++ b/notebooks/chapter_2_modeling/tutorial_7_summary.ipynb @@ -51,7 +51,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_2_modeling/tutorial_7_summary.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_load_results\n\n---\nname: ag_load_results\ndescription: Get a completed fit's results back into Python and turn them into science — the in-session `Result` object (max-log-likelihood instance, galaxies and fit), direct loading of one fit's output folder via `from_json` and `SamplesNest.from_table`, the `Samples` API for medians and errors, and the aggregator for a whole sample of fits with its `ag.agg` generators, queries and CSV/FITS/PNG workflow exports. Also covers the traps: linear light-profile intensities are solved rather than sampled and are absent from the samples, derived-quantity errors need posterior draws, and test-mode results are not physically meaningful. Use when a search has finished (or is mid-run) and the user wants numbers, errors, derived quantities, a results table, or a comparison across fits. Not for running the fit (`ag_run_search`), not for rendering figures of a single fit (`ag_plot_fit`), and not for diagnosing a fit that converged somewhere wrong (`ag_debug_fit_failure`).\n---\n\n# Reading a finished fit\n\nThe search is over; the question is what it measured. This skill is the bridge from an\n`output/` folder to a sentence you could put in a paper: *\"the bulge has an effective radius\nof 1.62 ± 0.08 arcseconds and a Sersic index of 3.9 ± 0.3\"*.\n\nLoading is never the goal on its own — the user already wants something specific: a\nparameter with errors, a derived quantity the fit did not parameterise directly, the\nresiduals, a table across fifty galaxies. The job here is to establish which, load only that,\nand be honest about what the fit can and cannot support.\n\nTwo things about the statistics are worth stating before any API. First, the default view of a\nresult is the **maximum log likelihood** model — the single best-fitting parameter vector.\nThat is not the same as the posterior, and quoting it without errors is quoting half a\nmeasurement. Second, a nested-sampling run gives you the full posterior, so errors,\ncovariances and the Bayesian evidence are all available; a gradient optimiser such as\n`MultiStartProdigy` is a maximum-a-posteriori method and gives you **no errors at all**\n(`autogalaxy_workspace:scripts/imaging/start_here.py` `__Posterior__`). If the fit used the\noptimiser and the user wants uncertainties, the answer is to re-run with `Nautilus`, not to\nmanufacture them.\n\nThe concept page behind everything below is\n[`wiki/core/concepts/samples_and_posteriors.md`](../wiki/core/concepts/samples_and_posteriors.md);\nthe aggregator's full API surface is\n[`wiki/core/api/aggregator.md`](../wiki/core/api/aggregator.md).\n\n## Ask\n\nTwo questions, and they choose the branch outright:\n\n- **What do you want out of it?** *\"A parameter and its error\"* → the `Samples` branch.\n *\"The residuals / how good is the fit\"* → the fit branch, then\n [`ag_plot_fit`](./ag_plot_fit.md). *\"A physical quantity in kpc or solar luminosities\"* →\n the derived-quantities branch. *\"A table over all my galaxies\"* → the aggregator branch.\n- **One fit, or many?** One fit you already have a path to → simple loading. More than a\n handful, or you want to iterate and filter → the aggregator, which is generator-based and\n keeps memory bounded no matter how many fits the tree holds.\n\nIf they give you a path, list it and confirm which sub-folder: the layout is\n`output/////`, and a parent path can hold many\nfits. If the path contains a `test_mode` segment, say so immediately — every number in it is a\nwiring check, not a measurement\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## Branch — the result you already have in the session\n\nIf the fit just ran, `search.fit(...)` returned everything, no disk access needed:\n\n```python\nresult = search.fit(model=model, analysis=analysis)\n\nprint(result.info) # human-readable summary, parameters + errors\nprint(result.max_log_likelihood_instance) # best-fit model as concrete objects\n\ngalaxies = result.max_log_likelihood_galaxies # ag.Galaxies at the best-fit values\nfit = result.max_log_likelihood_fit # ag.FitImaging: model image, residuals, chi²\nsamples = result.samples # the full posterior\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py` `__Result__` and\n`autogalaxy_workspace:scripts/guides/results/start_here.py`. The full member list —\n`result.samples_summary`, `result.model`, `result.instance`, `result.dataset`, `result.grids`,\n`result.unmasked_model_image`, the per-galaxy image dictionaries — is tabulated in\n[`wiki/core/api/analysis_objects.md`](../wiki/core/api/analysis_objects.md)\n\"What the result gives you\". Sources: `PyAutoGalaxy:autogalaxy/analysis/result.py` and\n`PyAutoGalaxy:autogalaxy/imaging/model/result.py`.\n\n`result.samples_summary` is worth knowing about: it holds pre-computed maximum-likelihood\nvalues and 1σ/3σ errors, so reaching for it instead of re-deriving from `samples` is\nsubstantially faster and gives the same answer.\n\n## Branch — loading one fit from disk\n\nEverything the `Result` holds was also written to the output folder, and each file loads back\ninto a full Python object in one line — much cheaper than re-running the search:\n\n```python\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nfrom autogalaxy import from_json\n\nFIT_PATH = Path(\"output\") / \"imaging\" / \"\" / \"sersic\" / \"\"\nfiles_path = FIT_PATH / \"files\"\nimage_path = FIT_PATH / \"image\"\n\ngalaxies = from_json(file_path=files_path / \"galaxies.json\")\nmodel = from_json(file_path=files_path / \"model.json\")\n\nsamples = af.SamplesNest.from_table(filename=files_path / \"samples.csv\", model=model)\nprint(samples.max_log_likelihood())\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/results/start_here.py`\n\"Simple Loading\". If the fit ran in the same session, `search.paths.output_path` already\npoints at the right folder, so you never have to know the hash.\n\nTwo things to know about what comes back:\n\n- **`galaxies.json` deserialises to a plain Python list of `Galaxy` objects, not an\n `ag.Galaxies`.** The list is enough for `ag.FitImaging(dataset=dataset, galaxies=galaxies)`\n and for indexing (`galaxies[0].bulge`), but it has no `image_2d_from`. Wrap it when you need\n the collection's own methods: `galaxies = ag.Galaxies(galaxies=galaxies)`.\n- **`model.json` is the *prior* model, with free parameters** — not the best-fit instance. It\n is what you pass to `SamplesNest.from_table` so the sample columns can be mapped back onto\n named parameters, and it is worth printing (`model.info`) to confirm what was actually\n fitted.\n\nThe `image/` folder holds the imaging products as FITS, loadable with the standard readers —\n`ag.Imaging.from_fits` for `dataset.fits` (multi-HDU, so pass the `*_hdu` arguments) and\n`ag.Array2D.from_fits` for the per-galaxy image stacks. The annotated tree of everything the\nfit wrote is `__Output Folder Layout__` in\n[`autogalaxy_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/modeling.py),\nalso condensed in\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n\"The output folder\".\n\nThe whole `/` folder is portable: a collaborator with a compatible environment\nloads it exactly as above. `files/*.json`, `files/samples.csv`, the `image/*.fits` products\nand the human-readable `model.info` / `model.results` are what matter to them.\n\n## Branch — parameters with errors, from `Samples`\n\nThe `Samples` object holds every accepted sample and its likelihood, which is what makes error\nestimation possible at all:\n\n```python\nsamples = result.samples\n\nmedian_instance = samples.median_pdf()\nu3 = samples.values_at_upper_sigma(sigma=3.0)\nl3 = samples.values_at_lower_sigma(sigma=3.0)\n\nprint(median_instance.galaxies.galaxy.bulge)\nprint(u3.galaxies.galaxy.bulge, \"\\n\", l3.galaxies.galaxy.bulge)\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/results/start_here.py` `__Samples__`. Each\nof these returns a **model instance** — the same shape of object as the model you composed, so\n`instance.galaxies.galaxy.bulge.sersic_index` addresses a parameter by the names you chose.\n`samples.max_log_likelihood()` gives the best-fit instance, `samples.parameter_lists` the raw\nvectors, `samples.log_likelihood_list` and `samples.log_evidence` the statistics.\n`samples.errors_at_upper_sigma(...)` returns the error rather than the value.\n\nTwo disciplines when reporting:\n\n- **Quote the sigma level and the summary you used.** \"Effective radius 1.62, +0.08/−0.07 at\n 1σ from the marginalised PDF\" is a result. \"1.62\" is not.\n- **Be explicit about units.** PyAutoGalaxy works in arcseconds and instrumental flux units.\n \"Effective radius = 1.6 arcsec\" is fine; \"effective radius = 1.6\" is a bug waiting to\n happen.\n\n### Linear intensities are not in the samples\n\nThis one catches everyone. A linear light profile (`ag.lp_linear.*`, and every basis built\nfrom them — a Multi-Gaussian Expansion, a shapelet expansion) has its `intensity` solved by\nlinear inversion at every iteration rather than sampled. So in the `Samples` object those\nintensities are placeholders of 1.0, and reading them there gives you nothing\n(`autogalaxy_workspace:scripts/guides/results/start_here.py` `__Linear Light Profiles__`).\n\nThe solved values live on the fit. Either take them off the result directly:\n\n```python\nprint(result.max_log_likelihood_galaxies[0].bulge.intensity)\n```\n\nor, if you are working from a `Samples` instance you loaded yourself, rebuild the fit and let\nit solve:\n\n```python\nml_instance = samples.max_log_likelihood()\n\nfit = ag.FitImaging(dataset=dataset, galaxies=ml_instance.galaxies)\ngalaxies = fit.galaxies_linear_light_profiles_to_light_profiles\n\nprint(galaxies[0].bulge.intensity)\n```\n\nThe same conversion is what lets you plot a linear-profile model at all\n([`ag_plot_fit`](./ag_plot_fit.md)). Background:\n[`wiki/core/concepts/linear_light_profiles_and_mge.md`](../wiki/core/concepts/linear_light_profiles_and_mge.md).\nThe same principle applies to a pixelised reconstruction's pixel fluxes —\n[`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\n## Branch — derived quantities, and their errors\n\nMost interesting numbers are not model parameters. A bulge-to-total light ratio, a luminosity\ninside an aperture, an effective radius in kiloparsecs — each is a *function* of the\nparameters, so its error has to be propagated rather than read off.\n\nCompute the quantity from the best-fit galaxies:\n\n```python\ngalaxies = result.max_log_likelihood_galaxies\n\nluminosity = galaxies[0].luminosity_within_circle_from(radius=10.0)\n\ncosmology = ag.cosmo.Planck15()\nkpc_per_arcsec = cosmology.kpc_per_arcsec_from(redshift=galaxies[0].redshift)\neffective_radius_kpc = galaxies[0].bulge.effective_radius * kpc_per_arcsec\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/results/aggregator/models.py` and\n`autogalaxy_workspace:scripts/guides/results/start_here.py`\n`__Units and Cosmological Quantities__`. The angular-to-physical machinery, fluxes, magnitudes\nand luminosities are\n[`wiki/core/concepts/cosmology_and_units.md`](../wiki/core/concepts/cosmology_and_units.md);\nthe runnable guides are `autogalaxy_workspace:scripts/guides/units/cosmology.py` and\n`autogalaxy_workspace:scripts/guides/units/flux.py`.\n\nFor the **error** on a derived quantity, recompute it for galaxies drawn from the posterior\nand take the spread. The aggregator's `randomly_drawn_via_pdf_gen_from` exists for exactly\nthis, and `all_above_weight_gen_from` / `weights_above_gen_from` give you the weighted version\n(`autogalaxy_workspace:scripts/guides/results/aggregator/models.py`). Anything else — scaling\nthe parameter's own error, or quoting the best-fit value with no error — is guesswork.\n\nQuantities the library can compute but the model never sampled can also be recorded during the\nfit as **latent variables**, which puts them in the samples with errors like any other\nparameter. That machinery, including subclassing `ag.LatentGalaxy` for your own, is\n`autogalaxy_workspace:scripts/guides/results/latent_variables.py` and\n[`wiki/core/concepts/samples_and_posteriors.md`](../wiki/core/concepts/samples_and_posteriors.md)\n\"Latent variables\". Note that any active `PYAUTO_TEST_MODE` level skips the latent pass, so a\nsmoke run never has them.\n\n## Branch — many fits, with the aggregator\n\nOnce the unit of work is a *sample* — a hundred galaxies with one model, or one galaxy with\nten models — the aggregator gives you one query surface over all of them and, crucially,\nreturns **generators** rather than lists, so memory stays bounded:\n\n```python\nfrom pathlib import Path\nfrom autofit.aggregator.aggregator import Aggregator\n\nagg = Aggregator.from_directory(directory=Path(\"output\") / \"imaging\")\n\nfor samples in agg.values(\"samples\"):\n print(samples.parameter_lists[0])\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/results/start_here.py`\n\"Aggregator\". Note the explicit import: `Aggregator.from_directory` lives in\n`PyAutoFit:autofit/aggregator/aggregator.py` and is **not** `af.Aggregator`, which is the\ndatabase-backed class. Keys worth knowing for `agg.values(...)`: `\"samples\"`,\n`\"samples_summary\"` (much faster — nothing re-derived), `\"samples_info\"`, `\"model\"`,\n`\"search\"`, `\"info\"`, `\"covariance\"`, `\"cosmology\"`, and the `\"dataset/...\"` family.\n\nA generator is consumed once. Remake it rather than storing it — this is why the workspace\nexamples build each one at the point of use.\n\n**Queries** compose, because each returns a new aggregator\n(`autogalaxy_workspace:scripts/guides/results/aggregator/queries.py`):\n\n```python\nunique_tag = agg.search.unique_tag\nagg_query = agg.query(unique_tag == \"\")\n\nbulge = agg.model.galaxies.galaxy.bulge\nagg_query = agg.query((bulge == ag.lp_linear.Sersic) & (bulge.effective_radius > 3.0))\n```\n\n`agg.search` addresses fit-level fields (`name`, `unique_tag`, `path_prefix`, `is_complete`);\n`agg.model` addresses the fitted model by the names you chose, so you can select on a\ncomponent's class or on an inferred value.\n\n### `ag.agg` — galaxy objects back out of stored fits\n\nPyAutoFit's aggregator loads what the search wrote; PyAutoGalaxy's `ag.agg` rebuilds\n*galaxy-domain* objects from those files, as generators. The classes are `ImagingAgg`,\n`InterferometerAgg`, `GalaxiesAgg`, `FitImagingAgg`, `FitInterferometerAgg`, `EllipsesAgg`,\n`FitEllipseAgg` and `MultipolesAgg`:\n\n```python\nimport autogalaxy.plot as aplt\n\ngalaxies_agg = ag.agg.GalaxiesAgg(aggregator=agg)\ngalaxies_gen = galaxies_agg.max_log_likelihood_gen_from()\n\ndataset_agg = ag.agg.ImagingAgg(aggregator=agg)\ndataset_gen = dataset_agg.dataset_gen_from()\n\nfor dataset_list, galaxies_list in zip(dataset_gen, galaxies_gen):\n dataset = dataset_list[0] # one entry per analysis in the fit\n galaxies = galaxies_list[0]\n\n fit = ag.FitImaging(dataset=dataset, galaxies=galaxies)\n galaxies = fit.galaxies_linear_light_profiles_to_light_profiles\n\n print(galaxies[0].bulge.intensity)\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/results/aggregator/models.py`. The inner\n`[0]` is not noise: a fit can hold several analyses (a multi-band factor graph, for instance),\nso each generator yields a *list* per fit. The dataset classes expose `dataset_gen_from()`;\nthe model classes share `max_log_likelihood_gen_from()`,\n`randomly_drawn_via_pdf_gen_from(total_samples=...)`,\n`all_above_weight_gen_from(minimum_weight=...)` and\n`weights_above_gen_from(minimum_weight=...)`, all built on `object_via_gen_from(...)`.\n`FitImagingAgg` also takes a `settings=` argument if you need to rebuild the fit with\ndifferent settings than it ran with\n(`autogalaxy_workspace:scripts/guides/results/aggregator/data_fitting.py`).\n\n### The three enumerations, and the workflow exports\n\n`ag.agg` exposes exactly three enumerations, naming panels and HDUs the completed fits\n**already have on disk** — you are extracting stored output, not re-rendering it\n(`PyAutoGalaxy:autogalaxy/aggregator/subplot.py`):\n\n| Enumeration | Members |\n|---|---|\n| `ag.agg.fits_fit` | `model_data`, `residual_map`, `normalized_residual_map`, `chi_squared_map` |\n| `ag.agg.subplot_dataset` | `data`, `data_log_10`, `noise_map`, `psf`, `psf_log_10`, `signal_to_noise_map`, `over_sample_size_lp`, `over_sample_size_pixelization` |\n| `ag.agg.subplot_fit` | `data`, `signal_to_noise_map`, `model_data`, `normalized_residual_map`, `normalized_residual_map_one_sigma`, `chi_squared_map` |\n\nThey feed three PyAutoFit export helpers, each taking `aggregator=agg`\n(`autogalaxy_workspace:scripts/guides/results/workflow/csv_make.py`,\n`fits_make.py` and `png_make.py`):\n\n```python\nimport autofit as af\n\nworkflow_path = Path(\"output\") / \"workflow\"\n\nagg_csv = af.AggregateCSV(aggregator=agg)\nagg_csv.add_variable(\n argument=\"galaxies.galaxy.bulge.sersic_index\",\n value_types=[af.ValueType.Median, af.ValueType.ValuesAt3Sigma],\n)\nagg_csv.add_variable(argument=\"galaxies.galaxy.bulge.effective_radius\")\nagg_csv.save(path=workflow_path / \"results.csv\")\n\nagg_fits = af.AggregateFITS(aggregator=agg)\nagg_fits.output_to_folder(\n folder=workflow_path,\n name=\"unique_tag\",\n hdus=[ag.agg.fits_fit.model_data, ag.agg.fits_fit.residual_map],\n)\n\nagg_image = af.AggregateImages(aggregator=agg)\nagg_image.output_to_folder(\n folder=workflow_path,\n name=\"unique_tag\",\n subplots=[\n ag.agg.subplot_fit.data,\n ag.agg.subplot_fit.model_data,\n ag.agg.subplot_fit.normalized_residual_map,\n ],\n)\n```\n\n`af.ValueType` has four members — `Median`, `MaxLogLikelihood`, `ValuesAt1Sigma`,\n`ValuesAt3Sigma`. `AggregateCSV` also offers `add_computed_column` (a function of the loaded\nobjects, for a derived quantity) and `add_label_column` (an explicit per-fit label, e.g. the\ndataset names from `[search.unique_tag for search in agg.values(\"search\")]`). `extract_fits`\nand `extract_image` return one combined object across all fits; `output_to_folder` writes one\nfile per fit instead, which is usually easier to click through when reviewing a sample.\n\nFull API surface, including the database-backed `af.Aggregator.from_database` route for\nhundreds of fits: [`wiki/core/api/aggregator.md`](../wiki/core/api/aggregator.md). The\ndatabase walkthrough is `autogalaxy_workspace:scripts/guides/results/database/start_here.py`\n— note that `from_database` has no overwrite flag, which is why that example deletes a stale\n`.sqlite` itself. Start with the directory aggregator and move to the database only when\nreading from disk becomes the slow part.\n\nThe shape that makes this worth the setup: **query** the subset you care about, **load or\nderive** the quantity per fit, **export** it under a uniform naming scheme. Fitting is\nexpensive; changing your mind about which columns you wanted should cost seconds.\n\n## Branch — the honest caveats\n\nSay these out loud rather than letting a user discover them:\n\n- **A test-mode result is not a measurement.** Any `PYAUTO_TEST_MODE` level truncates or mocks\n the sampler, so the parameters are whatever the short-circuited run produced, the errors are\n degenerate, and latent variables were skipped. The `test_mode` path segment is the tell.\n- **A gradient-optimiser fit has no errors.** `MultiStartProdigy` returns one best-fit model.\n If the science needs uncertainties, re-run with `Nautilus`\n ([`ag_configure_search`](./ag_configure_search.md)).\n- **A resumed fit may not be the fit you think.** The unique identifier does not hash the\n pixel values, so a result can be a silent resume of an earlier run on different data — see\n [`ag_run_search`](./ag_run_search.md) \"Resuming\".\n- **An unconverged search still produces a `samples.csv`.** Check `search.summary` and the\n log-evidence before trusting a posterior width.\n\n## Combine\n\n- [`ag_plot_fit`](./ag_plot_fit.md) — turn the loaded fit into figures, and read the residuals\n properly before quoting anything.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) — the numbers loaded fine but they are\n not believable.\n- [`ag_run_search`](./ag_run_search.md) — the run that produced this output, and what it wrote\n where.\n- [`ag_configure_search`](./ag_configure_search.md) — the posterior is too coarse, or you need\n errors an optimiser cannot give.\n\nThere is a second, lighter route to a result: the read-only results-inspector MCP server,\nwhich lets a chat harness with no code execution list fits, read summaries and view result\nimages without a script — [`ag_inspect_results_mcp`](./ag_inspect_results_mcp.md). It is the\nfallback, not the upgrade: whenever code execution is available, this skill's Python is richer\nand is the way in.\n\nWhen a load turns into real analysis — a table, a derived quantity, a comparison across fits —\noffer (default-yes) the dated `wiki/project/YYYY-MM-DD-.md` entry: the science question,\nwhat was inferred and how, and the script produced (per [`_style.md`](./_style.md) property\n#5).\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Results](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_7_results.ipynb):\n the `Result` object from first principles — best-fit model, galaxies, posterior samples, and\n pulling parameter values with uncertainties out of them.\n- **General reference** — [RTD: Fitting API reference](https://pyautogalaxy.readthedocs.io/en/latest/api/fitting.html):\n the generated reference for the fit objects a loaded result rebuilds.\n- **Experienced PyAutoGalaxy user** — [workspace: guides/results/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/guides/results/start_here.py):\n both routes in one runnable script — direct JSON/CSV loading of one fit, then the aggregator\n over many.\n\n## Agent procedural checklist\n\n1. Establish what the user wants out of the result before loading anything.\n2. Establish one fit or many; pick simple loading or the aggregator accordingly.\n3. Check the path for a `test_mode` segment and say so if it is there.\n4. Check which search ran — no errors are available from a gradient optimiser.\n5. For any linear light profile or pixelisation, get intensities from the fit, never from the\n samples.\n6. Quote a sigma level, a summary statistic and a unit with every number.\n7. For a derived quantity's error, draw from the posterior; never scale a parameter error.\n8. Write the loading recipe to a script in `scripts/` rather than leaving it inline.\n9. Route figures to the fit-plotting skill and unbelievable numbers to the debug skill.\n10. Offer the `wiki/project/` entry when the load became analysis.\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_2_modeling/tutorial_7_summary.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_run_search\n\n---\nname: ag_run_search\ndescription: Run the fit — take a composed model, an analysis and a configured search and drive `search.fit(model=model, analysis=analysis)` to completion, then read what it wrote. Covers the output-folder anatomy and the on-the-fly announcement, the unique-identifier resume behaviour and when it silently reuses a stale fit, `iterations_per_quick_update` and `live_visual_update`, JAX/GPU acceleration and when it actually pays, VRAM checks before a long GPU run, the `PYAUTO_TEST_MODE` smoke levels, and the `if __name__ == \"__main__\"` parallelisation fix. Use once `ag_build_imaging_model` and `ag_configure_search` have produced `model`, `analysis` and `search` objects, or when a fit is running and the user wants to know what to watch. Not for composing the model or choosing the search (those two skills), not for interpreting the finished posterior (`ag_load_results`), and not for diagnosing a fit that ran but converged somewhere unphysical (`ag_debug_fit_failure`).\n---\n\n# Running the fit\n\nThis is the moment the inference actually happens. Everything before it was preparation:\na `model` says which morphological parameters are free and what priors they carry, an\n`analysis` binds that model to one dataset and knows how to turn a parameter vector into a\nlog likelihood, and a `search` knows how to explore the parameter space. One call joins\nthem:\n\n```python\nresult = search.fit(model=model, analysis=analysis)\n```\n\nStatistically, that call is sampling (or optimising) the posterior\n$P(\\theta | d) \\propto \\mathcal{L}(d | \\theta) P(\\theta)$, where the likelihood is the\nGaussian-noise chi-squared of the PSF-convolved model image against the data — walked\nline by line in `autogalaxy_workspace:scripts/imaging/likelihood_function.py`. Scientifically,\nit is where a Sersic index, an effective radius or a bulge-to-total ratio stops being a guess\nand becomes a measurement with errors. What this skill adds is everything *around* the call:\nhow to watch it, how long to expect, how to make it fast, and how to prove the script works\nbefore committing hours to it.\n\nTwo wiki pages carry the background this skill assumes. Read\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md) for\nwhat each sampler does and how run time scales with the model, and\n[`wiki/core/api/analysis_objects.md`](../wiki/core/api/analysis_objects.md) for what the\nreturned `Result` contains.\n\n## Ask\n\nThree questions, and the answers change the branch:\n\n- *\"Do you already have `model`, `analysis` and `search`?\"* If not, route to\n [`ag_build_imaging_model`](./ag_build_imaging_model.md) and\n [`ag_configure_search`](./ag_configure_search.md) first. A fit assembled from a\n half-remembered model is the most expensive mistake available here.\n- *\"Smoke test first, or straight to the production run?\"* Almost always smoke test first —\n it takes seconds and answers \"does this script execute end to end?\", which is a different\n question from \"is this galaxy's Sersic index 3.2?\". The smoke branch is below.\n- *\"How long can this run, and on what?\"* A `MultiStartProdigy` fit is minutes; a `Nautilus`\n fit of a smooth model is tens of minutes on a GPU and can be hours on a CPU; a pixelised\n fit can be far longer. That answer decides foreground vs background, laptop vs cluster,\n and whether `live_visual_update` is worth switching on.\n\nIf the data is real observational imaging, the inspection gate in\n[`../AGENTS.md`](../AGENTS.md) applies before you get here at all — contaminants and mask\nextent are settled in [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md), not\nretrospectively.\n\n## Branch — the production run\n\nThe deliverable is one script in `scripts/` the user can re-run and edit. Adapted from\n`autogalaxy_workspace:scripts/imaging/start_here.py` (the fit and result sections) and\n`autogalaxy_workspace:scripts/imaging/modeling.py` (the Nautilus configuration and the VRAM\ncheck):\n\n```python\n\"\"\"\nGalaxy Structure: Run the Fit\n=============================\n\nFit a galaxy's surface-brightness profile to CCD imaging: load and mask the data, compose a\nlinear Sersic bulge, and sample the posterior with Nautilus so the inferred effective radius\nand Sersic index come with errors.\n\n__Contents__\n\n- **Imports:** JAX environment first, then the standard trio.\n- **Dataset:** Load imaging, mask it, and apply adaptive over-sampling.\n- **Model:** Compose the galaxy's light profile.\n- **Search:** Configure Nautilus and its update cadence.\n- **Analysis:** Bind the model to the data and choose the JAX backend.\n- **Model-Fit:** Run the search and announce the output folder.\n- **Result:** Read the best-fit model back.\n\"\"\"\nfrom autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\n\"\"\"\n__Dataset__\n\nGalaxy modeling needs three ingredients: the image in CCD counts, a per-pixel RMS noise-map,\nand the PSF. The PSF is forward-modelled rather than divided out, which is what separates a\ngenuinely compact bulge from a seeing-broadened one. `pixel_scales` converts pixels to\narcseconds and must match the instrument (`ag.Imaging.from_fits`,\n`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe mask sets which pixels enter the likelihood, and its radius is a science choice, not a\ndefault: truncate the outer isophotes and the effective radius and Sersic index are biased\ndirectly. Over-sampling evaluates the light profile several times per pixel where the\ngradient is steep, which matters most in the central few tenths of an arcsecond\n(`ag.util.over_sample.over_sample_size_via_radial_bins_from`).\n\"\"\"\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"\"\nMASK_RADIUS = 2.5\n\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n pixel_scales=0.1,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\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)\n\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n\n\"\"\"\n__Model__\n\nA linear `Sersic` bulge: the `intensity` is solved by linear inversion each iteration rather\nthan sampled, so the search explores one fewer dimension per component for free\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Linear Light Profiles__`).\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\n\n\"\"\"\n__Search__\n\n`Nautilus` is nested sampling: it returns the full posterior — every parameter's density,\nits errors, and the correlations between them. `n_live` trades accuracy against run time and\n200 covers the vast majority of galaxy models. `unique_tag` is conventionally the dataset\nname, which is what keeps the same model fitted to different data in different folders\n(`PyAutoFit:autofit/non_linear/search/nest/nautilus/search.py`).\n\"\"\"\nsearch = af.Nautilus(\n path_prefix=Path(\"imaging\"),\n name=\"sersic\",\n unique_tag=\"\",\n n_live=200,\n iterations_per_quick_update=10000,\n live_visual_update=False,\n)\n\n\"\"\"\n__Analysis__\n\n`ag.AnalysisImaging` defines the `log_likelihood_function` the search calls, and defaults to\n`use_jax=True` when JAX is installed (`PyAutoGalaxy:autogalaxy/imaging/model/analysis.py`).\n\"\"\"\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\n\"\"\"\n__Model-Fit__\n\nResults are written to the output folder on the fly, from the best model found so far, so the\nfolder is worth opening the moment the search starts.\n\"\"\"\nprint(f\"Output folder: {search.paths.output_path.resolve()}\")\n\nresult = search.fit(model=model, analysis=analysis)\n\n\"\"\"\n__Result__\n\"\"\"\nprint(result.info)\nprint(result.max_log_likelihood_instance)\n```\n\nRun it with writable caches if the default locations are not writable — a sandbox, CI, or an\ninstall imported from a Windows mount under WSL\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)):\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\n`search.fit` itself is `PyAutoFit:autofit/non_linear/search/abstract_search.py`.\n\n## Branch — what the output folder contains, and when to look\n\n**Announce the folder at launch, not at the end.** Quote\n`search.paths.output_path.resolve()` once the fit is running and say plainly that\n`model.results` and `image/fit.png` refresh as the search goes — there is nothing to wait\nfor. Users new to the stack sit watching a silent terminal because nobody told them.\n\nThe annotated tree of `files/`, `image/`, `model.info`, `model.results`, `search.summary`\nand the `` folder is `__Output Folder Layout__` in\n[`autogalaxy_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/modeling.py);\nthe same section appears in the `interferometer`, `multi_dataset`, `multi_galaxy` and\n`cluster` `modeling.py` scripts. Link it rather than copying the tree into the conversation,\nwhere it would rot. The condensed version is also in\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n\"The output folder\".\n\nName what to open first, in this order:\n\n1. `model.results` — the human-readable fit summary, parameters with errors.\n2. `image/fit.png` — data, model image, residuals and chi-squared map in one figure.\n3. `search.log` — tail it if you want to watch progress from a terminal.\n\nDepth follows [`_style.md`](./_style.md) \"Adaptive depth\": for a newcomer, or in teacher\nmode, walk all three. For a returning user, quoting the path is enough.\n\n## Branch — resuming, and the trap inside it\n\n`` is derived from the model, the search settings and the dataset identifier, so\nre-running an identical configuration **resumes** the existing fit rather than restarting it\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Unique Identifier__`). That is a\nfeature — an interrupted overnight run picks up where it stopped.\n\nIt is also the sharpest edge in the workflow. **The identifier does not hash the pixel\nvalues of your data.** Swap `data.fits` for a different galaxy, keep the model, the search\nand the `unique_tag` identical, and the next run finds a completed fit at the same path and\nreturns it — silently, in seconds, with the previous galaxy's parameters. If the data\nchanges, change the `unique_tag`. If you are unsure whether a result is stale, delete the\n`` folder and re-run rather than reasoning about it.\n\nTest mode namespaces its output separately: any active `PYAUTO_TEST_MODE` level inserts a\n`test_mode` segment straight after the output root, so a smoke run lands in\n`output/test_mode//...` and cannot short-circuit a later real fit\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## Branch — the update cadence and the live view\n\nTwo settings control what you see while the fit runs, both on the search\n(`PyAutoFit:autofit/non_linear/search/abstract_search.py`):\n\n- **`iterations_per_quick_update`** — how often the current best model is visualised and\n written to disk. The unit depends on the search: likelihood evaluations for `Nautilus`\n (hence the large `10000` in `modeling.py`), gradient steps for `MultiStartProdigy` (hence\n the much smaller `50` in `start_here.py`). Each update costs roughly ten seconds, so too\n low a value and output dominates the run time; too high and you cannot see progress. If\n the log is constantly reporting that it is outputting results, raise it.\n- **`live_visual_update`** — additionally push the quick-update image to a live surface: a\n matplotlib window that refreshes in a plain script, or a self-updating cell in Jupyter and\n Colab. The `fit.png` disk write happens either way. Leave it `False` on anything headless\n — an HPC node, a background process, CI.\n\nIf the search configuration already records the choice, don't re-ask; that decision belongs\nto [`ag_configure_search`](./ag_configure_search.md).\n\n## Branch — JAX, GPUs, and when the acceleration pays\n\nImaging fits run through JAX by default. Installing the extra (`pip install autogalaxy[jax]`)\nis all that is required: `ag.AnalysisImaging` then defaults to `use_jax=True`, and the search\ndriver wraps the likelihood in `jax.vmap(jax.jit(...))` so a whole batch of parameter vectors\nevaluates in one call. You will see a one-time log line as the JIT compile starts; every\nevaluation after that re-uses the compiled trace. This is described in\n`autogalaxy_workspace:scripts/guides/using_jax.py` `__Auto-Enabled Modeling__`, and if JAX is\nabsent the analysis warns once and falls back to NumPy.\n\n**When it pays.** The gain scales with how much array work each likelihood evaluation does,\nso it is largest for big masks, fine over-sampling, many-component bases and pixelised\nreconstructions, and smallest for a tiny mask with one smooth profile. GPU gains dwarf CPU\ngains: `autogalaxy_workspace:scripts/imaging/modeling.py` `__JAX__` quotes roughly ten\nminutes on a GPU against an hour on a CPU for its example, with a CPU still gaining from\nmultithreading. Gradient-based searches like `MultiStartProdigy` are not merely faster under\nJAX — they are only possible with it, because JAX is what supplies the likelihood's\nderivatives and evaluates all the parallel starts in one batched call\n(`autogalaxy_workspace:scripts/imaging/start_here.py` `__Multi Start Gradient Optimization__`).\n\n**Check VRAM before a long GPU run.** A JAX fit must fit inside the GPU's memory, and it\nfails at JIT-compile time or on the first likelihood call if it does not:\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py` `__VRAM Use__`. It takes\ntwenty or thirty seconds, so comment it out once you know your model's footprint. Batch size\nis the lever: larger batches cut wall-clock time and raise VRAM, smaller batches the reverse.\nA smooth-profile fit on a modest dataset is tens of megabytes; a pixelised reconstruction on\nhigh-resolution data can exceed ten gigabytes.\n\n**Turn JAX off to debug.** `ag.AnalysisImaging(dataset=dataset, use_jax=False)`, or\n`PYAUTO_DISABLE_JAX=1` to force it globally without editing code. NumPy stack traces are far\neasier to read, and you can drop a debugger or a `print` into code JAX would otherwise\ncompile. That is the first lever to pull when deciding whether a failure is a JAX problem at\nall — see [`ag_debug_fit_failure`](./ag_debug_fit_failure.md).\n\nFor running on a cluster — SLURM array jobs, one galaxy per task, the CPU and GPU batch\nscripts, and `number_of_cores` read from `SLURM_CPUS_PER_TASK` — read\n[`../wiki/core/operations/hpc.md`](../wiki/core/operations/hpc.md) for the concepts and\n[`../wiki/core/operations/hpc_infrastructure.md`](../wiki/core/operations/hpc_infrastructure.md)\nfor the `hpc/` templates and `sync` CLI this repo ships; the upstream ground truth behind both\nis `autogalaxy_workspace:scripts/guides/hpc/example_cpu_and_gpu.py`. The Python modeling code\nis identical for a GPU run; only the batch script changes.\n\n## Branch — the smoke test, before you spend hours\n\nEvery script gets one fast structural run before a real one. `PYAUTO_TEST_MODE` has four\nlevels ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)), and the\nchoice between them matters more than it looks:\n\n```bash\n# Level 1 — sampler runs with minimal iterations. A real (tiny) search: writes\n# model.results, image/fit.png and a samples.csv you can load back.\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n\n# Level 2 — sampler bypassed, likelihood called exactly once. The fastest proof that\n# the model composes and the likelihood evaluates.\nPYAUTO_TEST_MODE=2 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\n**Level 2 does not write the fit products.** A level-2 run returns a `Result`, proving the\nwiring, but leaves no `model.results` and no `image/fit.png` behind — so if the next thing\nyou want to do is plot or load the fit, use level 1. Level 3 skips the likelihood call as\nwell, which is only useful for checking that a script's non-fitting scaffolding runs.\n\n**The parameter values from any test-mode run are meaningless.** The sampler was truncated or\nmocked. Never quote a structural parameter measured in test mode; say explicitly that the\nnumber is a wiring check.\n\nFor the fastest possible loop, combine test mode with the dataset and output short-circuits:\n\n```bash\nPYAUTO_TEST_MODE=2 PYAUTO_SKIP_FIT_OUTPUT=1 PYAUTO_SKIP_VISUALIZATION=1 \\\n PYAUTO_SMALL_DATASETS=1 PYAUTO_FAST_PLOTS=1 python scripts/run_fit.py\n```\n\n`PYAUTO_SMALL_DATASETS=1` caps every array, mask and grid to 16 × 16 pixels — so delete any\npreviously simulated `dataset/` when you toggle it, or a full-resolution dataset on disk will\nbe reused and mismatch the capped grids.\n\n## Branch — the error that appears the moment the search starts\n\nOn some combinations of operating system and Python version, a script raises as soon as the\nsearch begins, from Python's process spawning rather than from anything about your model. The\nfix is to wrap the whole fit in a function and call it under a main guard:\n\n```python\ndef fit():\n from autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\n import autofit as af\n import autogalaxy as ag\n\n # ... dataset, model, search, analysis as above ...\n result = search.fit(model=model, analysis=analysis)\n\n\nif __name__ == \"__main__\":\n fit()\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/modeling/bug_fix.py`, which is the same\n`modeling.py` fit with this one structural change. It works for every dataset type, so adopt\nit for any modeling script that hits the error. If parallelisation still will not work after\nthe fix, that script points at the project's support channel.\n\n## Combine\n\n- [`ag_plot_fit`](./ag_plot_fit.md) — render the fit yourself, at whatever scaling and\n cropping the science needs, rather than reading the auto-generated `image/fit.png`.\n- [`ag_load_results`](./ag_load_results.md) — pull the posterior, the best-fit galaxies and\n the derived quantities back into Python, in-session or from disk later.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) — the fit finished but the residuals or\n the parameters are wrong.\n- [`ag_configure_search`](./ag_configure_search.md) — the fit is too slow, or the sampler is\n the wrong one for the model.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) — build a controlled dataset with known\n truth and fit that first, which is the cleanest way to separate a model problem from a\n data problem.\n\nWhen the script and its fit are worth keeping, offer (default-yes) to record the run in a\ndated `wiki/project/YYYY-MM-DD-.md` entry: the science question, what was inferred and\nwith what search, and the output path — per [`_style.md`](./_style.md) property #5.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Practicalities](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running a fit — output structure, reviewing results as they appear,\n and managing run times.\n- **General reference** — [RTD: New user guide](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n the decision tree for which fit to run first, by system scale and dataset type.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit, with the JAX and quick-update sections this skill\n mirrors.\n\n## Agent procedural checklist\n\n1. Confirm `model`, `analysis` and `search` exist; if not, route to the model-building and\n search-configuration skills.\n2. On real observational data, confirm the inspection gate has been satisfied.\n3. Write the script to `scripts/` in the generated-script style; never leave it inline only.\n4. Validate it with `PYAUTO_TEST_MODE=1` (level 2 if you only need the likelihood proved),\n with the cache variables set if the environment needs them.\n5. Launch the production run; **quote the absolute output path immediately** and say results\n refresh on the fly.\n6. Name `model.results` and `image/fit.png` as the first two things to open.\n7. If the data changed but the model did not, confirm the `unique_tag` changed too.\n8. On a GPU, run the VRAM check before a long fit.\n9. On completion, hand off to the results-loading or fit-plotting skill rather than\n interpreting the numbers inline.\n10. Offer the `wiki/project/` entry.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb b/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb index 4a278ab..73be93b 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb @@ -446,7 +446,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 \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_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 explains it through reconstruction experiments.\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. HowToGalaxy chapter 3 illustrates how the terms select the smoothing strength;\nthe mathematical derivations are in 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_2_bayesian_regularization.ipynb):\n choose the smoothing strength by comparing log evidence. `tutorial_3_fit_problems`\n motivates adaptive mesh placement and smoothing in `tutorial_4_adaptive_reconstruction`;\n `tutorial_5_model_fit` combines an MGE with a pixelization through search chaining.\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_bayesian_regularization.ipynb b/notebooks/chapter_3_pixelizations/tutorial_2_bayesian_regularization.ipynb index 7613cc5..ab1560c 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_2_bayesian_regularization.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_2_bayesian_regularization.ipynb @@ -826,7 +826,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_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" + "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 explains it through reconstruction experiments.\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. HowToGalaxy chapter 3 illustrates how the terms select the smoothing strength;\nthe mathematical derivations are in 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_2_bayesian_regularization.ipynb):\n choose the smoothing strength by comparing log evidence. `tutorial_3_fit_problems`\n motivates adaptive mesh placement and smoothing in `tutorial_4_adaptive_reconstruction`;\n `tutorial_5_model_fit` combines an MGE with a pixelization through search chaining.\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_3_fit_problems.ipynb b/notebooks/chapter_3_pixelizations/tutorial_3_fit_problems.ipynb index 4e92217..3f7e4f5 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_3_fit_problems.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_3_fit_problems.ipynb @@ -957,7 +957,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_3_fit_problems.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_3_fit_problems.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 explains it through reconstruction experiments.\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. HowToGalaxy chapter 3 illustrates how the terms select the smoothing strength;\nthe mathematical derivations are in 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_2_bayesian_regularization.ipynb):\n choose the smoothing strength by comparing log evidence. `tutorial_3_fit_problems`\n motivates adaptive mesh placement and smoothing in `tutorial_4_adaptive_reconstruction`;\n `tutorial_5_model_fit` combines an MGE with a pixelization through search chaining.\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_adaptive_reconstruction.ipynb b/notebooks/chapter_3_pixelizations/tutorial_4_adaptive_reconstruction.ipynb index efc0aba..0244bdf 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_4_adaptive_reconstruction.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_4_adaptive_reconstruction.ipynb @@ -1484,7 +1484,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_adaptive_reconstruction.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_4_adaptive_reconstruction.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 explains it through reconstruction experiments.\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. HowToGalaxy chapter 3 illustrates how the terms select the smoothing strength;\nthe mathematical derivations are in 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_2_bayesian_regularization.ipynb):\n choose the smoothing strength by comparing log evidence. `tutorial_3_fit_problems`\n motivates adaptive mesh placement and smoothing in `tutorial_4_adaptive_reconstruction`;\n `tutorial_5_model_fit` combines an MGE with a pixelization through search chaining.\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_5_model_fit.ipynb b/notebooks/chapter_3_pixelizations/tutorial_5_model_fit.ipynb index dba5fa1..37c3ec9 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_5_model_fit.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_5_model_fit.ipynb @@ -328,7 +328,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_5_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" + "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_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 explains it through reconstruction experiments.\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. HowToGalaxy chapter 3 illustrates how the terms select the smoothing strength;\nthe mathematical derivations are in 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_2_bayesian_regularization.ipynb):\n choose the smoothing strength by comparing log evidence. `tutorial_3_fit_problems`\n motivates adaptive mesh placement and smoothing in `tutorial_4_adaptive_reconstruction`;\n `tutorial_5_model_fit` combines an MGE with a pixelization through search chaining.\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_4_scaling_up_galaxies/README.md b/notebooks/chapter_4_scaling_up_galaxies/README.md index 20a1455..8dcd4ad 100644 --- a/notebooks/chapter_4_scaling_up_galaxies/README.md +++ b/notebooks/chapter_4_scaling_up_galaxies/README.md @@ -5,8 +5,8 @@ systems, and cluster fields. # Files -- [Tutorial 1: Extra Galaxies](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_4_scaling_up_galaxies/tutorial_1_extra_galaxies.ipynb) — Handling nearby galaxies by scaling their light out of the fit or modeling them explicitly. +- [Tutorial 1: Extra Galaxies](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_4_scaling_up_galaxies/tutorial_1_extra_galaxies.ipynb) — Handling nearby galaxies by scaling their light out of the fit or modeling them explicitly. -- [Tutorial 2: Multi Galaxy](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy.ipynb) — Modeling two or more blended galaxies simultaneously and the degeneracies this creates. +- [Tutorial 2: Multi Galaxy](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy.ipynb) — Modeling two or more blended galaxies simultaneously and the degeneracies this creates. -- [Tutorial 3: Cluster](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_4_scaling_up_galaxies/tutorial_3_cluster.ipynb) — Modeling a cluster field's BCG and catalogue-driven member population. +- [Tutorial 3: Cluster](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_4_scaling_up_galaxies/tutorial_3_cluster.ipynb) — Modeling a cluster field's BCG and catalogue-driven member population. diff --git a/notebooks/chapter_optional/tutorial_need_for_speed.ipynb b/notebooks/chapter_optional/tutorial_need_for_speed.ipynb index 1d0b8d1..aa034f6 100644 --- a/notebooks/chapter_optional/tutorial_need_for_speed.ipynb +++ b/notebooks/chapter_optional/tutorial_need_for_speed.ipynb @@ -111,7 +111,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_optional/tutorial_need_for_speed.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_configure_search\n\n---\nname: ag_configure_search\ndescription: Choose and configure the non-linear search that fits a galaxy model to data — `af.Nautilus` for a full posterior with errors you can quote, `af.MultiStartProdigy` for a fast maximum-a-posteriori check, `af.DynestyStatic` for isophote/ellipse fitting and as a cross-check, and the MCMC / quasi-Newton / diagnostic alternatives. Covers `n_live` and `n_batch`, `n_starts` and `n_steps`, the `iterations_per_quick_update` output cadence, the start-point initialiser API, grid searches, and — critically — the `unique_tag` / unique-identifier and resume semantics, since the identifier is a hash of the model and search but **not** of the data, so re-using a tag across datasets silently resumes the wrong fit. Use once a model and analysis exist. Not for composing the model (`ag_build_imaging_model`), not for executing the fit or reading its output folder (`ag_run_search`), and not for diagnosing a fit that already failed.\n---\n\n# Choosing and configuring the search\n\nA search is the algorithm that explores your model's parameter space, calling\n`analysis.log_likelihood_function(instance)` over and over and deciding where to look next.\nEvery search in PyAutoFit takes the same two arguments, so swapping one for another is a\none-line change:\n\n```python\nresult = search.fit(model=model, analysis=analysis)\n```\n\nThe choice matters for one reason above all others: **some searches return a posterior and\nsome return a point.** A nested sampler maps the probability density of every parameter, its\nerrors, and the covariances between them — so it can tell you whether an inferred effective\nradius of 1.6\" is 1.6 ± 0.01 or 1.6 ± 0.5, and whether it trades off against the Sersic index.\nA gradient optimiser hands you a single best-fit model and *nothing else*: no errors, no\ncovariances. Both are useful, for different questions, and confusing them is the most\nconsequential mistake available here.\n\nThe runnable tour of the whole menu is\n`autogalaxy_workspace:scripts/guides/modeling/searches.py`; the catalogue with every argument\nis [`../wiki/core/api/searches.md`](../wiki/core/api/searches.md), and what each family\nactually does is\n[`../wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md).\n\n## Ask\n\n- *\"Do you need error bars, or do you just want to know whether this model fits at all?\"*\n This is the whole decision. Errors → `Nautilus`. A quick check → `MultiStartProdigy`.\n- *\"How many free parameters does the model have?\"* — `print(model.info)` if you don't know.\n It sets `n_live`, and it is the main driver of run time.\n- *\"Is this dataset one of several you will fit with the same model?\"* — if yes, the\n `unique_tag` section below is not optional reading; it is where results silently collide.\n- *\"Is JAX available, and a GPU?\"* — `MultiStartProdigy` requires a JAX-traceable analysis\n (`use_jax=True`) and is not available without it.\n\n## Branch — `af.Nautilus`, the default\n\nThe search every workspace `modeling.py` example uses, and the one to reach for when the\nanswer will be quoted in a paper. Extensive testing across galaxy modelling found it the most\naccurate and efficient search available. Adapted from\n`autogalaxy_workspace:scripts/imaging/modeling.py`.\n\n```python\nsearch = af.Nautilus(\n path_prefix=Path(\"imaging\"),\n name=\"modeling\",\n unique_tag=dataset_name,\n n_live=200,\n n_batch=50,\n iterations_per_quick_update=10000,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/nautilus/`; optional dependency\n`nautilus-sampler`. Reference: Lange (2023), arXiv:2306.16923.\n\n**`n_live` is the accuracy / run-time dial**, and essentially the only setting you need to\nthink about. More live points map the posterior more reliably but cost more likelihood\nevaluations; fewer are faster but risk converging on a local maximum. 200 is sufficient for\nthe vast majority of galaxy models, and more parameters want more — a bulge-plus-disk model\nat N = 9 is comfortable at 200, while a model past ~30 free parameters is worth running at\n400. Dropping to 100 on a simple model to save time is a legitimate move (`modeling.py` does\nexactly that) but it is a deliberate accuracy trade, so say so when you make it.\n\n**`n_batch` is where the GPU speed-up comes from**, and it is worth understanding because\nNautilus is *gradient-free* — it never differentiates the likelihood, so unlike the optimisers\nbelow it does not use JAX's derivatives at all. What it does do is propose points in batches,\nand when the analysis is JAX-traceable PyAutoFit evaluates the whole batch through one\n`jax.vmap(jax.jit(...))` call, fitting all `n_batch` models simultaneously. It is therefore\nalso the main control on VRAM: a bigger batch holds more models in memory at once. Pair it\nwith `analysis.print_vram_use(model=model, batch_size=search.batch_size)` before a GPU run\n(see [`ag_build_imaging_model`](./ag_build_imaging_model.md)).\n\nFor parallel CPU runs, `number_of_cores` scales well: roughly linearly below 8 cores and\nabout `0.5 * number_of_cores` above, continuing past 50 cores — which is why supercomputing\nfacilities make even large models tractable.\n\n## Branch — `af.MultiStartProdigy`, when you want an answer now\n\nThe search every workspace `start_here.py` example uses. Far faster than Nautilus, and\nreturns a single best-fit model with **no errors at all**. Adapted from\n`autogalaxy_workspace:scripts/imaging/start_here.py`.\n\n```python\nsearch = af.MultiStartProdigy(\n path_prefix=Path(\"imaging\"),\n name=\"start_here\",\n unique_tag=dataset_name,\n n_starts=48,\n n_steps=300,\n iterations_per_quick_update=50,\n live_visual_update=False,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/mle/multi_start_gradient/`; optional dependencies\n`jax` and `optax`.\n\nThe design is what makes gradient descent usable on this problem at all. Galaxy-model\nparameter spaces are multi-modal, so a *single*-start optimiser routinely descends confidently\ninto a local maximum — which is exactly the weakness of `LBFGS` below.\n`MultiStartProdigy` launches `n_starts` independent descents from broad starting points spread\nacross the parameter space, runs them **all in parallel** through `jax.vmap`, and returns the\nbest. That wide population is what reliably finds the global maximum-likelihood basin; it is\nthe approach introduced for galaxy modelling by GIGA-Lens (Gu, Huang et al. 2022,\narXiv:2202.07663). Prodigy adds a *learning-rate free* update rule (Mishchenko & Defazio 2024,\narXiv:2306.06101): it estimates its own step size as it runs, so there is no `learning_rate`\nfor you to tune — which is precisely why it is the recommended member of the family over\n`MultiStartAdam`, `MultiStartADABelief` and `MultiStartLion`, all of which want one chosen.\n\nThree things to hold onto:\n\n- **It requires `use_jax=True`.** It is gradient-based, so a NumPy analysis cannot supply what\n it needs. It is therefore unavailable for `ag.AnalysisEllipse`, which is not JAX-traceable.\n- **`n_steps` is a ceiling, not a target.** The search stops early once the best fit stops\n improving, so expect a handful of quick updates rather than `n_steps / 50` of them.\n- **There is no posterior.** If the fit reports `effective_radius = 1.6\"`, this search cannot\n tell you the uncertainty, and no amount of extra starts will change that.\n\nThe workflow the workspace recommends, and the one to recommend to the user: run\n`MultiStartProdigy` first to confirm cheaply that the model and data are sensible, then run\n`Nautilus` on the same model when you need numbers you can quote.\n\n## Branch — `af.DynestyStatic`, for isophotes and as a cross-check\n\nThe nested-sampling alternative, and the search the workspace's **ellipse** examples use,\nbecause testing showed it the most reliable for isophote fitting specifically.\n\n```python\nsearch = af.DynestyStatic(\n path_prefix=Path(\"ellipse\"),\n name=\"fit_start\",\n unique_tag=dataset_name,\n sample=\"rwalk\",\n nlive=50,\n iterations_per_quick_update=2500,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/dynesty/`. Reference: Speagle (2020),\narXiv:1904.02180.\n\nNote `nlive`, not `n_live` — the argument names follow each upstream sampler's own convention,\nwhich is a real source of typos when switching. Dynesty's sampler options pass straight\nthrough (`sample`, `walks`, `bound`, `bootstrap`, `enlarge`, `update_interval`, `facc`,\n`slices`, `fmove`, `max_move`), and `af.DynestyDynamic` reallocates live points as it runs —\ntoward the tails for a better evidence estimate, toward the bulk for better parameters —\ntaking `nlive_init`, `dlogz_init` and the other `_init` variants instead.\n\nTwo reasons to reach for it. **Isophote fitting**: use it whenever the analysis is\n`ag.AnalysisEllipse`, where the gradient optimisers are unavailable anyway. **Independent\ncross-check**: a posterior that reproduces under a different nested sampler is far more\nconvincing than one that does not, and this is the cheapest such check available. Ellipse\nfitting has its own page,\n[`../wiki/core/api/ellipse.md`](../wiki/core/api/ellipse.md), and its own skill,\n[`ag_ellipse_fitting`](./ag_ellipse_fitting.md).\n\n## Branch — the rest of the catalogue\n\nEvery search PyAutoFit ships, generated from the installed release's search manifest\n(`python -m autofit search-manifest --json`; regenerate with PyAutoHands\n`autohands regenerate_search_roster --root .`, never by hand):\n\n\n\n- **Markov chain Monte Carlo** (`mcmc`): `af.Emcee`, `af.Zeus`, `af.BlackJAXNUTS`, `af.SMC` (experimental) — example: `autofit_workspace:scripts/searches/mcmc.py`\n- **Nested sampling** (`nest`): `af.DynestyStatic`, `af.DynestyDynamic`, `af.Nautilus`, `af.NSS` (experimental) — example: `autofit_workspace:scripts/searches/nest.py`\n- **Maximum likelihood / maximum a posteriori** (`mle`): `af.Drawer`, `af.BFGS`, `af.LBFGS`, `af.MultiStartAdam`, `af.MultiStartADABelief` (experimental), `af.MultiStartLion` (experimental), `af.MultiStartProdigy` — example: `autofit_workspace:scripts/searches/mle.py`\n\n\nReach for these only when you know why. All are tabulated with full argument lists in\n[`../wiki/core/api/searches.md`](../wiki/core/api/searches.md) and demonstrated in\n`autogalaxy_workspace:scripts/guides/modeling/searches.py`.\n\n| Search | When |\n|---|---|\n| `af.Zeus` | Ensemble MCMC **slice** sampler; the best-performing MCMC in the workspace's tests, though still behind Nautilus. Good for characterising a posterior around a mode you already found. |\n| `af.Emcee` | The familiar affine-invariant ensemble sampler. Same role as Zeus, generally a little worse on these parameter spaces. |\n| `af.NSS` | Nested slice sampling via BlackJAX, run entirely inside `jax.jit`. Needs a JAX-traceable analysis (`use_jax=True`); returns the evidence like the other nested samplers. |\n| `af.BlackJAXNUTS` / `af.SMC` | JAX gradient MCMC: the No-U-Turn sampler, and BlackJAX adaptive tempered sequential Monte Carlo (which also returns the evidence). Both need `use_jax=True`. |\n| `af.LBFGS` / `af.BFGS` | Single-start quasi-Newton descent via SciPy. Fast in principle, but galaxy-model parameter spaces are usually too complex to use it without careful initialisation — `MultiStartProdigy` exists to fix exactly that. |\n| `af.Drawer` | Not a search: draws models from the prior and evaluates them. A diagnostic for \"are my priors sane and does my likelihood run at all?\", and the workspace's one-draw container for collecting many completed fits into a single output folder (`total_draws=1`). |\n\nMCMC and MLE searches monitor convergence differently from nested samplers — both `Emcee` and\n`Zeus` accept an `af.AutoCorrelationsSettings(check_for_convergence=True, check_size=100,\nrequired_length=50, change_threshold=0.01)` and will terminate early when the chains satisfy\nit.\n\n## Branch — the output cadence\n\nEvery search writes results to disk **as it runs**, using the highest-likelihood model found\nso far, and `iterations_per_quick_update` sets how often. This is not free, and the two\ncanonical values look contradictory until you notice the unit differs:\n\n- `Nautilus(iterations_per_quick_update=10000)` — the unit is a likelihood evaluation, and on\n a fast fit writing output every few hundred would dominate the run time.\n- `MultiStartProdigy(iterations_per_quick_update=50)` — the unit is a *gradient step*, a far\n coarser thing, so 50 gives a useful handful of updates.\n\nIf the log keeps announcing that it is outputting results, raise the number. The heavier\n`iterations_per_full_update` controls the full pass — all visuals plus `model.results` and\n`search.summary`. Defaults for both live in `autogalaxy_assistant:config/general.yaml` under\n`updates:` (set to effectively infinite there, so the per-search value governs), and the\nconfig layer is [`../wiki/core/api/configuration.md`](../wiki/core/api/configuration.md).\n\n`live_visual_update=False` is the default and the right choice on a headless or cluster run.\nSet it `True` to also push each quick update to a live surface — a matplotlib window that\nrefreshes from a script, or an in-place refresh of the Jupyter cell. The disk write happens\neither way.\n\n## The unique identifier, `unique_tag`, and resuming — read this one\n\nOutput lands at `output////`, where the identifier is a\n32-character hash. Re-running an identical configuration **resumes** the existing fit rather\nthan starting over, which is a genuinely useful feature — and the sharp edge of this whole\nskill, because of what goes into the hash and what does not.\n\n**The identifier is a hash of the model and the search. It is not a hash of the data.**\n\nThat is not a subtlety; it is a trap with a silent failure mode. Fit galaxy A, then change\nonly the FITS paths and fit galaxy B with the same model and the same search: the identifier\nis identical, PyAutoFit finds a completed fit at that path, and reports \"Fit Already\nCompleted\". You get galaxy A's result back, labelled as galaxy B, with no error raised.\n\nThe fix is one argument, and it is why every workspace example passes it:\n\n```python\nsearch = af.Nautilus(\n path_prefix=Path(\"imaging\"),\n name=\"modeling\",\n unique_tag=dataset_name, # <-- the discriminator the data itself does not supply\n n_live=200,\n)\n```\n\n**Pass your dataset name as `unique_tag`, always.** Then the two galaxies hash differently and\nland in different folders. And the corollary that catches people a second time: if the *data*\nchanges but its name does not — you re-reduced it, fixed the noise-map, changed the mask,\nre-ran the simulator with different truth — **bump the `unique_tag`** (or delete the output\nfolder). Otherwise you resume a fit to data that no longer exists.\n\nChanging the model or the search *does* change the identifier, so you never need to manage\nthat case by hand: a bulge-plus-disk fit cannot collide with a single-Sersic fit, and an\n`n_live=200` run cannot collide with an `n_live=400` one. It is only the data axis that is\ninvisible to the hash.\n\nVerify rather than trust when it matters. Comparing the identifier across two configurations\nbefore launching a long run costs nothing:\n\n```python\nsearch.paths.model = model\nsearch.paths.search = search\n\nprint(search.paths.identifier)\n```\n\nTwo runs printing the same string will share an output folder, whatever you believe about\nthem. The annotated tour of what lands in that folder — `files/`, `image/`, `model.info`,\n`model.results`, `search.summary` — is the `__Output Folder Layout__` section of\n`autogalaxy_workspace:scripts/imaging/modeling.py`, and the run-search skill\n(`ag_run_search`) owns reading it.\n\n## Branch — a start point, for MCMC and MLE only\n\nMCMC and optimiser searches have a *location* in parameter space, so you can say where they\nbegin. Nested samplers draw from the prior and cannot use this API. Adapted from\n`autogalaxy_workspace:scripts/guides/modeling/searches.py`, where an early-type galaxy is\nstarted near n = 4.\n\n```python\ninitializer = af.InitializerParamBounds(\n {\n model.galaxies.galaxy.bulge.centre_0: (-0.01, 0.01),\n model.galaxies.galaxy.bulge.centre_1: (-0.01, 0.01),\n model.galaxies.galaxy.bulge.effective_radius: (0.9, 1.1),\n model.galaxies.galaxy.bulge.sersic_index: (3.9, 4.1),\n }\n)\n\nsearch = af.Emcee(\n path_prefix=Path(\"imaging\"),\n name=\"start_point\",\n unique_tag=dataset_name,\n nwalkers=50,\n nsteps=500,\n initializer=initializer,\n)\n```\n\nParameters you do not name are drawn from their priors. `af.InitializerBall(lower_limit=0.49,\nupper_limit=0.51)` is the other common choice — a tight ball in unit-prior space around the\nprior centres, and the recommended initialisation for both MCMC samplers.\n\nThe statistical point here is worth stating explicitly, because there is a tempting shortcut\nthat is not equivalent. You *could* achieve a similar effect by tightening priors instead —\na narrow `af.TruncatedGaussianPrior` on `sersic_index`, say. But priors change the posterior,\nand therefore change the errors you quote and the model you infer. The start-point API moves\nwhere the search *looks* without moving what you *infer*. Prefer it whenever your knowledge is\nabout where the answer probably is rather than about what the answer must be.\n\n## Branch — mapping a parameter on a grid\n\nTo scan a parameter on a fixed grid rather than marginalising over it — a light centre, a\nfixed `sersic_index`, anything you want mapped — wrap a search:\n\n```python\ngrid_search = af.SearchGridSearch(\n search=search, number_of_steps=4, number_of_cores=1, result_output_interval=100\n)\n```\n\nOne child fit runs per grid cell and an `af.GridSearchResult` comes back. Source:\n`PyAutoFit:autofit/non_linear/grid/`. This is the one search whose defaults *do* live in a\nYAML — `autogalaxy_assistant:config/non_linear/GridSearch.yaml` sets `number_of_cores` and\n`step_size` in unit-prior values, and it is the only file in that folder because per-search\ndefaults ship inside PyAutoFit itself\n(`autogalaxy_assistant:config/non_linear/README.md`).\n\n## A different lever: chaining instead of a better search\n\nWhen a model is too complex for any single search, the answer is usually not a bigger\n`n_live` — it is to fit a simpler model first and pass its posterior forward as the priors of\nthe complex one. Fit a single Sersic, then chain into a bulge-plus-disk or pixelised fit,\nwhich starts from a region of parameter space that is already good.\n`autogalaxy_workspace:scripts/guides/modeling/chaining.py` is the walkthrough, the\n`width_modifier` entries in the prior YAMLs control how wide the passed priors become, and it\ngets its own skill in a later phase (`ag_chain_searches`).\n\n## Picking one at a glance\n\n| Goal | Pick |\n|---|---|\n| Quick check that model + data are sensible | `MultiStartProdigy(n_starts=48, n_steps=300)` |\n| Results you will quote, model under ~30 free parameters | `Nautilus(n_live=200)` |\n| Production run, complex or multi-modal model | `Nautilus(n_live=400)`, higher `n_batch` if VRAM allows |\n| Bayesian evidence comparison between models | `Nautilus` or `DynestyStatic` |\n| Ellipse / isophote fitting | `DynestyStatic(sample=\"rwalk\", nlive=50)` |\n| Independent cross-check of a posterior | `DynestyStatic` or `Zeus` |\n| Posterior refinement around a known mode | `Zeus` or `Emcee` with an `initializer` |\n| Map a parameter on a fixed grid | `af.SearchGridSearch` |\n| Check the priors are sane and the likelihood runs | `af.Drawer` |\n\n## Combine — where this hands off\n\n- **Run the fit** → the run-search skill (`ag_run_search`), which owns\n `search.fit(model=model, analysis=analysis)`, announcing the output folder at launch, and\n what to open first while it runs.\n- **The model isn't right yet** → [`ag_build_imaging_model`](./ag_build_imaging_model.md).\n Changing the search rarely rescues a badly-specified model, and a search that will not\n converge is more often a model problem than a sampler problem.\n- **It ran and failed, stalled, or returned something unphysical** → the fit-debugging skill\n (`ag_debug_fit_failure`), which is also where \"Fit Already Completed\" on data you thought was\n new gets diagnosed.\n- **Read the posterior that comes back** → the results-loading and fit-plotting skills\n (`ag_load_results`, `ag_plot_fit`); the `Samples` API and how errors are computed is\n [`../wiki/core/concepts/samples_and_posteriors.md`](../wiki/core/concepts/samples_and_posteriors.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording the search and\nits settings — `n_live` in particular, since it is an accuracy claim about the posterior you\nare about to publish.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: The non-linear search](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb):\n what a non-linear search actually is — parameter spaces, likelihoods, priors — and the\n statistical foundation under every setting on this page. The\n [optional chapter](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_optional/tutorial_searches.ipynb)\n tours the sampler zoo.\n- **General reference** — [RTD: Configs](https://pyautogalaxy.readthedocs.io/en/latest/general/configs.html):\n how the configuration files customise searches, visualisation and output, and where each is\n looked up.\n- **Experienced PyAutoGalaxy user** — [workspace: guides/modeling/searches.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/guides/modeling/searches.py):\n every available search instantiated with its settings spelled out, plus the start-point API.\n\n## Agent procedural checklist\n\n1. Ask the one question that decides it: errors needed, or a fast check?\n2. `Nautilus(n_live=200)` by default; `MultiStartProdigy` for speed (needs `use_jax=True`);\n `DynestyStatic` for isophotes or a cross-check.\n3. Set `n_live` from the model's free-parameter count, and say when you trade it down.\n4. **Always pass `unique_tag=dataset_name`** — and bump it when the data changes but the name\n does not.\n5. Print `search.paths.identifier` before a long run whenever a collision is plausible.\n6. Set `iterations_per_quick_update` to the search's unit — thousands for Nautilus, tens for a\n gradient optimiser. Keep `live_visual_update=False` on headless runs.\n7. Run `analysis.print_vram_use(model=model, batch_size=search.batch_size)` before a GPU run.\n8. Hand off to `ag_run_search`, and offer the `wiki/project/` entry recording the settings.\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_optional/tutorial_need_for_speed.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_run_search\n\n---\nname: ag_run_search\ndescription: Run the fit — take a composed model, an analysis and a configured search and drive `search.fit(model=model, analysis=analysis)` to completion, then read what it wrote. Covers the output-folder anatomy and the on-the-fly announcement, the unique-identifier resume behaviour and when it silently reuses a stale fit, `iterations_per_quick_update` and `live_visual_update`, JAX/GPU acceleration and when it actually pays, VRAM checks before a long GPU run, the `PYAUTO_TEST_MODE` smoke levels, and the `if __name__ == \"__main__\"` parallelisation fix. Use once `ag_build_imaging_model` and `ag_configure_search` have produced `model`, `analysis` and `search` objects, or when a fit is running and the user wants to know what to watch. Not for composing the model or choosing the search (those two skills), not for interpreting the finished posterior (`ag_load_results`), and not for diagnosing a fit that ran but converged somewhere unphysical (`ag_debug_fit_failure`).\n---\n\n# Running the fit\n\nThis is the moment the inference actually happens. Everything before it was preparation:\na `model` says which morphological parameters are free and what priors they carry, an\n`analysis` binds that model to one dataset and knows how to turn a parameter vector into a\nlog likelihood, and a `search` knows how to explore the parameter space. One call joins\nthem:\n\n```python\nresult = search.fit(model=model, analysis=analysis)\n```\n\nStatistically, that call is sampling (or optimising) the posterior\n$P(\\theta | d) \\propto \\mathcal{L}(d | \\theta) P(\\theta)$, where the likelihood is the\nGaussian-noise chi-squared of the PSF-convolved model image against the data — walked\nline by line in `autogalaxy_workspace:scripts/imaging/likelihood_function.py`. Scientifically,\nit is where a Sersic index, an effective radius or a bulge-to-total ratio stops being a guess\nand becomes a measurement with errors. What this skill adds is everything *around* the call:\nhow to watch it, how long to expect, how to make it fast, and how to prove the script works\nbefore committing hours to it.\n\nTwo wiki pages carry the background this skill assumes. Read\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md) for\nwhat each sampler does and how run time scales with the model, and\n[`wiki/core/api/analysis_objects.md`](../wiki/core/api/analysis_objects.md) for what the\nreturned `Result` contains.\n\n## Ask\n\nThree questions, and the answers change the branch:\n\n- *\"Do you already have `model`, `analysis` and `search`?\"* If not, route to\n [`ag_build_imaging_model`](./ag_build_imaging_model.md) and\n [`ag_configure_search`](./ag_configure_search.md) first. A fit assembled from a\n half-remembered model is the most expensive mistake available here.\n- *\"Smoke test first, or straight to the production run?\"* Almost always smoke test first —\n it takes seconds and answers \"does this script execute end to end?\", which is a different\n question from \"is this galaxy's Sersic index 3.2?\". The smoke branch is below.\n- *\"How long can this run, and on what?\"* A `MultiStartProdigy` fit is minutes; a `Nautilus`\n fit of a smooth model is tens of minutes on a GPU and can be hours on a CPU; a pixelised\n fit can be far longer. That answer decides foreground vs background, laptop vs cluster,\n and whether `live_visual_update` is worth switching on.\n\nIf the data is real observational imaging, the inspection gate in\n[`../AGENTS.md`](../AGENTS.md) applies before you get here at all — contaminants and mask\nextent are settled in [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md), not\nretrospectively.\n\n## Branch — the production run\n\nThe deliverable is one script in `scripts/` the user can re-run and edit. Adapted from\n`autogalaxy_workspace:scripts/imaging/start_here.py` (the fit and result sections) and\n`autogalaxy_workspace:scripts/imaging/modeling.py` (the Nautilus configuration and the VRAM\ncheck):\n\n```python\n\"\"\"\nGalaxy Structure: Run the Fit\n=============================\n\nFit a galaxy's surface-brightness profile to CCD imaging: load and mask the data, compose a\nlinear Sersic bulge, and sample the posterior with Nautilus so the inferred effective radius\nand Sersic index come with errors.\n\n__Contents__\n\n- **Imports:** JAX environment first, then the standard trio.\n- **Dataset:** Load imaging, mask it, and apply adaptive over-sampling.\n- **Model:** Compose the galaxy's light profile.\n- **Search:** Configure Nautilus and its update cadence.\n- **Analysis:** Bind the model to the data and choose the JAX backend.\n- **Model-Fit:** Run the search and announce the output folder.\n- **Result:** Read the best-fit model back.\n\"\"\"\nfrom autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\n\"\"\"\n__Dataset__\n\nGalaxy modeling needs three ingredients: the image in CCD counts, a per-pixel RMS noise-map,\nand the PSF. The PSF is forward-modelled rather than divided out, which is what separates a\ngenuinely compact bulge from a seeing-broadened one. `pixel_scales` converts pixels to\narcseconds and must match the instrument (`ag.Imaging.from_fits`,\n`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe mask sets which pixels enter the likelihood, and its radius is a science choice, not a\ndefault: truncate the outer isophotes and the effective radius and Sersic index are biased\ndirectly. Over-sampling evaluates the light profile several times per pixel where the\ngradient is steep, which matters most in the central few tenths of an arcsecond\n(`ag.util.over_sample.over_sample_size_via_radial_bins_from`).\n\"\"\"\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"\"\nMASK_RADIUS = 2.5\n\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n pixel_scales=0.1,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\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)\n\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n\n\"\"\"\n__Model__\n\nA linear `Sersic` bulge: the `intensity` is solved by linear inversion each iteration rather\nthan sampled, so the search explores one fewer dimension per component for free\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Linear Light Profiles__`).\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\n\n\"\"\"\n__Search__\n\n`Nautilus` is nested sampling: it returns the full posterior — every parameter's density,\nits errors, and the correlations between them. `n_live` trades accuracy against run time and\n200 covers the vast majority of galaxy models. `unique_tag` is conventionally the dataset\nname, which is what keeps the same model fitted to different data in different folders\n(`PyAutoFit:autofit/non_linear/search/nest/nautilus/search.py`).\n\"\"\"\nsearch = af.Nautilus(\n path_prefix=Path(\"imaging\"),\n name=\"sersic\",\n unique_tag=\"\",\n n_live=200,\n iterations_per_quick_update=10000,\n live_visual_update=False,\n)\n\n\"\"\"\n__Analysis__\n\n`ag.AnalysisImaging` defines the `log_likelihood_function` the search calls, and defaults to\n`use_jax=True` when JAX is installed (`PyAutoGalaxy:autogalaxy/imaging/model/analysis.py`).\n\"\"\"\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\n\"\"\"\n__Model-Fit__\n\nResults are written to the output folder on the fly, from the best model found so far, so the\nfolder is worth opening the moment the search starts.\n\"\"\"\nprint(f\"Output folder: {search.paths.output_path.resolve()}\")\n\nresult = search.fit(model=model, analysis=analysis)\n\n\"\"\"\n__Result__\n\"\"\"\nprint(result.info)\nprint(result.max_log_likelihood_instance)\n```\n\nRun it with writable caches if the default locations are not writable — a sandbox, CI, or an\ninstall imported from a Windows mount under WSL\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)):\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\n`search.fit` itself is `PyAutoFit:autofit/non_linear/search/abstract_search.py`.\n\n## Branch — what the output folder contains, and when to look\n\n**Announce the folder at launch, not at the end.** Quote\n`search.paths.output_path.resolve()` once the fit is running and say plainly that\n`model.results` and `image/fit.png` refresh as the search goes — there is nothing to wait\nfor. Users new to the stack sit watching a silent terminal because nobody told them.\n\nThe annotated tree of `files/`, `image/`, `model.info`, `model.results`, `search.summary`\nand the `` folder is `__Output Folder Layout__` in\n[`autogalaxy_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/modeling.py);\nthe same section appears in the `interferometer`, `multi_dataset`, `multi_galaxy` and\n`cluster` `modeling.py` scripts. Link it rather than copying the tree into the conversation,\nwhere it would rot. The condensed version is also in\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n\"The output folder\".\n\nName what to open first, in this order:\n\n1. `model.results` — the human-readable fit summary, parameters with errors.\n2. `image/fit.png` — data, model image, residuals and chi-squared map in one figure.\n3. `search.log` — tail it if you want to watch progress from a terminal.\n\nDepth follows [`_style.md`](./_style.md) \"Adaptive depth\": for a newcomer, or in teacher\nmode, walk all three. For a returning user, quoting the path is enough.\n\n## Branch — resuming, and the trap inside it\n\n`` is derived from the model, the search settings and the dataset identifier, so\nre-running an identical configuration **resumes** the existing fit rather than restarting it\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Unique Identifier__`). That is a\nfeature — an interrupted overnight run picks up where it stopped.\n\nIt is also the sharpest edge in the workflow. **The identifier does not hash the pixel\nvalues of your data.** Swap `data.fits` for a different galaxy, keep the model, the search\nand the `unique_tag` identical, and the next run finds a completed fit at the same path and\nreturns it — silently, in seconds, with the previous galaxy's parameters. If the data\nchanges, change the `unique_tag`. If you are unsure whether a result is stale, delete the\n`` folder and re-run rather than reasoning about it.\n\nTest mode namespaces its output separately: any active `PYAUTO_TEST_MODE` level inserts a\n`test_mode` segment straight after the output root, so a smoke run lands in\n`output/test_mode//...` and cannot short-circuit a later real fit\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## Branch — the update cadence and the live view\n\nTwo settings control what you see while the fit runs, both on the search\n(`PyAutoFit:autofit/non_linear/search/abstract_search.py`):\n\n- **`iterations_per_quick_update`** — how often the current best model is visualised and\n written to disk. The unit depends on the search: likelihood evaluations for `Nautilus`\n (hence the large `10000` in `modeling.py`), gradient steps for `MultiStartProdigy` (hence\n the much smaller `50` in `start_here.py`). Each update costs roughly ten seconds, so too\n low a value and output dominates the run time; too high and you cannot see progress. If\n the log is constantly reporting that it is outputting results, raise it.\n- **`live_visual_update`** — additionally push the quick-update image to a live surface: a\n matplotlib window that refreshes in a plain script, or a self-updating cell in Jupyter and\n Colab. The `fit.png` disk write happens either way. Leave it `False` on anything headless\n — an HPC node, a background process, CI.\n\nIf the search configuration already records the choice, don't re-ask; that decision belongs\nto [`ag_configure_search`](./ag_configure_search.md).\n\n## Branch — JAX, GPUs, and when the acceleration pays\n\nImaging fits run through JAX by default. Installing the extra (`pip install autogalaxy[jax]`)\nis all that is required: `ag.AnalysisImaging` then defaults to `use_jax=True`, and the search\ndriver wraps the likelihood in `jax.vmap(jax.jit(...))` so a whole batch of parameter vectors\nevaluates in one call. You will see a one-time log line as the JIT compile starts; every\nevaluation after that re-uses the compiled trace. This is described in\n`autogalaxy_workspace:scripts/guides/using_jax.py` `__Auto-Enabled Modeling__`, and if JAX is\nabsent the analysis warns once and falls back to NumPy.\n\n**When it pays.** The gain scales with how much array work each likelihood evaluation does,\nso it is largest for big masks, fine over-sampling, many-component bases and pixelised\nreconstructions, and smallest for a tiny mask with one smooth profile. GPU gains dwarf CPU\ngains: `autogalaxy_workspace:scripts/imaging/modeling.py` `__JAX__` quotes roughly ten\nminutes on a GPU against an hour on a CPU for its example, with a CPU still gaining from\nmultithreading. Gradient-based searches like `MultiStartProdigy` are not merely faster under\nJAX — they are only possible with it, because JAX is what supplies the likelihood's\nderivatives and evaluates all the parallel starts in one batched call\n(`autogalaxy_workspace:scripts/imaging/start_here.py` `__Multi Start Gradient Optimization__`).\n\n**Check VRAM before a long GPU run.** A JAX fit must fit inside the GPU's memory, and it\nfails at JIT-compile time or on the first likelihood call if it does not:\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py` `__VRAM Use__`. It takes\ntwenty or thirty seconds, so comment it out once you know your model's footprint. Batch size\nis the lever: larger batches cut wall-clock time and raise VRAM, smaller batches the reverse.\nA smooth-profile fit on a modest dataset is tens of megabytes; a pixelised reconstruction on\nhigh-resolution data can exceed ten gigabytes.\n\n**Turn JAX off to debug.** `ag.AnalysisImaging(dataset=dataset, use_jax=False)`, or\n`PYAUTO_DISABLE_JAX=1` to force it globally without editing code. NumPy stack traces are far\neasier to read, and you can drop a debugger or a `print` into code JAX would otherwise\ncompile. That is the first lever to pull when deciding whether a failure is a JAX problem at\nall — see [`ag_debug_fit_failure`](./ag_debug_fit_failure.md).\n\nFor running on a cluster — SLURM array jobs, one galaxy per task, the CPU and GPU batch\nscripts, and `number_of_cores` read from `SLURM_CPUS_PER_TASK` — read\n[`../wiki/core/operations/hpc.md`](../wiki/core/operations/hpc.md) for the concepts and\n[`../wiki/core/operations/hpc_infrastructure.md`](../wiki/core/operations/hpc_infrastructure.md)\nfor the `hpc/` templates and `sync` CLI this repo ships; the upstream ground truth behind both\nis `autogalaxy_workspace:scripts/guides/hpc/example_cpu_and_gpu.py`. The Python modeling code\nis identical for a GPU run; only the batch script changes.\n\n## Branch — the smoke test, before you spend hours\n\nEvery script gets one fast structural run before a real one. `PYAUTO_TEST_MODE` has four\nlevels ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)), and the\nchoice between them matters more than it looks:\n\n```bash\n# Level 1 — sampler runs with minimal iterations. A real (tiny) search: writes\n# model.results, image/fit.png and a samples.csv you can load back.\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n\n# Level 2 — sampler bypassed, likelihood called exactly once. The fastest proof that\n# the model composes and the likelihood evaluates.\nPYAUTO_TEST_MODE=2 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\n**Level 2 does not write the fit products.** A level-2 run returns a `Result`, proving the\nwiring, but leaves no `model.results` and no `image/fit.png` behind — so if the next thing\nyou want to do is plot or load the fit, use level 1. Level 3 skips the likelihood call as\nwell, which is only useful for checking that a script's non-fitting scaffolding runs.\n\n**The parameter values from any test-mode run are meaningless.** The sampler was truncated or\nmocked. Never quote a structural parameter measured in test mode; say explicitly that the\nnumber is a wiring check.\n\nFor the fastest possible loop, combine test mode with the dataset and output short-circuits:\n\n```bash\nPYAUTO_TEST_MODE=2 PYAUTO_SKIP_FIT_OUTPUT=1 PYAUTO_SKIP_VISUALIZATION=1 \\\n PYAUTO_SMALL_DATASETS=1 PYAUTO_FAST_PLOTS=1 python scripts/run_fit.py\n```\n\n`PYAUTO_SMALL_DATASETS=1` caps every array, mask and grid to 16 × 16 pixels — so delete any\npreviously simulated `dataset/` when you toggle it, or a full-resolution dataset on disk will\nbe reused and mismatch the capped grids.\n\n## Branch — the error that appears the moment the search starts\n\nOn some combinations of operating system and Python version, a script raises as soon as the\nsearch begins, from Python's process spawning rather than from anything about your model. The\nfix is to wrap the whole fit in a function and call it under a main guard:\n\n```python\ndef fit():\n from autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\n import autofit as af\n import autogalaxy as ag\n\n # ... dataset, model, search, analysis as above ...\n result = search.fit(model=model, analysis=analysis)\n\n\nif __name__ == \"__main__\":\n fit()\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/modeling/bug_fix.py`, which is the same\n`modeling.py` fit with this one structural change. It works for every dataset type, so adopt\nit for any modeling script that hits the error. If parallelisation still will not work after\nthe fix, that script points at the project's support channel.\n\n## Combine\n\n- [`ag_plot_fit`](./ag_plot_fit.md) — render the fit yourself, at whatever scaling and\n cropping the science needs, rather than reading the auto-generated `image/fit.png`.\n- [`ag_load_results`](./ag_load_results.md) — pull the posterior, the best-fit galaxies and\n the derived quantities back into Python, in-session or from disk later.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) — the fit finished but the residuals or\n the parameters are wrong.\n- [`ag_configure_search`](./ag_configure_search.md) — the fit is too slow, or the sampler is\n the wrong one for the model.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) — build a controlled dataset with known\n truth and fit that first, which is the cleanest way to separate a model problem from a\n data problem.\n\nWhen the script and its fit are worth keeping, offer (default-yes) to record the run in a\ndated `wiki/project/YYYY-MM-DD-.md` entry: the science question, what was inferred and\nwith what search, and the output path — per [`_style.md`](./_style.md) property #5.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Practicalities](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running a fit — output structure, reviewing results as they appear,\n and managing run times.\n- **General reference** — [RTD: New user guide](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n the decision tree for which fit to run first, by system scale and dataset type.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit, with the JAX and quick-update sections this skill\n mirrors.\n\n## Agent procedural checklist\n\n1. Confirm `model`, `analysis` and `search` exist; if not, route to the model-building and\n search-configuration skills.\n2. On real observational data, confirm the inspection gate has been satisfied.\n3. Write the script to `scripts/` in the generated-script style; never leave it inline only.\n4. Validate it with `PYAUTO_TEST_MODE=1` (level 2 if you only need the likelihood proved),\n with the cache variables set if the environment needs them.\n5. Launch the production run; **quote the absolute output path immediately** and say results\n refresh on the fly.\n6. Name `model.results` and `image/fit.png` as the first two things to open.\n7. If the data changed but the model did not, confirm the `unique_tag` changed too.\n8. On a GPU, run the VRAM check before a long fit.\n9. On completion, hand off to the results-loading or fit-plotting skill rather than\n interpreting the numbers inline.\n10. Offer the `wiki/project/` entry.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_optional/tutorial_prior_passing.ipynb b/notebooks/chapter_optional/tutorial_prior_passing.ipynb index 62ccfff..47f7117 100644 --- a/notebooks/chapter_optional/tutorial_prior_passing.ipynb +++ b/notebooks/chapter_optional/tutorial_prior_passing.ipynb @@ -79,7 +79,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_optional/tutorial_prior_passing.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_configure_search\n\n---\nname: ag_configure_search\ndescription: Choose and configure the non-linear search that fits a galaxy model to data — `af.Nautilus` for a full posterior with errors you can quote, `af.MultiStartProdigy` for a fast maximum-a-posteriori check, `af.DynestyStatic` for isophote/ellipse fitting and as a cross-check, and the MCMC / quasi-Newton / diagnostic alternatives. Covers `n_live` and `n_batch`, `n_starts` and `n_steps`, the `iterations_per_quick_update` output cadence, the start-point initialiser API, grid searches, and — critically — the `unique_tag` / unique-identifier and resume semantics, since the identifier is a hash of the model and search but **not** of the data, so re-using a tag across datasets silently resumes the wrong fit. Use once a model and analysis exist. Not for composing the model (`ag_build_imaging_model`), not for executing the fit or reading its output folder (`ag_run_search`), and not for diagnosing a fit that already failed.\n---\n\n# Choosing and configuring the search\n\nA search is the algorithm that explores your model's parameter space, calling\n`analysis.log_likelihood_function(instance)` over and over and deciding where to look next.\nEvery search in PyAutoFit takes the same two arguments, so swapping one for another is a\none-line change:\n\n```python\nresult = search.fit(model=model, analysis=analysis)\n```\n\nThe choice matters for one reason above all others: **some searches return a posterior and\nsome return a point.** A nested sampler maps the probability density of every parameter, its\nerrors, and the covariances between them — so it can tell you whether an inferred effective\nradius of 1.6\" is 1.6 ± 0.01 or 1.6 ± 0.5, and whether it trades off against the Sersic index.\nA gradient optimiser hands you a single best-fit model and *nothing else*: no errors, no\ncovariances. Both are useful, for different questions, and confusing them is the most\nconsequential mistake available here.\n\nThe runnable tour of the whole menu is\n`autogalaxy_workspace:scripts/guides/modeling/searches.py`; the catalogue with every argument\nis [`../wiki/core/api/searches.md`](../wiki/core/api/searches.md), and what each family\nactually does is\n[`../wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md).\n\n## Ask\n\n- *\"Do you need error bars, or do you just want to know whether this model fits at all?\"*\n This is the whole decision. Errors → `Nautilus`. A quick check → `MultiStartProdigy`.\n- *\"How many free parameters does the model have?\"* — `print(model.info)` if you don't know.\n It sets `n_live`, and it is the main driver of run time.\n- *\"Is this dataset one of several you will fit with the same model?\"* — if yes, the\n `unique_tag` section below is not optional reading; it is where results silently collide.\n- *\"Is JAX available, and a GPU?\"* — `MultiStartProdigy` requires a JAX-traceable analysis\n (`use_jax=True`) and is not available without it.\n\n## Branch — `af.Nautilus`, the default\n\nThe search every workspace `modeling.py` example uses, and the one to reach for when the\nanswer will be quoted in a paper. Extensive testing across galaxy modelling found it the most\naccurate and efficient search available. Adapted from\n`autogalaxy_workspace:scripts/imaging/modeling.py`.\n\n```python\nsearch = af.Nautilus(\n path_prefix=Path(\"imaging\"),\n name=\"modeling\",\n unique_tag=dataset_name,\n n_live=200,\n n_batch=50,\n iterations_per_quick_update=10000,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/nautilus/`; optional dependency\n`nautilus-sampler`. Reference: Lange (2023), arXiv:2306.16923.\n\n**`n_live` is the accuracy / run-time dial**, and essentially the only setting you need to\nthink about. More live points map the posterior more reliably but cost more likelihood\nevaluations; fewer are faster but risk converging on a local maximum. 200 is sufficient for\nthe vast majority of galaxy models, and more parameters want more — a bulge-plus-disk model\nat N = 9 is comfortable at 200, while a model past ~30 free parameters is worth running at\n400. Dropping to 100 on a simple model to save time is a legitimate move (`modeling.py` does\nexactly that) but it is a deliberate accuracy trade, so say so when you make it.\n\n**`n_batch` is where the GPU speed-up comes from**, and it is worth understanding because\nNautilus is *gradient-free* — it never differentiates the likelihood, so unlike the optimisers\nbelow it does not use JAX's derivatives at all. What it does do is propose points in batches,\nand when the analysis is JAX-traceable PyAutoFit evaluates the whole batch through one\n`jax.vmap(jax.jit(...))` call, fitting all `n_batch` models simultaneously. It is therefore\nalso the main control on VRAM: a bigger batch holds more models in memory at once. Pair it\nwith `analysis.print_vram_use(model=model, batch_size=search.batch_size)` before a GPU run\n(see [`ag_build_imaging_model`](./ag_build_imaging_model.md)).\n\nFor parallel CPU runs, `number_of_cores` scales well: roughly linearly below 8 cores and\nabout `0.5 * number_of_cores` above, continuing past 50 cores — which is why supercomputing\nfacilities make even large models tractable.\n\n## Branch — `af.MultiStartProdigy`, when you want an answer now\n\nThe search every workspace `start_here.py` example uses. Far faster than Nautilus, and\nreturns a single best-fit model with **no errors at all**. Adapted from\n`autogalaxy_workspace:scripts/imaging/start_here.py`.\n\n```python\nsearch = af.MultiStartProdigy(\n path_prefix=Path(\"imaging\"),\n name=\"start_here\",\n unique_tag=dataset_name,\n n_starts=48,\n n_steps=300,\n iterations_per_quick_update=50,\n live_visual_update=False,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/mle/multi_start_gradient/`; optional dependencies\n`jax` and `optax`.\n\nThe design is what makes gradient descent usable on this problem at all. Galaxy-model\nparameter spaces are multi-modal, so a *single*-start optimiser routinely descends confidently\ninto a local maximum — which is exactly the weakness of `LBFGS` below.\n`MultiStartProdigy` launches `n_starts` independent descents from broad starting points spread\nacross the parameter space, runs them **all in parallel** through `jax.vmap`, and returns the\nbest. That wide population is what reliably finds the global maximum-likelihood basin; it is\nthe approach introduced for galaxy modelling by GIGA-Lens (Gu, Huang et al. 2022,\narXiv:2202.07663). Prodigy adds a *learning-rate free* update rule (Mishchenko & Defazio 2024,\narXiv:2306.06101): it estimates its own step size as it runs, so there is no `learning_rate`\nfor you to tune — which is precisely why it is the recommended member of the family over\n`MultiStartAdam`, `MultiStartADABelief` and `MultiStartLion`, all of which want one chosen.\n\nThree things to hold onto:\n\n- **It requires `use_jax=True`.** It is gradient-based, so a NumPy analysis cannot supply what\n it needs. It is therefore unavailable for `ag.AnalysisEllipse`, which is not JAX-traceable.\n- **`n_steps` is a ceiling, not a target.** The search stops early once the best fit stops\n improving, so expect a handful of quick updates rather than `n_steps / 50` of them.\n- **There is no posterior.** If the fit reports `effective_radius = 1.6\"`, this search cannot\n tell you the uncertainty, and no amount of extra starts will change that.\n\nThe workflow the workspace recommends, and the one to recommend to the user: run\n`MultiStartProdigy` first to confirm cheaply that the model and data are sensible, then run\n`Nautilus` on the same model when you need numbers you can quote.\n\n## Branch — `af.DynestyStatic`, for isophotes and as a cross-check\n\nThe nested-sampling alternative, and the search the workspace's **ellipse** examples use,\nbecause testing showed it the most reliable for isophote fitting specifically.\n\n```python\nsearch = af.DynestyStatic(\n path_prefix=Path(\"ellipse\"),\n name=\"fit_start\",\n unique_tag=dataset_name,\n sample=\"rwalk\",\n nlive=50,\n iterations_per_quick_update=2500,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/dynesty/`. Reference: Speagle (2020),\narXiv:1904.02180.\n\nNote `nlive`, not `n_live` — the argument names follow each upstream sampler's own convention,\nwhich is a real source of typos when switching. Dynesty's sampler options pass straight\nthrough (`sample`, `walks`, `bound`, `bootstrap`, `enlarge`, `update_interval`, `facc`,\n`slices`, `fmove`, `max_move`), and `af.DynestyDynamic` reallocates live points as it runs —\ntoward the tails for a better evidence estimate, toward the bulk for better parameters —\ntaking `nlive_init`, `dlogz_init` and the other `_init` variants instead.\n\nTwo reasons to reach for it. **Isophote fitting**: use it whenever the analysis is\n`ag.AnalysisEllipse`, where the gradient optimisers are unavailable anyway. **Independent\ncross-check**: a posterior that reproduces under a different nested sampler is far more\nconvincing than one that does not, and this is the cheapest such check available. Ellipse\nfitting has its own page,\n[`../wiki/core/api/ellipse.md`](../wiki/core/api/ellipse.md), and its own skill,\n[`ag_ellipse_fitting`](./ag_ellipse_fitting.md).\n\n## Branch — the rest of the catalogue\n\nEvery search PyAutoFit ships, generated from the installed release's search manifest\n(`python -m autofit search-manifest --json`; regenerate with PyAutoHands\n`autohands regenerate_search_roster --root .`, never by hand):\n\n\n\n- **Markov chain Monte Carlo** (`mcmc`): `af.Emcee`, `af.Zeus`, `af.BlackJAXNUTS`, `af.SMC` (experimental) — example: `autofit_workspace:scripts/searches/mcmc.py`\n- **Nested sampling** (`nest`): `af.DynestyStatic`, `af.DynestyDynamic`, `af.Nautilus`, `af.NSS` (experimental) — example: `autofit_workspace:scripts/searches/nest.py`\n- **Maximum likelihood / maximum a posteriori** (`mle`): `af.Drawer`, `af.BFGS`, `af.LBFGS`, `af.MultiStartAdam`, `af.MultiStartADABelief` (experimental), `af.MultiStartLion` (experimental), `af.MultiStartProdigy` — example: `autofit_workspace:scripts/searches/mle.py`\n\n\nReach for these only when you know why. All are tabulated with full argument lists in\n[`../wiki/core/api/searches.md`](../wiki/core/api/searches.md) and demonstrated in\n`autogalaxy_workspace:scripts/guides/modeling/searches.py`.\n\n| Search | When |\n|---|---|\n| `af.Zeus` | Ensemble MCMC **slice** sampler; the best-performing MCMC in the workspace's tests, though still behind Nautilus. Good for characterising a posterior around a mode you already found. |\n| `af.Emcee` | The familiar affine-invariant ensemble sampler. Same role as Zeus, generally a little worse on these parameter spaces. |\n| `af.NSS` | Nested slice sampling via BlackJAX, run entirely inside `jax.jit`. Needs a JAX-traceable analysis (`use_jax=True`); returns the evidence like the other nested samplers. |\n| `af.BlackJAXNUTS` / `af.SMC` | JAX gradient MCMC: the No-U-Turn sampler, and BlackJAX adaptive tempered sequential Monte Carlo (which also returns the evidence). Both need `use_jax=True`. |\n| `af.LBFGS` / `af.BFGS` | Single-start quasi-Newton descent via SciPy. Fast in principle, but galaxy-model parameter spaces are usually too complex to use it without careful initialisation — `MultiStartProdigy` exists to fix exactly that. |\n| `af.Drawer` | Not a search: draws models from the prior and evaluates them. A diagnostic for \"are my priors sane and does my likelihood run at all?\", and the workspace's one-draw container for collecting many completed fits into a single output folder (`total_draws=1`). |\n\nMCMC and MLE searches monitor convergence differently from nested samplers — both `Emcee` and\n`Zeus` accept an `af.AutoCorrelationsSettings(check_for_convergence=True, check_size=100,\nrequired_length=50, change_threshold=0.01)` and will terminate early when the chains satisfy\nit.\n\n## Branch — the output cadence\n\nEvery search writes results to disk **as it runs**, using the highest-likelihood model found\nso far, and `iterations_per_quick_update` sets how often. This is not free, and the two\ncanonical values look contradictory until you notice the unit differs:\n\n- `Nautilus(iterations_per_quick_update=10000)` — the unit is a likelihood evaluation, and on\n a fast fit writing output every few hundred would dominate the run time.\n- `MultiStartProdigy(iterations_per_quick_update=50)` — the unit is a *gradient step*, a far\n coarser thing, so 50 gives a useful handful of updates.\n\nIf the log keeps announcing that it is outputting results, raise the number. The heavier\n`iterations_per_full_update` controls the full pass — all visuals plus `model.results` and\n`search.summary`. Defaults for both live in `autogalaxy_assistant:config/general.yaml` under\n`updates:` (set to effectively infinite there, so the per-search value governs), and the\nconfig layer is [`../wiki/core/api/configuration.md`](../wiki/core/api/configuration.md).\n\n`live_visual_update=False` is the default and the right choice on a headless or cluster run.\nSet it `True` to also push each quick update to a live surface — a matplotlib window that\nrefreshes from a script, or an in-place refresh of the Jupyter cell. The disk write happens\neither way.\n\n## The unique identifier, `unique_tag`, and resuming — read this one\n\nOutput lands at `output////`, where the identifier is a\n32-character hash. Re-running an identical configuration **resumes** the existing fit rather\nthan starting over, which is a genuinely useful feature — and the sharp edge of this whole\nskill, because of what goes into the hash and what does not.\n\n**The identifier is a hash of the model and the search. It is not a hash of the data.**\n\nThat is not a subtlety; it is a trap with a silent failure mode. Fit galaxy A, then change\nonly the FITS paths and fit galaxy B with the same model and the same search: the identifier\nis identical, PyAutoFit finds a completed fit at that path, and reports \"Fit Already\nCompleted\". You get galaxy A's result back, labelled as galaxy B, with no error raised.\n\nThe fix is one argument, and it is why every workspace example passes it:\n\n```python\nsearch = af.Nautilus(\n path_prefix=Path(\"imaging\"),\n name=\"modeling\",\n unique_tag=dataset_name, # <-- the discriminator the data itself does not supply\n n_live=200,\n)\n```\n\n**Pass your dataset name as `unique_tag`, always.** Then the two galaxies hash differently and\nland in different folders. And the corollary that catches people a second time: if the *data*\nchanges but its name does not — you re-reduced it, fixed the noise-map, changed the mask,\nre-ran the simulator with different truth — **bump the `unique_tag`** (or delete the output\nfolder). Otherwise you resume a fit to data that no longer exists.\n\nChanging the model or the search *does* change the identifier, so you never need to manage\nthat case by hand: a bulge-plus-disk fit cannot collide with a single-Sersic fit, and an\n`n_live=200` run cannot collide with an `n_live=400` one. It is only the data axis that is\ninvisible to the hash.\n\nVerify rather than trust when it matters. Comparing the identifier across two configurations\nbefore launching a long run costs nothing:\n\n```python\nsearch.paths.model = model\nsearch.paths.search = search\n\nprint(search.paths.identifier)\n```\n\nTwo runs printing the same string will share an output folder, whatever you believe about\nthem. The annotated tour of what lands in that folder — `files/`, `image/`, `model.info`,\n`model.results`, `search.summary` — is the `__Output Folder Layout__` section of\n`autogalaxy_workspace:scripts/imaging/modeling.py`, and the run-search skill\n(`ag_run_search`) owns reading it.\n\n## Branch — a start point, for MCMC and MLE only\n\nMCMC and optimiser searches have a *location* in parameter space, so you can say where they\nbegin. Nested samplers draw from the prior and cannot use this API. Adapted from\n`autogalaxy_workspace:scripts/guides/modeling/searches.py`, where an early-type galaxy is\nstarted near n = 4.\n\n```python\ninitializer = af.InitializerParamBounds(\n {\n model.galaxies.galaxy.bulge.centre_0: (-0.01, 0.01),\n model.galaxies.galaxy.bulge.centre_1: (-0.01, 0.01),\n model.galaxies.galaxy.bulge.effective_radius: (0.9, 1.1),\n model.galaxies.galaxy.bulge.sersic_index: (3.9, 4.1),\n }\n)\n\nsearch = af.Emcee(\n path_prefix=Path(\"imaging\"),\n name=\"start_point\",\n unique_tag=dataset_name,\n nwalkers=50,\n nsteps=500,\n initializer=initializer,\n)\n```\n\nParameters you do not name are drawn from their priors. `af.InitializerBall(lower_limit=0.49,\nupper_limit=0.51)` is the other common choice — a tight ball in unit-prior space around the\nprior centres, and the recommended initialisation for both MCMC samplers.\n\nThe statistical point here is worth stating explicitly, because there is a tempting shortcut\nthat is not equivalent. You *could* achieve a similar effect by tightening priors instead —\na narrow `af.TruncatedGaussianPrior` on `sersic_index`, say. But priors change the posterior,\nand therefore change the errors you quote and the model you infer. The start-point API moves\nwhere the search *looks* without moving what you *infer*. Prefer it whenever your knowledge is\nabout where the answer probably is rather than about what the answer must be.\n\n## Branch — mapping a parameter on a grid\n\nTo scan a parameter on a fixed grid rather than marginalising over it — a light centre, a\nfixed `sersic_index`, anything you want mapped — wrap a search:\n\n```python\ngrid_search = af.SearchGridSearch(\n search=search, number_of_steps=4, number_of_cores=1, result_output_interval=100\n)\n```\n\nOne child fit runs per grid cell and an `af.GridSearchResult` comes back. Source:\n`PyAutoFit:autofit/non_linear/grid/`. This is the one search whose defaults *do* live in a\nYAML — `autogalaxy_assistant:config/non_linear/GridSearch.yaml` sets `number_of_cores` and\n`step_size` in unit-prior values, and it is the only file in that folder because per-search\ndefaults ship inside PyAutoFit itself\n(`autogalaxy_assistant:config/non_linear/README.md`).\n\n## A different lever: chaining instead of a better search\n\nWhen a model is too complex for any single search, the answer is usually not a bigger\n`n_live` — it is to fit a simpler model first and pass its posterior forward as the priors of\nthe complex one. Fit a single Sersic, then chain into a bulge-plus-disk or pixelised fit,\nwhich starts from a region of parameter space that is already good.\n`autogalaxy_workspace:scripts/guides/modeling/chaining.py` is the walkthrough, the\n`width_modifier` entries in the prior YAMLs control how wide the passed priors become, and it\ngets its own skill in a later phase (`ag_chain_searches`).\n\n## Picking one at a glance\n\n| Goal | Pick |\n|---|---|\n| Quick check that model + data are sensible | `MultiStartProdigy(n_starts=48, n_steps=300)` |\n| Results you will quote, model under ~30 free parameters | `Nautilus(n_live=200)` |\n| Production run, complex or multi-modal model | `Nautilus(n_live=400)`, higher `n_batch` if VRAM allows |\n| Bayesian evidence comparison between models | `Nautilus` or `DynestyStatic` |\n| Ellipse / isophote fitting | `DynestyStatic(sample=\"rwalk\", nlive=50)` |\n| Independent cross-check of a posterior | `DynestyStatic` or `Zeus` |\n| Posterior refinement around a known mode | `Zeus` or `Emcee` with an `initializer` |\n| Map a parameter on a fixed grid | `af.SearchGridSearch` |\n| Check the priors are sane and the likelihood runs | `af.Drawer` |\n\n## Combine — where this hands off\n\n- **Run the fit** → the run-search skill (`ag_run_search`), which owns\n `search.fit(model=model, analysis=analysis)`, announcing the output folder at launch, and\n what to open first while it runs.\n- **The model isn't right yet** → [`ag_build_imaging_model`](./ag_build_imaging_model.md).\n Changing the search rarely rescues a badly-specified model, and a search that will not\n converge is more often a model problem than a sampler problem.\n- **It ran and failed, stalled, or returned something unphysical** → the fit-debugging skill\n (`ag_debug_fit_failure`), which is also where \"Fit Already Completed\" on data you thought was\n new gets diagnosed.\n- **Read the posterior that comes back** → the results-loading and fit-plotting skills\n (`ag_load_results`, `ag_plot_fit`); the `Samples` API and how errors are computed is\n [`../wiki/core/concepts/samples_and_posteriors.md`](../wiki/core/concepts/samples_and_posteriors.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording the search and\nits settings — `n_live` in particular, since it is an accuracy claim about the posterior you\nare about to publish.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: The non-linear search](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb):\n what a non-linear search actually is — parameter spaces, likelihoods, priors — and the\n statistical foundation under every setting on this page. The\n [optional chapter](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_optional/tutorial_searches.ipynb)\n tours the sampler zoo.\n- **General reference** — [RTD: Configs](https://pyautogalaxy.readthedocs.io/en/latest/general/configs.html):\n how the configuration files customise searches, visualisation and output, and where each is\n looked up.\n- **Experienced PyAutoGalaxy user** — [workspace: guides/modeling/searches.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/guides/modeling/searches.py):\n every available search instantiated with its settings spelled out, plus the start-point API.\n\n## Agent procedural checklist\n\n1. Ask the one question that decides it: errors needed, or a fast check?\n2. `Nautilus(n_live=200)` by default; `MultiStartProdigy` for speed (needs `use_jax=True`);\n `DynestyStatic` for isophotes or a cross-check.\n3. Set `n_live` from the model's free-parameter count, and say when you trade it down.\n4. **Always pass `unique_tag=dataset_name`** — and bump it when the data changes but the name\n does not.\n5. Print `search.paths.identifier` before a long run whenever a collision is plausible.\n6. Set `iterations_per_quick_update` to the search's unit — thousands for Nautilus, tens for a\n gradient optimiser. Keep `live_visual_update=False` on headless runs.\n7. Run `analysis.print_vram_use(model=model, batch_size=search.batch_size)` before a GPU run.\n8. Hand off to `ag_run_search`, and offer the `wiki/project/` entry recording the settings.\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_optional/tutorial_prior_passing.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_chain_searches\n\n---\nname: ag_chain_searches\ndescription: Break one hard fit into a sequence of easier non-linear searches, using each result to initialize the next. Covers when chaining beats a single search and when it does not, passing a whole profile or galaxy with `result.model` (which preserves the original priors) versus narrowing them with `result.model_centred` and its absolute, relative and bounded variants, the `TruncatedGaussianPrior` those produce and where its sigma comes from in the `priors` config `width_modifier`, fixing a component with `result.instance` to remove its dimensions, and the output-path convention that keeps a chain's searches together. Use when a model is too complex for one search, when an early search should use cheap settings and a later one accurate ones, or when several galaxies must be added one at a time. Not for choosing a single search (`ag_configure_search`), not for driving one fit (`ag_run_search`), and not for combining several datasets (`ag_multi_dataset`).\n---\n\n# Chaining searches\n\nEvery other modelling skill in this workspace composes one model and hands it to one search.\nChaining is the alternative shape: split the problem into a sequence of searches, and use what\neach one learned to tell the next where to look.\n\nThe reason is statistical, not cosmetic. A non-linear search has to map a parameter space it knows\nnothing about, and the cost of doing that grows sharply with dimensionality while the risk of\nsettling in a local maximum grows with multi-modality. A galaxy model with a bulge, a disk, a sky\nlevel and two blended neighbours has both problems at once. Fit the bulge alone and the space is\nsmall, unimodal and mapped in minutes; then the disk only has to be added to a galaxy whose size\nand centre are already known. Each search in a chain solves a problem that is easy *because* of\nthe one before it.\n\nThree distinct benefits, and they are worth separating because they justify chaining in different\nsituations:\n\n- **Lower dimensionality per search.** Earlier searches fit simpler models with a parameter space\n that can be sampled properly, which reduces the chance of an incorrect local maximum in the\n final one.\n- **Cheap settings early, accurate settings late.** An early search only needs to find the high-\n likelihood region, so it can use a fast optimizer or a small `n_live`. Only the final search\n needs settings good enough to quantify errors.\n- **Cheap approximations early.** An early search can use a smaller mask, coarser over-sampling\n or a simplified component, and revert to the accurate-but-expensive settings at the end. The\n approximation costs some fidelity in the early result, which is fine when that result is only\n being used to place a prior.\n\nThis skill has **one** grounding script: `autogalaxy_workspace:scripts/guides/modeling/chaining.py`.\nIt is deliberately an API overview rather than a library of pipelines, and this skill is scoped to\nmatch it — the mechanics of prior passing, done honestly, rather than a catalogue of recipes that\ndo not exist upstream. The end of chapter 2 of the HowToGalaxy lecture series (tutorials 9-10) is where the pedagogy lives.\nRead [`../wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md) for\nhow run time scales with the model, which is the quantity chaining exists to manage.\n\n## Ask\n\n- *\"What makes this fit hard — too many parameters, or a search that keeps landing somewhere\n wrong?\"* Both are chaining's territory, but they suggest different splits: dimensionality\n suggests adding components one at a time, multi-modality suggests fixing the thing the search\n keeps getting wrong.\n- *\"What would you fit first if you had to pick one component?\"* Usually the brightest and\n simplest. If the user cannot name one, chaining may not be the right tool — see the branch on\n when not to chain.\n- *\"Is a single search actually failing, or just slow?\"* A slow-but-correct search is often better\n served by a faster sampler or JAX than by a chain, because a chain adds a whole class of\n failure: a wrong early result confidently narrowing a later prior.\n\n## Branch — the two-search chain\n\nThe deliverable is one script containing the whole chain, so it can be re-run end to end. Adapted\nfrom `autogalaxy_workspace:scripts/guides/modeling/chaining.py`.\n\n```python\n\"\"\"\nGalaxy Structure: Chained Searches\n=================================\n\nFit a galaxy's bulge alone, then add a disk with the bulge's parameters initialized from the\nfirst fit. Splitting the fit this way lets each search sample a parameter space it can actually\nmap, and makes the two-component decomposition a refinement of a known galaxy rather than a\nfourteen-dimensional search from broad priors.\n\n__Contents__\n\n- **Imports:** JAX environment first, then the standard trio.\n- **Dataset:** Load, mask and over-sample the imaging once, for every search.\n- **Paths:** One output prefix shared by every search in the chain.\n- **Model (Search 1):** A single linear Sersic bulge.\n- **Model-Fit (Search 1):** Fit it, cheaply.\n- **Model Chaining:** Pass the bulge into search 2 and add a disk.\n- **Model-Fit (Search 2):** Fit the two-component model with accurate settings.\n- **Result:** Read the final model back.\n\"\"\"\nfrom autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\n\"\"\"\n__Dataset__\n\nLoaded, masked and over-sampled once. Every search in the chain shares one `analysis`, which is\nwhat makes their likelihoods comparable — if search 2 used a different mask, its log likelihood\nwould not be on the same scale as search 1's, and the priors passed between them would refer to a\ndifferent dataset.\n\"\"\"\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"\"\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=0.1,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=3.0,\n)\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)\n\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\n\"\"\"\n__Paths__\n\nOne `path_prefix` for the whole chain, with each search distinguished only by `name`. This keeps\nevery stage of one chain in one directory tree, which matters when you come back to a fit and\nneed to see what search 1 actually inferred before trusting search 2.\n\"\"\"\npath_prefix = Path(\"imaging\") / \"chaining\" / \"\"\n\n\"\"\"\n__Model (Search 1)__\n\nThe bulge alone. A linear `Sersic` solves its own `intensity`, so this is a compact space the\nsearch can map quickly (`PyAutoGalaxy:autogalaxy/profiles/light/linear/sersic.py`).\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel_1 = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model_1.info)\n\n\"\"\"\n__Model-Fit (Search 1)__\n\nCheap settings on purpose: this search only has to find the high-likelihood region, not measure\nerrors. Inspect its result before relying on it — a chain built on a bad first search propagates\nthat error into every subsequent prior, with more confidence at every step.\n\"\"\"\nsearch_1 = af.Nautilus(\n path_prefix=path_prefix,\n name=\"search[1]__bulge\",\n unique_tag=\"\",\n n_live=100,\n)\n\nresult_1 = search_1.fit(model=model_1, analysis=analysis)\n\nprint(result_1.info)\n\n\"\"\"\n__Model Chaining__\n\n`result_1.model_centred` returns the search-1 model with every free parameter replaced by a\n`TruncatedGaussianPrior` centred on that parameter's median from search 1\n(`PyAutoFit:autofit/non_linear/result.py`,\n`PyAutoFit:autofit/mapper/prior/truncated_gaussian.py`). Search 2 therefore starts sampling in\nthe region search 1 found, rather than from broad priors.\n\nNote the attribute: `result_1.model` passes the component through with its **original** priors\nunchanged, which is useful when you want the structure of a previous model but not its\nconstraints. `model_centred` is the one that narrows.\n\"\"\"\nbulge = result_1.model_centred.galaxies.galaxy.bulge\ndisk = af.Model(ag.lp_linear.Exponential)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n\nmodel_2 = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model_2.info)\n\n\"\"\"\n__Model-Fit (Search 2)__\n\nThe accurate search. Read search 2's `model.info` in the output folder to confirm the priors\narrived as intended before trusting the result.\n\"\"\"\nsearch_2 = af.Nautilus(\n path_prefix=path_prefix,\n name=\"search[2]__bulge_disk\",\n unique_tag=\"\",\n n_live=150,\n)\n\nresult_2 = search_2.fit(model=model_2, analysis=analysis)\n\n\"\"\"\n__Result__\n\"\"\"\nprint(result_2.info)\n\nPLOT_DIR = Path(\"scripts\") / \"scratch\" / \"\" / \"chained\"\n\naplt.subplot_fit_imaging(\n fit=result_2.max_log_likelihood_fit,\n output_path=str(PLOT_DIR),\n output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nWhole components pass, not just single parameters: `result_1.model_centred.galaxies.galaxy.bulge`\ncarries every one of the bulge's parameters across in one expression, provided the component's\n*type* has not changed. A single parameter passes the same way —\n`galaxy.bulge.effective_radius = result_1.model_centred.galaxies.galaxy.bulge.effective_radius` —\nwhich is how you narrow some parameters and leave others broad.\n\n## Branch — `model`, `model_centred`, and `instance`\n\nThis is the part to get right, and the distinction is sharper than the workspace script's prose\nsuggests. Three attributes on a `Result`, three different things:\n\n**`result.model`** — the same model with the **same priors it had before**. On the released stack\nthis attribute preserves the priors rather than narrowing them\n(`PyAutoFit:autofit/non_linear/result.py`), so a component passed this way brings its structure\nacross but no information from the fit. That is occasionally exactly what you want — reuse the\ncomposition, refit from scratch — but it is *not* prior passing, and reading the workspace\nscript's older description of it as producing narrowed Gaussians will mislead you. Check what you\nactually got:\n\n```python\nprint(type(model_2.galaxies.galaxy.bulge.sersic_index).__name__)\n```\n\n**`result.model_centred`** — the narrowing one. Every free parameter becomes a\n`TruncatedGaussianPrior` whose `mean` is that parameter's median from the previous search and whose\n`sigma` comes from the parameter's `width_modifier` in the `priors` config. Three further variants\nlet you override that width:\n\n| Attribute | Prior produced | `sigma` |\n|---|---|---|\n| `result.model_centred` | `TruncatedGaussianPrior` | from the parameter's config `width_modifier` |\n| `result.model_centred_absolute(a=0.1)` | `TruncatedGaussianPrior` | exactly `a`, for every parameter |\n| `result.model_centred_relative(r=0.2)` | `TruncatedGaussianPrior` | `r × mean`, per parameter |\n| `result.model_centred_max_lh_bounded(b=0.3)` | `UniformPrior` | bounds at `mean ± b` |\n\n**`result.instance`** — the maximum-likelihood *values*, as fixed numbers. A component passed this\nway has no free parameters at all, so search 2's dimensionality drops by that component's\nparameter count. This is the lever for \"fit the bulge, freeze it, then fit the disk against a\nfixed bulge\", and it is much stronger medicine than a narrow prior: the later search cannot\nrevisit the frozen component even if the added component would have changed it.\n\n```python\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=result_1.instance.galaxies.galaxy.bulge, # fixed, contributes 0 parameters\n disk=af.Model(ag.lp_linear.Exponential),\n)\n```\n\nThe common three-stage pattern uses all of it: fit the bulge; fix it and fit the disk; then free\nboth from the second result's narrowed priors for a final search where everything moves together.\nFreezing permanently is a real bias risk, because a bulge fitted without a disk absorbs some of\nthe disk's light — so the third stage is not optional if the decomposition is the result you are\nquoting.\n\n## Branch — where `sigma` comes from, and its two traps\n\n`model_centred` reads each parameter's width from the `width_modifier` field of its entry in the\n`priors` config (`autogalaxy_assistant:config/priors/`, mapped in\n[`../wiki/core/api/configuration.md`](../wiki/core/api/configuration.md)). Two forms:\n\n- **Absolute** — `sigma` is the config value directly. For a linear `Sersic`, `sersic_index`\n carries `Absolute: 1.5`, each `centre` component `Absolute: 0.05`, and each `ell_comps`\n component `Absolute: 0.2`.\n- **Relative** — `sigma` is that fraction of the inferred value. `effective_radius` carries\n `Relative: 1.0`.\n\nThe reasoning behind which is which is worth understanding, because it tells you when to override.\nA relative width on a centre makes no sense: a galaxy centred near `(0.0, 0.0)` would get a sigma\nnear zero and the next search could not move it at all. An absolute width on an `intensity` makes\nno sense either, because intensity depends on units, exposure and brightness, so no single number\ngeneralises. Hence absolute centres and relative radii.\n\nTwo traps follow directly, and both are worth stating to a user before they hit them:\n\n**Relative widths break on parameters that can be negative or zero.**\n`model_centred_relative(r=...)` applies one relative width to *every* parameter, including\n`ell_comps`, whose median is legitimately near zero and often negative. That yields a negative\n`sigma` and raises rather than silently misbehaving — which is the good outcome, but it does mean\nthe blanket relative form is unusable on a general light-profile model. Use `model_centred`\n(per-parameter config widths), or `model_centred_absolute` where a single absolute width is\ndefensible for the parameters you are passing.\n\n**The bounded variant does not inherit the parameter's physical limits.**\n`model_centred_max_lh_bounded(b=...)` builds a `UniformPrior` at `mean ± b` regardless of the\nparameter's configured limits, so a `sersic_index` inferred near its ceiling of 5.0 can come back\nwith an upper limit above 5.0. Set the bound with the parameter's range in mind, or clamp the\nprior yourself afterwards.\n\nThe width you want is a genuine trade-off with no default that is right everywhere: wide enough\nthat a better nearby solution can still be found, narrow enough that the search is not doing\nsearch-1's work over again. The shipped `width_modifier` values are a considered balance rather\nthan a physical truth, and overriding them for one parameter you understand well is normal.\n\n## Branch — when chaining is the wrong tool\n\nChaining adds a failure mode that a single search does not have: **a wrong early result narrows a\nlater prior around the wrong place, and the later search never looks anywhere else.** The final\nposterior then looks tight and well-behaved and is simply wrong. Three situations where a single\nsearch is better:\n\n- **The single search works and is merely slow.** Reach for a faster sampler, a linear light\n profile, JAX or a GPU first ([`ag_configure_search`](./ag_configure_search.md),\n [`ag_run_search`](./ag_run_search.md)). Complexity you do not need is complexity that can be\n wrong.\n- **The early model is not a subset of the late one.** Prior passing assumes the parameter means\n something similar in both searches. Passing a `Sersic`'s parameters into an `Exponential`, or a\n parametric component's into a pixelised one, is either an error or meaningless.\n- **The parameter you fixed early is the one you are measuring.** If a bulge fitted without a disk\n is the number going in the paper, do not chain to a frozen bulge — chain to a narrowed one and\n let the final search move it.\n\nAlways inspect the intermediate result rather than trusting the chain. `result_1.info`, and\n`model.info` inside search 2's output folder, are the two things to read before believing the\nfinal number.\n\n## Branch — the practical mechanics\n\n**One analysis, reused.** Build the `ag.AnalysisImaging` once, before search 1, and pass the same\nobject to every search — unless you are deliberately changing the data between stages (a smaller\nmask early, the full one late), in which case say so explicitly, because the log likelihoods are\nthen not comparable across stages.\n\n**Naming.** One `path_prefix` for the chain, and `name=\"search[1]__\"` per stage. The bracket\nconvention is the workspace's and it sorts correctly; the `__` suffix is what makes an\noutput tree readable a month later.\n\n**`unique_tag`.** Keep it identical across the chain's searches, since it identifies the *dataset*.\nEach stage still lands in its own folder because `name` differs. And the identifier trap from\n[`ag_configure_search`](./ag_configure_search.md) applies to every stage: it does not hash your\ndata's pixel values, so if you swap datasets without changing `unique_tag`, every search in the\nchain silently returns the previous galaxy's result.\n\n**Smoke test the whole chain, not one search.** A chain's characteristic bug is a mis-typed\nattribute path in the passing expression, and that only fires at the second search:\n\n```bash\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/chained_fit.py\n```\n\nLevel 1 rather than level 2 here: level 1 runs a real (tiny) search at each stage, so a `Result`\nexists with samples for the next stage to pass from. Level 2 bypasses the sampler and leaves the\nchain nothing meaningful to narrow around. The levels are\n[`../wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md), and the priors a\ntest-mode chain produces are wiring evidence only — never quote them.\n\n## Combine\n\n- [`ag_configure_search`](./ag_configure_search.md) — cheap settings for early searches and\n accurate ones for the last; also the `unique_tag` semantics every stage inherits.\n- [`ag_run_search`](./ag_run_search.md) — driving each stage and reading its output folder.\n- [`ag_build_imaging_model`](./ag_build_imaging_model.md) — composing the models the chain steps\n between, including prior customisation by hand when you want to override a passed width.\n- [`ag_multi_galaxy_and_cluster`](./ag_multi_galaxy_and_cluster.md) — adding galaxies one at a\n time is the most common real use of chaining.\n- [`ag_multi_dataset`](./ag_multi_dataset.md) — its one-by-one branch is a chain across datasets\n rather than across model complexity.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) — when a single search lands somewhere\n unphysical, which is the diagnosis that most often leads here.\n- `ag_pixelization` — a smooth-profile fit chained into a pixelised one is a natural pairing,\n because the pixelisation wants a decent light model to start from.\n\nWhen a chain is worth keeping, offer (default-yes) to record it in a dated\n`wiki/project/YYYY-MM-DD-.md` entry: why the fit was split, what each stage fitted, what was\npassed as a narrowed prior versus fixed as an instance, and the shared output prefix — per\n[`_style.md`](./_style.md) property #5. The split and the passing decisions are the reasoning a\nreader will want, and they are invisible in the final `model.results`.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Search chaining](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_6_search_chaining.ipynb):\n fit a neighbouring galaxy first, then fix its geometry while refining the target.\n `chapter_optional/tutorial_prior_passing` explains historical prior narrowing, not a recommended next step;\n `chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy` applies the ideas to blended galaxies.\n- **General reference** — [RTD: Configs](https://pyautogalaxy.readthedocs.io/en/latest/general/configs.html):\n how the config files are laid out and looked up — the `priors` tree is where each parameter's\n `width_modifier` lives, and hence where a passed prior's `sigma` comes from.\n- **Experienced PyAutoGalaxy user** — [workspace: guides/modeling/chaining.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/guides/modeling/chaining.py):\n the API overview this skill is grounded in, with its own long discussion of absolute versus\n relative widths.\n\n## Agent procedural checklist\n\n1. Ask whether the single search is failing or merely slow; recommend a faster search before a\n chain when it is only slow.\n2. Choose the split with the user and say what each stage buys — dimensionality, settings, or a\n cheap approximation.\n3. Build the dataset and one `ag.AnalysisImaging` before search 1 and reuse it, or state\n explicitly why a stage uses different data.\n4. Write the whole chain into one script under one `path_prefix`, with `search[N]__` names.\n5. Use `result.model_centred` (or a `model_centred_*` variant) to narrow, `result.instance` to\n fix, and `result.model` only when you deliberately want the original priors back.\n6. Verify what you built: print the passed prior's type, and read `model.info` in the later\n search's output folder.\n7. Do not use `model_centred_relative` on a model containing `ell_comps` or a centre — it raises\n on a negative median.\n8. Inspect `result_1.info` before trusting anything downstream of it.\n9. If a component is frozen mid-chain, plan the final stage that frees it again before quoting its\n parameters.\n10. Validate the whole chain with `PYAUTO_TEST_MODE=1` (not 2 — the chain needs samples to pass).\n11. Offer the `wiki/project/` entry recording the split and the passing decisions.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/scripts/README.md b/scripts/README.md index e54ca64..c22eaa6 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -4,9 +4,10 @@ The `HowToGalaxy` folder contains **HowToGalaxy** lectures, which teach a new us - `chapter_1_introduction`: An introduction to galaxy morphology and structure using **PyAutoGalaxy**. - `chapter_2_modeling`: How to model galaxies, with data, models, Analysis objects and searches. -- `chapter_3_pixelizations`: How to perform pixelized reconstructions of a galaxy. +- `chapter_3_pixelizations`: Reconstruct complex galaxy light, choose regularization using Bayesian + evidence, diagnose fit problems and adapt the mesh and smoothing. - `chapter_4_scaling_up_galaxies`: How to scale up modeling to multiple galaxies, from blended pairs to cluster fields. -- `chapter_optional`: Optional tutorials. +- `chapter_optional`: Alternative searches, runtime and historical prior passing. - `simulators`: Scripts used to simulate the galaxy datasets fitted throughout the **HowToGalaxy** lectures. # Full Explanation @@ -95,15 +96,15 @@ fit CCD imaging data of a galaxy with a model. At the end, you'll understand: **Using an inversion to perform a pixelized morphology reconstruction** -In chapter 3, we'll learn how to reconstruct the morphological features of a galaxy using a pixel-grid, ensuring -that we can fit an accurate model to galaxies with complex and irregular morphologies. You'll learn how to: +In chapter 3, we'll reconstruct complex galaxy light using a pixel-grid, compare reconstructions using Bayesian +evidence, and investigate where the mesh and smoothing limit the fit. You'll learn how to: -1. Pixelize a galaxy reconstruction into pixels. -2. Perform a linear inversion using this pixelization to reconstruct the galaxy's light. -3. Apply a smoothness prior on the galaxy reconstruction, called regularization. -4. Apply smoothing within a Bayesian framework to objectively quantify the reconstruction's complexity. -5. Write down the linear algebra and Bayesian evidence equations that underpin the whole framework. -6. Use these features to fit a model via non-linear searches. +1. Connect reconstruction mesh points to image pixels through mappings. +2. Solve for the galaxy's brightness using a linear inversion. +3. Apply regularization and compare log evidences to choose its strength. +4. Diagnose compact-galaxy fit problems that remain after choosing the regularization coefficient. +5. Combine Delaunay meshes, Hilbert brightness adaptation and adaptive Split regularization. +6. Fit a smooth analytic light component alongside a pixelization. # OVERVIEW OF CHAPTER 4 (Advanced) diff --git a/scripts/chapter_1_introduction/README.md b/scripts/chapter_1_introduction/README.md index 49f18ad..54173cc 100644 --- a/scripts/chapter_1_introduction/README.md +++ b/scripts/chapter_1_introduction/README.md @@ -4,14 +4,14 @@ In chapter 1, we introduce you to galaxies, the light they emit and the core **P # Files -- [Tutorial 0: Visualization](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_1_introduction/tutorial_0_visualization.ipynb) — Setting up **PyAutoGalaxy**'s visualization library. +- [Tutorial 0: Visualization](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_0_visualization.ipynb) — Setting up **PyAutoGalaxy**'s visualization library. -- [Tutorial 1: Grids And Galaxies](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb) — How grids of (y,x) coordinates are used to create images of galaxies that ultimately quantify their morphology. +- [Tutorial 1: Grids And Galaxies](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb) — How grids of (y,x) coordinates are used to create images of galaxies that ultimately quantify their morphology. -- [Tutorial 2: Data](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_1_introduction/tutorial_2_data.ipynb) — Simulating and inspecting telescope imaging data of a galaxy, for example from the Hubble Space Telescope. +- [Tutorial 2: Data](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_2_data.ipynb) — Simulating and inspecting telescope imaging data of a galaxy, for example from the Hubble Space Telescope. -- [Tutorial 3: Fitting](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_1_introduction/tutorial_3_fitting.ipynb) — How to fit imaging data of a galaxy and quantify whether a fit is good or bad. +- [Tutorial 3: Fitting](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_3_fitting.ipynb) — How to fit imaging data of a galaxy and quantify whether a fit is good or bad. -- [Tutorial 4: Methods](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_1_introduction/tutorial_4_methods.ipynb) — An overview of the different methods used to fit galaxies with. +- [Tutorial 4: Methods](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_4_methods.ipynb) — An overview of the different methods used to fit galaxies with. -- [Tutorial 5: Summary](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_1_introduction/tutorial_5_summary.ipynb) — A summary of the chapter. +- [Tutorial 5: Summary](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_5_summary.ipynb) — A summary of the chapter. diff --git a/scripts/chapter_4_scaling_up_galaxies/README.md b/scripts/chapter_4_scaling_up_galaxies/README.md index 20a1455..8dcd4ad 100644 --- a/scripts/chapter_4_scaling_up_galaxies/README.md +++ b/scripts/chapter_4_scaling_up_galaxies/README.md @@ -5,8 +5,8 @@ systems, and cluster fields. # Files -- [Tutorial 1: Extra Galaxies](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_4_scaling_up_galaxies/tutorial_1_extra_galaxies.ipynb) — Handling nearby galaxies by scaling their light out of the fit or modeling them explicitly. +- [Tutorial 1: Extra Galaxies](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_4_scaling_up_galaxies/tutorial_1_extra_galaxies.ipynb) — Handling nearby galaxies by scaling their light out of the fit or modeling them explicitly. -- [Tutorial 2: Multi Galaxy](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy.ipynb) — Modeling two or more blended galaxies simultaneously and the degeneracies this creates. +- [Tutorial 2: Multi Galaxy](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy.ipynb) — Modeling two or more blended galaxies simultaneously and the degeneracies this creates. -- [Tutorial 3: Cluster](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.11.1.1/notebooks/chapter_4_scaling_up_galaxies/tutorial_3_cluster.ipynb) — Modeling a cluster field's BCG and catalogue-driven member population. +- [Tutorial 3: Cluster](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_4_scaling_up_galaxies/tutorial_3_cluster.ipynb) — Modeling a cluster field's BCG and catalogue-driven member population. diff --git a/start_here.ipynb b/start_here.ipynb index 9fa134b..933138f 100644 --- a/start_here.ipynb +++ b/start_here.ipynb @@ -152,7 +152,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 (start_here.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_build_imaging_model\n\n---\nname: ag_build_imaging_model\ndescription: Compose the galaxy model for a CCD imaging fit \u2014 an `af.Model` / `af.Collection` tree of light profiles on one or more galaxies, plus the `ag.AnalysisImaging` that scores it against a loaded dataset. Covers a single Sersic, a bulge-plus-disk decomposition, why `ag.lp_linear` profiles are the default, a Multi-Gaussian Expansion for irregular morphology, prior customisation, pairing / fixing / assertions, `ag.DatasetModel` for a residual sky or astrometric offset, modelling contaminating extra galaxies with fixed centres, and checking the model with `print(model.info)` and a single likelihood evaluation before spending a search on it. Use once a dataset is loaded and masked. Requires the real-data inspection gate to have been satisfied first (`ag_prepare_imaging_data`). Not for choosing or configuring the search (`ag_configure_search`), not for running the fit, and not for visibility-plane data.\n---\n\n# Composing an imaging galaxy model\n\nThe model is your statement of what this galaxy *could* be: how many components, with what\nfunctional forms, which parameters free and which fixed, and what prior on each. It is the\nhalf of the fit you are responsible for \u2014 the search only explores what you wrote down. A\nmodel too simple leaves structure in the residuals and biases every parameter that has to\nabsorb it; a model too complex has a parameter space the search cannot map, and returns wide\nerrors or a local maximum. Getting this right is most of galaxy morphology.\n\nA fit has exactly two halves: the **model** says what could be true, and the **analysis**\nholds a dataset and knows how to score a proposal against it. A search shuttles between them:\n\n```python\nresult = search.fit(model=model, analysis=analysis)\n```\n\nEverything in this skill builds one of those two arguments. The canonical script is\n`autogalaxy_workspace:scripts/imaging/modeling.py`; the API page is\n[`../wiki/core/api/analysis_objects.md`](../wiki/core/api/analysis_objects.md), and the\nsystematic composition reference is\n`autogalaxy_workspace:scripts/guides/modeling/cookbook.py`.\n\n## Before you compose \u2014 the gate\n\nIf the dataset is **real observational data**, confirm the inspection gate has been\nsatisfied: that the user has seen `dataset.png`, and that both (a) contaminating extra\ngalaxies / foreground stars / artefacts and (b) the mask extent were settled from that look.\nIf either is still open, stop and do it in\n[`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md) first \u2014 composing a model over data\nwith an unaddressed contaminant, or a mask left at a silent default, produces a confident\nwrong answer rather than an obvious failure. Simulated data is exempt.\n\n## Ask\n\n- *\"One galaxy, or several whose light blends?\"* The only structural choice. This skill\n assumes a single target with optional contaminating neighbours; two or more co-dominant\n galaxies is a different skill,\n [`ag_multi_galaxy_and_cluster`](./ag_multi_galaxy_and_cluster.md).\n- *\"A single Sersic to start, or straight to a bulge-plus-disk decomposition?\"* Single Sersic\n first is almost always the right answer, even when you want the decomposition: it converges\n fast, tells you the galaxy's overall size and concentration, and gives you something to\n compare the two-component fit against.\n- *\"Is the morphology smooth, or irregular \u2014 spiral arms, asymmetry, a merger?\"* Smooth means\n Sersic-family profiles. Irregular means a Multi-Gaussian Expansion, and beyond that a\n pixelised reconstruction (`ag_pixelization`, not yet written).\n- *\"What redshift?\"* Even a ballpark value is enough; it is needed only for physical-unit\n conversions, not for the fit itself.\n- *\"Has the sky background been subtracted, and do you trust that subtraction?\"* If the faint\n outer envelope is what you care about, the answer decides whether you need a\n `ag.DatasetModel`.\n\n## Branch \u2014 a single Sersic\n\nThe minimum viable model, and the right first fit for almost any galaxy.\n\n```python\n\"\"\"\nGalaxy Structure: Single Sersic\n===============================\n\nCompose and check a one-component galaxy model for CCD imaging: an elliptical Sersic profile\nwhose effective radius and Sersic index measure the galaxy's size and central concentration.\nThis is the first fit to run on any galaxy \u2014 it converges quickly, and its inferred size and\nconcentration are the reference every more complex model is judged against.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the masked, over-sampled imaging dataset produced during preparation.\n- **Model:** Compose the galaxy's light as a single linear Sersic profile.\n- **Check:** Print the model and evaluate the likelihood once before committing to a search.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPIXEL_SCALES = 0.1\nMASK_RADIUS = 2.5\n\n\"\"\"\n__Dataset__\n\nThe dataset arrives already prepared: loaded from FITS, contaminant noise scaled, masked to\nthe radius chosen by inspecting the data, and over-sampled adaptively in the centre where the\nprofile's intensity gradient is steep. All four decisions belong to data preparation rather\nthan to the model, and all four change the answer, so they are reproduced here rather than\nhidden (`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\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_lp=over_sample_size)\n\n\"\"\"\n__Model__\n\nA single elliptical Sersic. Its `sersic_index` is free, so the fit itself decides whether this\ngalaxy is a de Vaucouleurs-like spheroid (n ~ 4) or an exponential disk (n ~ 1) rather than\nyou asserting it, and `effective_radius` is the radius containing half the profile's light.\nThe profile is elliptical via `ell_comps` rather than an axis-ratio and position-angle pair,\nwhich avoids the periodic-boundary pathology a position angle creates for a non-linear search\n(`PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py`).\n\nWe use `ag.lp_linear` rather than `ag.lp`: a linear light profile has its `intensity` solved\nanalytically by a linear inversion inside each likelihood evaluation instead of being sampled\nas a free parameter. The profile is identical; one dimension simply leaves the search's\nparameter space, which improves speed, accuracy and reliability at no cost. Every workspace\nmodeling example uses them by default\n(`PyAutoGalaxy:autogalaxy/profiles/light/linear/sersic.py`).\n\n`af.Model` wraps the class so its parameters become free; `af.Collection` groups models into\nthe named tree the analysis expects \u2014 the `galaxies` collection is a convention the analysis\nrelies on, not a stylistic choice (`PyAutoFit:autofit/mapper/prior_model/collection.py`).\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\n`model.info` prints every free parameter with its prior, and it is the cheapest sanity check\navailable: a model subtly larger, smaller or more constrained than intended shows up here\nrather than after hours of searching. Evaluating the likelihood once at the prior medians is\nthe second cheap check \u2014 it proves the model, dataset and analysis are mutually compatible\nand that a finite likelihood comes back, without paying for inference.\n\n`ag.AnalysisImaging` holds the dataset and defines the `log_likelihood_function` the search\ncalls. `use_jax=True` is the default and is what makes the gradient-based searches possible\nat all; pass `use_jax=False` when debugging, because NumPy tracebacks are far easier to read\nthan JAX ones (`PyAutoGalaxy:autogalaxy/imaging/model/analysis.py`).\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)\n\nprint(f\"log likelihood at prior medians: {float(log_likelihood):.2f}\")\n```\n\nThat composes to **N = 6** free parameters: centre (2), `ell_comps` (2), `effective_radius`,\n`sersic_index` \u2014 with `intensity` solved rather than sampled. Six parameters is a parameter\nspace any search handles comfortably.\n\nWhat each profile represents and when to reach for which is\n[`../wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md); the\n`ell_comps` convention has its own section there. The catalogue of every available profile,\nby module, is\n[`../wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md).\n\n## Branch \u2014 bulge plus disk\n\nThe decomposition galaxy morphology usually wants, because the ratio of the two components'\ninferred luminosities is the bulge-to-total light ratio. Adapted from\n`autogalaxy_workspace:scripts/imaging/modeling.py`.\n\n```python\nbulge = af.Model(ag.lp_linear.Sersic)\ndisk = af.Model(ag.lp_linear.Exponential)\n\nbulge.centre = disk.centre\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\n```\n\nN = 9. The physics is in the asymmetry between the two components: the bulge's\n`sersic_index` is free so it can find a concentrated spheroid, while the `Exponential` disk\nhas n fixed at 1 by construction. That contrast is what makes the decomposition identifiable\nat all \u2014 two free Sersics on the same galaxy are largely degenerate, and the fit will happily\ntrade light between them.\n\n`bulge.centre = disk.centre` is the load-bearing line. It asserts the two components are\nconcentric, which is physically reasonable for most galaxies and removes two parameters\nrather than fitting the same centre twice. Drop it only if you have a specific reason to\nbelieve the components are offset \u2014 a lopsided or interacting system \u2014 and expect a harder\nsearch when you do.\n\nThe attribute names are entirely yours. `bulge`, `disk`, `bar`, `clump`, `bulge_0` \u2014 whatever\nyou pass to `af.Model(ag.Galaxy, ...)` is the key you address afterwards\n(`model.galaxies.galaxy.bulge.sersic_index`), because `ag.Galaxy` takes `redshift` and then\narbitrary keyword arguments (`PyAutoGalaxy:autogalaxy/galaxy/galaxy.py`). Name them for what\nthey measure.\n\nThere is a concise form when you do not need to touch the components first \u2014 passing a\nprofile *class* rather than an `af.Model` promotes it automatically\n(`autogalaxy_workspace:scripts/guides/modeling/cookbook.py`):\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 bar=ag.lp_linear.Sersic,\n)\n```\n\nHow several profiles and galaxies compose into what is actually fitted is\n[`../wiki/core/concepts/galaxies.md`](../wiki/core/concepts/galaxies.md).\n\n## Branch \u2014 a Multi-Gaussian Expansion, for morphology a Sersic cannot fit\n\nWhen the galaxy is irregular, asymmetric or has structure a smooth profile leaves in the\nresiduals, decompose its light into tens of Gaussians instead. Because they are *linear*\nprofiles, all of their intensities are solved by the inversion, so a 20-Gaussian basis costs\nthe search almost nothing in dimensionality \u2014 it is far more flexible than a Sersic at a\n*lower* parameter count.\n\nThe composition is long and technical, so the library ships a helper:\n\n```python\nbulge = ag.model_util.mge_model_from(\n mask_radius=MASK_RADIUS,\n total_gaussians=20,\n centre_prior_is_uniform=True,\n)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/start_here.py`, where the MGE is the\n*recommended default* model \u2014 it balances speed, flexibility and accuracy well enough to fit\nthe vast majority of galaxies. N = 4: a shared centre and shared `ell_comps` across the\nbasis, with every `sigma` fixed on a logarithmic ladder from below the pixel scale to beyond\nthe galaxy's extent, and every intensity solved. `mask_radius` is what sets the outer end of\nthat ladder, so pass the radius you actually masked at.\n\nOther arguments worth knowing: `centre_fixed=(y, x)` pins the centre entirely (used for\ncontaminating neighbours, below), `gaussian_per_basis` splits the ladder into several bases\nwith independent ellipticities for a twisting galaxy, and `use_spherical=True` drops the\nellipticity. The physics of why fewer free parameters wins here is\n[`../wiki/core/concepts/linear_light_profiles_and_mge.md`](../wiki/core/concepts/linear_light_profiles_and_mge.md);\nthe orthonormal-basis alternative is\n[`../wiki/core/concepts/shapelets.md`](../wiki/core/concepts/shapelets.md). Both get their own\nskill in a later phase (`ag_basis_profiles`).\n\n## Branch \u2014 priors, pairing, fixing, assertions\n\nEvery parameter has a default prior from the configuration YAMLs\n([`../wiki/core/api/configuration.md`](../wiki/core/api/configuration.md)). Override one when\nyou know something the default cannot. Adapted from\n`autogalaxy_workspace:scripts/guides/modeling/cookbook.py`.\n\n```python\nbulge = af.Model(ag.lp_linear.Sersic)\n\nbulge.centre.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\nbulge.centre.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\nbulge.sersic_index = af.TruncatedGaussianPrior(\n mean=4.0, sigma=1.0, lower_limit=0.8, upper_limit=5.0\n)\n```\n\nThe centre priors say \"this galaxy is within 0.1\" of the image centre\", which is true if the\ndata was cut out around it and is worth asserting because it removes a large volume of\nparameter space the search would otherwise wander through. The `sersic_index` prior says\n\"this is an early-type\" \u2014 and that is a genuine statistical commitment, not a convenience:\nit changes the posterior and therefore the errors you quote. If you want to *guide* a search\nwithout moving what you infer, the start-point API in\n[`ag_configure_search`](./ag_configure_search.md) is the right tool instead.\n\nThree other levers reduce complexity without adding a prior:\n\n```python\nbulge = af.Model(ag.lp_linear.Sersic)\ndisk = af.Model(ag.lp_linear.Exponential)\n\nbulge.centre = disk.centre # pair: one centre, not two (N -= 2)\nbulge.sersic_index = 4.0 # fix: a de Vaucouleurs bulge (N -= 1)\nbulge.effective_radius = disk.effective_radius - 0.5 # offset: a relation, not a parameter\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nmodel.add_assertion(\n model.galaxies.galaxy.bulge.effective_radius\n < model.galaxies.galaxy.disk.effective_radius\n)\n```\n\nAssertions are added **after** the components are collected, and they are the cleanest way to\nrule out the unphysical solution a decomposition is prone to: a \"bulge\" that is larger than\nits disk, which is the search relabelling the two components rather than fitting them. A\nmodel can also be round-tripped through JSON with `model.dict()` and\n`af.Model.from_json(file=...)`, which is how you hand a model to a collaborator or edit one\nby hand.\n\n## Branch \u2014 nuisance parameters of the data, not the galaxy\n\nSome free parameters belong to the dataset: a residual background sky, a sub-pixel\nastrometric offset, a small rotation. These live in `ag.DatasetModel` and sit alongside\n`galaxies` rather than inside it. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/sky_background/modeling.py`.\n\n```python\ndataset_model = af.Model(ag.DatasetModel)\ndataset_model.background_sky_level = af.UniformPrior(lower_limit=0.0, upper_limit=5.0)\n\nmodel = af.Collection(\n galaxies=af.Collection(galaxy=galaxy), dataset_model=dataset_model\n)\n```\n\nYou **must** set the sky prior by hand \u2014 unlike a light profile's priors, the right range\ndepends entirely on your data's units and depth, so no default can be correct. This costs one\nparameter and matters for exactly the measurement galaxy structure cares most about: the\nfaint outer envelope that sets `effective_radius` and `sersic_index`. It is worth including\neven on data you believe is sky-subtracted, precisely to check that belief. The other fields\nare `grid_offset=(y, x)` and `grid_rotation_angle`, which earn their keep in multi-band work\nwhere bands are not perfectly registered. Concept page:\n[`../wiki/core/concepts/sky_background_and_operated_profiles.md`](../wiki/core/concepts/sky_background_and_operated_profiles.md).\n\n## Branch \u2014 modelling contaminating extra galaxies\n\nWhen a neighbour's light genuinely overlaps the target's, neither masking nor noise scaling\ncan separate them without removing signal you need \u2014 so model it. The convention is that its\ncentre is **fixed** to a value measured from the data, leaving its other parameters free.\nAdapted from `autogalaxy_workspace:scripts/imaging/features/extra_galaxies/modeling.py`.\n\n```python\nextra_galaxies_centres = ag.from_json(\n file_path=DATASET_PATH / \"extra_galaxies_centres.json\"\n)\n\nextra_galaxies_list = []\n\nfor extra_galaxy_centre in extra_galaxies_centres:\n\n extra_galaxy = af.Model(\n ag.Galaxy, redshift=0.5, bulge=ag.lp_linear.SersicSph\n )\n extra_galaxy.bulge.centre = extra_galaxy_centre\n\n extra_galaxies_list.append(extra_galaxy)\n\nmodel = af.Collection(\n galaxies=af.Collection(galaxy=galaxy),\n extra_galaxies=af.Collection(extra_galaxies_list),\n)\n```\n\nThe centres come from the JSON written during data preparation. A spherical `SersicSph` costs\nabout two free parameters per neighbour once its intensity is solved \u2014 cheap enough that a\nhandful of companions is affordable. For irregular or asymmetric companions, swap the\nspherical Sersic for an MGE with a pinned centre,\n`ag.model_util.mge_model_from(mask_radius=MASK_RADIUS, total_gaussians=10,\ncentre_fixed=tuple(extra_galaxy_centre))`, which costs the same in the linear limit while\nbeing far more flexible. Note that `extra_galaxies` is its own top-level collection, not a\nmember of `galaxies`. When to model versus mask versus scale is\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Wrap with an analysis, and check it before you search\n\n```python\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n```\n\nSource: `PyAutoGalaxy:autogalaxy/imaging/model/analysis.py`. The full surface is\n`AnalysisImaging(dataset, adapt_images=None, cosmology=None, settings=None,\ntitle_prefix=None, use_jax=True)`. Pass `cosmology=ag.cosmo.Planck15()` when a derived\nquantity needs angular-to-physical conversion; `settings=ag.Settings(...)` only to override\nan inversion or linear-solver default; `adapt_images` only for an adaptive pixelised\nreconstruction.\n\nTwo checks before you hand this to a search, both cheap and both catching a different class\nof mistake:\n\n```python\nprint(model.info)\n\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\n`model.info` catches a *model* mistake \u2014 a parameter you thought was fixed, a prior wider\nthan intended, a component you added twice. `print_vram_use` catches a *resource* mistake:\nJAX must hold the whole batched likelihood in GPU memory, and this reports the estimate in\n20-30 seconds rather than letting you discover the limit as an out-of-memory error mid-compile\n(`autogalaxy_workspace:scripts/imaging/modeling.py` quotes ~0.027 GB for an MGE on a\nlow-resolution dataset, and more than 1 GB \u2014 occasionally more than 10 GB \u2014 for a pixelised\nreconstruction at high resolution). Add the single likelihood evaluation from the first branch\nwhen you have changed anything structural; a finite number back means the three pieces fit\ntogether.\n\n## Combine \u2014 where this hands off\n\n- **Pick and configure the search** \u2192 [`ag_configure_search`](./ag_configure_search.md).\n `MultiStartProdigy` for a fast check that this model and dataset are sensible, `Nautilus`\n when you need errors you can quote.\n- **Run the fit** \u2192 the run-search skill (`ag_run_search`), which owns\n `search.fit(model=model, analysis=analysis)` and the output folder.\n- **The search fails, stalls or returns something unphysical** \u2192 the fit-debugging skill\n (`ag_debug_fit_failure`). Nine times in ten the fix is here rather than in the search: a\n model too complex for the data, an unpaired centre, a missing assertion, or a contaminant\n that should have been handled during preparation.\n- **A smooth profile leaves structure in the residuals** \u2192 the basis-profile and pixelisation\n skills (`ag_basis_profiles`, `ag_pixelization`) in a later phase; the MGE branch above is\n the first step in that direction and often enough on its own.\n- **Several datasets of the same galaxy** \u2192 the multi-dataset skill (`ag_multi_dataset`).\n Datasets are combined through a factor graph \u2014 one `af.AnalysisFactor` per dataset, folded\n into an `af.FactorGraphModel`; see\n [`../wiki/core/concepts/multi_wavelength.md`](../wiki/core/concepts/multi_wavelength.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry: the components you\nchose, the parameters you fixed or paired, and *why*, are the modelling assumptions a referee\nwill ask about.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [HowToGalaxy: Realism and complexity](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_3_realism_and_complexity.ipynb):\n the trade-off at the heart of this skill \u2014 what happens when a model is too simple for the\n data, and what happens when it is too complex for the search.\n- **General reference** \u2014 [RTD: Model cookbook](https://pyautogalaxy.readthedocs.io/en/latest/general/model_cookbook.html):\n the systematic reference for `af.Model` and `af.Collection` \u2014 multiple components, multiple\n galaxies, prior customisation, pairing, and many-profile bases.\n- **Experienced PyAutoGalaxy user** \u2014 [workspace: imaging/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/modeling.py):\n the canonical bulge-plus-disk fit end to end, including the VRAM check, run-time estimation\n and the annotated output-folder layout.\n\n## Agent procedural checklist\n\n1. On real data, confirm the inspection gate was satisfied; if not, return to\n `ag_prepare_imaging_data`.\n2. Ask: one galaxy or several; single Sersic or a decomposition; smooth or irregular.\n3. Prefer `ag.lp_linear` over `ag.lp` \u2014 the intensity is solved, not sampled.\n4. Start with a single Sersic even when the goal is a decomposition; keep it as the reference.\n5. Pair concentric centres, fix what physics fixes, and add assertions that rule out the\n relabelling solution.\n6. `print(model.info)` and check `total_free_parameters` against what you intended.\n7. Build `ag.AnalysisImaging`, run one likelihood evaluation, and `print_vram_use` before a\n GPU run.\n8. Save the script to `scripts/`, hand off to `ag_configure_search`, and offer the\n `wiki/project/` entry recording the modelling assumptions.\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 (start_here.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_build_imaging_model\n\n---\nname: ag_build_imaging_model\ndescription: Compose the galaxy model for a CCD imaging fit \u2014 an `af.Model` / `af.Collection` tree of light profiles on one or more galaxies, plus the `ag.AnalysisImaging` that scores it against a loaded dataset. Covers a single Sersic, a bulge-plus-disk decomposition, why `ag.lp_linear` profiles are the default, a Multi-Gaussian Expansion for irregular morphology, prior customisation, pairing / fixing / assertions, `ag.DatasetModel` for a residual sky or astrometric offset, modelling contaminating extra galaxies with fixed centres, and checking the model with `print(model.info)` and a single likelihood evaluation before spending a search on it. Use once a dataset is loaded and masked. Requires the real-data inspection gate to have been satisfied first (`ag_prepare_imaging_data`). Not for choosing or configuring the search (`ag_configure_search`), not for running the fit, and not for visibility-plane data.\n---\n\n# Composing an imaging galaxy model\n\nThe model is your statement of what this galaxy *could* be: how many components, with what\nfunctional forms, which parameters free and which fixed, and what prior on each. It is the\nhalf of the fit you are responsible for \u2014 the search only explores what you wrote down. A\nmodel too simple leaves structure in the residuals and biases every parameter that has to\nabsorb it; a model too complex has a parameter space the search cannot map, and returns wide\nerrors or a local maximum. Getting this right is most of galaxy morphology.\n\nA fit has exactly two halves: the **model** says what could be true, and the **analysis**\nholds a dataset and knows how to score a proposal against it. A search shuttles between them:\n\n```python\nresult = search.fit(model=model, analysis=analysis)\n```\n\nEverything in this skill builds one of those two arguments. The canonical script is\n`autogalaxy_workspace:scripts/imaging/modeling.py`; the API page is\n[`../wiki/core/api/analysis_objects.md`](../wiki/core/api/analysis_objects.md), and the\nsystematic composition reference is\n`autogalaxy_workspace:scripts/guides/modeling/cookbook.py`.\n\n## Before you compose \u2014 the gate\n\nIf the dataset is **real observational data**, confirm the inspection gate has been\nsatisfied: that the user has seen `dataset.png`, and that both (a) contaminating extra\ngalaxies / foreground stars / artefacts and (b) the mask extent were settled from that look.\nIf either is still open, stop and do it in\n[`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md) first \u2014 composing a model over data\nwith an unaddressed contaminant, or a mask left at a silent default, produces a confident\nwrong answer rather than an obvious failure. Simulated data is exempt.\n\n## Ask\n\n- *\"One galaxy, or several whose light blends?\"* The only structural choice. This skill\n assumes a single target with optional contaminating neighbours; two or more co-dominant\n galaxies is a different skill,\n [`ag_multi_galaxy_and_cluster`](./ag_multi_galaxy_and_cluster.md).\n- *\"A single Sersic to start, or straight to a bulge-plus-disk decomposition?\"* Single Sersic\n first is almost always the right answer, even when you want the decomposition: it converges\n fast, tells you the galaxy's overall size and concentration, and gives you something to\n compare the two-component fit against.\n- *\"Is the morphology smooth, or irregular \u2014 spiral arms, asymmetry, a merger?\"* Smooth means\n Sersic-family profiles. Irregular means a Multi-Gaussian Expansion, and beyond that a\n pixelised reconstruction (`ag_pixelization`, not yet written).\n- *\"What redshift?\"* Even a ballpark value is enough; it is needed only for physical-unit\n conversions, not for the fit itself.\n- *\"Has the sky background been subtracted, and do you trust that subtraction?\"* If the faint\n outer envelope is what you care about, the answer decides whether you need a\n `ag.DatasetModel`.\n\n## Branch \u2014 a single Sersic\n\nThe minimum viable model, and the right first fit for almost any galaxy.\n\n```python\n\"\"\"\nGalaxy Structure: Single Sersic\n===============================\n\nCompose and check a one-component galaxy model for CCD imaging: an elliptical Sersic profile\nwhose effective radius and Sersic index measure the galaxy's size and central concentration.\nThis is the first fit to run on any galaxy \u2014 it converges quickly, and its inferred size and\nconcentration are the reference every more complex model is judged against.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the masked, over-sampled imaging dataset produced during preparation.\n- **Model:** Compose the galaxy's light as a single linear Sersic profile.\n- **Check:** Print the model and evaluate the likelihood once before committing to a search.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPIXEL_SCALES = 0.1\nMASK_RADIUS = 2.5\n\n\"\"\"\n__Dataset__\n\nThe dataset arrives already prepared: loaded from FITS, contaminant noise scaled, masked to\nthe radius chosen by inspecting the data, and over-sampled adaptively in the centre where the\nprofile's intensity gradient is steep. All four decisions belong to data preparation rather\nthan to the model, and all four change the answer, so they are reproduced here rather than\nhidden (`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\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_lp=over_sample_size)\n\n\"\"\"\n__Model__\n\nA single elliptical Sersic. Its `sersic_index` is free, so the fit itself decides whether this\ngalaxy is a de Vaucouleurs-like spheroid (n ~ 4) or an exponential disk (n ~ 1) rather than\nyou asserting it, and `effective_radius` is the radius containing half the profile's light.\nThe profile is elliptical via `ell_comps` rather than an axis-ratio and position-angle pair,\nwhich avoids the periodic-boundary pathology a position angle creates for a non-linear search\n(`PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py`).\n\nWe use `ag.lp_linear` rather than `ag.lp`: a linear light profile has its `intensity` solved\nanalytically by a linear inversion inside each likelihood evaluation instead of being sampled\nas a free parameter. The profile is identical; one dimension simply leaves the search's\nparameter space, which improves speed, accuracy and reliability at no cost. Every workspace\nmodeling example uses them by default\n(`PyAutoGalaxy:autogalaxy/profiles/light/linear/sersic.py`).\n\n`af.Model` wraps the class so its parameters become free; `af.Collection` groups models into\nthe named tree the analysis expects \u2014 the `galaxies` collection is a convention the analysis\nrelies on, not a stylistic choice (`PyAutoFit:autofit/mapper/prior_model/collection.py`).\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\n`model.info` prints every free parameter with its prior, and it is the cheapest sanity check\navailable: a model subtly larger, smaller or more constrained than intended shows up here\nrather than after hours of searching. Evaluating the likelihood once at the prior medians is\nthe second cheap check \u2014 it proves the model, dataset and analysis are mutually compatible\nand that a finite likelihood comes back, without paying for inference.\n\n`ag.AnalysisImaging` holds the dataset and defines the `log_likelihood_function` the search\ncalls. `use_jax=True` is the default and is what makes the gradient-based searches possible\nat all; pass `use_jax=False` when debugging, because NumPy tracebacks are far easier to read\nthan JAX ones (`PyAutoGalaxy:autogalaxy/imaging/model/analysis.py`).\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)\n\nprint(f\"log likelihood at prior medians: {float(log_likelihood):.2f}\")\n```\n\nThat composes to **N = 6** free parameters: centre (2), `ell_comps` (2), `effective_radius`,\n`sersic_index` \u2014 with `intensity` solved rather than sampled. Six parameters is a parameter\nspace any search handles comfortably.\n\nWhat each profile represents and when to reach for which is\n[`../wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md); the\n`ell_comps` convention has its own section there. The catalogue of every available profile,\nby module, is\n[`../wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md).\n\n## Branch \u2014 bulge plus disk\n\nThe decomposition galaxy morphology usually wants, because the ratio of the two components'\ninferred luminosities is the bulge-to-total light ratio. Adapted from\n`autogalaxy_workspace:scripts/imaging/modeling.py`.\n\n```python\nbulge = af.Model(ag.lp_linear.Sersic)\ndisk = af.Model(ag.lp_linear.Exponential)\n\nbulge.centre = disk.centre\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\n```\n\nN = 9. The physics is in the asymmetry between the two components: the bulge's\n`sersic_index` is free so it can find a concentrated spheroid, while the `Exponential` disk\nhas n fixed at 1 by construction. That contrast is what makes the decomposition identifiable\nat all \u2014 two free Sersics on the same galaxy are largely degenerate, and the fit will happily\ntrade light between them.\n\n`bulge.centre = disk.centre` is the load-bearing line. It asserts the two components are\nconcentric, which is physically reasonable for most galaxies and removes two parameters\nrather than fitting the same centre twice. Drop it only if you have a specific reason to\nbelieve the components are offset \u2014 a lopsided or interacting system \u2014 and expect a harder\nsearch when you do.\n\nThe attribute names are entirely yours. `bulge`, `disk`, `bar`, `clump`, `bulge_0` \u2014 whatever\nyou pass to `af.Model(ag.Galaxy, ...)` is the key you address afterwards\n(`model.galaxies.galaxy.bulge.sersic_index`), because `ag.Galaxy` takes `redshift` and then\narbitrary keyword arguments (`PyAutoGalaxy:autogalaxy/galaxy/galaxy.py`). Name them for what\nthey measure.\n\nThere is a concise form when you do not need to touch the components first \u2014 passing a\nprofile *class* rather than an `af.Model` promotes it automatically\n(`autogalaxy_workspace:scripts/guides/modeling/cookbook.py`):\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 bar=ag.lp_linear.Sersic,\n)\n```\n\nHow several profiles and galaxies compose into what is actually fitted is\n[`../wiki/core/concepts/galaxies.md`](../wiki/core/concepts/galaxies.md).\n\n## Branch \u2014 a Multi-Gaussian Expansion, for morphology a Sersic cannot fit\n\nWhen the galaxy is irregular, asymmetric or has structure a smooth profile leaves in the\nresiduals, decompose its light into tens of Gaussians instead. Because they are *linear*\nprofiles, all of their intensities are solved by the inversion, so a 20-Gaussian basis costs\nthe search almost nothing in dimensionality \u2014 it is far more flexible than a Sersic at a\n*lower* parameter count.\n\nThe composition is long and technical, so the library ships a helper:\n\n```python\nbulge = ag.model_util.mge_model_from(\n mask_radius=MASK_RADIUS,\n total_gaussians=20,\n centre_prior_is_uniform=True,\n)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/start_here.py`, where the MGE is the\n*recommended default* model \u2014 it balances speed, flexibility and accuracy well enough to fit\nthe vast majority of galaxies. N = 4: a shared centre and shared `ell_comps` across the\nbasis, with every `sigma` fixed on a logarithmic ladder from below the pixel scale to beyond\nthe galaxy's extent, and every intensity solved. `mask_radius` is what sets the outer end of\nthat ladder, so pass the radius you actually masked at.\n\nOther arguments worth knowing: `centre_fixed=(y, x)` pins the centre entirely (used for\ncontaminating neighbours, below), `gaussian_per_basis` splits the ladder into several bases\nwith independent ellipticities for a twisting galaxy, and `use_spherical=True` drops the\nellipticity. The physics of why fewer free parameters wins here is\n[`../wiki/core/concepts/linear_light_profiles_and_mge.md`](../wiki/core/concepts/linear_light_profiles_and_mge.md);\nthe orthonormal-basis alternative is\n[`../wiki/core/concepts/shapelets.md`](../wiki/core/concepts/shapelets.md). Both get their own\nskill in a later phase (`ag_basis_profiles`).\n\n## Branch \u2014 priors, pairing, fixing, assertions\n\nEvery parameter has a default prior from the configuration YAMLs\n([`../wiki/core/api/configuration.md`](../wiki/core/api/configuration.md)). Override one when\nyou know something the default cannot. Adapted from\n`autogalaxy_workspace:scripts/guides/modeling/cookbook.py`.\n\n```python\nbulge = af.Model(ag.lp_linear.Sersic)\n\nbulge.centre.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\nbulge.centre.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\nbulge.sersic_index = af.TruncatedGaussianPrior(\n mean=4.0, sigma=1.0, lower_limit=0.8, upper_limit=5.0\n)\n```\n\nThe centre priors say \"this galaxy is within 0.1\" of the image centre\", which is true if the\ndata was cut out around it and is worth asserting because it removes a large volume of\nparameter space the search would otherwise wander through. The `sersic_index` prior says\n\"this is an early-type\" \u2014 and that is a genuine statistical commitment, not a convenience:\nit changes the posterior and therefore the errors you quote. If you want to *guide* a search\nwithout moving what you infer, the start-point API in\n[`ag_configure_search`](./ag_configure_search.md) is the right tool instead.\n\nThree other levers reduce complexity without adding a prior:\n\n```python\nbulge = af.Model(ag.lp_linear.Sersic)\ndisk = af.Model(ag.lp_linear.Exponential)\n\nbulge.centre = disk.centre # pair: one centre, not two (N -= 2)\nbulge.sersic_index = 4.0 # fix: a de Vaucouleurs bulge (N -= 1)\nbulge.effective_radius = disk.effective_radius - 0.5 # offset: a relation, not a parameter\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nmodel.add_assertion(\n model.galaxies.galaxy.bulge.effective_radius\n < model.galaxies.galaxy.disk.effective_radius\n)\n```\n\nAssertions are added **after** the components are collected, and they are the cleanest way to\nrule out the unphysical solution a decomposition is prone to: a \"bulge\" that is larger than\nits disk, which is the search relabelling the two components rather than fitting them. A\nmodel can also be round-tripped through JSON with `model.dict()` and\n`af.Model.from_json(file=...)`, which is how you hand a model to a collaborator or edit one\nby hand.\n\n## Branch \u2014 nuisance parameters of the data, not the galaxy\n\nSome free parameters belong to the dataset: a residual background sky, a sub-pixel\nastrometric offset, a small rotation. These live in `ag.DatasetModel` and sit alongside\n`galaxies` rather than inside it. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/sky_background/modeling.py`.\n\n```python\ndataset_model = af.Model(ag.DatasetModel)\ndataset_model.background_sky_level = af.UniformPrior(lower_limit=0.0, upper_limit=5.0)\n\nmodel = af.Collection(\n galaxies=af.Collection(galaxy=galaxy), dataset_model=dataset_model\n)\n```\n\nYou **must** set the sky prior by hand \u2014 unlike a light profile's priors, the right range\ndepends entirely on your data's units and depth, so no default can be correct. This costs one\nparameter and matters for exactly the measurement galaxy structure cares most about: the\nfaint outer envelope that sets `effective_radius` and `sersic_index`. It is worth including\neven on data you believe is sky-subtracted, precisely to check that belief. The other fields\nare `grid_offset=(y, x)` and `grid_rotation_angle`, which earn their keep in multi-band work\nwhere bands are not perfectly registered. Concept page:\n[`../wiki/core/concepts/sky_background_and_operated_profiles.md`](../wiki/core/concepts/sky_background_and_operated_profiles.md).\n\n## Branch \u2014 modelling contaminating extra galaxies\n\nWhen a neighbour's light genuinely overlaps the target's, neither masking nor noise scaling\ncan separate them without removing signal you need \u2014 so model it. The convention is that its\ncentre is **fixed** to a value measured from the data, leaving its other parameters free.\nAdapted from `autogalaxy_workspace:scripts/imaging/features/extra_galaxies/modeling.py`.\n\n```python\nextra_galaxies_centres = ag.from_json(\n file_path=DATASET_PATH / \"extra_galaxies_centres.json\"\n)\n\nextra_galaxies_list = []\n\nfor extra_galaxy_centre in extra_galaxies_centres:\n\n extra_galaxy = af.Model(\n ag.Galaxy, redshift=0.5, bulge=ag.lp_linear.SersicSph\n )\n extra_galaxy.bulge.centre = extra_galaxy_centre\n\n extra_galaxies_list.append(extra_galaxy)\n\nmodel = af.Collection(\n galaxies=af.Collection(galaxy=galaxy),\n extra_galaxies=af.Collection(extra_galaxies_list),\n)\n```\n\nThe centres come from the JSON written during data preparation. A spherical `SersicSph` costs\nabout two free parameters per neighbour once its intensity is solved \u2014 cheap enough that a\nhandful of companions is affordable. For irregular or asymmetric companions, swap the\nspherical Sersic for an MGE with a pinned centre,\n`ag.model_util.mge_model_from(mask_radius=MASK_RADIUS, total_gaussians=10,\ncentre_fixed=tuple(extra_galaxy_centre))`, which costs the same in the linear limit while\nbeing far more flexible. Note that `extra_galaxies` is its own top-level collection, not a\nmember of `galaxies`. When to model versus mask versus scale is\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Wrap with an analysis, and check it before you search\n\n```python\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n```\n\nSource: `PyAutoGalaxy:autogalaxy/imaging/model/analysis.py`. The full surface is\n`AnalysisImaging(dataset, adapt_images=None, cosmology=None, settings=None,\ntitle_prefix=None, use_jax=True)`. Pass `cosmology=ag.cosmo.Planck15()` when a derived\nquantity needs angular-to-physical conversion; `settings=ag.Settings(...)` only to override\nan inversion or linear-solver default; `adapt_images` only for an adaptive pixelised\nreconstruction.\n\nTwo checks before you hand this to a search, both cheap and both catching a different class\nof mistake:\n\n```python\nprint(model.info)\n\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\n`model.info` catches a *model* mistake \u2014 a parameter you thought was fixed, a prior wider\nthan intended, a component you added twice. `print_vram_use` catches a *resource* mistake:\nJAX must hold the whole batched likelihood in GPU memory, and this reports the estimate in\n20-30 seconds rather than letting you discover the limit as an out-of-memory error mid-compile\n(`autogalaxy_workspace:scripts/imaging/modeling.py` quotes ~0.027 GB for an MGE on a\nlow-resolution dataset, and more than 1 GB \u2014 occasionally more than 10 GB \u2014 for a pixelised\nreconstruction at high resolution). Add the single likelihood evaluation from the first branch\nwhen you have changed anything structural; a finite number back means the three pieces fit\ntogether.\n\n## Combine \u2014 where this hands off\n\n- **Pick and configure the search** \u2192 [`ag_configure_search`](./ag_configure_search.md).\n `MultiStartProdigy` for a fast check that this model and dataset are sensible, `Nautilus`\n when you need errors you can quote.\n- **Run the fit** \u2192 the run-search skill (`ag_run_search`), which owns\n `search.fit(model=model, analysis=analysis)` and the output folder.\n- **The search fails, stalls or returns something unphysical** \u2192 the fit-debugging skill\n (`ag_debug_fit_failure`). Nine times in ten the fix is here rather than in the search: a\n model too complex for the data, an unpaired centre, a missing assertion, or a contaminant\n that should have been handled during preparation.\n- **A smooth profile leaves structure in the residuals** \u2192 the basis-profile and pixelisation\n skills (`ag_basis_profiles`, `ag_pixelization`) in a later phase; the MGE branch above is\n the first step in that direction and often enough on its own.\n- **Several datasets of the same galaxy** \u2192 the multi-dataset skill (`ag_multi_dataset`).\n Datasets are combined through a factor graph \u2014 one `af.AnalysisFactor` per dataset, folded\n into an `af.FactorGraphModel`; see\n [`../wiki/core/concepts/multi_wavelength.md`](../wiki/core/concepts/multi_wavelength.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry: the components you\nchose, the parameters you fixed or paired, and *why*, are the modelling assumptions a referee\nwill ask about.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [HowToGalaxy: Why modeling is hard](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_3_why_modeling_is_hard.ipynb):\n the trade-off at the heart of this skill \u2014 what happens when a model is too simple for the\n data, and what happens when it is too complex for the search.\n- **General reference** \u2014 [RTD: Model cookbook](https://pyautogalaxy.readthedocs.io/en/latest/general/model_cookbook.html):\n the systematic reference for `af.Model` and `af.Collection` \u2014 multiple components, multiple\n galaxies, prior customisation, pairing, and many-profile bases.\n- **Experienced PyAutoGalaxy user** \u2014 [workspace: imaging/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/modeling.py):\n the canonical bulge-plus-disk fit end to end, including the VRAM check, run-time estimation\n and the annotated output-folder layout.\n\n## Agent procedural checklist\n\n1. On real data, confirm the inspection gate was satisfied; if not, return to\n `ag_prepare_imaging_data`.\n2. Ask: one galaxy or several; single Sersic or a decomposition; smooth or irregular.\n3. Prefer `ag.lp_linear` over `ag.lp` \u2014 the intensity is solved, not sampled.\n4. Start with a single Sersic even when the goal is a decomposition; keep it as the reference.\n5. Pair concentric centres, fix what physics fixes, and add assertions that rule out the\n relabelling solution.\n6. `print(model.info)` and check `total_free_parameters` against what you intended.\n7. Build `ag.AnalysisImaging`, run one likelihood evaluation, and `print_vram_use` before a\n GPU run.\n8. Save the script to `scripts/`, hand off to `ag_configure_search`, and offer the\n `wiki/project/` entry recording the modelling assumptions.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54"