diff --git a/notebooks/chapter_1_introduction/tutorial_0_visualization.ipynb b/notebooks/chapter_1_introduction/tutorial_0_visualization.ipynb index c7e2f62..dcb0fa0 100644 --- a/notebooks/chapter_1_introduction/tutorial_0_visualization.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_0_visualization.ipynb @@ -26,21 +26,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", diff --git a/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb b/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb index 1398af9..107bebf 100644 --- a/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb @@ -54,21 +54,22 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Run this cell to install PyAutoGalaxy and download the files needed for this notebook on Google Colab.\n", + "If you\u2019re running locally or in HTML, it leaves your installation unchanged.\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", diff --git a/notebooks/chapter_1_introduction/tutorial_2_data.ipynb b/notebooks/chapter_1_introduction/tutorial_2_data.ipynb index c057031..9801c52 100644 --- a/notebooks/chapter_1_introduction/tutorial_2_data.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_2_data.ipynb @@ -41,21 +41,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", diff --git a/notebooks/chapter_1_introduction/tutorial_3_fitting.ipynb b/notebooks/chapter_1_introduction/tutorial_3_fitting.ipynb index 3c1ecf1..05c4bb1 100644 --- a/notebooks/chapter_1_introduction/tutorial_3_fitting.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_3_fitting.ipynb @@ -41,21 +41,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", diff --git a/notebooks/chapter_1_introduction/tutorial_4_methods.ipynb b/notebooks/chapter_1_introduction/tutorial_4_methods.ipynb index cc125fb..6e61ca6 100644 --- a/notebooks/chapter_1_introduction/tutorial_4_methods.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_4_methods.ipynb @@ -26,21 +26,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -105,7 +105,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_1_introduction/tutorial_4_methods.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_plot_fit\n\n---\nname: ag_plot_fit\ndescription: Visualise a dataset, a galaxy, or a fit with the functional `aplt` plotting API \u2014 dataset and fit subplots, individual model-image / residual / normalised-residual / chi-squared panels, per-galaxy breakdowns, log10 stretch and fixed colour limits, overlays, writing figures to disk and writing FITS. Also carries the residual-inspection discipline: what a good chi-squared map looks like, what each characteristic residual pattern is telling you about the model, and how to compare two fits honestly. Use when the user wants to look at data before fitting it, look at a finished fit, produce a figure for a paper or a talk, or decide whether a fit is acceptable. Not for composing or running the fit (`ag_build_imaging_model`, `ag_run_search`), not for pulling numbers and posteriors out of a result (`ag_load_results`), and not for the diagnostic workflow when a fit has clearly failed (`ag_debug_fit_failure`).\n---\n\n# Looking at the data, the galaxy, and the fit\n\nPlotting is not decoration here \u2014 it is the main instrument of judgement. A galaxy model is\naccepted or rejected on whether its residuals look like noise, and no summary statistic\nreplaces that look. A chi-squared of 1.05 per pixel with a coherent ring of residuals at one\narcsecond is a *worse* result than a chi-squared of 1.3 scattered randomly, because the first\none is telling you the model is structurally wrong while the second is telling you the noise\nestimate is slightly off.\n\nThe plotting surface is **functional only**. One import, then module-level functions:\n\n```python\nimport autogalaxy.plot as aplt\n```\n\nQuantities are computed from PyAutoGalaxy objects by their own methods, and the resulting\narray or grid is passed to a function\n(`autogalaxy_workspace:scripts/guides/plot/start_here.py`). Because the layer takes plain\narrays, anything the library can compute you can plot, and there is no per-object plotting\nclass to learn.\n\nThere are **no plotter classes and no figure-configuration objects** \u2014 the object-oriented\nplotters and the matplotlib-wrapper objects that older releases shipped were removed. Those\nolder releases are heavily represented in language-model training data, which makes\nreconstructing them from memory the single most common stale-API error in this library. If a\ncall you remember is not in `dir(aplt)`, it is not part of the current API: check before you\nemit it. [`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md) is the authoritative\nenumeration of what does exist, with a \"when to use which\" note on each entry.\n\n## Ask\n\n- *\"Are we looking at the data, a galaxy model, or a fit?\"* Three different branches below.\n Data before fitting is the inspection gate; a galaxy on its own is usually a sanity check on\n a model you just composed; a fit is the judgement call.\n- *\"On screen, or to a file?\"* With no `output_path`, a figure is displayed. From a terminal\n that flashes and vanishes, so default to writing files.\n- *\"Quick look, or a figure for a paper?\"* A quick look is one subplot. A paper figure means\n fixed colour limits, a log10 stretch, a chosen colormap and probably several formats.\n\n## Branch \u2014 the dataset, before you fit it\n\nOne call gives the whole dataset: data, noise-map, PSF, signal-to-noise map and the\nover-sampling panels.\n\n```python\nfrom pathlib import Path\n\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"\"\nPLOT_DIR = Path(\"scripts\") / \"scratch\" / \"\"\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\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\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\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Dataset Subplot__`. Individual\ncomponents are attributes, plotted with the fundamental array function:\n\n```python\naplt.plot_array(array=dataset.data, title=\"Data\")\naplt.plot_array(array=dataset.noise_map, title=\"Noise Map\")\naplt.plot_array(array=dataset.psf.kernel, title=\"PSF\")\naplt.plot_array(array=dataset.signal_to_noise_map, title=\"Signal-to-Noise Map\")\n```\n\nWhat to look for in this figure is the substance of\n[`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md) \u2014 neighbouring galaxies, foreground\nstars, reduction artefacts, and where the galaxy's emission meets the sky, which is what sets\nthe mask radius. Re-plot after `apply_mask` and after `apply_over_sampling`: the subplot's\nlower panels update to show the over-sampling scheme, so you can see the scheme you asked for\nrather than trusting it (`autogalaxy_workspace:scripts/imaging/modeling.py`\n`__Over Sampling__`). Masks and over-sampling as concepts are\n[`wiki/core/concepts/grids_and_masks.md`](../wiki/core/concepts/grids_and_masks.md); the\ndataset object itself is [`wiki/core/api/datasets.md`](../wiki/core/api/datasets.md).\n\n## Branch \u2014 a galaxy or a light profile on its own\n\nUseful before any data is involved: does the model you just composed actually look like the\ngalaxy you have in mind? Every object exposes `image_2d_from(grid=grid)`, and the array goes\nstraight to `plot_array`\n(`autogalaxy_workspace:scripts/guides/plot/plotters.py`):\n\n```python\ngrid = ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.05)\n\nbulge = ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=4.0,\n effective_radius=0.6,\n sersic_index=3.0,\n)\ndisk = ag.lp.Exponential(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.7, angle=30.0),\n intensity=2.0,\n effective_radius=1.6,\n)\n\ngalaxy = ag.Galaxy(redshift=0.5, bulge=bulge, disk=disk)\n\naplt.plot_array(array=bulge.image_2d_from(grid=grid), title=\"Bulge Image\")\naplt.plot_array(array=galaxy.image_2d_from(grid=grid), title=\"Galaxy Image\", use_log10=True)\n```\n\nA galaxy's image is the sum of its light profiles' images, so the bulge/disk decomposition is\nvisible by plotting each component beside the total. `aplt.subplot_galaxy_light_profiles`\ndoes that as one figure; `aplt.subplot_galaxies` shows the summed image plus a panel per\ngalaxy, and takes `auto_filename` to name its file. The physics of what the effective radius\nand Sersic index actually measure is\n[`wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md), and how\nseveral profiles and galaxies compose is\n[`wiki/core/concepts/galaxies.md`](../wiki/core/concepts/galaxies.md).\n\n**Linear light profiles cannot be plotted directly.** An `ag.lp_linear.*` profile has no\n`intensity` until the linear inversion solves for it, so the galaxy-level subplots reject\nthem. Get the solved profiles from a fit \u2014 `fit.galaxies_linear_light_profiles_to_light_profiles`\n\u2014 and plot those instead (`autogalaxy_workspace:scripts/guides/results/start_here.py`\n`__Linear Light Profiles__`). Background:\n[`wiki/core/concepts/linear_light_profiles_and_mge.md`](../wiki/core/concepts/linear_light_profiles_and_mge.md).\n\n## Branch \u2014 the fit, and how to read the residuals\n\nA `FitImaging` compares a model galaxy against the data, PSF convolution included. Build one\nfrom a dataset and galaxies, or take the best-fit one straight off a result:\n\n```python\nfit = ag.FitImaging(dataset=dataset, galaxies=galaxies)\n\n# or, from a completed search:\nfit = result.max_log_likelihood_fit\n```\n\nThe summary figure is six panels \u2014 data, signal-to-noise map, model image, residual map,\nnormalised residual map and chi-squared map:\n\n```python\naplt.subplot_fit_imaging(\n fit=fit,\n output_path=PLOT_DIR,\n output_format=\"png\",\n)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Fit Subplot__`.\n\n**Most fit subplots do not take `output_filename`.** They write a fixed stem into\n`output_path`: `subplot_fit_imaging` writes `fit.png`, and\n`subplot_fit_imaging_of_galaxy` writes `of_galaxy_.png`\n(`PyAutoGalaxy:autogalaxy/imaging/plot/fit_imaging_plots.py`). So the *directory* is what\ndistinguishes one context from another \u2014 give each fit, or each variant of a figure, its own\nfolder under `scripts/scratch/`. The one exception is `subplot_fit_imaging_list` below, which\ndoes take `output_filename`. `plot_array`, `plot_grid` and `subplot_imaging_dataset` do\ntake `output_filename`; `subplot_galaxies` takes `auto_filename`\n(`PyAutoGalaxy:autogalaxy/galaxy/plot/galaxies_plots.py`). Check the signature rather than\nassuming a uniform interface.\n\nTo compare several fits side by side \u2014 the same galaxy under competing models, or one model\nacross a set of datasets \u2014 `subplot_fit_imaging_list` draws one row per fit rather than making\nyou place several `fit.png` files next to each other:\n\n```python\naplt.subplot_fit_imaging_list(\n fit_list=[fit_sersic, fit_bulge_disk, fit_mge],\n output_path=PLOT_DIR,\n output_filename=\"model_comparison\",\n output_format=\"png\",\n)\n```\n\nNote it takes `fit_list=`, not `fit=`. Its rows are data | signal-to-noise | model image |\nnormalised residuals | chi-squared \u2014 five columns, not the six of the single-fit subplot, and\nit drops `colormap` / `use_log10` (`PyAutoGalaxy:autogalaxy/imaging/plot/fit_imaging_plots.py`).\nRead the normalised-residual column across rows: the model that flattens it is the one to keep,\nand the discipline below applies unchanged.\n\nIndividual quantities are attributes, so they go through `plot_array` \u2014 which is also how you\nget per-panel control the subplot does not offer:\n\n```python\naplt.plot_array(array=fit.model_data, title=\"Model Image\")\naplt.plot_array(array=fit.residual_map, title=\"Residual Map\")\naplt.plot_array(array=fit.normalized_residual_map, title=\"Normalized Residual Map\", symmetric=True)\naplt.plot_array(array=fit.chi_squared_map, title=\"Chi-Squared Map\")\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Fit Figures__`. `symmetric=True`\nputs zero at the centre of a diverging colour scale, which is the right choice for a residual\nmap \u2014 otherwise a colormap keyed to the extremes hides the sign of the structure you are\nlooking for.\n\n### The inspection discipline\n\nThree maps, three different questions:\n\n- **`residual_map`** = data \u2212 model, in data units. Answers *how much* flux is unaccounted\n for, and where. Useful for judging whether a mismatch matters physically.\n- **`normalized_residual_map`** = residual / noise. Answers *how significant* the mismatch is.\n This is the map to read first, because it is the only one calibrated against the noise.\n Values scattered within roughly \u00b13 are consistent with noise; coherent structure well\n outside that is a model failure, however small it looks in flux.\n- **`chi_squared_map`** = normalised residual squared. Answers *where the likelihood is being\n paid*, since `fit.chi_squared` is its sum\n (`autogalaxy_workspace:scripts/imaging/likelihood_function.py` `__Chi Squared__`). Squaring\n discards the sign, so read it alongside the normalised residuals rather than instead of\n them.\n\nRead the pattern, not just the magnitude. The characteristic ones:\n\n| Pattern in the normalised residuals | Usually means |\n|---|---|\n| Structure concentrated at the very centre | Over-sampling too coarse, or a genuinely cored/nuclear component the model lacks |\n| A symmetric ring at one radius | The radial profile is wrong \u2014 one Sersic where a bulge plus disk is needed, or a fixed Sersic index |\n| Four-lobed pattern, alternating sign | The ellipticity or position angle is wrong, or the isophotes twist with radius |\n| A compact blob away from the centre | A neighbouring galaxy, a foreground star, or a reduction artefact left in the fit |\n| Clumpy structure with no symmetry | Real asymmetric morphology no smooth profile can absorb |\n| Uniformly slightly too large everywhere | The noise-map is underestimated, or a sky background is unmodelled |\n\nEach row routes somewhere. Ellipticity and isophote twists are\n[`wiki/core/concepts/ellipse_fitting_and_multipoles.md`](../wiki/core/concepts/ellipse_fitting_and_multipoles.md);\nneighbours are\n[`wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md);\nirreducible clumpiness is\n[`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md);\nan unmodelled background is\n[`wiki/core/concepts/sky_background_and_operated_profiles.md`](../wiki/core/concepts/sky_background_and_operated_profiles.md).\nTurning any of those diagnoses into a plan is\n[`ag_debug_fit_failure`](./ag_debug_fit_failure.md).\n\nFor a blended pair or a galaxy with a modelled neighbour, the per-galaxy view is what shows\nwhether the decomposition is real or just two profiles trading flux:\n\n```python\naplt.plot_array(array=fit.model_images_of_galaxies_list[0], title=\"Galaxy 0 Model Image\")\naplt.subplot_fit_imaging_of_galaxy(fit=fit, galaxy_index=0, output_path=PLOT_DIR, output_format=\"png\")\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Galaxy Images__` and\n`__Galaxy Subplots__`. The per-galaxy subplot shows the data with the *other* galaxies\nsubtracted, alongside that galaxy's model image and residuals.\n\n## Branch \u2014 making the figure say what you mean\n\nCustomisation is keyword arguments, never a wrapper object\n(`autogalaxy_workspace:scripts/guides/plot/start_here.py` `__Customization__`):\n\n```python\naplt.plot_array(array=dataset.data, title=\"Jet\", colormap=\"jet\")\naplt.plot_array(array=galaxy.image_2d_from(grid=grid), title=\"Log10\", use_log10=True)\naplt.plot_array(array=dataset.data, title=\"Fixed Scale\", vmin=0.0, vmax=1.0)\n```\n\nThree of these carry scientific weight:\n\n- **`use_log10=True`** \u2014 a galaxy's surface brightness spans orders of magnitude, so a linear\n stretch shows the bright core and nothing else. The log10 view is where faint extended\n emission, tidal features and a disk under a bright bulge become visible. It is available on\n the subplots too, and is often the more honest default for a galaxy.\n- **`vmin` / `vmax`** \u2014 fixed limits are what make two figures comparable. Comparing two fits\n on auto-scaled colour bars is not a comparison.\n- **`symmetric=True`** \u2014 for anything that can be negative, which is every residual map.\n\nOverlays are keyword arguments as well\n(`autogalaxy_workspace:scripts/guides/plot/visuals.py`): `positions=` scatters points such as\nlight-profile centres, `grid=` draws a coordinate grid, `lines=` / `line_colors=` draw\npolylines. Two accepted forms for positions:\n\n```python\nimport numpy as np\n\nlight_profile_centres = galaxies.extract_attribute(cls=ag.LightProfile, attr_name=\"centre\")\n\naplt.plot_array(\n array=galaxies.image_2d_from(grid=grid),\n positions=[np.array(light_profile_centres)],\n title=\"Image with Light Profile Centres\",\n)\n\naplt.plot_array(\n array=galaxy.image_2d_from(grid=grid),\n positions=ag.Grid2DIrregular(values=[(0.0, 0.0)]),\n title=\"Image with Centre\",\n)\n```\n\n1D radial profiles are plain matplotlib on a radially projected grid, not an `aplt` function \u2014\nincluding the shaded error region drawn from a set of profiles sampled from the posterior\n(`autogalaxy_workspace:scripts/guides/plot/plotters.py` `__One Dimensional Plots__` and\n`__Probability Density Function (PDF) Plots__`, which uses\n`ag.util.error.profile_1d_median_and_error_region_via_quantile`).\n\nAnything not passed explicitly comes from `config/visualize/general.yaml` \u2014 the default\ncolormap, tick counts, colorbar label sizes, contour levels, the unit label. Editing that file\nchanges the look project-wide without touching code, after a session or kernel restart. See\n[`wiki/core/api/configuration.md`](../wiki/core/api/configuration.md).\n\n## Branch \u2014 writing to disk, and announcing it\n\nWith `output_path` set (a directory) plus `output_format`, the figure is written rather than\ndisplayed. Without `output_filename` the file is named from the title; `output_format` also\naccepts a list, which writes several formats in one call \u2014 a PNG to look at and a PDF for the\npaper (`autogalaxy_workspace:scripts/guides/plot/start_here.py` `__Output__`):\n\n```python\naplt.plot_array(\n array=dataset.data,\n title=\"Image\",\n output_path=PLOT_DIR,\n output_filename=\"data\",\n output_format=[\"png\", \"pdf\"],\n)\n```\n\nThree rules from [`_style.md`](./_style.md) \"Plot output and path announcement\", and they are\nnot optional:\n\n1. Throwaway figures go to the gitignored `scripts/scratch//`, where `` is\n usually the dataset name. Never `output/` \u2014 that belongs to the fit runtime.\n2. `print(f\"Saved to: {PLOT_DIR.resolve()}\")` at the end of the recipe, so the absolute\n location lands in stdout.\n3. After running, **quote that absolute path back to the user and offer to open it** \u2014\n `xdg-open` on Linux, `open` on macOS, `explorer.exe` or `wslview` from WSL. One offer per\n plot run. \"Plot saved\" on its own is not useful to someone who cannot see your filesystem.\n\nTo write data rather than an image, the `fits_*` functions are separate\n(`autogalaxy_workspace:scripts/imaging/plot.py` `__Outputting to FITS__`):\n\n```python\naplt.fits_imaging(dataset=dataset, file_path=PLOT_DIR / \"dataset.fits\", overwrite=True)\naplt.fits_array(array=mask, file_path=DATASET_PATH / \"mask.fits\", overwrite=True)\n```\n\n`file_path` writes one multi-HDU file with named extensions; the per-component\n`data_path` / `psf_path` / `noise_map_path` arguments write separate files instead.\n\n## Branch \u2014 the figures a fit produces on its own\n\nYou do not need any of the above to watch a fit converge. Each analysis carries a `Visualizer`\nthat PyAutoFit invokes at every update interval and again at the end, writing the standard\ndataset, fit and per-galaxy figures into the fit's `image/` folder using the best model found\nso far (`autogalaxy_workspace:scripts/imaging/plot.py` `__Visualizer__`;\n`PyAutoGalaxy:autogalaxy/imaging/model/visualizer.py`). Which figures appear is set by\n`config/visualize/plots.yaml` \u2014 `dataset -> subplot_dataset`, `fit -> subplot_fit`,\n`fit -> subplot_of_galaxies` \u2014 so switching a figure on or off for every fit is a YAML edit,\nnot a code change. The cadence is the search's `iterations_per_quick_update`\n([`ag_run_search`](./ag_run_search.md)).\n\nReach for this skill when you want something the automatic figures do not give you: a\ndifferent stretch, a crop, fixed limits across two fits, a specific panel at publication\nsize, or a per-galaxy breakdown that `plots.yaml` has switched off.\n\nPosterior figures \u2014 corner plots and likelihood traces \u2014 come from PyAutoFit and take\n`samples` plus `path` / `filename` / `format` rather than the `output_*` names, e.g.\n`aplt.corner_cornerpy(samples=result.samples)`. They belong to\n[`ag_load_results`](./ag_load_results.md); the surface is tabulated in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md) \"Search results\".\n\n## Combine\n\n- [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md) \u2014 the inspection the dataset\n subplot exists to serve, and the mask that follows from it.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) \u2014 you have read the residuals and they\n are wrong; this is the triage.\n- [`ag_load_results`](./ag_load_results.md) \u2014 the numbers behind the figures, and figures\n across many fits at once.\n- [`ag_run_search`](./ag_run_search.md) \u2014 the fit that produced the `image/` folder, and the\n cadence at which it refreshes.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) \u2014 plot a simulated fit where you know the\n truth, to calibrate what an acceptable residual map looks like for your data quality.\n\nWhen a figure is going into a paper or a talk, offer (default-yes) the dated\n`wiki/project/YYYY-MM-DD-.md` entry recording what it shows and which fit it came from\n\u2014 per [`_style.md`](./_style.md) property #5.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [HowToGalaxy: Fitting](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_3_fitting.ipynb):\n builds up residuals, normalised residuals and the chi-squared map from first principles, so\n the six panels of a fit subplot stop being opaque.\n- **General reference** \u2014 [RTD: Plot API reference](https://pyautogalaxy.readthedocs.io/en/latest/api/plot.html):\n the generated reference for the visualisation library.\n- **Experienced PyAutoGalaxy user** \u2014 [workspace: guides/plot/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/guides/plot/start_here.py):\n the plotting API in one runnable script \u2014 customisation, output, config defaults, overlays\n and subplots.\n\n## Agent procedural checklist\n\n1. Establish what is being plotted: dataset, galaxy/profile, or fit.\n2. Ground every call against [`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md) or\n `dir(aplt)`. Never write a plotter class or a figure-configuration object.\n3. Check the signature for `output_filename` before passing it \u2014 the fit and galaxy subplots\n do not accept it and write a fixed stem instead.\n4. Write the recipe into a script; send figures to `scripts/scratch//`.\n5. `print` the resolved plot directory at the end of the script.\n6. For a fit, read the **normalised residual** map first, then the chi-squared map; report the\n pattern, not only the number.\n7. Use `symmetric=True` on residuals, `use_log10=True` for galaxy light, and fixed\n `vmin`/`vmax` whenever two figures will be compared.\n8. Quote the absolute path back and offer to open it \u2014 once per plot run.\n9. Route any diagnosed model failure to the debug skill rather than tweaking the figure until\n it looks acceptable.\n10. Offer the `wiki/project/` entry for a figure that will be published.\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_1_introduction/tutorial_4_methods.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_plot_fit\n\n---\nname: ag_plot_fit\ndescription: Visualise a dataset, a galaxy, or a fit with the functional `aplt` plotting API — dataset and fit subplots, individual model-image / residual / normalised-residual / chi-squared panels, per-galaxy breakdowns, log10 stretch and fixed colour limits, overlays, writing figures to disk and writing FITS. Also carries the residual-inspection discipline: what a good chi-squared map looks like, what each characteristic residual pattern is telling you about the model, and how to compare two fits honestly. Use when the user wants to look at data before fitting it, look at a finished fit, produce a figure for a paper or a talk, or decide whether a fit is acceptable. Not for composing or running the fit (`ag_build_imaging_model`, `ag_run_search`), not for pulling numbers and posteriors out of a result (`ag_load_results`), and not for the diagnostic workflow when a fit has clearly failed (`ag_debug_fit_failure`).\n---\n\n# Looking at the data, the galaxy, and the fit\n\nPlotting is not decoration here — it is the main instrument of judgement. A galaxy model is\naccepted or rejected on whether its residuals look like noise, and no summary statistic\nreplaces that look. A chi-squared of 1.05 per pixel with a coherent ring of residuals at one\narcsecond is a *worse* result than a chi-squared of 1.3 scattered randomly, because the first\none is telling you the model is structurally wrong while the second is telling you the noise\nestimate is slightly off.\n\nThe plotting surface is **functional only**. One import, then module-level functions:\n\n```python\nimport autogalaxy.plot as aplt\n```\n\nQuantities are computed from PyAutoGalaxy objects by their own methods, and the resulting\narray or grid is passed to a function\n(`autogalaxy_workspace:scripts/guides/plot/start_here.py`). Because the layer takes plain\narrays, anything the library can compute you can plot, and there is no per-object plotting\nclass to learn.\n\nThere are **no plotter classes and no figure-configuration objects** — the object-oriented\nplotters and the matplotlib-wrapper objects that older releases shipped were removed. Those\nolder releases are heavily represented in language-model training data, which makes\nreconstructing them from memory the single most common stale-API error in this library. If a\ncall you remember is not in `dir(aplt)`, it is not part of the current API: check before you\nemit it. [`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md) is the authoritative\nenumeration of what does exist, with a \"when to use which\" note on each entry.\n\n## Ask\n\n- *\"Are we looking at the data, a galaxy model, or a fit?\"* Three different branches below.\n Data before fitting is the inspection gate; a galaxy on its own is usually a sanity check on\n a model you just composed; a fit is the judgement call.\n- *\"On screen, or to a file?\"* With no `output_path`, a figure is displayed. From a terminal\n that flashes and vanishes, so default to writing files.\n- *\"Quick look, or a figure for a paper?\"* A quick look is one subplot. A paper figure means\n fixed colour limits, a log10 stretch, a chosen colormap and probably several formats.\n\n## Branch — the dataset, before you fit it\n\nOne call gives the whole dataset: data, noise-map, PSF, signal-to-noise map and the\nover-sampling panels.\n\n```python\nfrom pathlib import Path\n\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"\"\nPLOT_DIR = Path(\"scripts\") / \"scratch\" / \"\"\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\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\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\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Dataset Subplot__`. Individual\ncomponents are attributes, plotted with the fundamental array function:\n\n```python\naplt.plot_array(array=dataset.data, title=\"Data\")\naplt.plot_array(array=dataset.noise_map, title=\"Noise Map\")\naplt.plot_array(array=dataset.psf.kernel, title=\"PSF\")\naplt.plot_array(array=dataset.signal_to_noise_map, title=\"Signal-to-Noise Map\")\n```\n\nWhat to look for in this figure is the substance of\n[`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md) — neighbouring galaxies, foreground\nstars, reduction artefacts, and where the galaxy's emission meets the sky, which is what sets\nthe mask radius. Re-plot after `apply_mask` and after `apply_over_sampling`: the subplot's\nlower panels update to show the over-sampling scheme, so you can see the scheme you asked for\nrather than trusting it (`autogalaxy_workspace:scripts/imaging/modeling.py`\n`__Over Sampling__`). Masks and over-sampling as concepts are\n[`wiki/core/concepts/grids_and_masks.md`](../wiki/core/concepts/grids_and_masks.md); the\ndataset object itself is [`wiki/core/api/datasets.md`](../wiki/core/api/datasets.md).\n\n## Branch — a galaxy or a light profile on its own\n\nUseful before any data is involved: does the model you just composed actually look like the\ngalaxy you have in mind? Every object exposes `image_2d_from(grid=grid)`, and the array goes\nstraight to `plot_array`\n(`autogalaxy_workspace:scripts/guides/plot/plotters.py`):\n\n```python\ngrid = ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.05)\n\nbulge = ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=4.0,\n effective_radius=0.6,\n sersic_index=3.0,\n)\ndisk = ag.lp.Exponential(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.7, angle=30.0),\n intensity=2.0,\n effective_radius=1.6,\n)\n\ngalaxy = ag.Galaxy(redshift=0.5, bulge=bulge, disk=disk)\n\naplt.plot_array(array=bulge.image_2d_from(grid=grid), title=\"Bulge Image\")\naplt.plot_array(array=galaxy.image_2d_from(grid=grid), title=\"Galaxy Image\", use_log10=True)\n```\n\nA galaxy's image is the sum of its light profiles' images, so the bulge/disk decomposition is\nvisible by plotting each component beside the total. `aplt.subplot_galaxy_light_profiles`\ndoes that as one figure; `aplt.subplot_galaxies` shows the summed image plus a panel per\ngalaxy, and takes `auto_filename` to name its file. The physics of what the effective radius\nand Sersic index actually measure is\n[`wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md), and how\nseveral profiles and galaxies compose is\n[`wiki/core/concepts/galaxies.md`](../wiki/core/concepts/galaxies.md).\n\n**Linear light profiles cannot be plotted directly.** An `ag.lp_linear.*` profile has no\n`intensity` until the linear inversion solves for it, so the galaxy-level subplots reject\nthem. Get the solved profiles from a fit — `fit.galaxies_linear_light_profiles_to_light_profiles`\n— and plot those instead (`autogalaxy_workspace:scripts/guides/results/start_here.py`\n`__Linear Light Profiles__`). Background:\n[`wiki/core/concepts/linear_light_profiles_and_mge.md`](../wiki/core/concepts/linear_light_profiles_and_mge.md).\n\n## Branch — the fit, and how to read the residuals\n\nA `FitImaging` compares a model galaxy against the data, PSF convolution included. Build one\nfrom a dataset and galaxies, or take the best-fit one straight off a result:\n\n```python\nfit = ag.FitImaging(dataset=dataset, galaxies=galaxies)\n\n# or, from a completed search:\nfit = result.max_log_likelihood_fit\n```\n\nThe summary figure is six panels — data, signal-to-noise map, model image, residual map,\nnormalised residual map and chi-squared map:\n\n```python\naplt.subplot_fit_imaging(\n fit=fit,\n output_path=PLOT_DIR,\n output_format=\"png\",\n)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Fit Subplot__`.\n\n**Most fit subplots do not take `output_filename`.** They write a fixed stem into\n`output_path`: `subplot_fit_imaging` writes `fit.png`, and\n`subplot_fit_imaging_of_galaxy` writes `of_galaxy_.png`\n(`PyAutoGalaxy:autogalaxy/imaging/plot/fit_imaging_plots.py`). So the *directory* is what\ndistinguishes one context from another — give each fit, or each variant of a figure, its own\nfolder under `scripts/scratch/`. The one exception is `subplot_fit_imaging_list` below, which\ndoes take `output_filename`. `plot_array`, `plot_grid` and `subplot_imaging_dataset` do\ntake `output_filename`; `subplot_galaxies` takes `auto_filename`\n(`PyAutoGalaxy:autogalaxy/galaxy/plot/galaxies_plots.py`). Check the signature rather than\nassuming a uniform interface.\n\nTo compare several fits side by side — the same galaxy under competing models, or one model\nacross a set of datasets — `subplot_fit_imaging_list` draws one row per fit rather than making\nyou place several `fit.png` files next to each other:\n\n```python\naplt.subplot_fit_imaging_list(\n fit_list=[fit_sersic, fit_bulge_disk, fit_mge],\n output_path=PLOT_DIR,\n output_filename=\"model_comparison\",\n output_format=\"png\",\n)\n```\n\nNote it takes `fit_list=`, not `fit=`. Its rows are data | signal-to-noise | model image |\nnormalised residuals | chi-squared — five columns, not the six of the single-fit subplot, and\nit drops `colormap` / `use_log10` (`PyAutoGalaxy:autogalaxy/imaging/plot/fit_imaging_plots.py`).\nRead the normalised-residual column across rows: the model that flattens it is the one to keep,\nand the discipline below applies unchanged.\n\nIndividual quantities are attributes, so they go through `plot_array` — which is also how you\nget per-panel control the subplot does not offer:\n\n```python\naplt.plot_array(array=fit.model_data, title=\"Model Image\")\naplt.plot_array(array=fit.residual_map, title=\"Residual Map\")\naplt.plot_array(array=fit.normalized_residual_map, title=\"Normalized Residual Map\", symmetric=True)\naplt.plot_array(array=fit.chi_squared_map, title=\"Chi-Squared Map\")\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Fit Figures__`. `symmetric=True`\nputs zero at the centre of a diverging colour scale, which is the right choice for a residual\nmap — otherwise a colormap keyed to the extremes hides the sign of the structure you are\nlooking for.\n\n### The inspection discipline\n\nThree maps, three different questions:\n\n- **`residual_map`** = data − model, in data units. Answers *how much* flux is unaccounted\n for, and where. Useful for judging whether a mismatch matters physically.\n- **`normalized_residual_map`** = residual / noise. Answers *how significant* the mismatch is.\n This is the map to read first, because it is the only one calibrated against the noise.\n Values scattered within roughly ±3 are consistent with noise; coherent structure well\n outside that is a model failure, however small it looks in flux.\n- **`chi_squared_map`** = normalised residual squared. Answers *where the likelihood is being\n paid*, since `fit.chi_squared` is its sum\n (`autogalaxy_workspace:scripts/imaging/likelihood_function.py` `__Chi Squared__`). Squaring\n discards the sign, so read it alongside the normalised residuals rather than instead of\n them.\n\nRead the pattern, not just the magnitude. The characteristic ones:\n\n| Pattern in the normalised residuals | Usually means |\n|---|---|\n| Structure concentrated at the very centre | Over-sampling too coarse, or a genuinely cored/nuclear component the model lacks |\n| A symmetric ring at one radius | The radial profile is wrong — one Sersic where a bulge plus disk is needed, or a fixed Sersic index |\n| Four-lobed pattern, alternating sign | The ellipticity or position angle is wrong, or the isophotes twist with radius |\n| A compact blob away from the centre | A neighbouring galaxy, a foreground star, or a reduction artefact left in the fit |\n| Clumpy structure with no symmetry | Real asymmetric morphology no smooth profile can absorb |\n| Uniformly slightly too large everywhere | The noise-map is underestimated, or a sky background is unmodelled |\n\nEach row routes somewhere. Ellipticity and isophote twists are\n[`wiki/core/concepts/ellipse_fitting_and_multipoles.md`](../wiki/core/concepts/ellipse_fitting_and_multipoles.md);\nneighbours are\n[`wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md);\nirreducible clumpiness is\n[`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md);\nan unmodelled background is\n[`wiki/core/concepts/sky_background_and_operated_profiles.md`](../wiki/core/concepts/sky_background_and_operated_profiles.md).\nTurning any of those diagnoses into a plan is\n[`ag_debug_fit_failure`](./ag_debug_fit_failure.md).\n\nFor a blended pair or a galaxy with a modelled neighbour, the per-galaxy view is what shows\nwhether the decomposition is real or just two profiles trading flux:\n\n```python\naplt.plot_array(array=fit.model_images_of_galaxies_list[0], title=\"Galaxy 0 Model Image\")\naplt.subplot_fit_imaging_of_galaxy(fit=fit, galaxy_index=0, output_path=PLOT_DIR, output_format=\"png\")\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Galaxy Images__` and\n`__Galaxy Subplots__`. The per-galaxy subplot shows the data with the *other* galaxies\nsubtracted, alongside that galaxy's model image and residuals.\n\n## Branch — making the figure say what you mean\n\nCustomisation is keyword arguments, never a wrapper object\n(`autogalaxy_workspace:scripts/guides/plot/start_here.py` `__Customization__`):\n\n```python\naplt.plot_array(array=dataset.data, title=\"Jet\", colormap=\"jet\")\naplt.plot_array(array=galaxy.image_2d_from(grid=grid), title=\"Log10\", use_log10=True)\naplt.plot_array(array=dataset.data, title=\"Fixed Scale\", vmin=0.0, vmax=1.0)\n```\n\nThree of these carry scientific weight:\n\n- **`use_log10=True`** — a galaxy's surface brightness spans orders of magnitude, so a linear\n stretch shows the bright core and nothing else. The log10 view is where faint extended\n emission, tidal features and a disk under a bright bulge become visible. It is available on\n the subplots too, and is often the more honest default for a galaxy.\n- **`vmin` / `vmax`** — fixed limits are what make two figures comparable. Comparing two fits\n on auto-scaled colour bars is not a comparison.\n- **`symmetric=True`** — for anything that can be negative, which is every residual map.\n\nOverlays are keyword arguments as well\n(`autogalaxy_workspace:scripts/guides/plot/visuals.py`): `positions=` scatters points such as\nlight-profile centres, `grid=` draws a coordinate grid, `lines=` / `line_colors=` draw\npolylines. Two accepted forms for positions:\n\n```python\nimport numpy as np\n\nlight_profile_centres = galaxies.extract_attribute(cls=ag.LightProfile, attr_name=\"centre\")\n\naplt.plot_array(\n array=galaxies.image_2d_from(grid=grid),\n positions=[np.array(light_profile_centres)],\n title=\"Image with Light Profile Centres\",\n)\n\naplt.plot_array(\n array=galaxy.image_2d_from(grid=grid),\n positions=ag.Grid2DIrregular(values=[(0.0, 0.0)]),\n title=\"Image with Centre\",\n)\n```\n\n1D radial profiles are plain matplotlib on a radially projected grid, not an `aplt` function —\nincluding the shaded error region drawn from a set of profiles sampled from the posterior\n(`autogalaxy_workspace:scripts/guides/plot/plotters.py` `__One Dimensional Plots__` and\n`__Probability Density Function (PDF) Plots__`, which uses\n`ag.util.error.profile_1d_median_and_error_region_via_quantile`).\n\nAnything not passed explicitly comes from `config/visualize/general.yaml` — the default\ncolormap, tick counts, colorbar label sizes, contour levels, the unit label. Editing that file\nchanges the look project-wide without touching code, after a session or kernel restart. See\n[`wiki/core/api/configuration.md`](../wiki/core/api/configuration.md).\n\n## Branch — writing to disk, and announcing it\n\nWith `output_path` set (a directory) plus `output_format`, the figure is written rather than\ndisplayed. Without `output_filename` the file is named from the title; `output_format` also\naccepts a list, which writes several formats in one call — a PNG to look at and a PDF for the\npaper (`autogalaxy_workspace:scripts/guides/plot/start_here.py` `__Output__`):\n\n```python\naplt.plot_array(\n array=dataset.data,\n title=\"Image\",\n output_path=PLOT_DIR,\n output_filename=\"data\",\n output_format=[\"png\", \"pdf\"],\n)\n```\n\nThree rules from [`_style.md`](./_style.md) \"Plot output and path announcement\", and they are\nnot optional:\n\n1. Throwaway figures go to the gitignored `scripts/scratch//`, where `` is\n usually the dataset name. Never `output/` — that belongs to the fit runtime.\n2. `print(f\"Saved to: {PLOT_DIR.resolve()}\")` at the end of the recipe, so the absolute\n location lands in stdout.\n3. After running, **quote that absolute path 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 per\n plot run. \"Plot saved\" on its own is not useful to someone who cannot see your filesystem.\n\nTo write data rather than an image, the `fits_*` functions are separate\n(`autogalaxy_workspace:scripts/imaging/plot.py` `__Outputting to FITS__`):\n\n```python\naplt.fits_imaging(dataset=dataset, file_path=PLOT_DIR / \"dataset.fits\", overwrite=True)\naplt.fits_array(array=mask, file_path=DATASET_PATH / \"mask.fits\", overwrite=True)\n```\n\n`file_path` writes one multi-HDU file with named extensions; the per-component\n`data_path` / `psf_path` / `noise_map_path` arguments write separate files instead.\n\n## Branch — the figures a fit produces on its own\n\nYou do not need any of the above to watch a fit converge. Each analysis carries a `Visualizer`\nthat PyAutoFit invokes at every update interval and again at the end, writing the standard\ndataset, fit and per-galaxy figures into the fit's `image/` folder using the best model found\nso far (`autogalaxy_workspace:scripts/imaging/plot.py` `__Visualizer__`;\n`PyAutoGalaxy:autogalaxy/imaging/model/visualizer.py`). Which figures appear is set by\n`config/visualize/plots.yaml` — `dataset -> subplot_dataset`, `fit -> subplot_fit`,\n`fit -> subplot_of_galaxies` — so switching a figure on or off for every fit is a YAML edit,\nnot a code change. The cadence is the search's `iterations_per_quick_update`\n([`ag_run_search`](./ag_run_search.md)).\n\nReach for this skill when you want something the automatic figures do not give you: a\ndifferent stretch, a crop, fixed limits across two fits, a specific panel at publication\nsize, or a per-galaxy breakdown that `plots.yaml` has switched off.\n\nPosterior figures — corner plots and likelihood traces — come from PyAutoFit and take\n`samples` plus `path` / `filename` / `format` rather than the `output_*` names, e.g.\n`aplt.corner_cornerpy(samples=result.samples)`. They belong to\n[`ag_load_results`](./ag_load_results.md); the surface is tabulated in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md) \"Search results\".\n\n## Combine\n\n- [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md) — the inspection the dataset\n subplot exists to serve, and the mask that follows from it.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) — you have read the residuals and they\n are wrong; this is the triage.\n- [`ag_load_results`](./ag_load_results.md) — the numbers behind the figures, and figures\n across many fits at once.\n- [`ag_run_search`](./ag_run_search.md) — the fit that produced the `image/` folder, and the\n cadence at which it refreshes.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) — plot a simulated fit where you know the\n truth, to calibrate what an acceptable residual map looks like for your data quality.\n\nWhen a figure is going into a paper or a talk, offer (default-yes) the dated\n`wiki/project/YYYY-MM-DD-.md` entry recording what it shows and which fit it came from\n— per [`_style.md`](./_style.md) property #5.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Fitting](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_3_fitting.ipynb):\n builds up residuals, normalised residuals and the chi-squared map from first principles, so\n the six panels of a fit subplot stop being opaque.\n- **General reference** — [RTD: Plot API reference](https://pyautogalaxy.readthedocs.io/en/latest/api/plot.html):\n the generated reference for the visualisation library.\n- **Experienced PyAutoGalaxy user** — [workspace: guides/plot/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/guides/plot/start_here.py):\n the plotting API in one runnable script — customisation, output, config defaults, overlays\n and subplots.\n\n## Agent procedural checklist\n\n1. Establish what is being plotted: dataset, galaxy/profile, or fit.\n2. Ground every call against [`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md) or\n `dir(aplt)`. Never write a plotter class or a figure-configuration object.\n3. Check the signature for `output_filename` before passing it — the fit and galaxy subplots\n do not accept it and write a fixed stem instead.\n4. Write the recipe into a script; send figures to `scripts/scratch//`.\n5. `print` the resolved plot directory at the end of the script.\n6. For a fit, read the **normalised residual** map first, then the chi-squared map; report the\n pattern, not only the number.\n7. Use `symmetric=True` on residuals, `use_log10=True` for galaxy light, and fixed\n `vmin`/`vmax` whenever two figures will be compared.\n8. Quote the absolute path back and offer to open it — once per plot run.\n9. Route any diagnosed model failure to the debug skill rather than tweaking the figure until\n it looks acceptable.\n10. Offer the `wiki/project/` entry for a figure that will be published.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_1_introduction/tutorial_5_summary.ipynb b/notebooks/chapter_1_introduction/tutorial_5_summary.ipynb index 9cea46f..2a9eb68 100644 --- a/notebooks/chapter_1_introduction/tutorial_5_summary.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_5_summary.ipynb @@ -36,21 +36,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -309,7 +309,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_1_introduction/tutorial_5_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_plot_fit\n\n---\nname: ag_plot_fit\ndescription: Visualise a dataset, a galaxy, or a fit with the functional `aplt` plotting API \u2014 dataset and fit subplots, individual model-image / residual / normalised-residual / chi-squared panels, per-galaxy breakdowns, log10 stretch and fixed colour limits, overlays, writing figures to disk and writing FITS. Also carries the residual-inspection discipline: what a good chi-squared map looks like, what each characteristic residual pattern is telling you about the model, and how to compare two fits honestly. Use when the user wants to look at data before fitting it, look at a finished fit, produce a figure for a paper or a talk, or decide whether a fit is acceptable. Not for composing or running the fit (`ag_build_imaging_model`, `ag_run_search`), not for pulling numbers and posteriors out of a result (`ag_load_results`), and not for the diagnostic workflow when a fit has clearly failed (`ag_debug_fit_failure`).\n---\n\n# Looking at the data, the galaxy, and the fit\n\nPlotting is not decoration here \u2014 it is the main instrument of judgement. A galaxy model is\naccepted or rejected on whether its residuals look like noise, and no summary statistic\nreplaces that look. A chi-squared of 1.05 per pixel with a coherent ring of residuals at one\narcsecond is a *worse* result than a chi-squared of 1.3 scattered randomly, because the first\none is telling you the model is structurally wrong while the second is telling you the noise\nestimate is slightly off.\n\nThe plotting surface is **functional only**. One import, then module-level functions:\n\n```python\nimport autogalaxy.plot as aplt\n```\n\nQuantities are computed from PyAutoGalaxy objects by their own methods, and the resulting\narray or grid is passed to a function\n(`autogalaxy_workspace:scripts/guides/plot/start_here.py`). Because the layer takes plain\narrays, anything the library can compute you can plot, and there is no per-object plotting\nclass to learn.\n\nThere are **no plotter classes and no figure-configuration objects** \u2014 the object-oriented\nplotters and the matplotlib-wrapper objects that older releases shipped were removed. Those\nolder releases are heavily represented in language-model training data, which makes\nreconstructing them from memory the single most common stale-API error in this library. If a\ncall you remember is not in `dir(aplt)`, it is not part of the current API: check before you\nemit it. [`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md) is the authoritative\nenumeration of what does exist, with a \"when to use which\" note on each entry.\n\n## Ask\n\n- *\"Are we looking at the data, a galaxy model, or a fit?\"* Three different branches below.\n Data before fitting is the inspection gate; a galaxy on its own is usually a sanity check on\n a model you just composed; a fit is the judgement call.\n- *\"On screen, or to a file?\"* With no `output_path`, a figure is displayed. From a terminal\n that flashes and vanishes, so default to writing files.\n- *\"Quick look, or a figure for a paper?\"* A quick look is one subplot. A paper figure means\n fixed colour limits, a log10 stretch, a chosen colormap and probably several formats.\n\n## Branch \u2014 the dataset, before you fit it\n\nOne call gives the whole dataset: data, noise-map, PSF, signal-to-noise map and the\nover-sampling panels.\n\n```python\nfrom pathlib import Path\n\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"\"\nPLOT_DIR = Path(\"scripts\") / \"scratch\" / \"\"\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\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\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\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Dataset Subplot__`. Individual\ncomponents are attributes, plotted with the fundamental array function:\n\n```python\naplt.plot_array(array=dataset.data, title=\"Data\")\naplt.plot_array(array=dataset.noise_map, title=\"Noise Map\")\naplt.plot_array(array=dataset.psf.kernel, title=\"PSF\")\naplt.plot_array(array=dataset.signal_to_noise_map, title=\"Signal-to-Noise Map\")\n```\n\nWhat to look for in this figure is the substance of\n[`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md) \u2014 neighbouring galaxies, foreground\nstars, reduction artefacts, and where the galaxy's emission meets the sky, which is what sets\nthe mask radius. Re-plot after `apply_mask` and after `apply_over_sampling`: the subplot's\nlower panels update to show the over-sampling scheme, so you can see the scheme you asked for\nrather than trusting it (`autogalaxy_workspace:scripts/imaging/modeling.py`\n`__Over Sampling__`). Masks and over-sampling as concepts are\n[`wiki/core/concepts/grids_and_masks.md`](../wiki/core/concepts/grids_and_masks.md); the\ndataset object itself is [`wiki/core/api/datasets.md`](../wiki/core/api/datasets.md).\n\n## Branch \u2014 a galaxy or a light profile on its own\n\nUseful before any data is involved: does the model you just composed actually look like the\ngalaxy you have in mind? Every object exposes `image_2d_from(grid=grid)`, and the array goes\nstraight to `plot_array`\n(`autogalaxy_workspace:scripts/guides/plot/plotters.py`):\n\n```python\ngrid = ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.05)\n\nbulge = ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=4.0,\n effective_radius=0.6,\n sersic_index=3.0,\n)\ndisk = ag.lp.Exponential(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.7, angle=30.0),\n intensity=2.0,\n effective_radius=1.6,\n)\n\ngalaxy = ag.Galaxy(redshift=0.5, bulge=bulge, disk=disk)\n\naplt.plot_array(array=bulge.image_2d_from(grid=grid), title=\"Bulge Image\")\naplt.plot_array(array=galaxy.image_2d_from(grid=grid), title=\"Galaxy Image\", use_log10=True)\n```\n\nA galaxy's image is the sum of its light profiles' images, so the bulge/disk decomposition is\nvisible by plotting each component beside the total. `aplt.subplot_galaxy_light_profiles`\ndoes that as one figure; `aplt.subplot_galaxies` shows the summed image plus a panel per\ngalaxy, and takes `auto_filename` to name its file. The physics of what the effective radius\nand Sersic index actually measure is\n[`wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md), and how\nseveral profiles and galaxies compose is\n[`wiki/core/concepts/galaxies.md`](../wiki/core/concepts/galaxies.md).\n\n**Linear light profiles cannot be plotted directly.** An `ag.lp_linear.*` profile has no\n`intensity` until the linear inversion solves for it, so the galaxy-level subplots reject\nthem. Get the solved profiles from a fit \u2014 `fit.galaxies_linear_light_profiles_to_light_profiles`\n\u2014 and plot those instead (`autogalaxy_workspace:scripts/guides/results/start_here.py`\n`__Linear Light Profiles__`). Background:\n[`wiki/core/concepts/linear_light_profiles_and_mge.md`](../wiki/core/concepts/linear_light_profiles_and_mge.md).\n\n## Branch \u2014 the fit, and how to read the residuals\n\nA `FitImaging` compares a model galaxy against the data, PSF convolution included. Build one\nfrom a dataset and galaxies, or take the best-fit one straight off a result:\n\n```python\nfit = ag.FitImaging(dataset=dataset, galaxies=galaxies)\n\n# or, from a completed search:\nfit = result.max_log_likelihood_fit\n```\n\nThe summary figure is six panels \u2014 data, signal-to-noise map, model image, residual map,\nnormalised residual map and chi-squared map:\n\n```python\naplt.subplot_fit_imaging(\n fit=fit,\n output_path=PLOT_DIR,\n output_format=\"png\",\n)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Fit Subplot__`.\n\n**Most fit subplots do not take `output_filename`.** They write a fixed stem into\n`output_path`: `subplot_fit_imaging` writes `fit.png`, and\n`subplot_fit_imaging_of_galaxy` writes `of_galaxy_.png`\n(`PyAutoGalaxy:autogalaxy/imaging/plot/fit_imaging_plots.py`). So the *directory* is what\ndistinguishes one context from another \u2014 give each fit, or each variant of a figure, its own\nfolder under `scripts/scratch/`. The one exception is `subplot_fit_imaging_list` below, which\ndoes take `output_filename`. `plot_array`, `plot_grid` and `subplot_imaging_dataset` do\ntake `output_filename`; `subplot_galaxies` takes `auto_filename`\n(`PyAutoGalaxy:autogalaxy/galaxy/plot/galaxies_plots.py`). Check the signature rather than\nassuming a uniform interface.\n\nTo compare several fits side by side \u2014 the same galaxy under competing models, or one model\nacross a set of datasets \u2014 `subplot_fit_imaging_list` draws one row per fit rather than making\nyou place several `fit.png` files next to each other:\n\n```python\naplt.subplot_fit_imaging_list(\n fit_list=[fit_sersic, fit_bulge_disk, fit_mge],\n output_path=PLOT_DIR,\n output_filename=\"model_comparison\",\n output_format=\"png\",\n)\n```\n\nNote it takes `fit_list=`, not `fit=`. Its rows are data | signal-to-noise | model image |\nnormalised residuals | chi-squared \u2014 five columns, not the six of the single-fit subplot, and\nit drops `colormap` / `use_log10` (`PyAutoGalaxy:autogalaxy/imaging/plot/fit_imaging_plots.py`).\nRead the normalised-residual column across rows: the model that flattens it is the one to keep,\nand the discipline below applies unchanged.\n\nIndividual quantities are attributes, so they go through `plot_array` \u2014 which is also how you\nget per-panel control the subplot does not offer:\n\n```python\naplt.plot_array(array=fit.model_data, title=\"Model Image\")\naplt.plot_array(array=fit.residual_map, title=\"Residual Map\")\naplt.plot_array(array=fit.normalized_residual_map, title=\"Normalized Residual Map\", symmetric=True)\naplt.plot_array(array=fit.chi_squared_map, title=\"Chi-Squared Map\")\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Fit Figures__`. `symmetric=True`\nputs zero at the centre of a diverging colour scale, which is the right choice for a residual\nmap \u2014 otherwise a colormap keyed to the extremes hides the sign of the structure you are\nlooking for.\n\n### The inspection discipline\n\nThree maps, three different questions:\n\n- **`residual_map`** = data \u2212 model, in data units. Answers *how much* flux is unaccounted\n for, and where. Useful for judging whether a mismatch matters physically.\n- **`normalized_residual_map`** = residual / noise. Answers *how significant* the mismatch is.\n This is the map to read first, because it is the only one calibrated against the noise.\n Values scattered within roughly \u00b13 are consistent with noise; coherent structure well\n outside that is a model failure, however small it looks in flux.\n- **`chi_squared_map`** = normalised residual squared. Answers *where the likelihood is being\n paid*, since `fit.chi_squared` is its sum\n (`autogalaxy_workspace:scripts/imaging/likelihood_function.py` `__Chi Squared__`). Squaring\n discards the sign, so read it alongside the normalised residuals rather than instead of\n them.\n\nRead the pattern, not just the magnitude. The characteristic ones:\n\n| Pattern in the normalised residuals | Usually means |\n|---|---|\n| Structure concentrated at the very centre | Over-sampling too coarse, or a genuinely cored/nuclear component the model lacks |\n| A symmetric ring at one radius | The radial profile is wrong \u2014 one Sersic where a bulge plus disk is needed, or a fixed Sersic index |\n| Four-lobed pattern, alternating sign | The ellipticity or position angle is wrong, or the isophotes twist with radius |\n| A compact blob away from the centre | A neighbouring galaxy, a foreground star, or a reduction artefact left in the fit |\n| Clumpy structure with no symmetry | Real asymmetric morphology no smooth profile can absorb |\n| Uniformly slightly too large everywhere | The noise-map is underestimated, or a sky background is unmodelled |\n\nEach row routes somewhere. Ellipticity and isophote twists are\n[`wiki/core/concepts/ellipse_fitting_and_multipoles.md`](../wiki/core/concepts/ellipse_fitting_and_multipoles.md);\nneighbours are\n[`wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md);\nirreducible clumpiness is\n[`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md);\nan unmodelled background is\n[`wiki/core/concepts/sky_background_and_operated_profiles.md`](../wiki/core/concepts/sky_background_and_operated_profiles.md).\nTurning any of those diagnoses into a plan is\n[`ag_debug_fit_failure`](./ag_debug_fit_failure.md).\n\nFor a blended pair or a galaxy with a modelled neighbour, the per-galaxy view is what shows\nwhether the decomposition is real or just two profiles trading flux:\n\n```python\naplt.plot_array(array=fit.model_images_of_galaxies_list[0], title=\"Galaxy 0 Model Image\")\naplt.subplot_fit_imaging_of_galaxy(fit=fit, galaxy_index=0, output_path=PLOT_DIR, output_format=\"png\")\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Galaxy Images__` and\n`__Galaxy Subplots__`. The per-galaxy subplot shows the data with the *other* galaxies\nsubtracted, alongside that galaxy's model image and residuals.\n\n## Branch \u2014 making the figure say what you mean\n\nCustomisation is keyword arguments, never a wrapper object\n(`autogalaxy_workspace:scripts/guides/plot/start_here.py` `__Customization__`):\n\n```python\naplt.plot_array(array=dataset.data, title=\"Jet\", colormap=\"jet\")\naplt.plot_array(array=galaxy.image_2d_from(grid=grid), title=\"Log10\", use_log10=True)\naplt.plot_array(array=dataset.data, title=\"Fixed Scale\", vmin=0.0, vmax=1.0)\n```\n\nThree of these carry scientific weight:\n\n- **`use_log10=True`** \u2014 a galaxy's surface brightness spans orders of magnitude, so a linear\n stretch shows the bright core and nothing else. The log10 view is where faint extended\n emission, tidal features and a disk under a bright bulge become visible. It is available on\n the subplots too, and is often the more honest default for a galaxy.\n- **`vmin` / `vmax`** \u2014 fixed limits are what make two figures comparable. Comparing two fits\n on auto-scaled colour bars is not a comparison.\n- **`symmetric=True`** \u2014 for anything that can be negative, which is every residual map.\n\nOverlays are keyword arguments as well\n(`autogalaxy_workspace:scripts/guides/plot/visuals.py`): `positions=` scatters points such as\nlight-profile centres, `grid=` draws a coordinate grid, `lines=` / `line_colors=` draw\npolylines. Two accepted forms for positions:\n\n```python\nimport numpy as np\n\nlight_profile_centres = galaxies.extract_attribute(cls=ag.LightProfile, attr_name=\"centre\")\n\naplt.plot_array(\n array=galaxies.image_2d_from(grid=grid),\n positions=[np.array(light_profile_centres)],\n title=\"Image with Light Profile Centres\",\n)\n\naplt.plot_array(\n array=galaxy.image_2d_from(grid=grid),\n positions=ag.Grid2DIrregular(values=[(0.0, 0.0)]),\n title=\"Image with Centre\",\n)\n```\n\n1D radial profiles are plain matplotlib on a radially projected grid, not an `aplt` function \u2014\nincluding the shaded error region drawn from a set of profiles sampled from the posterior\n(`autogalaxy_workspace:scripts/guides/plot/plotters.py` `__One Dimensional Plots__` and\n`__Probability Density Function (PDF) Plots__`, which uses\n`ag.util.error.profile_1d_median_and_error_region_via_quantile`).\n\nAnything not passed explicitly comes from `config/visualize/general.yaml` \u2014 the default\ncolormap, tick counts, colorbar label sizes, contour levels, the unit label. Editing that file\nchanges the look project-wide without touching code, after a session or kernel restart. See\n[`wiki/core/api/configuration.md`](../wiki/core/api/configuration.md).\n\n## Branch \u2014 writing to disk, and announcing it\n\nWith `output_path` set (a directory) plus `output_format`, the figure is written rather than\ndisplayed. Without `output_filename` the file is named from the title; `output_format` also\naccepts a list, which writes several formats in one call \u2014 a PNG to look at and a PDF for the\npaper (`autogalaxy_workspace:scripts/guides/plot/start_here.py` `__Output__`):\n\n```python\naplt.plot_array(\n array=dataset.data,\n title=\"Image\",\n output_path=PLOT_DIR,\n output_filename=\"data\",\n output_format=[\"png\", \"pdf\"],\n)\n```\n\nThree rules from [`_style.md`](./_style.md) \"Plot output and path announcement\", and they are\nnot optional:\n\n1. Throwaway figures go to the gitignored `scripts/scratch//`, where `` is\n usually the dataset name. Never `output/` \u2014 that belongs to the fit runtime.\n2. `print(f\"Saved to: {PLOT_DIR.resolve()}\")` at the end of the recipe, so the absolute\n location lands in stdout.\n3. After running, **quote that absolute path back to the user and offer to open it** \u2014\n `xdg-open` on Linux, `open` on macOS, `explorer.exe` or `wslview` from WSL. One offer per\n plot run. \"Plot saved\" on its own is not useful to someone who cannot see your filesystem.\n\nTo write data rather than an image, the `fits_*` functions are separate\n(`autogalaxy_workspace:scripts/imaging/plot.py` `__Outputting to FITS__`):\n\n```python\naplt.fits_imaging(dataset=dataset, file_path=PLOT_DIR / \"dataset.fits\", overwrite=True)\naplt.fits_array(array=mask, file_path=DATASET_PATH / \"mask.fits\", overwrite=True)\n```\n\n`file_path` writes one multi-HDU file with named extensions; the per-component\n`data_path` / `psf_path` / `noise_map_path` arguments write separate files instead.\n\n## Branch \u2014 the figures a fit produces on its own\n\nYou do not need any of the above to watch a fit converge. Each analysis carries a `Visualizer`\nthat PyAutoFit invokes at every update interval and again at the end, writing the standard\ndataset, fit and per-galaxy figures into the fit's `image/` folder using the best model found\nso far (`autogalaxy_workspace:scripts/imaging/plot.py` `__Visualizer__`;\n`PyAutoGalaxy:autogalaxy/imaging/model/visualizer.py`). Which figures appear is set by\n`config/visualize/plots.yaml` \u2014 `dataset -> subplot_dataset`, `fit -> subplot_fit`,\n`fit -> subplot_of_galaxies` \u2014 so switching a figure on or off for every fit is a YAML edit,\nnot a code change. The cadence is the search's `iterations_per_quick_update`\n([`ag_run_search`](./ag_run_search.md)).\n\nReach for this skill when you want something the automatic figures do not give you: a\ndifferent stretch, a crop, fixed limits across two fits, a specific panel at publication\nsize, or a per-galaxy breakdown that `plots.yaml` has switched off.\n\nPosterior figures \u2014 corner plots and likelihood traces \u2014 come from PyAutoFit and take\n`samples` plus `path` / `filename` / `format` rather than the `output_*` names, e.g.\n`aplt.corner_cornerpy(samples=result.samples)`. They belong to\n[`ag_load_results`](./ag_load_results.md); the surface is tabulated in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md) \"Search results\".\n\n## Combine\n\n- [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md) \u2014 the inspection the dataset\n subplot exists to serve, and the mask that follows from it.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) \u2014 you have read the residuals and they\n are wrong; this is the triage.\n- [`ag_load_results`](./ag_load_results.md) \u2014 the numbers behind the figures, and figures\n across many fits at once.\n- [`ag_run_search`](./ag_run_search.md) \u2014 the fit that produced the `image/` folder, and the\n cadence at which it refreshes.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) \u2014 plot a simulated fit where you know the\n truth, to calibrate what an acceptable residual map looks like for your data quality.\n\nWhen a figure is going into a paper or a talk, offer (default-yes) the dated\n`wiki/project/YYYY-MM-DD-.md` entry recording what it shows and which fit it came from\n\u2014 per [`_style.md`](./_style.md) property #5.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [HowToGalaxy: Fitting](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_3_fitting.ipynb):\n builds up residuals, normalised residuals and the chi-squared map from first principles, so\n the six panels of a fit subplot stop being opaque.\n- **General reference** \u2014 [RTD: Plot API reference](https://pyautogalaxy.readthedocs.io/en/latest/api/plot.html):\n the generated reference for the visualisation library.\n- **Experienced PyAutoGalaxy user** \u2014 [workspace: guides/plot/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/guides/plot/start_here.py):\n the plotting API in one runnable script \u2014 customisation, output, config defaults, overlays\n and subplots.\n\n## Agent procedural checklist\n\n1. Establish what is being plotted: dataset, galaxy/profile, or fit.\n2. Ground every call against [`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md) or\n `dir(aplt)`. Never write a plotter class or a figure-configuration object.\n3. Check the signature for `output_filename` before passing it \u2014 the fit and galaxy subplots\n do not accept it and write a fixed stem instead.\n4. Write the recipe into a script; send figures to `scripts/scratch//`.\n5. `print` the resolved plot directory at the end of the script.\n6. For a fit, read the **normalised residual** map first, then the chi-squared map; report the\n pattern, not only the number.\n7. Use `symmetric=True` on residuals, `use_log10=True` for galaxy light, and fixed\n `vmin`/`vmax` whenever two figures will be compared.\n8. Quote the absolute path back and offer to open it \u2014 once per plot run.\n9. Route any diagnosed model failure to the debug skill rather than tweaking the figure until\n it looks acceptable.\n10. Offer the `wiki/project/` entry for a figure that will be published.\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_1_introduction/tutorial_5_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_plot_fit\n\n---\nname: ag_plot_fit\ndescription: Visualise a dataset, a galaxy, or a fit with the functional `aplt` plotting API — dataset and fit subplots, individual model-image / residual / normalised-residual / chi-squared panels, per-galaxy breakdowns, log10 stretch and fixed colour limits, overlays, writing figures to disk and writing FITS. Also carries the residual-inspection discipline: what a good chi-squared map looks like, what each characteristic residual pattern is telling you about the model, and how to compare two fits honestly. Use when the user wants to look at data before fitting it, look at a finished fit, produce a figure for a paper or a talk, or decide whether a fit is acceptable. Not for composing or running the fit (`ag_build_imaging_model`, `ag_run_search`), not for pulling numbers and posteriors out of a result (`ag_load_results`), and not for the diagnostic workflow when a fit has clearly failed (`ag_debug_fit_failure`).\n---\n\n# Looking at the data, the galaxy, and the fit\n\nPlotting is not decoration here — it is the main instrument of judgement. A galaxy model is\naccepted or rejected on whether its residuals look like noise, and no summary statistic\nreplaces that look. A chi-squared of 1.05 per pixel with a coherent ring of residuals at one\narcsecond is a *worse* result than a chi-squared of 1.3 scattered randomly, because the first\none is telling you the model is structurally wrong while the second is telling you the noise\nestimate is slightly off.\n\nThe plotting surface is **functional only**. One import, then module-level functions:\n\n```python\nimport autogalaxy.plot as aplt\n```\n\nQuantities are computed from PyAutoGalaxy objects by their own methods, and the resulting\narray or grid is passed to a function\n(`autogalaxy_workspace:scripts/guides/plot/start_here.py`). Because the layer takes plain\narrays, anything the library can compute you can plot, and there is no per-object plotting\nclass to learn.\n\nThere are **no plotter classes and no figure-configuration objects** — the object-oriented\nplotters and the matplotlib-wrapper objects that older releases shipped were removed. Those\nolder releases are heavily represented in language-model training data, which makes\nreconstructing them from memory the single most common stale-API error in this library. If a\ncall you remember is not in `dir(aplt)`, it is not part of the current API: check before you\nemit it. [`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md) is the authoritative\nenumeration of what does exist, with a \"when to use which\" note on each entry.\n\n## Ask\n\n- *\"Are we looking at the data, a galaxy model, or a fit?\"* Three different branches below.\n Data before fitting is the inspection gate; a galaxy on its own is usually a sanity check on\n a model you just composed; a fit is the judgement call.\n- *\"On screen, or to a file?\"* With no `output_path`, a figure is displayed. From a terminal\n that flashes and vanishes, so default to writing files.\n- *\"Quick look, or a figure for a paper?\"* A quick look is one subplot. A paper figure means\n fixed colour limits, a log10 stretch, a chosen colormap and probably several formats.\n\n## Branch — the dataset, before you fit it\n\nOne call gives the whole dataset: data, noise-map, PSF, signal-to-noise map and the\nover-sampling panels.\n\n```python\nfrom pathlib import Path\n\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"\"\nPLOT_DIR = Path(\"scripts\") / \"scratch\" / \"\"\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\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\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\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Dataset Subplot__`. Individual\ncomponents are attributes, plotted with the fundamental array function:\n\n```python\naplt.plot_array(array=dataset.data, title=\"Data\")\naplt.plot_array(array=dataset.noise_map, title=\"Noise Map\")\naplt.plot_array(array=dataset.psf.kernel, title=\"PSF\")\naplt.plot_array(array=dataset.signal_to_noise_map, title=\"Signal-to-Noise Map\")\n```\n\nWhat to look for in this figure is the substance of\n[`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md) — neighbouring galaxies, foreground\nstars, reduction artefacts, and where the galaxy's emission meets the sky, which is what sets\nthe mask radius. Re-plot after `apply_mask` and after `apply_over_sampling`: the subplot's\nlower panels update to show the over-sampling scheme, so you can see the scheme you asked for\nrather than trusting it (`autogalaxy_workspace:scripts/imaging/modeling.py`\n`__Over Sampling__`). Masks and over-sampling as concepts are\n[`wiki/core/concepts/grids_and_masks.md`](../wiki/core/concepts/grids_and_masks.md); the\ndataset object itself is [`wiki/core/api/datasets.md`](../wiki/core/api/datasets.md).\n\n## Branch — a galaxy or a light profile on its own\n\nUseful before any data is involved: does the model you just composed actually look like the\ngalaxy you have in mind? Every object exposes `image_2d_from(grid=grid)`, and the array goes\nstraight to `plot_array`\n(`autogalaxy_workspace:scripts/guides/plot/plotters.py`):\n\n```python\ngrid = ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.05)\n\nbulge = ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=4.0,\n effective_radius=0.6,\n sersic_index=3.0,\n)\ndisk = ag.lp.Exponential(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.7, angle=30.0),\n intensity=2.0,\n effective_radius=1.6,\n)\n\ngalaxy = ag.Galaxy(redshift=0.5, bulge=bulge, disk=disk)\n\naplt.plot_array(array=bulge.image_2d_from(grid=grid), title=\"Bulge Image\")\naplt.plot_array(array=galaxy.image_2d_from(grid=grid), title=\"Galaxy Image\", use_log10=True)\n```\n\nA galaxy's image is the sum of its light profiles' images, so the bulge/disk decomposition is\nvisible by plotting each component beside the total. `aplt.subplot_galaxy_light_profiles`\ndoes that as one figure; `aplt.subplot_galaxies` shows the summed image plus a panel per\ngalaxy, and takes `auto_filename` to name its file. The physics of what the effective radius\nand Sersic index actually measure is\n[`wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md), and how\nseveral profiles and galaxies compose is\n[`wiki/core/concepts/galaxies.md`](../wiki/core/concepts/galaxies.md).\n\n**Linear light profiles cannot be plotted directly.** An `ag.lp_linear.*` profile has no\n`intensity` until the linear inversion solves for it, so the galaxy-level subplots reject\nthem. Get the solved profiles from a fit — `fit.galaxies_linear_light_profiles_to_light_profiles`\n— and plot those instead (`autogalaxy_workspace:scripts/guides/results/start_here.py`\n`__Linear Light Profiles__`). Background:\n[`wiki/core/concepts/linear_light_profiles_and_mge.md`](../wiki/core/concepts/linear_light_profiles_and_mge.md).\n\n## Branch — the fit, and how to read the residuals\n\nA `FitImaging` compares a model galaxy against the data, PSF convolution included. Build one\nfrom a dataset and galaxies, or take the best-fit one straight off a result:\n\n```python\nfit = ag.FitImaging(dataset=dataset, galaxies=galaxies)\n\n# or, from a completed search:\nfit = result.max_log_likelihood_fit\n```\n\nThe summary figure is six panels — data, signal-to-noise map, model image, residual map,\nnormalised residual map and chi-squared map:\n\n```python\naplt.subplot_fit_imaging(\n fit=fit,\n output_path=PLOT_DIR,\n output_format=\"png\",\n)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Fit Subplot__`.\n\n**Most fit subplots do not take `output_filename`.** They write a fixed stem into\n`output_path`: `subplot_fit_imaging` writes `fit.png`, and\n`subplot_fit_imaging_of_galaxy` writes `of_galaxy_.png`\n(`PyAutoGalaxy:autogalaxy/imaging/plot/fit_imaging_plots.py`). So the *directory* is what\ndistinguishes one context from another — give each fit, or each variant of a figure, its own\nfolder under `scripts/scratch/`. The one exception is `subplot_fit_imaging_list` below, which\ndoes take `output_filename`. `plot_array`, `plot_grid` and `subplot_imaging_dataset` do\ntake `output_filename`; `subplot_galaxies` takes `auto_filename`\n(`PyAutoGalaxy:autogalaxy/galaxy/plot/galaxies_plots.py`). Check the signature rather than\nassuming a uniform interface.\n\nTo compare several fits side by side — the same galaxy under competing models, or one model\nacross a set of datasets — `subplot_fit_imaging_list` draws one row per fit rather than making\nyou place several `fit.png` files next to each other:\n\n```python\naplt.subplot_fit_imaging_list(\n fit_list=[fit_sersic, fit_bulge_disk, fit_mge],\n output_path=PLOT_DIR,\n output_filename=\"model_comparison\",\n output_format=\"png\",\n)\n```\n\nNote it takes `fit_list=`, not `fit=`. Its rows are data | signal-to-noise | model image |\nnormalised residuals | chi-squared — five columns, not the six of the single-fit subplot, and\nit drops `colormap` / `use_log10` (`PyAutoGalaxy:autogalaxy/imaging/plot/fit_imaging_plots.py`).\nRead the normalised-residual column across rows: the model that flattens it is the one to keep,\nand the discipline below applies unchanged.\n\nIndividual quantities are attributes, so they go through `plot_array` — which is also how you\nget per-panel control the subplot does not offer:\n\n```python\naplt.plot_array(array=fit.model_data, title=\"Model Image\")\naplt.plot_array(array=fit.residual_map, title=\"Residual Map\")\naplt.plot_array(array=fit.normalized_residual_map, title=\"Normalized Residual Map\", symmetric=True)\naplt.plot_array(array=fit.chi_squared_map, title=\"Chi-Squared Map\")\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Fit Figures__`. `symmetric=True`\nputs zero at the centre of a diverging colour scale, which is the right choice for a residual\nmap — otherwise a colormap keyed to the extremes hides the sign of the structure you are\nlooking for.\n\n### The inspection discipline\n\nThree maps, three different questions:\n\n- **`residual_map`** = data − model, in data units. Answers *how much* flux is unaccounted\n for, and where. Useful for judging whether a mismatch matters physically.\n- **`normalized_residual_map`** = residual / noise. Answers *how significant* the mismatch is.\n This is the map to read first, because it is the only one calibrated against the noise.\n Values scattered within roughly ±3 are consistent with noise; coherent structure well\n outside that is a model failure, however small it looks in flux.\n- **`chi_squared_map`** = normalised residual squared. Answers *where the likelihood is being\n paid*, since `fit.chi_squared` is its sum\n (`autogalaxy_workspace:scripts/imaging/likelihood_function.py` `__Chi Squared__`). Squaring\n discards the sign, so read it alongside the normalised residuals rather than instead of\n them.\n\nRead the pattern, not just the magnitude. The characteristic ones:\n\n| Pattern in the normalised residuals | Usually means |\n|---|---|\n| Structure concentrated at the very centre | Over-sampling too coarse, or a genuinely cored/nuclear component the model lacks |\n| A symmetric ring at one radius | The radial profile is wrong — one Sersic where a bulge plus disk is needed, or a fixed Sersic index |\n| Four-lobed pattern, alternating sign | The ellipticity or position angle is wrong, or the isophotes twist with radius |\n| A compact blob away from the centre | A neighbouring galaxy, a foreground star, or a reduction artefact left in the fit |\n| Clumpy structure with no symmetry | Real asymmetric morphology no smooth profile can absorb |\n| Uniformly slightly too large everywhere | The noise-map is underestimated, or a sky background is unmodelled |\n\nEach row routes somewhere. Ellipticity and isophote twists are\n[`wiki/core/concepts/ellipse_fitting_and_multipoles.md`](../wiki/core/concepts/ellipse_fitting_and_multipoles.md);\nneighbours are\n[`wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md);\nirreducible clumpiness is\n[`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md);\nan unmodelled background is\n[`wiki/core/concepts/sky_background_and_operated_profiles.md`](../wiki/core/concepts/sky_background_and_operated_profiles.md).\nTurning any of those diagnoses into a plan is\n[`ag_debug_fit_failure`](./ag_debug_fit_failure.md).\n\nFor a blended pair or a galaxy with a modelled neighbour, the per-galaxy view is what shows\nwhether the decomposition is real or just two profiles trading flux:\n\n```python\naplt.plot_array(array=fit.model_images_of_galaxies_list[0], title=\"Galaxy 0 Model Image\")\naplt.subplot_fit_imaging_of_galaxy(fit=fit, galaxy_index=0, output_path=PLOT_DIR, output_format=\"png\")\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Galaxy Images__` and\n`__Galaxy Subplots__`. The per-galaxy subplot shows the data with the *other* galaxies\nsubtracted, alongside that galaxy's model image and residuals.\n\n## Branch — making the figure say what you mean\n\nCustomisation is keyword arguments, never a wrapper object\n(`autogalaxy_workspace:scripts/guides/plot/start_here.py` `__Customization__`):\n\n```python\naplt.plot_array(array=dataset.data, title=\"Jet\", colormap=\"jet\")\naplt.plot_array(array=galaxy.image_2d_from(grid=grid), title=\"Log10\", use_log10=True)\naplt.plot_array(array=dataset.data, title=\"Fixed Scale\", vmin=0.0, vmax=1.0)\n```\n\nThree of these carry scientific weight:\n\n- **`use_log10=True`** — a galaxy's surface brightness spans orders of magnitude, so a linear\n stretch shows the bright core and nothing else. The log10 view is where faint extended\n emission, tidal features and a disk under a bright bulge become visible. It is available on\n the subplots too, and is often the more honest default for a galaxy.\n- **`vmin` / `vmax`** — fixed limits are what make two figures comparable. Comparing two fits\n on auto-scaled colour bars is not a comparison.\n- **`symmetric=True`** — for anything that can be negative, which is every residual map.\n\nOverlays are keyword arguments as well\n(`autogalaxy_workspace:scripts/guides/plot/visuals.py`): `positions=` scatters points such as\nlight-profile centres, `grid=` draws a coordinate grid, `lines=` / `line_colors=` draw\npolylines. Two accepted forms for positions:\n\n```python\nimport numpy as np\n\nlight_profile_centres = galaxies.extract_attribute(cls=ag.LightProfile, attr_name=\"centre\")\n\naplt.plot_array(\n array=galaxies.image_2d_from(grid=grid),\n positions=[np.array(light_profile_centres)],\n title=\"Image with Light Profile Centres\",\n)\n\naplt.plot_array(\n array=galaxy.image_2d_from(grid=grid),\n positions=ag.Grid2DIrregular(values=[(0.0, 0.0)]),\n title=\"Image with Centre\",\n)\n```\n\n1D radial profiles are plain matplotlib on a radially projected grid, not an `aplt` function —\nincluding the shaded error region drawn from a set of profiles sampled from the posterior\n(`autogalaxy_workspace:scripts/guides/plot/plotters.py` `__One Dimensional Plots__` and\n`__Probability Density Function (PDF) Plots__`, which uses\n`ag.util.error.profile_1d_median_and_error_region_via_quantile`).\n\nAnything not passed explicitly comes from `config/visualize/general.yaml` — the default\ncolormap, tick counts, colorbar label sizes, contour levels, the unit label. Editing that file\nchanges the look project-wide without touching code, after a session or kernel restart. See\n[`wiki/core/api/configuration.md`](../wiki/core/api/configuration.md).\n\n## Branch — writing to disk, and announcing it\n\nWith `output_path` set (a directory) plus `output_format`, the figure is written rather than\ndisplayed. Without `output_filename` the file is named from the title; `output_format` also\naccepts a list, which writes several formats in one call — a PNG to look at and a PDF for the\npaper (`autogalaxy_workspace:scripts/guides/plot/start_here.py` `__Output__`):\n\n```python\naplt.plot_array(\n array=dataset.data,\n title=\"Image\",\n output_path=PLOT_DIR,\n output_filename=\"data\",\n output_format=[\"png\", \"pdf\"],\n)\n```\n\nThree rules from [`_style.md`](./_style.md) \"Plot output and path announcement\", and they are\nnot optional:\n\n1. Throwaway figures go to the gitignored `scripts/scratch//`, where `` is\n usually the dataset name. Never `output/` — that belongs to the fit runtime.\n2. `print(f\"Saved to: {PLOT_DIR.resolve()}\")` at the end of the recipe, so the absolute\n location lands in stdout.\n3. After running, **quote that absolute path 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 per\n plot run. \"Plot saved\" on its own is not useful to someone who cannot see your filesystem.\n\nTo write data rather than an image, the `fits_*` functions are separate\n(`autogalaxy_workspace:scripts/imaging/plot.py` `__Outputting to FITS__`):\n\n```python\naplt.fits_imaging(dataset=dataset, file_path=PLOT_DIR / \"dataset.fits\", overwrite=True)\naplt.fits_array(array=mask, file_path=DATASET_PATH / \"mask.fits\", overwrite=True)\n```\n\n`file_path` writes one multi-HDU file with named extensions; the per-component\n`data_path` / `psf_path` / `noise_map_path` arguments write separate files instead.\n\n## Branch — the figures a fit produces on its own\n\nYou do not need any of the above to watch a fit converge. Each analysis carries a `Visualizer`\nthat PyAutoFit invokes at every update interval and again at the end, writing the standard\ndataset, fit and per-galaxy figures into the fit's `image/` folder using the best model found\nso far (`autogalaxy_workspace:scripts/imaging/plot.py` `__Visualizer__`;\n`PyAutoGalaxy:autogalaxy/imaging/model/visualizer.py`). Which figures appear is set by\n`config/visualize/plots.yaml` — `dataset -> subplot_dataset`, `fit -> subplot_fit`,\n`fit -> subplot_of_galaxies` — so switching a figure on or off for every fit is a YAML edit,\nnot a code change. The cadence is the search's `iterations_per_quick_update`\n([`ag_run_search`](./ag_run_search.md)).\n\nReach for this skill when you want something the automatic figures do not give you: a\ndifferent stretch, a crop, fixed limits across two fits, a specific panel at publication\nsize, or a per-galaxy breakdown that `plots.yaml` has switched off.\n\nPosterior figures — corner plots and likelihood traces — come from PyAutoFit and take\n`samples` plus `path` / `filename` / `format` rather than the `output_*` names, e.g.\n`aplt.corner_cornerpy(samples=result.samples)`. They belong to\n[`ag_load_results`](./ag_load_results.md); the surface is tabulated in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md) \"Search results\".\n\n## Combine\n\n- [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md) — the inspection the dataset\n subplot exists to serve, and the mask that follows from it.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) — you have read the residuals and they\n are wrong; this is the triage.\n- [`ag_load_results`](./ag_load_results.md) — the numbers behind the figures, and figures\n across many fits at once.\n- [`ag_run_search`](./ag_run_search.md) — the fit that produced the `image/` folder, and the\n cadence at which it refreshes.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) — plot a simulated fit where you know the\n truth, to calibrate what an acceptable residual map looks like for your data quality.\n\nWhen a figure is going into a paper or a talk, offer (default-yes) the dated\n`wiki/project/YYYY-MM-DD-.md` entry recording what it shows and which fit it came from\n— per [`_style.md`](./_style.md) property #5.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Fitting](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_3_fitting.ipynb):\n builds up residuals, normalised residuals and the chi-squared map from first principles, so\n the six panels of a fit subplot stop being opaque.\n- **General reference** — [RTD: Plot API reference](https://pyautogalaxy.readthedocs.io/en/latest/api/plot.html):\n the generated reference for the visualisation library.\n- **Experienced PyAutoGalaxy user** — [workspace: guides/plot/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/guides/plot/start_here.py):\n the plotting API in one runnable script — customisation, output, config defaults, overlays\n and subplots.\n\n## Agent procedural checklist\n\n1. Establish what is being plotted: dataset, galaxy/profile, or fit.\n2. Ground every call against [`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md) or\n `dir(aplt)`. Never write a plotter class or a figure-configuration object.\n3. Check the signature for `output_filename` before passing it — the fit and galaxy subplots\n do not accept it and write a fixed stem instead.\n4. Write the recipe into a script; send figures to `scripts/scratch//`.\n5. `print` the resolved plot directory at the end of the script.\n6. For a fit, read the **normalised residual** map first, then the chi-squared map; report the\n pattern, not only the number.\n7. Use `symmetric=True` on residuals, `use_log10=True` for galaxy light, and fixed\n `vmin`/`vmax` whenever two figures will be compared.\n8. Quote the absolute path back and offer to open it — once per plot run.\n9. Route any diagnosed model failure to the debug skill rather than tweaking the figure until\n it looks acceptable.\n10. Offer the `wiki/project/` entry for a figure that will be published.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_2_modeling/tutorial_10_prior_passing.ipynb b/notebooks/chapter_2_modeling/tutorial_10_prior_passing.ipynb index 200e1c6..790d12f 100644 --- a/notebooks/chapter_2_modeling/tutorial_10_prior_passing.ipynb +++ b/notebooks/chapter_2_modeling/tutorial_10_prior_passing.ipynb @@ -35,21 +35,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", diff --git a/notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb b/notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb index 15aeccb..2b1a3ba 100644 --- a/notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb +++ b/notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb @@ -173,21 +173,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", diff --git a/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb b/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb index 49eb8d5..1495003 100644 --- a/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb +++ b/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb @@ -48,21 +48,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", diff --git a/notebooks/chapter_2_modeling/tutorial_3_realism_and_complexity.ipynb b/notebooks/chapter_2_modeling/tutorial_3_realism_and_complexity.ipynb index 18b3521..fa3a415 100644 --- a/notebooks/chapter_2_modeling/tutorial_3_realism_and_complexity.ipynb +++ b/notebooks/chapter_2_modeling/tutorial_3_realism_and_complexity.ipynb @@ -37,21 +37,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -453,7 +453,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_realism_and_complexity.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 \u2014 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 \u2014 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 \u2014\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 \u2014 contaminants and mask\nextent are settled in [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md), not\nretrospectively.\n\n## Branch \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u2014 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` \u2014 the human-readable fit summary, parameters with errors.\n2. `image/fit.png` \u2014 data, model image, residuals and chi-squared map in one figure.\n3. `search.log` \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u2014 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`** \u2014 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`** \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u2014 see [`ag_debug_fit_failure`](./ag_debug_fit_failure.md).\n\nFor running on a cluster \u2014 SLURM array jobs, one galaxy per task, the CPU and GPU batch\nscripts, and `number_of_cores` read from `SLURM_CPUS_PER_TASK` \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u00d7 16 pixels \u2014 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 \u2014 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) \u2014 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) \u2014 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) \u2014 the fit finished but the residuals or\n the parameters are wrong.\n- [`ag_configure_search`](./ag_configure_search.md) \u2014 the fit is too slow, or the sampler is\n the wrong one for the model.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) \u2014 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 \u2014 per [`_style.md`](./_style.md) property #5.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [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 \u2014 output structure, reviewing results as they appear,\n and managing run times.\n- **General reference** \u2014 [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** \u2014 [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_realism_and_complexity.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_2_modeling/tutorial_4_dealing_with_failure.ipynb b/notebooks/chapter_2_modeling/tutorial_4_dealing_with_failure.ipynb index 986b495..f2c662c 100644 --- a/notebooks/chapter_2_modeling/tutorial_4_dealing_with_failure.ipynb +++ b/notebooks/chapter_2_modeling/tutorial_4_dealing_with_failure.ipynb @@ -37,21 +37,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -748,7 +748,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_dealing_with_failure.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_dealing_with_failure.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: 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** — [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_5_linear_profiles.ipynb b/notebooks/chapter_2_modeling/tutorial_5_linear_profiles.ipynb index 85a9d77..63f4853 100644 --- a/notebooks/chapter_2_modeling/tutorial_5_linear_profiles.ipynb +++ b/notebooks/chapter_2_modeling/tutorial_5_linear_profiles.ipynb @@ -51,21 +51,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -875,7 +875,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_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_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** \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" + "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_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 — 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" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_2_modeling/tutorial_6_masking.ipynb b/notebooks/chapter_2_modeling/tutorial_6_masking.ipynb index d334733..0264640 100644 --- a/notebooks/chapter_2_modeling/tutorial_6_masking.ipynb +++ b/notebooks/chapter_2_modeling/tutorial_6_masking.ipynb @@ -26,21 +26,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -287,7 +287,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_masking.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 \u2014 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 \u2014 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 \u2014 which pixels are in the sum \u2014 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 \u2014 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** \u2014 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** \u2014 a planning-only or read-only session,\na harness whose tools are restricted \u2014 **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** \u2014 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?\"* \u2014 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?\"* \u2014 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?\"* \u2014 the (a) half of the gate.\n- *\"How far out do you care about the light \u2014 just the bright body, or the faint outer\n envelope?\"* \u2014 this is the (b) half of the gate phrased as a science question, which is\n how it should be decided.\n\n## Branch \u2014 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 \u2014 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 \u2014\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) \u2014 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 \u2014 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 \u2014 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 \u2014 `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 \u2014 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 \u2014 `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\u00d711 to 21\u00d721\npixels. Larger kernels (51\u00d751) 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 \u2014 (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 \u2014 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 \u2014 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 \u2014 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\u00d75 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 \u2014 (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` \u2014 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 \u2014 `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 \u2014 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 \u2014 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\u00d78\nsub-sampling inside 0.3\", 4\u00d74 between 0.3\" and 0.6\", and 2\u00d72 beyond \u2014 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\u00d72 while the target gets 8\u00d78 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 \u2014 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`** \u2014 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`** \u2014 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 \u2014 where this hands off\n\n- **The gate is satisfied and the dataset is loaded, masked and over-sampled** \u2192\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** \u2192\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** \u2192 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** \u2192 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 \u2014 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** \u2014 [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** \u2014 [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** \u2014 [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 \u2014 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 \u2192 the mask \u2192 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_masking.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" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_2_modeling/tutorial_7_results.ipynb b/notebooks/chapter_2_modeling/tutorial_7_results.ipynb index 4dd85e3..06ffb83 100644 --- a/notebooks/chapter_2_modeling/tutorial_7_results.ipynb +++ b/notebooks/chapter_2_modeling/tutorial_7_results.ipynb @@ -26,21 +26,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -285,7 +285,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_results.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 \u2014 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 \u00b1 0.08 arcseconds and a Sersic index of 3.9 \u00b1 0.3\"*.\n\nLoading is never the goal on its own \u2014 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 \u2014 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\"* \u2192 the `Samples` branch.\n *\"The residuals / how good is the fit\"* \u2192 the fit branch, then\n [`ag_plot_fit`](./ag_plot_fit.md). *\"A physical quantity in kpc or solar luminosities\"* \u2192\n the derived-quantities branch. *\"A table over all my galaxies\"* \u2192 the aggregator branch.\n- **One fit, or many?** One fit you already have a path to \u2192 simple loading. More than a\n handful, or you want to iterate and filter \u2192 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 \u2014 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 \u2014 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\u00b2\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 \u2014\n`result.samples_summary`, `result.model`, `result.instance`, `result.dataset`, `result.grids`,\n`result.unmasked_model_image`, the per-galaxy image dictionaries \u2014 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\u03c3/3\u03c3 errors, so reaching for it instead of re-deriving from `samples` is\nsubstantially faster and gives the same answer.\n\n## Branch \u2014 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 \u2014 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** \u2014 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 \u2014\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 \u2014 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** \u2014 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/\u22120.07 at\n 1\u03c3 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 \u2014 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 \u2014\n[`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\n## Branch \u2014 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 \u2014 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 \u2014 scaling\nthe parameter's own error, or quoting the best-fit value with no error \u2014 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 \u2014 many fits, with the aggregator\n\nOnce the unit of work is a *sample* \u2014 a hundred galaxies with one model, or one galaxy with\nten models \u2014 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 \u2014 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 \u2014 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` \u2014 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** \u2014 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 \u2014 `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\u2014 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 \u2014 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 \u2014 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) \u2014 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) \u2014 the numbers loaded fine but they are\n not believable.\n- [`ag_run_search`](./ag_run_search.md) \u2014 the run that produced this output, and what it wrote\n where.\n- [`ag_configure_search`](./ag_configure_search.md) \u2014 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 \u2014 [`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 \u2014 a table, a derived quantity, a comparison across fits \u2014\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** \u2014 [HowToGalaxy: Results](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_7_results.ipynb):\n the `Result` object from first principles \u2014 best-fit model, galaxies, posterior samples, and\n pulling parameter values with uncertainties out of them.\n- **General reference** \u2014 [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** \u2014 [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 \u2014 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 \u2014 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_results.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" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_2_modeling/tutorial_8_need_for_speed.ipynb b/notebooks/chapter_2_modeling/tutorial_8_need_for_speed.ipynb index 0979bc4..ca078d3 100644 --- a/notebooks/chapter_2_modeling/tutorial_8_need_for_speed.ipynb +++ b/notebooks/chapter_2_modeling/tutorial_8_need_for_speed.ipynb @@ -173,21 +173,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -240,7 +240,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_8_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 \u2014 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 \u2014 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 \u2014\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 \u2014 contaminants and mask\nextent are settled in [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md), not\nretrospectively.\n\n## Branch \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u2014 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` \u2014 the human-readable fit summary, parameters with errors.\n2. `image/fit.png` \u2014 data, model image, residuals and chi-squared map in one figure.\n3. `search.log` \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u2014 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`** \u2014 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`** \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u2014 see [`ag_debug_fit_failure`](./ag_debug_fit_failure.md).\n\nFor running on a cluster \u2014 SLURM array jobs, one galaxy per task, the CPU and GPU batch\nscripts, and `number_of_cores` read from `SLURM_CPUS_PER_TASK` \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u00d7 16 pixels \u2014 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 \u2014 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) \u2014 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) \u2014 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) \u2014 the fit finished but the residuals or\n the parameters are wrong.\n- [`ag_configure_search`](./ag_configure_search.md) \u2014 the fit is too slow, or the sampler is\n the wrong one for the model.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) \u2014 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 \u2014 per [`_style.md`](./_style.md) property #5.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [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 \u2014 output structure, reviewing results as they appear,\n and managing run times.\n- **General reference** \u2014 [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** \u2014 [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_8_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_2_modeling/tutorial_9_search_chaining.ipynb b/notebooks/chapter_2_modeling/tutorial_9_search_chaining.ipynb index 5ae381d..0af3807 100644 --- a/notebooks/chapter_2_modeling/tutorial_9_search_chaining.ipynb +++ b/notebooks/chapter_2_modeling/tutorial_9_search_chaining.ipynb @@ -62,21 +62,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -613,7 +613,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_9_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 \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u2014\n`galaxy.bulge.effective_radius = result_1.model_centred.galaxies.galaxy.bulge.effective_radius` \u2014\nwhich is how you narrow some parameters and leave others broad.\n\n## Branch \u2014 `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`** \u2014 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 \u2014 reuse the\ncomposition, refit from scratch \u2014 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`** \u2014 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 \u00d7 mean`, per parameter |\n| `result.model_centred_max_lh_bounded(b=0.3)` | `UniformPrior` | bounds at `mean \u00b1 b` |\n\n**`result.instance`** \u2014 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 \u2014 so the third stage is not optional if the decomposition is the result you are\nquoting.\n\n## Branch \u2014 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** \u2014 `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** \u2014 `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 \u2014 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 \u00b1 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 \u2014 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 \u2014 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 \u2014 the practical mechanics\n\n**One analysis, reused.** Build the `ag.AnalysisImaging` once, before search 1, and pass the same\nobject to every search \u2014 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 \u2014 never quote them.\n\n## Combine\n\n- [`ag_configure_search`](./ag_configure_search.md) \u2014 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) \u2014 driving each stage and reading its output folder.\n- [`ag_build_imaging_model`](./ag_build_imaging_model.md) \u2014 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) \u2014 adding galaxies one at a\n time is the most common real use of chaining.\n- [`ag_multi_dataset`](./ag_multi_dataset.md) \u2014 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) \u2014 when a single search lands somewhere\n unphysical, which is the diagnosis that most often leads here.\n- `ag_pixelization` \u2014 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 \u2014 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** \u2014 [HowToGalaxy: Search chaining](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_9_search_chaining.ipynb):\n the first chaining tutorial at the end of chapter 2, which builds the idea from a fit that fails\n without it; `tutorial_10_prior_passing` then walks the prior mechanics, and\n `chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy` applies the ideas to blended galaxies.\n- **General reference** \u2014 [RTD: Configs](https://pyautogalaxy.readthedocs.io/en/latest/general/configs.html):\n how the config files are laid out and looked up \u2014 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** \u2014 [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 \u2014 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 \u2014 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 \u2014 the chain needs samples to pass).\n11. Offer the `wiki/project/` entry recording the split and the passing 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_9_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_9_search_chaining.ipynb):\n the first chaining tutorial at the end of chapter 2, which builds the idea from a fit that fails\n without it; `tutorial_10_prior_passing` then walks the prior mechanics, and\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_3_pixelizations/tutorial_1_pixelizations.ipynb b/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb index 83cbf97..1bf0a4d 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb @@ -26,21 +26,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -341,7 +341,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 — the hybrid model that gives a smooth interpretable component plus a flexible flux map for everything the profile cannot explain. Covers when a pixelization is warranted and when it is overkill, choosing an `ag.mesh` and an `ag.reg` regularization scheme and what each costs in free parameters, why `mesh_shape` must be fixed before the fit, `over_sample_size_pixelization` rather than `over_sample_size_lp`, noise scaling instead of hard masking for contaminants, the positive-only solver, reading the reconstruction and its Bayesian-evidence terms out of the `Inversion`, exporting the reconstruction to CSV for collaborators, and the GPU/VRAM versus CPU run-time trade. Use when a Sersic, MGE or shapelet basis leaves structured residuals in discrete off-centre lumps. Not for morphology a basis can still fit (`ag_basis_profiles`), not for non-parametric isophote measurement (`ag_ellipse_fitting`), and not for the basics of model composition (`ag_build_imaging_model`).\n---\n\n# Reconstructing a galaxy on a pixel mesh\n\nEvery model in this workspace so far has been a *function*: you asserted a functional form and\nthe fit found its parameters. A pixelization drops the functional form. It lays a mesh of pixels\nover the galaxy, gives each pixel its own free flux value, and solves all of them at once by\nlinear inversion — thousands of amplitudes, none of them in the non-linear search's parameter\nspace. What stops that from simply fitting the noise is **regularization**: a prior that\npenalises solutions where neighbouring mesh pixels differ sharply, so the reconstruction is as\nsmooth as the data will allow and no smoother.\n\nThe science case is specific, and it is worth being honest about how specific. Galaxies with\nspiral arms, asymmetric star-forming clumps, tidal features or low-surface-brightness\nsubstructure have light that no smooth profile — and often no basis expansion either —\nreproduces. The canonical use is therefore **hybrid**: a linear `Sersic` for the smooth central\nbulge, and a pixelization for the irregular remainder. That split is the point. It gives you a\nlow-dimensional, physically interpretable description of the bulge *and* a flux map of exactly\nwhat the bulge could not explain, which is the quantity you want if the science question is \"how\nmuch of this galaxy's light is in its irregular components?\"\n\nThis is a **direct** reconstruction. There is no second plane, no de-projection, no inversion of\na geometric mapping — the mesh sits on the image plane, over the galaxy, at the same coordinates\nthe data occupies. If you have met pixelized reconstruction before in a different context, that\nextra step is the one that is absent here, and its absence makes everything simpler: what the\nmesh reconstructs is the galaxy's own surface brightness, and its coordinates are sky\ncoordinates in arcseconds.\n\nStatistically, the fit now has two nested layers. The non-linear search explores a handful of\nparameters — the bulge's shape, the regularization strength — and for each proposal an inversion\nsolves the mesh amplitudes exactly and returns a **Bayesian evidence** rather than a plain\nlikelihood. That evidence includes terms that penalise an unnecessarily complex reconstruction,\nwhich is what lets a model with 400 free flux values not simply win by over-fitting. The theory\nis [`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md);\nchapter 3 of HowToGalaxy derives it from scratch.\n\nThe canonical scripts are\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py` (via a search),\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` (one direct fit, with the\ninversion internals walked through) and\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py` (export).\n\n## Before you reach for one — the honest gate\n\nA pixelization is the most powerful and the most expensive model here, with failure modes the\nparametric models do not have. Three questions decide whether you need it:\n\n- *\"What do the residuals actually look like?\"* Structured residuals that **follow the\n isophotes** — a twist, a four-lobed pattern, an ellipticity that changes with radius — are a\n *shape* problem, and an MGE fixes them for four free parameters\n ([`ag_basis_profiles`](./ag_basis_profiles.md)). Residuals in **discrete off-centre lumps** are\n a substructure problem, and that is what a pixelization is for. Look before you choose.\n- *\"Is the structure resolved?\"* At low resolution the irregular structure is not in the data,\n and a pixelization will reconstruct noise while telling you it fitted well. The workspace is\n blunt about this: for low-resolution data pixelizations are unnecessary.\n- *\"Do you need global quantities or the light distribution?\"* If you want a total flux, a size,\n an axis ratio, a Sersic index — a parametric profile, an MGE or shapelets are enough and far\n cheaper. If you want the morphology itself, particularly for faint or low-surface-brightness\n features, nothing else comes close.\n\nIf the answer to the first is \"lumps\" and to the second \"yes\", continue. Otherwise you will\nspend hours to learn less.\n\n## Ask\n\n- *\"What is the smooth component?\"* Almost always a linear `Sersic`, sometimes a Sersic plus an\n Exponential disk. It matters that this exists: without it the pixelization has to reconstruct\n the bright central bulge too, which wastes mesh resolution on light a six-parameter profile\n describes perfectly and makes the regularization choice much harder.\n- *\"How many mesh pixels can you afford?\"* This is a hardware question as much as a science one\n (see the run-time branch). 20 × 20 is the workspace's default for a GPU run; 28 × 28 to 30 × 30\n for a better-resolved reconstruction; higher only with a large-VRAM GPU or a many-core CPU.\n- *\"Are there neighbours inside the mask?\"* For a pixelization the answer is *never* to mask\n their pixels out — that punches holes in the mesh and produces discontinuity systematics.\n Scale their noise instead (branch below).\n- *\"GPU or CPU?\"* Genuinely depends on your pixel scale, and the answer is counter-intuitive.\n Ask before assuming.\n\n## Branch — the hybrid model\n\nThe canonical composition. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py`.\n\n```python\n\"\"\"\nGalaxy Structure: Bulge Plus Pixelized Reconstruction\n=====================================================\n\nFit a galaxy whose light has two very different characters: a smooth central bulge, described by\na linear Sersic profile in six parameters, and asymmetric clumpy star formation, reconstructed\non a regularized rectangular mesh. The Sersic captures the smooth component interpretably; the\npixelization absorbs everything it cannot explain, and the reconstructed flux map is the\nmeasurement of the galaxy's irregular light.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the imaging, mask it, and apply pixelization over-sampling.\n- **Mesh Shape:** Fix the mesh dimensions before the model is composed.\n- **Model:** Compose the linear Sersic bulge plus the pixelization.\n- **Check:** Confirm the parameter count, evaluate one likelihood, and estimate VRAM.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPIXEL_SCALES = 0.1\nMASK_RADIUS = 2.0\n\n\"\"\"\n__Dataset__\n\nThe mask matters more than usual here. It defines the region the mesh is laid over, so a mask\nthat reaches well beyond the galaxy spends reconstruction pixels on empty sky, and one that\ntruncates the galaxy leaves its outer light unreconstructed\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe over-sampling argument changes too. A pixelization evaluates light on its *own* grid with\nits own over-sampling scheme, so the size is passed as `over_sample_size_pixelization`, not the\n`over_sample_size_lp` used for light profiles. Passing the wrong one silently leaves the\npixelization grid at its default.\n\"\"\"\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=PIXEL_SCALES,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\ndataset = dataset.apply_over_sampling(over_sample_size_pixelization=over_sample_size)\n\n\"\"\"\n__Mesh Shape__\n\nThe mesh dimensions are **fixed before the fit and cannot be a free parameter**. This is not a\nstylistic restriction: JAX compiles the likelihood against statically shaped arrays, and the\nmesh shape sets those shapes. A rectangular mesh uses the same number of pixels in y and x.\n\"\"\"\nmesh_pixels_yx = 20\nmesh_shape = (mesh_pixels_yx, mesh_pixels_yx)\n\n\"\"\"\n__Model__\n\n`ag.Pixelization` pairs a `mesh` — where the reconstruction pixels sit — with a `regularization`\nscheme — the prior that keeps the solution smooth. It is attached to the galaxy as a component\nalongside the light profiles, and the analysis knows to route it through the inversion\n(`PyAutoGalaxy:autogalaxy/galaxy/galaxy.py`).\n\nThe mesh itself contributes **zero** free parameters; the reconstruction's 400 flux values are\nsolved, not sampled. `ag.reg.GaussianKernel` contributes two (`coefficient`, `scale`). The bulge\nis `ag.lp_linear.Sersic` rather than `ag.lp.Sersic` deliberately: its `intensity` is then solved\nby the *same* inversion that solves the mesh amplitudes, which removes the degeneracy between\n\"bright bulge, faint reconstruction\" and \"faint bulge, bright reconstruction\" that a sampled\nintensity would create.\n\"\"\"\npixelization = af.Model(\n ag.Pixelization,\n mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n regularization=ag.reg.GaussianKernel,\n)\n\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n pixelization=pixelization,\n)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\nThree cheap checks, each catching a different class of mistake: the parameter count catches a\nmodel error, one likelihood evaluation catches an incompatibility between model, dataset and\nanalysis, and `print_vram_use` catches the resource error that otherwise appears as an\nout-of-memory failure mid-compile. Pixelizations use far more VRAM than profile-only models —\naround 0.05 GB per batched likelihood for 400 reconstruction pixels — which is why the\nworkspace uses a lower `n_batch` for these fits than for any other.\n\"\"\"\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\nlog_likelihood = analysis.log_likelihood_function(\n instance=model.instance_from_prior_medians()\n)\nprint(f\"log evidence at prior medians: {float(log_likelihood):.2f}\")\n```\n\n**N = 8**: the Sersic's centre (2), `ell_comps` (2), `effective_radius`, `sersic_index`, plus the\nregularization's `coefficient` and `scale`. Eight parameters, with 400 reconstruction pixels\nsolved. That is dramatically more parsimonious than stacking parametric profiles until every\nclump is described — a 20-plus-parameter approach that would still fail on genuinely irregular\nsubstructure.\n\nExtending the smooth side is exactly as you would expect — add components as further attributes\non the galaxy, keeping them linear so their intensities join the same inversion:\n\n```python\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n disk=ag.lp_linear.Exponential,\n pixelization=pixelization,\n)\n```\n\n## Branch — choosing a mesh and a regularization scheme\n\nThese are the two decisions that make or break a reconstruction, and the parameter cost is\nalmost entirely in the regularization.\n\n**Meshes** (`ag.mesh`, from `PyAutoArray:autoarray/inversion/mesh/`). All contribute zero free\nparameters, all take `shape=(y, x)`:\n\n| Mesh | Where the pixels go | Use when |\n|---|---|---|\n| `RectangularUniform` | a uniform grid over the masked region | you want the simplest, most predictable behaviour |\n| `RectangularBilinearAdaptDensity` | a rectangular grid whose spacing follows the density of image pixels mapping to it, via a rank CDF | **the default** — concentrates resolution where the data is, and the fast CPU path |\n| `RectangularBilinearAdaptImage` | adapts to the image's own brightness distribution | the irregular light is strongly concentrated |\n| `RectangularRTUAdaptDensity` / `RectangularRTUAdaptImage` | the same two adaptations through a kernel CDF | GPU, JAX gradient samplers and the interferometer sparse path — the only rectangular adaptive meshes with usable gradients |\n\n`Delaunay`, `KNearestNeighbor` and `KNNBarycentric` also exist for irregular tessellations. Start\nwith `RectangularBilinearAdaptDensity`; it is what every workspace example uses, and the\nrectangular meshes are what the fixed-`mesh_shape` JAX path is built around. (The unqualified\n`RectangularAdaptDensity` / `RectangularAdaptImage` names were split into the `Bilinear` and\n`RTU` families in PyAutoArray 2026.8.23.1 and no longer resolve.)\n\n**Regularization** (`ag.reg`, from `PyAutoArray:autoarray/inversion/regularization/`) is where\nthe free parameters are, and where the physics of \"how smooth should this be?\" lives:\n\n| Scheme | Free params | What it assumes |\n|---|---|---|\n| `ag.reg.Constant` | 1 (`coefficient`) | one smoothing strength everywhere — the simplest, and the right first try |\n| `ag.reg.GaussianKernel` | 2 (`coefficient`, `scale`) | smoothing with a Gaussian correlation length you also fit |\n| `ag.reg.MaternKernel` | 3 (`coefficient`, `scale`, `nu`) | as above, with the roughness `nu` free too |\n\nVerified counts, not guesses. `Constant` penalises the difference between neighbouring pixels\ndirectly; the kernel schemes impose a correlation *length*, which is physically closer to what a\ngalaxy's light does and generally reconstructs faint extended structure better at the cost of\none or two parameters. `ag.reg.Adapt` and its variants scale the smoothing with the\nreconstruction's own brightness — more flexible again, and requiring `adapt_images` on the\nanalysis, which is a step beyond this skill; ask if you want it.\n\nA practical route: fit once with `ag.reg.Constant`, look at the reconstruction. Over-smoothed\n(the clumps blurred into one blob) or over-fitted (isolated single-pixel spikes) both show up\nimmediately, and if `Constant` cannot get both the bright clumps and the faint envelope right at\none strength, that is the signal to move to `GaussianKernel`. Full discussion in\n[`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\n### The positive-only solver\n\nEvery pixelized reconstruction uses a **positive-only** linear solver: no mesh pixel may\nreconstruct negative flux. This is not a numerical nicety. A signed solver lets the\nreconstruction manufacture negative pixels that cancel positive ones to over-fit the data, and\nthat failure mode is a well-known systematic in the literature — many published methods allow\nit. Enforcing non-negativity efficiently needs bespoke linear algebra, which is why this is\nworth stating rather than assuming. You do not need to switch it on; it is the behaviour you get.\n(The one place in this workspace where you *must* disable it is a shapelet basis, which needs\nsigned amplitudes by construction — see [`ag_basis_profiles`](./ag_basis_profiles.md).)\n\n## Branch — contaminating neighbours: scale, never mask\n\nThe general advice for a neighbour inside the mask is to mask its pixels out. **For a\npixelization that advice is wrong.** Removing image pixels entirely removes their mapping into\nthe mesh, punching a hole in the reconstruction and producing discontinuities that show up as\nunexplained systematics.\n\nInstead, keep the pixels in the fit and make them contribute nothing: scale their data to zero\nand their noise to an enormous value, so the likelihood is indifferent to them while the mesh\nstays continuous. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py`.\n\n```python\n\"\"\"\n__Noise Scaling__\n\n`mask_extra_galaxies.fits` marks the contaminated pixels. It is loaded with `invert=True`\nbecause in this file `True` means \"scale this pixel\", the opposite of a modelling mask's\nconvention — getting this backwards scales the galaxy instead of the neighbour, so check the\nsubplot afterwards. `apply_noise_scaling` then zeroes those data values and inflates their\nnoise, driving their signal-to-noise to effectively zero without removing them from the mesh's\nmapping (`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nOrder matters: scale first, then apply the modelling mask.\n\"\"\"\nmask_extra_galaxies = ag.Mask2D.from_fits(\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n pixel_scales=PIXEL_SCALES,\n invert=True,\n)\n\ndataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=PIXEL_SCALES,\n centre=(0.0, 0.0),\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=\"scripts/scratch/my_galaxy/\",\n output_filename=\"noise_scaled\",\n output_format=\"png\",\n)\n```\n\nThe scaled pixels go to a noise value of order 1e8 — visibly so on the signal-to-noise panel of\nthe subplot, which is how you confirm you scaled the right region. Drawing that mask\ninteractively is `autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask_extra_galaxies.py`;\nthe modelling alternative, and when to prefer it, is\n[`ag_light_model_extras`](./ag_light_model_extras.md) and\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch — reading the reconstruction out\n\nThe reconstruction is the science product, and it lives on the `Inversion`. You can get there\nfrom a completed fit or from a single direct `ag.FitImaging` — the latter is the fast way to\nlearn the objects, and is what\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` does.\n\n```python\n\"\"\"\n__Reconstruction__\n\n`inversion.linear_obj_list` holds the linear objects the fit solved. For a hybrid model that is\none `LightProfileLinearObjFuncList` per linear light profile plus one `Mapper` for the\npixelization; with a non-linear `ag.lp.Sersic` bulge the `Mapper` is the only entry. The\n`Mapper` is the object that maps image pixels onto mesh pixels, and it is mesh-specific\n(`PyAutoArray:autoarray/inversion/mappers/`).\n\nThe reconstruction is a 1D array of one flux per mesh pixel, and the (y, x) arcsecond\ncoordinates of those pixels are `mapper.mesh_geometry.mesh_grid`. Pair them by index — they are\nthe same length and the same order — and you have the flux map.\n\"\"\"\ninversion = fit.inversion\n\nmapper = inversion.linear_obj_list[0]\n\nreconstruction = inversion.reconstruction\nmesh_grid = mapper.mesh_geometry.mesh_grid\n\nprint(f\"{len(reconstruction)} mesh pixels reconstructed\")\nprint(f\"coordinates shape: {mesh_grid.shape}\")\n\n\"\"\"\nThe reconstruction's own uncertainties, and its projection back onto the image, are also on the\ninversion. `mapped_reconstructed_operated_data` contains **only** the pixelized component — any\nparametric light profile in the model is excluded — which is exactly the quantity you want when\nasking how much light is in the irregular component.\n\"\"\"\nprint(inversion.reconstruction_noise_map)\nprint(inversion.mapped_reconstructed_operated_data.native.shape)\n```\n\nA caution on the `Mapper`'s grid attributes: `mapper.image_plane_mesh_grid` is `None` for a\nrectangular mesh, so do not reach for it. `mapper.mesh_geometry.mesh_grid` is the mesh pixel\ncentres (verified on the released stack), and `mapper.image_plane_data_grid` is the centre of\nevery masked *image* pixel. Some of the `Mapper`'s attribute names carry a plane-based prefix\ninherited from the shared inversion library that also serves a multi-plane use case; in\nPyAutoGalaxy there is only the one plane, so `mesh_geometry.mesh_grid` is both the clearer name\nand the one to use.\n\n### The evidence terms\n\nThe inversion's figure of merit is a Bayesian evidence, and its components are individually\nreadable — which is how you diagnose whether regularization is doing too much or too little:\n\n```python\nprint(f\"regularization term = {inversion.regularization_term}\")\nprint(f\"log det regularization = {inversion.log_det_regularization_matrix_term}\")\nprint(f\"log det curvature + reg = {inversion.log_det_curvature_reg_matrix_term}\")\n```\n\nThe `regularization_term` measures how non-smooth the solution is; the two log-determinant\nterms are the complexity penalty that stops a 400-pixel model winning by over-fitting. The\nmatrices themselves (`curvature_matrix`, `regularization_matrix`, `curvature_reg_matrix`) are\nthere too. The derivation is in HowToGalaxy chapter 3 and the papers it cites\n(arXiv:1708.07377, arXiv:astro-ph/0601493).\n\n### Diagnostic plots\n\n`aplt.subplot_fit_imaging` includes the reconstruction on the mesh alongside the usual data /\nmodel / residual panels, and is the first thing to look at. For the inversion's own internals\nthere are dedicated functions, which live in the shared inversion library rather than on `aplt`\nand so are imported explicitly — from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/plot.py`:\n\n```python\nfrom autoarray.inversion.plot.inversion_plots import subplot_of_mapper\nfrom autoarray.inversion.plot.mapper_plots import plot_mapper, subplot_image_and_mapper\n\nPLOT_DIR = \"scripts/scratch/my_galaxy/pixelization/\"\n\naplt.subplot_fit_imaging(fit=fit, output_path=PLOT_DIR, output_format=\"png\")\n\nsubplot_of_mapper(\n inversion=inversion, mapper_index=0, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nsubplot_image_and_mapper(\n mapper=mapper, image=dataset.data, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nprint(f\"Saved to: {Path(PLOT_DIR).resolve()}\")\n```\n\n`subplot_of_mapper` is the comprehensive diagnostic — reconstructed image, reconstruction, its\nnoise map and the regularization weights in one figure — and `mapper_index` selects which linear\nobject when there are several. `subplot_image_and_mapper` shows the data beside the mesh, which\nis how you check the mesh covers the structure you care about. Note that none of these three are\nexposed on the `aplt` module — `dir(aplt)` does not list them, so the explicit imports above are\nthe only route and writing them as `aplt.`-prefixed calls raises `AttributeError`. Quote the\nabsolute path back to the user and offer to open it.\n\n## Branch — exporting the reconstruction for downstream science\n\nA reconstruction that only exists inside a PyAutoGalaxy object is hard to share and hard to\nanalyse with other tools. Write it out as coordinates plus values and it becomes ordinary\ntabular data. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py`.\n\n```python\n\"\"\"\n__Export__\n\nFour columns — y, x, reconstruction, noise — is everything needed to rebuild, plot or analyse\nthe galaxy's irregular light without PyAutoGalaxy installed. A completed model-fit also writes\nthis file into its own `image/` folder automatically; glob for `*reconstruction_0.csv` there\nrather than hard-coding the stem, which carries a prefix from the shared inversion library.\n\"\"\"\nimport csv\n\nCSV_PATH = Path(\"scripts/scratch/my_galaxy/reconstruction.csv\")\nCSV_PATH.parent.mkdir(parents=True, exist_ok=True)\n\nwith CSV_PATH.open(\"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([\"y\", \"x\", \"reconstruction\", \"noise_map\"])\n for (y, x), value, sigma in zip(\n mesh_grid, inversion.reconstruction, inversion.reconstruction_noise_map\n ):\n writer.writerow([y, x, value, sigma])\n\nprint(f\"Reconstruction written to: {CSV_PATH.resolve()}\")\n```\n\nReloading needs nothing but the standard library, and from there the mesh is ordinary scattered\ndata. Two things the workspace does with it: a Delaunay triangulation via `scipy.spatial` for\nplotting on the mesh's own geometry, and interpolation onto a regular grid via\n`scipy.interpolate.griddata` for any tool that wants an image:\n\n```python\nimport numpy as np\nfrom scipy.interpolate import griddata\n\nwith CSV_PATH.open() as f:\n reader = csv.reader(f)\n header = next(reader) # ['y', 'x', 'reconstruction', 'noise_map']\n loaded = {key: [] for key in header}\n for row in reader:\n for key, value in zip(header, row):\n loaded[key].append(float(value))\n\npoints = np.stack((np.array(loaded[\"x\"]), np.array(loaded[\"y\"])), axis=-1)\n\ninterpolation_grid = ag.Grid2D.from_extent(\n extent=(-1.0, 1.0, -1.0, 1.0), shape_native=(201, 201)\n)\n\ninterpolated = griddata(\n points=points, values=np.array(loaded[\"reconstruction\"]), xi=interpolation_grid\n)\n```\n\nPick the `extent` to cover the reconstruction without over-resolving it — the mesh has a few\nhundred pixels, so interpolating to 201 × 201 is presentation, not information.\n\n## Branch — run time, VRAM, and the GPU-versus-CPU choice\n\nThis is the branch that decides whether your fit takes twenty minutes or three hours, and the\nanswer is not \"use the GPU\".\n\nPixelized inversions do linear algebra on very large, very **sparse** matrices. JAX has no sparse\nsupport and must work densely, which scales badly; the CPU implementation exploits the sparsity\nfully via `numba`. So the trade runs against pixel scale:\n\n- **Low resolution (`pixel_scales > 0.05`, e.g. Euclid)** — fewer sparse operations, modest VRAM.\n **GPU with JAX is usually fastest.**\n- **High resolution (`pixel_scales <= 0.03`, e.g. HST or JWST)** — the linear algebra is\n sparsity-dominated. **CPU with `numba` and many cores can beat a powerful GPU.**\n\nVRAM is the hard constraint on the GPU side. JAX must hold the whole batched likelihood in GPU\nmemory, and a pixelization needs far more than a profile model: around 0.05 GB per batched\nlikelihood at 400 reconstruction pixels, and more than 1 GB — occasionally more than 10 GB — at\nhigh resolution with a fine mesh. Two consequences: keep `n_batch` low (the workspace uses 20 for\npixelizations against 50 elsewhere), and run\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nbefore committing. It takes 20–30 seconds and it is the difference between knowing your limit\nand discovering it as an out-of-memory error mid-compile. If VRAM is exceeded the run time does\nnot degrade gracefully — it goes from under ten minutes to three hours or more.\n\nRough scaling with resolution, from the workspace's own measurements at a 20 × 20 mesh with VRAM\nunder control: ~10 minutes at 0.1\"/pixel, ~30 minutes at 0.05\", ~1 hour at 0.03\". Benchmark both\npaths for your own data and hardware rather than trusting either default; the search-side\nsettings are [`ag_configure_search`](./ag_configure_search.md) and\n[`../wiki/core/api/searches.md`](../wiki/core/api/searches.md).\n\n## Combine — where this hands off\n\n- **Try a basis first** → [`ag_basis_profiles`](./ag_basis_profiles.md). An MGE is four\n parameters and minutes, not hours, and it genuinely resolves the shape-mismatch case a\n pixelization is often reached for by mistake.\n- **Pick and configure the search** → [`ag_configure_search`](./ag_configure_search.md), with\n `n_batch` lowered for VRAM.\n- **Run the fit** → [`ag_run_search`](./ag_run_search.md); `image/fit.png` in the output folder\n refreshes on the fly and shows the reconstruction as it converges, which is worth watching for\n a fit this long.\n- **Plot and inspect** → [`ag_plot_fit`](./ag_plot_fit.md), plus the `subplot_of_mapper`\n diagnostics above.\n- **Load a completed fit programmatically** → [`ag_load_results`](./ag_load_results.md).\n- **Over-smoothed, over-fitted or unphysical reconstruction** →\n [`ag_debug_fit_failure`](./ag_debug_fit_failure.md). The pixelization-specific causes are a\n regularization scheme too rigid for the structure, a mask that punched holes via hard masking\n where noise scaling was needed, over-sampling passed as `over_sample_size_lp` instead of\n `over_sample_size_pixelization`, and VRAM exhaustion masquerading as a hung fit.\n- **Contaminating neighbours modelled rather than scaled** →\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- **Make the fit robust and fast by starting simple** → the search-chaining skill\n (`ag_chain_searches`). This is the biggest available win for a pixelization: fit a parametric\n model first, pass its bulge as priors, and let the expensive model start from a sensible place.\n The workspace recommends it explicitly.\n- **A non-parametric shape measurement instead of a reconstruction** →\n [`ag_ellipse_fitting`](./ag_ellipse_fitting.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording the mesh and its\nshape, the regularization scheme and why, the mask radius, the hardware path, and what the\nreconstruction showed — with a pixelization the choices *are* the result, and none of them are\nrecoverable from the output folder alone.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Bayesian regularization](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb):\n why a model with hundreds of free flux values does not simply over-fit, derived from scratch;\n `tutorial_6_model_fit` then runs the full fit.\n- **General reference** — [RTD: Pixelization API](https://pyautogalaxy.readthedocs.io/en/latest/api/pixelization.html):\n every mesh, regularization scheme and the objects that combine them.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n the hybrid fit end to end, with the run-time, VRAM and GPU-versus-CPU discussion in full.\n\n## Agent procedural checklist\n\n1. Look at the residual map of a parametric or basis fit first. Shape-following residuals mean\n `ag_basis_profiles`; discrete off-centre lumps mean a pixelization. Do not skip this.\n2. Confirm the structure is resolved — at coarse pixel scales a pixelization reconstructs noise.\n3. Always pair the pixelization with a linear light profile for the smooth component; never let\n the mesh reconstruct the bulge.\n4. Fix `mesh_shape` before composing the model; it cannot be a free parameter.\n5. Pass over-sampling as `over_sample_size_pixelization`, not `over_sample_size_lp`.\n6. Start with `RectangularBilinearAdaptDensity` + `ag.reg.Constant`; move to `GaussianKernel` only when\n one smoothing strength demonstrably cannot serve both the bright and faint structure.\n7. Scale contaminant noise (`apply_noise_scaling`, `invert=True`) — never hard-mask pixels inside\n a pixelization fit — and check the signal-to-noise panel afterwards.\n8. `print(model.info)`, evaluate one likelihood, then `print_vram_use` before any GPU run; keep\n `n_batch` low.\n9. Read the reconstruction via `inversion.reconstruction` +\n `mapper.mesh_geometry.mesh_grid`; export to CSV for anything downstream.\n10. Save the script to `scripts/`, quote every plot's absolute path and offer to open it, then\n offer the `wiki/project/` entry recording mesh, regularization and hardware choices.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_3_pixelizations/tutorial_2_mappers.ipynb b/notebooks/chapter_3_pixelizations/tutorial_2_mappers.ipynb index d8247fe..935843a 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_2_mappers.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_2_mappers.ipynb @@ -27,21 +27,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -384,7 +384,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_mappers.ipynb in HowToGalaxy).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoGalaxy calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoGalaxy docs (https://pyautogalaxy.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_pixelization\n\n---\nname: ag_pixelization\ndescription: Reconstruct a galaxy's clumpy or irregular light directly on a regularized pixel mesh, using `ag.Pixelization` alongside a parametric `ag.lp_linear` bulge \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_mappers.ipynb in HowToGalaxy).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoGalaxy calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoGalaxy docs (https://pyautogalaxy.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_pixelization\n\n---\nname: ag_pixelization\ndescription: Reconstruct a galaxy's clumpy or irregular light directly on a regularized pixel mesh, using `ag.Pixelization` alongside a parametric `ag.lp_linear` bulge — the hybrid model that gives a smooth interpretable component plus a flexible flux map for everything the profile cannot explain. Covers when a pixelization is warranted and when it is overkill, choosing an `ag.mesh` and an `ag.reg` regularization scheme and what each costs in free parameters, why `mesh_shape` must be fixed before the fit, `over_sample_size_pixelization` rather than `over_sample_size_lp`, noise scaling instead of hard masking for contaminants, the positive-only solver, reading the reconstruction and its Bayesian-evidence terms out of the `Inversion`, exporting the reconstruction to CSV for collaborators, and the GPU/VRAM versus CPU run-time trade. Use when a Sersic, MGE or shapelet basis leaves structured residuals in discrete off-centre lumps. Not for morphology a basis can still fit (`ag_basis_profiles`), not for non-parametric isophote measurement (`ag_ellipse_fitting`), and not for the basics of model composition (`ag_build_imaging_model`).\n---\n\n# Reconstructing a galaxy on a pixel mesh\n\nEvery model in this workspace so far has been a *function*: you asserted a functional form and\nthe fit found its parameters. A pixelization drops the functional form. It lays a mesh of pixels\nover the galaxy, gives each pixel its own free flux value, and solves all of them at once by\nlinear inversion — thousands of amplitudes, none of them in the non-linear search's parameter\nspace. What stops that from simply fitting the noise is **regularization**: a prior that\npenalises solutions where neighbouring mesh pixels differ sharply, so the reconstruction is as\nsmooth as the data will allow and no smoother.\n\nThe science case is specific, and it is worth being honest about how specific. Galaxies with\nspiral arms, asymmetric star-forming clumps, tidal features or low-surface-brightness\nsubstructure have light that no smooth profile — and often no basis expansion either —\nreproduces. The canonical use is therefore **hybrid**: a linear `Sersic` for the smooth central\nbulge, and a pixelization for the irregular remainder. That split is the point. It gives you a\nlow-dimensional, physically interpretable description of the bulge *and* a flux map of exactly\nwhat the bulge could not explain, which is the quantity you want if the science question is \"how\nmuch of this galaxy's light is in its irregular components?\"\n\nThis is a **direct** reconstruction. There is no second plane, no de-projection, no inversion of\na geometric mapping — the mesh sits on the image plane, over the galaxy, at the same coordinates\nthe data occupies. If you have met pixelized reconstruction before in a different context, that\nextra step is the one that is absent here, and its absence makes everything simpler: what the\nmesh reconstructs is the galaxy's own surface brightness, and its coordinates are sky\ncoordinates in arcseconds.\n\nStatistically, the fit now has two nested layers. The non-linear search explores a handful of\nparameters — the bulge's shape, the regularization strength — and for each proposal an inversion\nsolves the mesh amplitudes exactly and returns a **Bayesian evidence** rather than a plain\nlikelihood. That evidence includes terms that penalise an unnecessarily complex reconstruction,\nwhich is what lets a model with 400 free flux values not simply win by over-fitting. The theory\nis [`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md);\nchapter 3 of HowToGalaxy derives it from scratch.\n\nThe canonical scripts are\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py` (via a search),\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` (one direct fit, with the\ninversion internals walked through) and\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py` (export).\n\n## Before you reach for one — the honest gate\n\nA pixelization is the most powerful and the most expensive model here, with failure modes the\nparametric models do not have. Three questions decide whether you need it:\n\n- *\"What do the residuals actually look like?\"* Structured residuals that **follow the\n isophotes** — a twist, a four-lobed pattern, an ellipticity that changes with radius — are a\n *shape* problem, and an MGE fixes them for four free parameters\n ([`ag_basis_profiles`](./ag_basis_profiles.md)). Residuals in **discrete off-centre lumps** are\n a substructure problem, and that is what a pixelization is for. Look before you choose.\n- *\"Is the structure resolved?\"* At low resolution the irregular structure is not in the data,\n and a pixelization will reconstruct noise while telling you it fitted well. The workspace is\n blunt about this: for low-resolution data pixelizations are unnecessary.\n- *\"Do you need global quantities or the light distribution?\"* If you want a total flux, a size,\n an axis ratio, a Sersic index — a parametric profile, an MGE or shapelets are enough and far\n cheaper. If you want the morphology itself, particularly for faint or low-surface-brightness\n features, nothing else comes close.\n\nIf the answer to the first is \"lumps\" and to the second \"yes\", continue. Otherwise you will\nspend hours to learn less.\n\n## Ask\n\n- *\"What is the smooth component?\"* Almost always a linear `Sersic`, sometimes a Sersic plus an\n Exponential disk. It matters that this exists: without it the pixelization has to reconstruct\n the bright central bulge too, which wastes mesh resolution on light a six-parameter profile\n describes perfectly and makes the regularization choice much harder.\n- *\"How many mesh pixels can you afford?\"* This is a hardware question as much as a science one\n (see the run-time branch). 20 × 20 is the workspace's default for a GPU run; 28 × 28 to 30 × 30\n for a better-resolved reconstruction; higher only with a large-VRAM GPU or a many-core CPU.\n- *\"Are there neighbours inside the mask?\"* For a pixelization the answer is *never* to mask\n their pixels out — that punches holes in the mesh and produces discontinuity systematics.\n Scale their noise instead (branch below).\n- *\"GPU or CPU?\"* Genuinely depends on your pixel scale, and the answer is counter-intuitive.\n Ask before assuming.\n\n## Branch — the hybrid model\n\nThe canonical composition. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py`.\n\n```python\n\"\"\"\nGalaxy Structure: Bulge Plus Pixelized Reconstruction\n=====================================================\n\nFit a galaxy whose light has two very different characters: a smooth central bulge, described by\na linear Sersic profile in six parameters, and asymmetric clumpy star formation, reconstructed\non a regularized rectangular mesh. The Sersic captures the smooth component interpretably; the\npixelization absorbs everything it cannot explain, and the reconstructed flux map is the\nmeasurement of the galaxy's irregular light.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the imaging, mask it, and apply pixelization over-sampling.\n- **Mesh Shape:** Fix the mesh dimensions before the model is composed.\n- **Model:** Compose the linear Sersic bulge plus the pixelization.\n- **Check:** Confirm the parameter count, evaluate one likelihood, and estimate VRAM.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPIXEL_SCALES = 0.1\nMASK_RADIUS = 2.0\n\n\"\"\"\n__Dataset__\n\nThe mask matters more than usual here. It defines the region the mesh is laid over, so a mask\nthat reaches well beyond the galaxy spends reconstruction pixels on empty sky, and one that\ntruncates the galaxy leaves its outer light unreconstructed\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe over-sampling argument changes too. A pixelization evaluates light on its *own* grid with\nits own over-sampling scheme, so the size is passed as `over_sample_size_pixelization`, not the\n`over_sample_size_lp` used for light profiles. Passing the wrong one silently leaves the\npixelization grid at its default.\n\"\"\"\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=PIXEL_SCALES,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\ndataset = dataset.apply_over_sampling(over_sample_size_pixelization=over_sample_size)\n\n\"\"\"\n__Mesh Shape__\n\nThe mesh dimensions are **fixed before the fit and cannot be a free parameter**. This is not a\nstylistic restriction: JAX compiles the likelihood against statically shaped arrays, and the\nmesh shape sets those shapes. A rectangular mesh uses the same number of pixels in y and x.\n\"\"\"\nmesh_pixels_yx = 20\nmesh_shape = (mesh_pixels_yx, mesh_pixels_yx)\n\n\"\"\"\n__Model__\n\n`ag.Pixelization` pairs a `mesh` — where the reconstruction pixels sit — with a `regularization`\nscheme — the prior that keeps the solution smooth. It is attached to the galaxy as a component\nalongside the light profiles, and the analysis knows to route it through the inversion\n(`PyAutoGalaxy:autogalaxy/galaxy/galaxy.py`).\n\nThe mesh itself contributes **zero** free parameters; the reconstruction's 400 flux values are\nsolved, not sampled. `ag.reg.GaussianKernel` contributes two (`coefficient`, `scale`). The bulge\nis `ag.lp_linear.Sersic` rather than `ag.lp.Sersic` deliberately: its `intensity` is then solved\nby the *same* inversion that solves the mesh amplitudes, which removes the degeneracy between\n\"bright bulge, faint reconstruction\" and \"faint bulge, bright reconstruction\" that a sampled\nintensity would create.\n\"\"\"\npixelization = af.Model(\n ag.Pixelization,\n mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n regularization=ag.reg.GaussianKernel,\n)\n\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n pixelization=pixelization,\n)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\nThree cheap checks, each catching a different class of mistake: the parameter count catches a\nmodel error, one likelihood evaluation catches an incompatibility between model, dataset and\nanalysis, and `print_vram_use` catches the resource error that otherwise appears as an\nout-of-memory failure mid-compile. Pixelizations use far more VRAM than profile-only models —\naround 0.05 GB per batched likelihood for 400 reconstruction pixels — which is why the\nworkspace uses a lower `n_batch` for these fits than for any other.\n\"\"\"\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\nlog_likelihood = analysis.log_likelihood_function(\n instance=model.instance_from_prior_medians()\n)\nprint(f\"log evidence at prior medians: {float(log_likelihood):.2f}\")\n```\n\n**N = 8**: the Sersic's centre (2), `ell_comps` (2), `effective_radius`, `sersic_index`, plus the\nregularization's `coefficient` and `scale`. Eight parameters, with 400 reconstruction pixels\nsolved. That is dramatically more parsimonious than stacking parametric profiles until every\nclump is described — a 20-plus-parameter approach that would still fail on genuinely irregular\nsubstructure.\n\nExtending the smooth side is exactly as you would expect — add components as further attributes\non the galaxy, keeping them linear so their intensities join the same inversion:\n\n```python\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n disk=ag.lp_linear.Exponential,\n pixelization=pixelization,\n)\n```\n\n## Branch — choosing a mesh and a regularization scheme\n\nThese are the two decisions that make or break a reconstruction, and the parameter cost is\nalmost entirely in the regularization.\n\n**Meshes** (`ag.mesh`, from `PyAutoArray:autoarray/inversion/mesh/`). All contribute zero free\nparameters, all take `shape=(y, x)`:\n\n| Mesh | Where the pixels go | Use when |\n|---|---|---|\n| `RectangularUniform` | a uniform grid over the masked region | you want the simplest, most predictable behaviour |\n| `RectangularBilinearAdaptDensity` | a rectangular grid whose spacing follows the density of image pixels mapping to it, via a rank CDF | **the default** — concentrates resolution where the data is, and the fast CPU path |\n| `RectangularBilinearAdaptImage` | adapts to the image's own brightness distribution | the irregular light is strongly concentrated |\n| `RectangularRTUAdaptDensity` / `RectangularRTUAdaptImage` | the same two adaptations through a kernel CDF | GPU, JAX gradient samplers and the interferometer sparse path — the only rectangular adaptive meshes with usable gradients |\n\n`Delaunay`, `KNearestNeighbor` and `KNNBarycentric` also exist for irregular tessellations. Start\nwith `RectangularBilinearAdaptDensity`; it is what every workspace example uses, and the\nrectangular meshes are what the fixed-`mesh_shape` JAX path is built around. (The unqualified\n`RectangularAdaptDensity` / `RectangularAdaptImage` names were split into the `Bilinear` and\n`RTU` families in PyAutoArray 2026.8.23.1 and no longer resolve.)\n\n**Regularization** (`ag.reg`, from `PyAutoArray:autoarray/inversion/regularization/`) is where\nthe free parameters are, and where the physics of \"how smooth should this be?\" lives:\n\n| Scheme | Free params | What it assumes |\n|---|---|---|\n| `ag.reg.Constant` | 1 (`coefficient`) | one smoothing strength everywhere — the simplest, and the right first try |\n| `ag.reg.GaussianKernel` | 2 (`coefficient`, `scale`) | smoothing with a Gaussian correlation length you also fit |\n| `ag.reg.MaternKernel` | 3 (`coefficient`, `scale`, `nu`) | as above, with the roughness `nu` free too |\n\nVerified counts, not guesses. `Constant` penalises the difference between neighbouring pixels\ndirectly; the kernel schemes impose a correlation *length*, which is physically closer to what a\ngalaxy's light does and generally reconstructs faint extended structure better at the cost of\none or two parameters. `ag.reg.Adapt` and its variants scale the smoothing with the\nreconstruction's own brightness — more flexible again, and requiring `adapt_images` on the\nanalysis, which is a step beyond this skill; ask if you want it.\n\nA practical route: fit once with `ag.reg.Constant`, look at the reconstruction. Over-smoothed\n(the clumps blurred into one blob) or over-fitted (isolated single-pixel spikes) both show up\nimmediately, and if `Constant` cannot get both the bright clumps and the faint envelope right at\none strength, that is the signal to move to `GaussianKernel`. Full discussion in\n[`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\n### The positive-only solver\n\nEvery pixelized reconstruction uses a **positive-only** linear solver: no mesh pixel may\nreconstruct negative flux. This is not a numerical nicety. A signed solver lets the\nreconstruction manufacture negative pixels that cancel positive ones to over-fit the data, and\nthat failure mode is a well-known systematic in the literature — many published methods allow\nit. Enforcing non-negativity efficiently needs bespoke linear algebra, which is why this is\nworth stating rather than assuming. You do not need to switch it on; it is the behaviour you get.\n(The one place in this workspace where you *must* disable it is a shapelet basis, which needs\nsigned amplitudes by construction — see [`ag_basis_profiles`](./ag_basis_profiles.md).)\n\n## Branch — contaminating neighbours: scale, never mask\n\nThe general advice for a neighbour inside the mask is to mask its pixels out. **For a\npixelization that advice is wrong.** Removing image pixels entirely removes their mapping into\nthe mesh, punching a hole in the reconstruction and producing discontinuities that show up as\nunexplained systematics.\n\nInstead, keep the pixels in the fit and make them contribute nothing: scale their data to zero\nand their noise to an enormous value, so the likelihood is indifferent to them while the mesh\nstays continuous. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py`.\n\n```python\n\"\"\"\n__Noise Scaling__\n\n`mask_extra_galaxies.fits` marks the contaminated pixels. It is loaded with `invert=True`\nbecause in this file `True` means \"scale this pixel\", the opposite of a modelling mask's\nconvention — getting this backwards scales the galaxy instead of the neighbour, so check the\nsubplot afterwards. `apply_noise_scaling` then zeroes those data values and inflates their\nnoise, driving their signal-to-noise to effectively zero without removing them from the mesh's\nmapping (`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nOrder matters: scale first, then apply the modelling mask.\n\"\"\"\nmask_extra_galaxies = ag.Mask2D.from_fits(\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n pixel_scales=PIXEL_SCALES,\n invert=True,\n)\n\ndataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=PIXEL_SCALES,\n centre=(0.0, 0.0),\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=\"scripts/scratch/my_galaxy/\",\n output_filename=\"noise_scaled\",\n output_format=\"png\",\n)\n```\n\nThe scaled pixels go to a noise value of order 1e8 — visibly so on the signal-to-noise panel of\nthe subplot, which is how you confirm you scaled the right region. Drawing that mask\ninteractively is `autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask_extra_galaxies.py`;\nthe modelling alternative, and when to prefer it, is\n[`ag_light_model_extras`](./ag_light_model_extras.md) and\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch — reading the reconstruction out\n\nThe reconstruction is the science product, and it lives on the `Inversion`. You can get there\nfrom a completed fit or from a single direct `ag.FitImaging` — the latter is the fast way to\nlearn the objects, and is what\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` does.\n\n```python\n\"\"\"\n__Reconstruction__\n\n`inversion.linear_obj_list` holds the linear objects the fit solved. For a hybrid model that is\none `LightProfileLinearObjFuncList` per linear light profile plus one `Mapper` for the\npixelization; with a non-linear `ag.lp.Sersic` bulge the `Mapper` is the only entry. The\n`Mapper` is the object that maps image pixels onto mesh pixels, and it is mesh-specific\n(`PyAutoArray:autoarray/inversion/mappers/`).\n\nThe reconstruction is a 1D array of one flux per mesh pixel, and the (y, x) arcsecond\ncoordinates of those pixels are `mapper.mesh_geometry.mesh_grid`. Pair them by index — they are\nthe same length and the same order — and you have the flux map.\n\"\"\"\ninversion = fit.inversion\n\nmapper = inversion.linear_obj_list[0]\n\nreconstruction = inversion.reconstruction\nmesh_grid = mapper.mesh_geometry.mesh_grid\n\nprint(f\"{len(reconstruction)} mesh pixels reconstructed\")\nprint(f\"coordinates shape: {mesh_grid.shape}\")\n\n\"\"\"\nThe reconstruction's own uncertainties, and its projection back onto the image, are also on the\ninversion. `mapped_reconstructed_operated_data` contains **only** the pixelized component — any\nparametric light profile in the model is excluded — which is exactly the quantity you want when\nasking how much light is in the irregular component.\n\"\"\"\nprint(inversion.reconstruction_noise_map)\nprint(inversion.mapped_reconstructed_operated_data.native.shape)\n```\n\nA caution on the `Mapper`'s grid attributes: `mapper.image_plane_mesh_grid` is `None` for a\nrectangular mesh, so do not reach for it. `mapper.mesh_geometry.mesh_grid` is the mesh pixel\ncentres (verified on the released stack), and `mapper.image_plane_data_grid` is the centre of\nevery masked *image* pixel. Some of the `Mapper`'s attribute names carry a plane-based prefix\ninherited from the shared inversion library that also serves a multi-plane use case; in\nPyAutoGalaxy there is only the one plane, so `mesh_geometry.mesh_grid` is both the clearer name\nand the one to use.\n\n### The evidence terms\n\nThe inversion's figure of merit is a Bayesian evidence, and its components are individually\nreadable — which is how you diagnose whether regularization is doing too much or too little:\n\n```python\nprint(f\"regularization term = {inversion.regularization_term}\")\nprint(f\"log det regularization = {inversion.log_det_regularization_matrix_term}\")\nprint(f\"log det curvature + reg = {inversion.log_det_curvature_reg_matrix_term}\")\n```\n\nThe `regularization_term` measures how non-smooth the solution is; the two log-determinant\nterms are the complexity penalty that stops a 400-pixel model winning by over-fitting. The\nmatrices themselves (`curvature_matrix`, `regularization_matrix`, `curvature_reg_matrix`) are\nthere too. The derivation is in HowToGalaxy chapter 3 and the papers it cites\n(arXiv:1708.07377, arXiv:astro-ph/0601493).\n\n### Diagnostic plots\n\n`aplt.subplot_fit_imaging` includes the reconstruction on the mesh alongside the usual data /\nmodel / residual panels, and is the first thing to look at. For the inversion's own internals\nthere are dedicated functions, which live in the shared inversion library rather than on `aplt`\nand so are imported explicitly — from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/plot.py`:\n\n```python\nfrom autoarray.inversion.plot.inversion_plots import subplot_of_mapper\nfrom autoarray.inversion.plot.mapper_plots import plot_mapper, subplot_image_and_mapper\n\nPLOT_DIR = \"scripts/scratch/my_galaxy/pixelization/\"\n\naplt.subplot_fit_imaging(fit=fit, output_path=PLOT_DIR, output_format=\"png\")\n\nsubplot_of_mapper(\n inversion=inversion, mapper_index=0, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nsubplot_image_and_mapper(\n mapper=mapper, image=dataset.data, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nprint(f\"Saved to: {Path(PLOT_DIR).resolve()}\")\n```\n\n`subplot_of_mapper` is the comprehensive diagnostic — reconstructed image, reconstruction, its\nnoise map and the regularization weights in one figure — and `mapper_index` selects which linear\nobject when there are several. `subplot_image_and_mapper` shows the data beside the mesh, which\nis how you check the mesh covers the structure you care about. Note that none of these three are\nexposed on the `aplt` module — `dir(aplt)` does not list them, so the explicit imports above are\nthe only route and writing them as `aplt.`-prefixed calls raises `AttributeError`. Quote the\nabsolute path back to the user and offer to open it.\n\n## Branch — exporting the reconstruction for downstream science\n\nA reconstruction that only exists inside a PyAutoGalaxy object is hard to share and hard to\nanalyse with other tools. Write it out as coordinates plus values and it becomes ordinary\ntabular data. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py`.\n\n```python\n\"\"\"\n__Export__\n\nFour columns — y, x, reconstruction, noise — is everything needed to rebuild, plot or analyse\nthe galaxy's irregular light without PyAutoGalaxy installed. A completed model-fit also writes\nthis file into its own `image/` folder automatically; glob for `*reconstruction_0.csv` there\nrather than hard-coding the stem, which carries a prefix from the shared inversion library.\n\"\"\"\nimport csv\n\nCSV_PATH = Path(\"scripts/scratch/my_galaxy/reconstruction.csv\")\nCSV_PATH.parent.mkdir(parents=True, exist_ok=True)\n\nwith CSV_PATH.open(\"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([\"y\", \"x\", \"reconstruction\", \"noise_map\"])\n for (y, x), value, sigma in zip(\n mesh_grid, inversion.reconstruction, inversion.reconstruction_noise_map\n ):\n writer.writerow([y, x, value, sigma])\n\nprint(f\"Reconstruction written to: {CSV_PATH.resolve()}\")\n```\n\nReloading needs nothing but the standard library, and from there the mesh is ordinary scattered\ndata. Two things the workspace does with it: a Delaunay triangulation via `scipy.spatial` for\nplotting on the mesh's own geometry, and interpolation onto a regular grid via\n`scipy.interpolate.griddata` for any tool that wants an image:\n\n```python\nimport numpy as np\nfrom scipy.interpolate import griddata\n\nwith CSV_PATH.open() as f:\n reader = csv.reader(f)\n header = next(reader) # ['y', 'x', 'reconstruction', 'noise_map']\n loaded = {key: [] for key in header}\n for row in reader:\n for key, value in zip(header, row):\n loaded[key].append(float(value))\n\npoints = np.stack((np.array(loaded[\"x\"]), np.array(loaded[\"y\"])), axis=-1)\n\ninterpolation_grid = ag.Grid2D.from_extent(\n extent=(-1.0, 1.0, -1.0, 1.0), shape_native=(201, 201)\n)\n\ninterpolated = griddata(\n points=points, values=np.array(loaded[\"reconstruction\"]), xi=interpolation_grid\n)\n```\n\nPick the `extent` to cover the reconstruction without over-resolving it — the mesh has a few\nhundred pixels, so interpolating to 201 × 201 is presentation, not information.\n\n## Branch — run time, VRAM, and the GPU-versus-CPU choice\n\nThis is the branch that decides whether your fit takes twenty minutes or three hours, and the\nanswer is not \"use the GPU\".\n\nPixelized inversions do linear algebra on very large, very **sparse** matrices. JAX has no sparse\nsupport and must work densely, which scales badly; the CPU implementation exploits the sparsity\nfully via `numba`. So the trade runs against pixel scale:\n\n- **Low resolution (`pixel_scales > 0.05`, e.g. Euclid)** — fewer sparse operations, modest VRAM.\n **GPU with JAX is usually fastest.**\n- **High resolution (`pixel_scales <= 0.03`, e.g. HST or JWST)** — the linear algebra is\n sparsity-dominated. **CPU with `numba` and many cores can beat a powerful GPU.**\n\nVRAM is the hard constraint on the GPU side. JAX must hold the whole batched likelihood in GPU\nmemory, and a pixelization needs far more than a profile model: around 0.05 GB per batched\nlikelihood at 400 reconstruction pixels, and more than 1 GB — occasionally more than 10 GB — at\nhigh resolution with a fine mesh. Two consequences: keep `n_batch` low (the workspace uses 20 for\npixelizations against 50 elsewhere), and run\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nbefore committing. It takes 20–30 seconds and it is the difference between knowing your limit\nand discovering it as an out-of-memory error mid-compile. If VRAM is exceeded the run time does\nnot degrade gracefully — it goes from under ten minutes to three hours or more.\n\nRough scaling with resolution, from the workspace's own measurements at a 20 × 20 mesh with VRAM\nunder control: ~10 minutes at 0.1\"/pixel, ~30 minutes at 0.05\", ~1 hour at 0.03\". Benchmark both\npaths for your own data and hardware rather than trusting either default; the search-side\nsettings are [`ag_configure_search`](./ag_configure_search.md) and\n[`../wiki/core/api/searches.md`](../wiki/core/api/searches.md).\n\n## Combine — where this hands off\n\n- **Try a basis first** → [`ag_basis_profiles`](./ag_basis_profiles.md). An MGE is four\n parameters and minutes, not hours, and it genuinely resolves the shape-mismatch case a\n pixelization is often reached for by mistake.\n- **Pick and configure the search** → [`ag_configure_search`](./ag_configure_search.md), with\n `n_batch` lowered for VRAM.\n- **Run the fit** → [`ag_run_search`](./ag_run_search.md); `image/fit.png` in the output folder\n refreshes on the fly and shows the reconstruction as it converges, which is worth watching for\n a fit this long.\n- **Plot and inspect** → [`ag_plot_fit`](./ag_plot_fit.md), plus the `subplot_of_mapper`\n diagnostics above.\n- **Load a completed fit programmatically** → [`ag_load_results`](./ag_load_results.md).\n- **Over-smoothed, over-fitted or unphysical reconstruction** →\n [`ag_debug_fit_failure`](./ag_debug_fit_failure.md). The pixelization-specific causes are a\n regularization scheme too rigid for the structure, a mask that punched holes via hard masking\n where noise scaling was needed, over-sampling passed as `over_sample_size_lp` instead of\n `over_sample_size_pixelization`, and VRAM exhaustion masquerading as a hung fit.\n- **Contaminating neighbours modelled rather than scaled** →\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- **Make the fit robust and fast by starting simple** → the search-chaining skill\n (`ag_chain_searches`). This is the biggest available win for a pixelization: fit a parametric\n model first, pass its bulge as priors, and let the expensive model start from a sensible place.\n The workspace recommends it explicitly.\n- **A non-parametric shape measurement instead of a reconstruction** →\n [`ag_ellipse_fitting`](./ag_ellipse_fitting.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording the mesh and its\nshape, the regularization scheme and why, the mask radius, the hardware path, and what the\nreconstruction showed — with a pixelization the choices *are* the result, and none of them are\nrecoverable from the output folder alone.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Bayesian regularization](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb):\n why a model with hundreds of free flux values does not simply over-fit, derived from scratch;\n `tutorial_6_model_fit` then runs the full fit.\n- **General reference** — [RTD: Pixelization API](https://pyautogalaxy.readthedocs.io/en/latest/api/pixelization.html):\n every mesh, regularization scheme and the objects that combine them.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n the hybrid fit end to end, with the run-time, VRAM and GPU-versus-CPU discussion in full.\n\n## Agent procedural checklist\n\n1. Look at the residual map of a parametric or basis fit first. Shape-following residuals mean\n `ag_basis_profiles`; discrete off-centre lumps mean a pixelization. Do not skip this.\n2. Confirm the structure is resolved — at coarse pixel scales a pixelization reconstructs noise.\n3. Always pair the pixelization with a linear light profile for the smooth component; never let\n the mesh reconstruct the bulge.\n4. Fix `mesh_shape` before composing the model; it cannot be a free parameter.\n5. Pass over-sampling as `over_sample_size_pixelization`, not `over_sample_size_lp`.\n6. Start with `RectangularBilinearAdaptDensity` + `ag.reg.Constant`; move to `GaussianKernel` only when\n one smoothing strength demonstrably cannot serve both the bright and faint structure.\n7. Scale contaminant noise (`apply_noise_scaling`, `invert=True`) — never hard-mask pixels inside\n a pixelization fit — and check the signal-to-noise panel afterwards.\n8. `print(model.info)`, evaluate one likelihood, then `print_vram_use` before any GPU run; keep\n `n_batch` low.\n9. Read the reconstruction via `inversion.reconstruction` +\n `mapper.mesh_geometry.mesh_grid`; export to CSV for anything downstream.\n10. Save the script to `scripts/`, quote every plot's absolute path and offer to open it, then\n offer the `wiki/project/` entry recording mesh, regularization and hardware choices.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb b/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb index d175f42..601d865 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb @@ -31,21 +31,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -432,7 +432,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_inversions.ipynb in HowToGalaxy).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoGalaxy calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoGalaxy docs (https://pyautogalaxy.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_pixelization\n\n---\nname: ag_pixelization\ndescription: Reconstruct a galaxy's clumpy or irregular light directly on a regularized pixel mesh, using `ag.Pixelization` alongside a parametric `ag.lp_linear` bulge \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_inversions.ipynb in HowToGalaxy).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoGalaxy calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoGalaxy docs (https://pyautogalaxy.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_pixelization\n\n---\nname: ag_pixelization\ndescription: Reconstruct a galaxy's clumpy or irregular light directly on a regularized pixel mesh, using `ag.Pixelization` alongside a parametric `ag.lp_linear` bulge — the hybrid model that gives a smooth interpretable component plus a flexible flux map for everything the profile cannot explain. Covers when a pixelization is warranted and when it is overkill, choosing an `ag.mesh` and an `ag.reg` regularization scheme and what each costs in free parameters, why `mesh_shape` must be fixed before the fit, `over_sample_size_pixelization` rather than `over_sample_size_lp`, noise scaling instead of hard masking for contaminants, the positive-only solver, reading the reconstruction and its Bayesian-evidence terms out of the `Inversion`, exporting the reconstruction to CSV for collaborators, and the GPU/VRAM versus CPU run-time trade. Use when a Sersic, MGE or shapelet basis leaves structured residuals in discrete off-centre lumps. Not for morphology a basis can still fit (`ag_basis_profiles`), not for non-parametric isophote measurement (`ag_ellipse_fitting`), and not for the basics of model composition (`ag_build_imaging_model`).\n---\n\n# Reconstructing a galaxy on a pixel mesh\n\nEvery model in this workspace so far has been a *function*: you asserted a functional form and\nthe fit found its parameters. A pixelization drops the functional form. It lays a mesh of pixels\nover the galaxy, gives each pixel its own free flux value, and solves all of them at once by\nlinear inversion — thousands of amplitudes, none of them in the non-linear search's parameter\nspace. What stops that from simply fitting the noise is **regularization**: a prior that\npenalises solutions where neighbouring mesh pixels differ sharply, so the reconstruction is as\nsmooth as the data will allow and no smoother.\n\nThe science case is specific, and it is worth being honest about how specific. Galaxies with\nspiral arms, asymmetric star-forming clumps, tidal features or low-surface-brightness\nsubstructure have light that no smooth profile — and often no basis expansion either —\nreproduces. The canonical use is therefore **hybrid**: a linear `Sersic` for the smooth central\nbulge, and a pixelization for the irregular remainder. That split is the point. It gives you a\nlow-dimensional, physically interpretable description of the bulge *and* a flux map of exactly\nwhat the bulge could not explain, which is the quantity you want if the science question is \"how\nmuch of this galaxy's light is in its irregular components?\"\n\nThis is a **direct** reconstruction. There is no second plane, no de-projection, no inversion of\na geometric mapping — the mesh sits on the image plane, over the galaxy, at the same coordinates\nthe data occupies. If you have met pixelized reconstruction before in a different context, that\nextra step is the one that is absent here, and its absence makes everything simpler: what the\nmesh reconstructs is the galaxy's own surface brightness, and its coordinates are sky\ncoordinates in arcseconds.\n\nStatistically, the fit now has two nested layers. The non-linear search explores a handful of\nparameters — the bulge's shape, the regularization strength — and for each proposal an inversion\nsolves the mesh amplitudes exactly and returns a **Bayesian evidence** rather than a plain\nlikelihood. That evidence includes terms that penalise an unnecessarily complex reconstruction,\nwhich is what lets a model with 400 free flux values not simply win by over-fitting. The theory\nis [`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md);\nchapter 3 of HowToGalaxy derives it from scratch.\n\nThe canonical scripts are\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py` (via a search),\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` (one direct fit, with the\ninversion internals walked through) and\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py` (export).\n\n## Before you reach for one — the honest gate\n\nA pixelization is the most powerful and the most expensive model here, with failure modes the\nparametric models do not have. Three questions decide whether you need it:\n\n- *\"What do the residuals actually look like?\"* Structured residuals that **follow the\n isophotes** — a twist, a four-lobed pattern, an ellipticity that changes with radius — are a\n *shape* problem, and an MGE fixes them for four free parameters\n ([`ag_basis_profiles`](./ag_basis_profiles.md)). Residuals in **discrete off-centre lumps** are\n a substructure problem, and that is what a pixelization is for. Look before you choose.\n- *\"Is the structure resolved?\"* At low resolution the irregular structure is not in the data,\n and a pixelization will reconstruct noise while telling you it fitted well. The workspace is\n blunt about this: for low-resolution data pixelizations are unnecessary.\n- *\"Do you need global quantities or the light distribution?\"* If you want a total flux, a size,\n an axis ratio, a Sersic index — a parametric profile, an MGE or shapelets are enough and far\n cheaper. If you want the morphology itself, particularly for faint or low-surface-brightness\n features, nothing else comes close.\n\nIf the answer to the first is \"lumps\" and to the second \"yes\", continue. Otherwise you will\nspend hours to learn less.\n\n## Ask\n\n- *\"What is the smooth component?\"* Almost always a linear `Sersic`, sometimes a Sersic plus an\n Exponential disk. It matters that this exists: without it the pixelization has to reconstruct\n the bright central bulge too, which wastes mesh resolution on light a six-parameter profile\n describes perfectly and makes the regularization choice much harder.\n- *\"How many mesh pixels can you afford?\"* This is a hardware question as much as a science one\n (see the run-time branch). 20 × 20 is the workspace's default for a GPU run; 28 × 28 to 30 × 30\n for a better-resolved reconstruction; higher only with a large-VRAM GPU or a many-core CPU.\n- *\"Are there neighbours inside the mask?\"* For a pixelization the answer is *never* to mask\n their pixels out — that punches holes in the mesh and produces discontinuity systematics.\n Scale their noise instead (branch below).\n- *\"GPU or CPU?\"* Genuinely depends on your pixel scale, and the answer is counter-intuitive.\n Ask before assuming.\n\n## Branch — the hybrid model\n\nThe canonical composition. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py`.\n\n```python\n\"\"\"\nGalaxy Structure: Bulge Plus Pixelized Reconstruction\n=====================================================\n\nFit a galaxy whose light has two very different characters: a smooth central bulge, described by\na linear Sersic profile in six parameters, and asymmetric clumpy star formation, reconstructed\non a regularized rectangular mesh. The Sersic captures the smooth component interpretably; the\npixelization absorbs everything it cannot explain, and the reconstructed flux map is the\nmeasurement of the galaxy's irregular light.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the imaging, mask it, and apply pixelization over-sampling.\n- **Mesh Shape:** Fix the mesh dimensions before the model is composed.\n- **Model:** Compose the linear Sersic bulge plus the pixelization.\n- **Check:** Confirm the parameter count, evaluate one likelihood, and estimate VRAM.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPIXEL_SCALES = 0.1\nMASK_RADIUS = 2.0\n\n\"\"\"\n__Dataset__\n\nThe mask matters more than usual here. It defines the region the mesh is laid over, so a mask\nthat reaches well beyond the galaxy spends reconstruction pixels on empty sky, and one that\ntruncates the galaxy leaves its outer light unreconstructed\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe over-sampling argument changes too. A pixelization evaluates light on its *own* grid with\nits own over-sampling scheme, so the size is passed as `over_sample_size_pixelization`, not the\n`over_sample_size_lp` used for light profiles. Passing the wrong one silently leaves the\npixelization grid at its default.\n\"\"\"\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=PIXEL_SCALES,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\ndataset = dataset.apply_over_sampling(over_sample_size_pixelization=over_sample_size)\n\n\"\"\"\n__Mesh Shape__\n\nThe mesh dimensions are **fixed before the fit and cannot be a free parameter**. This is not a\nstylistic restriction: JAX compiles the likelihood against statically shaped arrays, and the\nmesh shape sets those shapes. A rectangular mesh uses the same number of pixels in y and x.\n\"\"\"\nmesh_pixels_yx = 20\nmesh_shape = (mesh_pixels_yx, mesh_pixels_yx)\n\n\"\"\"\n__Model__\n\n`ag.Pixelization` pairs a `mesh` — where the reconstruction pixels sit — with a `regularization`\nscheme — the prior that keeps the solution smooth. It is attached to the galaxy as a component\nalongside the light profiles, and the analysis knows to route it through the inversion\n(`PyAutoGalaxy:autogalaxy/galaxy/galaxy.py`).\n\nThe mesh itself contributes **zero** free parameters; the reconstruction's 400 flux values are\nsolved, not sampled. `ag.reg.GaussianKernel` contributes two (`coefficient`, `scale`). The bulge\nis `ag.lp_linear.Sersic` rather than `ag.lp.Sersic` deliberately: its `intensity` is then solved\nby the *same* inversion that solves the mesh amplitudes, which removes the degeneracy between\n\"bright bulge, faint reconstruction\" and \"faint bulge, bright reconstruction\" that a sampled\nintensity would create.\n\"\"\"\npixelization = af.Model(\n ag.Pixelization,\n mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n regularization=ag.reg.GaussianKernel,\n)\n\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n pixelization=pixelization,\n)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\nThree cheap checks, each catching a different class of mistake: the parameter count catches a\nmodel error, one likelihood evaluation catches an incompatibility between model, dataset and\nanalysis, and `print_vram_use` catches the resource error that otherwise appears as an\nout-of-memory failure mid-compile. Pixelizations use far more VRAM than profile-only models —\naround 0.05 GB per batched likelihood for 400 reconstruction pixels — which is why the\nworkspace uses a lower `n_batch` for these fits than for any other.\n\"\"\"\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\nlog_likelihood = analysis.log_likelihood_function(\n instance=model.instance_from_prior_medians()\n)\nprint(f\"log evidence at prior medians: {float(log_likelihood):.2f}\")\n```\n\n**N = 8**: the Sersic's centre (2), `ell_comps` (2), `effective_radius`, `sersic_index`, plus the\nregularization's `coefficient` and `scale`. Eight parameters, with 400 reconstruction pixels\nsolved. That is dramatically more parsimonious than stacking parametric profiles until every\nclump is described — a 20-plus-parameter approach that would still fail on genuinely irregular\nsubstructure.\n\nExtending the smooth side is exactly as you would expect — add components as further attributes\non the galaxy, keeping them linear so their intensities join the same inversion:\n\n```python\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n disk=ag.lp_linear.Exponential,\n pixelization=pixelization,\n)\n```\n\n## Branch — choosing a mesh and a regularization scheme\n\nThese are the two decisions that make or break a reconstruction, and the parameter cost is\nalmost entirely in the regularization.\n\n**Meshes** (`ag.mesh`, from `PyAutoArray:autoarray/inversion/mesh/`). All contribute zero free\nparameters, all take `shape=(y, x)`:\n\n| Mesh | Where the pixels go | Use when |\n|---|---|---|\n| `RectangularUniform` | a uniform grid over the masked region | you want the simplest, most predictable behaviour |\n| `RectangularBilinearAdaptDensity` | a rectangular grid whose spacing follows the density of image pixels mapping to it, via a rank CDF | **the default** — concentrates resolution where the data is, and the fast CPU path |\n| `RectangularBilinearAdaptImage` | adapts to the image's own brightness distribution | the irregular light is strongly concentrated |\n| `RectangularRTUAdaptDensity` / `RectangularRTUAdaptImage` | the same two adaptations through a kernel CDF | GPU, JAX gradient samplers and the interferometer sparse path — the only rectangular adaptive meshes with usable gradients |\n\n`Delaunay`, `KNearestNeighbor` and `KNNBarycentric` also exist for irregular tessellations. Start\nwith `RectangularBilinearAdaptDensity`; it is what every workspace example uses, and the\nrectangular meshes are what the fixed-`mesh_shape` JAX path is built around. (The unqualified\n`RectangularAdaptDensity` / `RectangularAdaptImage` names were split into the `Bilinear` and\n`RTU` families in PyAutoArray 2026.8.23.1 and no longer resolve.)\n\n**Regularization** (`ag.reg`, from `PyAutoArray:autoarray/inversion/regularization/`) is where\nthe free parameters are, and where the physics of \"how smooth should this be?\" lives:\n\n| Scheme | Free params | What it assumes |\n|---|---|---|\n| `ag.reg.Constant` | 1 (`coefficient`) | one smoothing strength everywhere — the simplest, and the right first try |\n| `ag.reg.GaussianKernel` | 2 (`coefficient`, `scale`) | smoothing with a Gaussian correlation length you also fit |\n| `ag.reg.MaternKernel` | 3 (`coefficient`, `scale`, `nu`) | as above, with the roughness `nu` free too |\n\nVerified counts, not guesses. `Constant` penalises the difference between neighbouring pixels\ndirectly; the kernel schemes impose a correlation *length*, which is physically closer to what a\ngalaxy's light does and generally reconstructs faint extended structure better at the cost of\none or two parameters. `ag.reg.Adapt` and its variants scale the smoothing with the\nreconstruction's own brightness — more flexible again, and requiring `adapt_images` on the\nanalysis, which is a step beyond this skill; ask if you want it.\n\nA practical route: fit once with `ag.reg.Constant`, look at the reconstruction. Over-smoothed\n(the clumps blurred into one blob) or over-fitted (isolated single-pixel spikes) both show up\nimmediately, and if `Constant` cannot get both the bright clumps and the faint envelope right at\none strength, that is the signal to move to `GaussianKernel`. Full discussion in\n[`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\n### The positive-only solver\n\nEvery pixelized reconstruction uses a **positive-only** linear solver: no mesh pixel may\nreconstruct negative flux. This is not a numerical nicety. A signed solver lets the\nreconstruction manufacture negative pixels that cancel positive ones to over-fit the data, and\nthat failure mode is a well-known systematic in the literature — many published methods allow\nit. Enforcing non-negativity efficiently needs bespoke linear algebra, which is why this is\nworth stating rather than assuming. You do not need to switch it on; it is the behaviour you get.\n(The one place in this workspace where you *must* disable it is a shapelet basis, which needs\nsigned amplitudes by construction — see [`ag_basis_profiles`](./ag_basis_profiles.md).)\n\n## Branch — contaminating neighbours: scale, never mask\n\nThe general advice for a neighbour inside the mask is to mask its pixels out. **For a\npixelization that advice is wrong.** Removing image pixels entirely removes their mapping into\nthe mesh, punching a hole in the reconstruction and producing discontinuities that show up as\nunexplained systematics.\n\nInstead, keep the pixels in the fit and make them contribute nothing: scale their data to zero\nand their noise to an enormous value, so the likelihood is indifferent to them while the mesh\nstays continuous. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py`.\n\n```python\n\"\"\"\n__Noise Scaling__\n\n`mask_extra_galaxies.fits` marks the contaminated pixels. It is loaded with `invert=True`\nbecause in this file `True` means \"scale this pixel\", the opposite of a modelling mask's\nconvention — getting this backwards scales the galaxy instead of the neighbour, so check the\nsubplot afterwards. `apply_noise_scaling` then zeroes those data values and inflates their\nnoise, driving their signal-to-noise to effectively zero without removing them from the mesh's\nmapping (`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nOrder matters: scale first, then apply the modelling mask.\n\"\"\"\nmask_extra_galaxies = ag.Mask2D.from_fits(\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n pixel_scales=PIXEL_SCALES,\n invert=True,\n)\n\ndataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=PIXEL_SCALES,\n centre=(0.0, 0.0),\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=\"scripts/scratch/my_galaxy/\",\n output_filename=\"noise_scaled\",\n output_format=\"png\",\n)\n```\n\nThe scaled pixels go to a noise value of order 1e8 — visibly so on the signal-to-noise panel of\nthe subplot, which is how you confirm you scaled the right region. Drawing that mask\ninteractively is `autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask_extra_galaxies.py`;\nthe modelling alternative, and when to prefer it, is\n[`ag_light_model_extras`](./ag_light_model_extras.md) and\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch — reading the reconstruction out\n\nThe reconstruction is the science product, and it lives on the `Inversion`. You can get there\nfrom a completed fit or from a single direct `ag.FitImaging` — the latter is the fast way to\nlearn the objects, and is what\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` does.\n\n```python\n\"\"\"\n__Reconstruction__\n\n`inversion.linear_obj_list` holds the linear objects the fit solved. For a hybrid model that is\none `LightProfileLinearObjFuncList` per linear light profile plus one `Mapper` for the\npixelization; with a non-linear `ag.lp.Sersic` bulge the `Mapper` is the only entry. The\n`Mapper` is the object that maps image pixels onto mesh pixels, and it is mesh-specific\n(`PyAutoArray:autoarray/inversion/mappers/`).\n\nThe reconstruction is a 1D array of one flux per mesh pixel, and the (y, x) arcsecond\ncoordinates of those pixels are `mapper.mesh_geometry.mesh_grid`. Pair them by index — they are\nthe same length and the same order — and you have the flux map.\n\"\"\"\ninversion = fit.inversion\n\nmapper = inversion.linear_obj_list[0]\n\nreconstruction = inversion.reconstruction\nmesh_grid = mapper.mesh_geometry.mesh_grid\n\nprint(f\"{len(reconstruction)} mesh pixels reconstructed\")\nprint(f\"coordinates shape: {mesh_grid.shape}\")\n\n\"\"\"\nThe reconstruction's own uncertainties, and its projection back onto the image, are also on the\ninversion. `mapped_reconstructed_operated_data` contains **only** the pixelized component — any\nparametric light profile in the model is excluded — which is exactly the quantity you want when\nasking how much light is in the irregular component.\n\"\"\"\nprint(inversion.reconstruction_noise_map)\nprint(inversion.mapped_reconstructed_operated_data.native.shape)\n```\n\nA caution on the `Mapper`'s grid attributes: `mapper.image_plane_mesh_grid` is `None` for a\nrectangular mesh, so do not reach for it. `mapper.mesh_geometry.mesh_grid` is the mesh pixel\ncentres (verified on the released stack), and `mapper.image_plane_data_grid` is the centre of\nevery masked *image* pixel. Some of the `Mapper`'s attribute names carry a plane-based prefix\ninherited from the shared inversion library that also serves a multi-plane use case; in\nPyAutoGalaxy there is only the one plane, so `mesh_geometry.mesh_grid` is both the clearer name\nand the one to use.\n\n### The evidence terms\n\nThe inversion's figure of merit is a Bayesian evidence, and its components are individually\nreadable — which is how you diagnose whether regularization is doing too much or too little:\n\n```python\nprint(f\"regularization term = {inversion.regularization_term}\")\nprint(f\"log det regularization = {inversion.log_det_regularization_matrix_term}\")\nprint(f\"log det curvature + reg = {inversion.log_det_curvature_reg_matrix_term}\")\n```\n\nThe `regularization_term` measures how non-smooth the solution is; the two log-determinant\nterms are the complexity penalty that stops a 400-pixel model winning by over-fitting. The\nmatrices themselves (`curvature_matrix`, `regularization_matrix`, `curvature_reg_matrix`) are\nthere too. The derivation is in HowToGalaxy chapter 3 and the papers it cites\n(arXiv:1708.07377, arXiv:astro-ph/0601493).\n\n### Diagnostic plots\n\n`aplt.subplot_fit_imaging` includes the reconstruction on the mesh alongside the usual data /\nmodel / residual panels, and is the first thing to look at. For the inversion's own internals\nthere are dedicated functions, which live in the shared inversion library rather than on `aplt`\nand so are imported explicitly — from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/plot.py`:\n\n```python\nfrom autoarray.inversion.plot.inversion_plots import subplot_of_mapper\nfrom autoarray.inversion.plot.mapper_plots import plot_mapper, subplot_image_and_mapper\n\nPLOT_DIR = \"scripts/scratch/my_galaxy/pixelization/\"\n\naplt.subplot_fit_imaging(fit=fit, output_path=PLOT_DIR, output_format=\"png\")\n\nsubplot_of_mapper(\n inversion=inversion, mapper_index=0, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nsubplot_image_and_mapper(\n mapper=mapper, image=dataset.data, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nprint(f\"Saved to: {Path(PLOT_DIR).resolve()}\")\n```\n\n`subplot_of_mapper` is the comprehensive diagnostic — reconstructed image, reconstruction, its\nnoise map and the regularization weights in one figure — and `mapper_index` selects which linear\nobject when there are several. `subplot_image_and_mapper` shows the data beside the mesh, which\nis how you check the mesh covers the structure you care about. Note that none of these three are\nexposed on the `aplt` module — `dir(aplt)` does not list them, so the explicit imports above are\nthe only route and writing them as `aplt.`-prefixed calls raises `AttributeError`. Quote the\nabsolute path back to the user and offer to open it.\n\n## Branch — exporting the reconstruction for downstream science\n\nA reconstruction that only exists inside a PyAutoGalaxy object is hard to share and hard to\nanalyse with other tools. Write it out as coordinates plus values and it becomes ordinary\ntabular data. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py`.\n\n```python\n\"\"\"\n__Export__\n\nFour columns — y, x, reconstruction, noise — is everything needed to rebuild, plot or analyse\nthe galaxy's irregular light without PyAutoGalaxy installed. A completed model-fit also writes\nthis file into its own `image/` folder automatically; glob for `*reconstruction_0.csv` there\nrather than hard-coding the stem, which carries a prefix from the shared inversion library.\n\"\"\"\nimport csv\n\nCSV_PATH = Path(\"scripts/scratch/my_galaxy/reconstruction.csv\")\nCSV_PATH.parent.mkdir(parents=True, exist_ok=True)\n\nwith CSV_PATH.open(\"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([\"y\", \"x\", \"reconstruction\", \"noise_map\"])\n for (y, x), value, sigma in zip(\n mesh_grid, inversion.reconstruction, inversion.reconstruction_noise_map\n ):\n writer.writerow([y, x, value, sigma])\n\nprint(f\"Reconstruction written to: {CSV_PATH.resolve()}\")\n```\n\nReloading needs nothing but the standard library, and from there the mesh is ordinary scattered\ndata. Two things the workspace does with it: a Delaunay triangulation via `scipy.spatial` for\nplotting on the mesh's own geometry, and interpolation onto a regular grid via\n`scipy.interpolate.griddata` for any tool that wants an image:\n\n```python\nimport numpy as np\nfrom scipy.interpolate import griddata\n\nwith CSV_PATH.open() as f:\n reader = csv.reader(f)\n header = next(reader) # ['y', 'x', 'reconstruction', 'noise_map']\n loaded = {key: [] for key in header}\n for row in reader:\n for key, value in zip(header, row):\n loaded[key].append(float(value))\n\npoints = np.stack((np.array(loaded[\"x\"]), np.array(loaded[\"y\"])), axis=-1)\n\ninterpolation_grid = ag.Grid2D.from_extent(\n extent=(-1.0, 1.0, -1.0, 1.0), shape_native=(201, 201)\n)\n\ninterpolated = griddata(\n points=points, values=np.array(loaded[\"reconstruction\"]), xi=interpolation_grid\n)\n```\n\nPick the `extent` to cover the reconstruction without over-resolving it — the mesh has a few\nhundred pixels, so interpolating to 201 × 201 is presentation, not information.\n\n## Branch — run time, VRAM, and the GPU-versus-CPU choice\n\nThis is the branch that decides whether your fit takes twenty minutes or three hours, and the\nanswer is not \"use the GPU\".\n\nPixelized inversions do linear algebra on very large, very **sparse** matrices. JAX has no sparse\nsupport and must work densely, which scales badly; the CPU implementation exploits the sparsity\nfully via `numba`. So the trade runs against pixel scale:\n\n- **Low resolution (`pixel_scales > 0.05`, e.g. Euclid)** — fewer sparse operations, modest VRAM.\n **GPU with JAX is usually fastest.**\n- **High resolution (`pixel_scales <= 0.03`, e.g. HST or JWST)** — the linear algebra is\n sparsity-dominated. **CPU with `numba` and many cores can beat a powerful GPU.**\n\nVRAM is the hard constraint on the GPU side. JAX must hold the whole batched likelihood in GPU\nmemory, and a pixelization needs far more than a profile model: around 0.05 GB per batched\nlikelihood at 400 reconstruction pixels, and more than 1 GB — occasionally more than 10 GB — at\nhigh resolution with a fine mesh. Two consequences: keep `n_batch` low (the workspace uses 20 for\npixelizations against 50 elsewhere), and run\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nbefore committing. It takes 20–30 seconds and it is the difference between knowing your limit\nand discovering it as an out-of-memory error mid-compile. If VRAM is exceeded the run time does\nnot degrade gracefully — it goes from under ten minutes to three hours or more.\n\nRough scaling with resolution, from the workspace's own measurements at a 20 × 20 mesh with VRAM\nunder control: ~10 minutes at 0.1\"/pixel, ~30 minutes at 0.05\", ~1 hour at 0.03\". Benchmark both\npaths for your own data and hardware rather than trusting either default; the search-side\nsettings are [`ag_configure_search`](./ag_configure_search.md) and\n[`../wiki/core/api/searches.md`](../wiki/core/api/searches.md).\n\n## Combine — where this hands off\n\n- **Try a basis first** → [`ag_basis_profiles`](./ag_basis_profiles.md). An MGE is four\n parameters and minutes, not hours, and it genuinely resolves the shape-mismatch case a\n pixelization is often reached for by mistake.\n- **Pick and configure the search** → [`ag_configure_search`](./ag_configure_search.md), with\n `n_batch` lowered for VRAM.\n- **Run the fit** → [`ag_run_search`](./ag_run_search.md); `image/fit.png` in the output folder\n refreshes on the fly and shows the reconstruction as it converges, which is worth watching for\n a fit this long.\n- **Plot and inspect** → [`ag_plot_fit`](./ag_plot_fit.md), plus the `subplot_of_mapper`\n diagnostics above.\n- **Load a completed fit programmatically** → [`ag_load_results`](./ag_load_results.md).\n- **Over-smoothed, over-fitted or unphysical reconstruction** →\n [`ag_debug_fit_failure`](./ag_debug_fit_failure.md). The pixelization-specific causes are a\n regularization scheme too rigid for the structure, a mask that punched holes via hard masking\n where noise scaling was needed, over-sampling passed as `over_sample_size_lp` instead of\n `over_sample_size_pixelization`, and VRAM exhaustion masquerading as a hung fit.\n- **Contaminating neighbours modelled rather than scaled** →\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- **Make the fit robust and fast by starting simple** → the search-chaining skill\n (`ag_chain_searches`). This is the biggest available win for a pixelization: fit a parametric\n model first, pass its bulge as priors, and let the expensive model start from a sensible place.\n The workspace recommends it explicitly.\n- **A non-parametric shape measurement instead of a reconstruction** →\n [`ag_ellipse_fitting`](./ag_ellipse_fitting.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording the mesh and its\nshape, the regularization scheme and why, the mask radius, the hardware path, and what the\nreconstruction showed — with a pixelization the choices *are* the result, and none of them are\nrecoverable from the output folder alone.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Bayesian regularization](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb):\n why a model with hundreds of free flux values does not simply over-fit, derived from scratch;\n `tutorial_6_model_fit` then runs the full fit.\n- **General reference** — [RTD: Pixelization API](https://pyautogalaxy.readthedocs.io/en/latest/api/pixelization.html):\n every mesh, regularization scheme and the objects that combine them.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n the hybrid fit end to end, with the run-time, VRAM and GPU-versus-CPU discussion in full.\n\n## Agent procedural checklist\n\n1. Look at the residual map of a parametric or basis fit first. Shape-following residuals mean\n `ag_basis_profiles`; discrete off-centre lumps mean a pixelization. Do not skip this.\n2. Confirm the structure is resolved — at coarse pixel scales a pixelization reconstructs noise.\n3. Always pair the pixelization with a linear light profile for the smooth component; never let\n the mesh reconstruct the bulge.\n4. Fix `mesh_shape` before composing the model; it cannot be a free parameter.\n5. Pass over-sampling as `over_sample_size_pixelization`, not `over_sample_size_lp`.\n6. Start with `RectangularBilinearAdaptDensity` + `ag.reg.Constant`; move to `GaussianKernel` only when\n one smoothing strength demonstrably cannot serve both the bright and faint structure.\n7. Scale contaminant noise (`apply_noise_scaling`, `invert=True`) — never hard-mask pixels inside\n a pixelization fit — and check the signal-to-noise panel afterwards.\n8. `print(model.info)`, evaluate one likelihood, then `print_vram_use` before any GPU run; keep\n `n_batch` low.\n9. Read the reconstruction via `inversion.reconstruction` +\n `mapper.mesh_geometry.mesh_grid`; export to CSV for anything downstream.\n10. Save the script to `scripts/`, quote every plot's absolute path and offer to open it, then\n offer the `wiki/project/` entry recording mesh, regularization and hardware choices.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb b/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb index af2e309..b30e7cc 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb @@ -36,21 +36,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", diff --git a/notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb b/notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb index 7ae9e0e..e8b9297 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb @@ -64,21 +64,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -973,7 +973,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_bayesian_formalism.ipynb in HowToGalaxy).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoGalaxy calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoGalaxy docs (https://pyautogalaxy.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_pixelization\n\n---\nname: ag_pixelization\ndescription: Reconstruct a galaxy's clumpy or irregular light directly on a regularized pixel mesh, using `ag.Pixelization` alongside a parametric `ag.lp_linear` bulge \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_bayesian_formalism.ipynb in HowToGalaxy).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoGalaxy calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoGalaxy docs (https://pyautogalaxy.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_pixelization\n\n---\nname: ag_pixelization\ndescription: Reconstruct a galaxy's clumpy or irregular light directly on a regularized pixel mesh, using `ag.Pixelization` alongside a parametric `ag.lp_linear` bulge — the hybrid model that gives a smooth interpretable component plus a flexible flux map for everything the profile cannot explain. Covers when a pixelization is warranted and when it is overkill, choosing an `ag.mesh` and an `ag.reg` regularization scheme and what each costs in free parameters, why `mesh_shape` must be fixed before the fit, `over_sample_size_pixelization` rather than `over_sample_size_lp`, noise scaling instead of hard masking for contaminants, the positive-only solver, reading the reconstruction and its Bayesian-evidence terms out of the `Inversion`, exporting the reconstruction to CSV for collaborators, and the GPU/VRAM versus CPU run-time trade. Use when a Sersic, MGE or shapelet basis leaves structured residuals in discrete off-centre lumps. Not for morphology a basis can still fit (`ag_basis_profiles`), not for non-parametric isophote measurement (`ag_ellipse_fitting`), and not for the basics of model composition (`ag_build_imaging_model`).\n---\n\n# Reconstructing a galaxy on a pixel mesh\n\nEvery model in this workspace so far has been a *function*: you asserted a functional form and\nthe fit found its parameters. A pixelization drops the functional form. It lays a mesh of pixels\nover the galaxy, gives each pixel its own free flux value, and solves all of them at once by\nlinear inversion — thousands of amplitudes, none of them in the non-linear search's parameter\nspace. What stops that from simply fitting the noise is **regularization**: a prior that\npenalises solutions where neighbouring mesh pixels differ sharply, so the reconstruction is as\nsmooth as the data will allow and no smoother.\n\nThe science case is specific, and it is worth being honest about how specific. Galaxies with\nspiral arms, asymmetric star-forming clumps, tidal features or low-surface-brightness\nsubstructure have light that no smooth profile — and often no basis expansion either —\nreproduces. The canonical use is therefore **hybrid**: a linear `Sersic` for the smooth central\nbulge, and a pixelization for the irregular remainder. That split is the point. It gives you a\nlow-dimensional, physically interpretable description of the bulge *and* a flux map of exactly\nwhat the bulge could not explain, which is the quantity you want if the science question is \"how\nmuch of this galaxy's light is in its irregular components?\"\n\nThis is a **direct** reconstruction. There is no second plane, no de-projection, no inversion of\na geometric mapping — the mesh sits on the image plane, over the galaxy, at the same coordinates\nthe data occupies. If you have met pixelized reconstruction before in a different context, that\nextra step is the one that is absent here, and its absence makes everything simpler: what the\nmesh reconstructs is the galaxy's own surface brightness, and its coordinates are sky\ncoordinates in arcseconds.\n\nStatistically, the fit now has two nested layers. The non-linear search explores a handful of\nparameters — the bulge's shape, the regularization strength — and for each proposal an inversion\nsolves the mesh amplitudes exactly and returns a **Bayesian evidence** rather than a plain\nlikelihood. That evidence includes terms that penalise an unnecessarily complex reconstruction,\nwhich is what lets a model with 400 free flux values not simply win by over-fitting. The theory\nis [`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md);\nchapter 3 of HowToGalaxy derives it from scratch.\n\nThe canonical scripts are\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py` (via a search),\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` (one direct fit, with the\ninversion internals walked through) and\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py` (export).\n\n## Before you reach for one — the honest gate\n\nA pixelization is the most powerful and the most expensive model here, with failure modes the\nparametric models do not have. Three questions decide whether you need it:\n\n- *\"What do the residuals actually look like?\"* Structured residuals that **follow the\n isophotes** — a twist, a four-lobed pattern, an ellipticity that changes with radius — are a\n *shape* problem, and an MGE fixes them for four free parameters\n ([`ag_basis_profiles`](./ag_basis_profiles.md)). Residuals in **discrete off-centre lumps** are\n a substructure problem, and that is what a pixelization is for. Look before you choose.\n- *\"Is the structure resolved?\"* At low resolution the irregular structure is not in the data,\n and a pixelization will reconstruct noise while telling you it fitted well. The workspace is\n blunt about this: for low-resolution data pixelizations are unnecessary.\n- *\"Do you need global quantities or the light distribution?\"* If you want a total flux, a size,\n an axis ratio, a Sersic index — a parametric profile, an MGE or shapelets are enough and far\n cheaper. If you want the morphology itself, particularly for faint or low-surface-brightness\n features, nothing else comes close.\n\nIf the answer to the first is \"lumps\" and to the second \"yes\", continue. Otherwise you will\nspend hours to learn less.\n\n## Ask\n\n- *\"What is the smooth component?\"* Almost always a linear `Sersic`, sometimes a Sersic plus an\n Exponential disk. It matters that this exists: without it the pixelization has to reconstruct\n the bright central bulge too, which wastes mesh resolution on light a six-parameter profile\n describes perfectly and makes the regularization choice much harder.\n- *\"How many mesh pixels can you afford?\"* This is a hardware question as much as a science one\n (see the run-time branch). 20 × 20 is the workspace's default for a GPU run; 28 × 28 to 30 × 30\n for a better-resolved reconstruction; higher only with a large-VRAM GPU or a many-core CPU.\n- *\"Are there neighbours inside the mask?\"* For a pixelization the answer is *never* to mask\n their pixels out — that punches holes in the mesh and produces discontinuity systematics.\n Scale their noise instead (branch below).\n- *\"GPU or CPU?\"* Genuinely depends on your pixel scale, and the answer is counter-intuitive.\n Ask before assuming.\n\n## Branch — the hybrid model\n\nThe canonical composition. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py`.\n\n```python\n\"\"\"\nGalaxy Structure: Bulge Plus Pixelized Reconstruction\n=====================================================\n\nFit a galaxy whose light has two very different characters: a smooth central bulge, described by\na linear Sersic profile in six parameters, and asymmetric clumpy star formation, reconstructed\non a regularized rectangular mesh. The Sersic captures the smooth component interpretably; the\npixelization absorbs everything it cannot explain, and the reconstructed flux map is the\nmeasurement of the galaxy's irregular light.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the imaging, mask it, and apply pixelization over-sampling.\n- **Mesh Shape:** Fix the mesh dimensions before the model is composed.\n- **Model:** Compose the linear Sersic bulge plus the pixelization.\n- **Check:** Confirm the parameter count, evaluate one likelihood, and estimate VRAM.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPIXEL_SCALES = 0.1\nMASK_RADIUS = 2.0\n\n\"\"\"\n__Dataset__\n\nThe mask matters more than usual here. It defines the region the mesh is laid over, so a mask\nthat reaches well beyond the galaxy spends reconstruction pixels on empty sky, and one that\ntruncates the galaxy leaves its outer light unreconstructed\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe over-sampling argument changes too. A pixelization evaluates light on its *own* grid with\nits own over-sampling scheme, so the size is passed as `over_sample_size_pixelization`, not the\n`over_sample_size_lp` used for light profiles. Passing the wrong one silently leaves the\npixelization grid at its default.\n\"\"\"\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=PIXEL_SCALES,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\ndataset = dataset.apply_over_sampling(over_sample_size_pixelization=over_sample_size)\n\n\"\"\"\n__Mesh Shape__\n\nThe mesh dimensions are **fixed before the fit and cannot be a free parameter**. This is not a\nstylistic restriction: JAX compiles the likelihood against statically shaped arrays, and the\nmesh shape sets those shapes. A rectangular mesh uses the same number of pixels in y and x.\n\"\"\"\nmesh_pixels_yx = 20\nmesh_shape = (mesh_pixels_yx, mesh_pixels_yx)\n\n\"\"\"\n__Model__\n\n`ag.Pixelization` pairs a `mesh` — where the reconstruction pixels sit — with a `regularization`\nscheme — the prior that keeps the solution smooth. It is attached to the galaxy as a component\nalongside the light profiles, and the analysis knows to route it through the inversion\n(`PyAutoGalaxy:autogalaxy/galaxy/galaxy.py`).\n\nThe mesh itself contributes **zero** free parameters; the reconstruction's 400 flux values are\nsolved, not sampled. `ag.reg.GaussianKernel` contributes two (`coefficient`, `scale`). The bulge\nis `ag.lp_linear.Sersic` rather than `ag.lp.Sersic` deliberately: its `intensity` is then solved\nby the *same* inversion that solves the mesh amplitudes, which removes the degeneracy between\n\"bright bulge, faint reconstruction\" and \"faint bulge, bright reconstruction\" that a sampled\nintensity would create.\n\"\"\"\npixelization = af.Model(\n ag.Pixelization,\n mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n regularization=ag.reg.GaussianKernel,\n)\n\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n pixelization=pixelization,\n)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\nThree cheap checks, each catching a different class of mistake: the parameter count catches a\nmodel error, one likelihood evaluation catches an incompatibility between model, dataset and\nanalysis, and `print_vram_use` catches the resource error that otherwise appears as an\nout-of-memory failure mid-compile. Pixelizations use far more VRAM than profile-only models —\naround 0.05 GB per batched likelihood for 400 reconstruction pixels — which is why the\nworkspace uses a lower `n_batch` for these fits than for any other.\n\"\"\"\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\nlog_likelihood = analysis.log_likelihood_function(\n instance=model.instance_from_prior_medians()\n)\nprint(f\"log evidence at prior medians: {float(log_likelihood):.2f}\")\n```\n\n**N = 8**: the Sersic's centre (2), `ell_comps` (2), `effective_radius`, `sersic_index`, plus the\nregularization's `coefficient` and `scale`. Eight parameters, with 400 reconstruction pixels\nsolved. That is dramatically more parsimonious than stacking parametric profiles until every\nclump is described — a 20-plus-parameter approach that would still fail on genuinely irregular\nsubstructure.\n\nExtending the smooth side is exactly as you would expect — add components as further attributes\non the galaxy, keeping them linear so their intensities join the same inversion:\n\n```python\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n disk=ag.lp_linear.Exponential,\n pixelization=pixelization,\n)\n```\n\n## Branch — choosing a mesh and a regularization scheme\n\nThese are the two decisions that make or break a reconstruction, and the parameter cost is\nalmost entirely in the regularization.\n\n**Meshes** (`ag.mesh`, from `PyAutoArray:autoarray/inversion/mesh/`). All contribute zero free\nparameters, all take `shape=(y, x)`:\n\n| Mesh | Where the pixels go | Use when |\n|---|---|---|\n| `RectangularUniform` | a uniform grid over the masked region | you want the simplest, most predictable behaviour |\n| `RectangularBilinearAdaptDensity` | a rectangular grid whose spacing follows the density of image pixels mapping to it, via a rank CDF | **the default** — concentrates resolution where the data is, and the fast CPU path |\n| `RectangularBilinearAdaptImage` | adapts to the image's own brightness distribution | the irregular light is strongly concentrated |\n| `RectangularRTUAdaptDensity` / `RectangularRTUAdaptImage` | the same two adaptations through a kernel CDF | GPU, JAX gradient samplers and the interferometer sparse path — the only rectangular adaptive meshes with usable gradients |\n\n`Delaunay`, `KNearestNeighbor` and `KNNBarycentric` also exist for irregular tessellations. Start\nwith `RectangularBilinearAdaptDensity`; it is what every workspace example uses, and the\nrectangular meshes are what the fixed-`mesh_shape` JAX path is built around. (The unqualified\n`RectangularAdaptDensity` / `RectangularAdaptImage` names were split into the `Bilinear` and\n`RTU` families in PyAutoArray 2026.8.23.1 and no longer resolve.)\n\n**Regularization** (`ag.reg`, from `PyAutoArray:autoarray/inversion/regularization/`) is where\nthe free parameters are, and where the physics of \"how smooth should this be?\" lives:\n\n| Scheme | Free params | What it assumes |\n|---|---|---|\n| `ag.reg.Constant` | 1 (`coefficient`) | one smoothing strength everywhere — the simplest, and the right first try |\n| `ag.reg.GaussianKernel` | 2 (`coefficient`, `scale`) | smoothing with a Gaussian correlation length you also fit |\n| `ag.reg.MaternKernel` | 3 (`coefficient`, `scale`, `nu`) | as above, with the roughness `nu` free too |\n\nVerified counts, not guesses. `Constant` penalises the difference between neighbouring pixels\ndirectly; the kernel schemes impose a correlation *length*, which is physically closer to what a\ngalaxy's light does and generally reconstructs faint extended structure better at the cost of\none or two parameters. `ag.reg.Adapt` and its variants scale the smoothing with the\nreconstruction's own brightness — more flexible again, and requiring `adapt_images` on the\nanalysis, which is a step beyond this skill; ask if you want it.\n\nA practical route: fit once with `ag.reg.Constant`, look at the reconstruction. Over-smoothed\n(the clumps blurred into one blob) or over-fitted (isolated single-pixel spikes) both show up\nimmediately, and if `Constant` cannot get both the bright clumps and the faint envelope right at\none strength, that is the signal to move to `GaussianKernel`. Full discussion in\n[`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\n### The positive-only solver\n\nEvery pixelized reconstruction uses a **positive-only** linear solver: no mesh pixel may\nreconstruct negative flux. This is not a numerical nicety. A signed solver lets the\nreconstruction manufacture negative pixels that cancel positive ones to over-fit the data, and\nthat failure mode is a well-known systematic in the literature — many published methods allow\nit. Enforcing non-negativity efficiently needs bespoke linear algebra, which is why this is\nworth stating rather than assuming. You do not need to switch it on; it is the behaviour you get.\n(The one place in this workspace where you *must* disable it is a shapelet basis, which needs\nsigned amplitudes by construction — see [`ag_basis_profiles`](./ag_basis_profiles.md).)\n\n## Branch — contaminating neighbours: scale, never mask\n\nThe general advice for a neighbour inside the mask is to mask its pixels out. **For a\npixelization that advice is wrong.** Removing image pixels entirely removes their mapping into\nthe mesh, punching a hole in the reconstruction and producing discontinuities that show up as\nunexplained systematics.\n\nInstead, keep the pixels in the fit and make them contribute nothing: scale their data to zero\nand their noise to an enormous value, so the likelihood is indifferent to them while the mesh\nstays continuous. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py`.\n\n```python\n\"\"\"\n__Noise Scaling__\n\n`mask_extra_galaxies.fits` marks the contaminated pixels. It is loaded with `invert=True`\nbecause in this file `True` means \"scale this pixel\", the opposite of a modelling mask's\nconvention — getting this backwards scales the galaxy instead of the neighbour, so check the\nsubplot afterwards. `apply_noise_scaling` then zeroes those data values and inflates their\nnoise, driving their signal-to-noise to effectively zero without removing them from the mesh's\nmapping (`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nOrder matters: scale first, then apply the modelling mask.\n\"\"\"\nmask_extra_galaxies = ag.Mask2D.from_fits(\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n pixel_scales=PIXEL_SCALES,\n invert=True,\n)\n\ndataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=PIXEL_SCALES,\n centre=(0.0, 0.0),\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=\"scripts/scratch/my_galaxy/\",\n output_filename=\"noise_scaled\",\n output_format=\"png\",\n)\n```\n\nThe scaled pixels go to a noise value of order 1e8 — visibly so on the signal-to-noise panel of\nthe subplot, which is how you confirm you scaled the right region. Drawing that mask\ninteractively is `autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask_extra_galaxies.py`;\nthe modelling alternative, and when to prefer it, is\n[`ag_light_model_extras`](./ag_light_model_extras.md) and\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch — reading the reconstruction out\n\nThe reconstruction is the science product, and it lives on the `Inversion`. You can get there\nfrom a completed fit or from a single direct `ag.FitImaging` — the latter is the fast way to\nlearn the objects, and is what\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` does.\n\n```python\n\"\"\"\n__Reconstruction__\n\n`inversion.linear_obj_list` holds the linear objects the fit solved. For a hybrid model that is\none `LightProfileLinearObjFuncList` per linear light profile plus one `Mapper` for the\npixelization; with a non-linear `ag.lp.Sersic` bulge the `Mapper` is the only entry. The\n`Mapper` is the object that maps image pixels onto mesh pixels, and it is mesh-specific\n(`PyAutoArray:autoarray/inversion/mappers/`).\n\nThe reconstruction is a 1D array of one flux per mesh pixel, and the (y, x) arcsecond\ncoordinates of those pixels are `mapper.mesh_geometry.mesh_grid`. Pair them by index — they are\nthe same length and the same order — and you have the flux map.\n\"\"\"\ninversion = fit.inversion\n\nmapper = inversion.linear_obj_list[0]\n\nreconstruction = inversion.reconstruction\nmesh_grid = mapper.mesh_geometry.mesh_grid\n\nprint(f\"{len(reconstruction)} mesh pixels reconstructed\")\nprint(f\"coordinates shape: {mesh_grid.shape}\")\n\n\"\"\"\nThe reconstruction's own uncertainties, and its projection back onto the image, are also on the\ninversion. `mapped_reconstructed_operated_data` contains **only** the pixelized component — any\nparametric light profile in the model is excluded — which is exactly the quantity you want when\nasking how much light is in the irregular component.\n\"\"\"\nprint(inversion.reconstruction_noise_map)\nprint(inversion.mapped_reconstructed_operated_data.native.shape)\n```\n\nA caution on the `Mapper`'s grid attributes: `mapper.image_plane_mesh_grid` is `None` for a\nrectangular mesh, so do not reach for it. `mapper.mesh_geometry.mesh_grid` is the mesh pixel\ncentres (verified on the released stack), and `mapper.image_plane_data_grid` is the centre of\nevery masked *image* pixel. Some of the `Mapper`'s attribute names carry a plane-based prefix\ninherited from the shared inversion library that also serves a multi-plane use case; in\nPyAutoGalaxy there is only the one plane, so `mesh_geometry.mesh_grid` is both the clearer name\nand the one to use.\n\n### The evidence terms\n\nThe inversion's figure of merit is a Bayesian evidence, and its components are individually\nreadable — which is how you diagnose whether regularization is doing too much or too little:\n\n```python\nprint(f\"regularization term = {inversion.regularization_term}\")\nprint(f\"log det regularization = {inversion.log_det_regularization_matrix_term}\")\nprint(f\"log det curvature + reg = {inversion.log_det_curvature_reg_matrix_term}\")\n```\n\nThe `regularization_term` measures how non-smooth the solution is; the two log-determinant\nterms are the complexity penalty that stops a 400-pixel model winning by over-fitting. The\nmatrices themselves (`curvature_matrix`, `regularization_matrix`, `curvature_reg_matrix`) are\nthere too. The derivation is in HowToGalaxy chapter 3 and the papers it cites\n(arXiv:1708.07377, arXiv:astro-ph/0601493).\n\n### Diagnostic plots\n\n`aplt.subplot_fit_imaging` includes the reconstruction on the mesh alongside the usual data /\nmodel / residual panels, and is the first thing to look at. For the inversion's own internals\nthere are dedicated functions, which live in the shared inversion library rather than on `aplt`\nand so are imported explicitly — from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/plot.py`:\n\n```python\nfrom autoarray.inversion.plot.inversion_plots import subplot_of_mapper\nfrom autoarray.inversion.plot.mapper_plots import plot_mapper, subplot_image_and_mapper\n\nPLOT_DIR = \"scripts/scratch/my_galaxy/pixelization/\"\n\naplt.subplot_fit_imaging(fit=fit, output_path=PLOT_DIR, output_format=\"png\")\n\nsubplot_of_mapper(\n inversion=inversion, mapper_index=0, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nsubplot_image_and_mapper(\n mapper=mapper, image=dataset.data, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nprint(f\"Saved to: {Path(PLOT_DIR).resolve()}\")\n```\n\n`subplot_of_mapper` is the comprehensive diagnostic — reconstructed image, reconstruction, its\nnoise map and the regularization weights in one figure — and `mapper_index` selects which linear\nobject when there are several. `subplot_image_and_mapper` shows the data beside the mesh, which\nis how you check the mesh covers the structure you care about. Note that none of these three are\nexposed on the `aplt` module — `dir(aplt)` does not list them, so the explicit imports above are\nthe only route and writing them as `aplt.`-prefixed calls raises `AttributeError`. Quote the\nabsolute path back to the user and offer to open it.\n\n## Branch — exporting the reconstruction for downstream science\n\nA reconstruction that only exists inside a PyAutoGalaxy object is hard to share and hard to\nanalyse with other tools. Write it out as coordinates plus values and it becomes ordinary\ntabular data. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py`.\n\n```python\n\"\"\"\n__Export__\n\nFour columns — y, x, reconstruction, noise — is everything needed to rebuild, plot or analyse\nthe galaxy's irregular light without PyAutoGalaxy installed. A completed model-fit also writes\nthis file into its own `image/` folder automatically; glob for `*reconstruction_0.csv` there\nrather than hard-coding the stem, which carries a prefix from the shared inversion library.\n\"\"\"\nimport csv\n\nCSV_PATH = Path(\"scripts/scratch/my_galaxy/reconstruction.csv\")\nCSV_PATH.parent.mkdir(parents=True, exist_ok=True)\n\nwith CSV_PATH.open(\"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([\"y\", \"x\", \"reconstruction\", \"noise_map\"])\n for (y, x), value, sigma in zip(\n mesh_grid, inversion.reconstruction, inversion.reconstruction_noise_map\n ):\n writer.writerow([y, x, value, sigma])\n\nprint(f\"Reconstruction written to: {CSV_PATH.resolve()}\")\n```\n\nReloading needs nothing but the standard library, and from there the mesh is ordinary scattered\ndata. Two things the workspace does with it: a Delaunay triangulation via `scipy.spatial` for\nplotting on the mesh's own geometry, and interpolation onto a regular grid via\n`scipy.interpolate.griddata` for any tool that wants an image:\n\n```python\nimport numpy as np\nfrom scipy.interpolate import griddata\n\nwith CSV_PATH.open() as f:\n reader = csv.reader(f)\n header = next(reader) # ['y', 'x', 'reconstruction', 'noise_map']\n loaded = {key: [] for key in header}\n for row in reader:\n for key, value in zip(header, row):\n loaded[key].append(float(value))\n\npoints = np.stack((np.array(loaded[\"x\"]), np.array(loaded[\"y\"])), axis=-1)\n\ninterpolation_grid = ag.Grid2D.from_extent(\n extent=(-1.0, 1.0, -1.0, 1.0), shape_native=(201, 201)\n)\n\ninterpolated = griddata(\n points=points, values=np.array(loaded[\"reconstruction\"]), xi=interpolation_grid\n)\n```\n\nPick the `extent` to cover the reconstruction without over-resolving it — the mesh has a few\nhundred pixels, so interpolating to 201 × 201 is presentation, not information.\n\n## Branch — run time, VRAM, and the GPU-versus-CPU choice\n\nThis is the branch that decides whether your fit takes twenty minutes or three hours, and the\nanswer is not \"use the GPU\".\n\nPixelized inversions do linear algebra on very large, very **sparse** matrices. JAX has no sparse\nsupport and must work densely, which scales badly; the CPU implementation exploits the sparsity\nfully via `numba`. So the trade runs against pixel scale:\n\n- **Low resolution (`pixel_scales > 0.05`, e.g. Euclid)** — fewer sparse operations, modest VRAM.\n **GPU with JAX is usually fastest.**\n- **High resolution (`pixel_scales <= 0.03`, e.g. HST or JWST)** — the linear algebra is\n sparsity-dominated. **CPU with `numba` and many cores can beat a powerful GPU.**\n\nVRAM is the hard constraint on the GPU side. JAX must hold the whole batched likelihood in GPU\nmemory, and a pixelization needs far more than a profile model: around 0.05 GB per batched\nlikelihood at 400 reconstruction pixels, and more than 1 GB — occasionally more than 10 GB — at\nhigh resolution with a fine mesh. Two consequences: keep `n_batch` low (the workspace uses 20 for\npixelizations against 50 elsewhere), and run\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nbefore committing. It takes 20–30 seconds and it is the difference between knowing your limit\nand discovering it as an out-of-memory error mid-compile. If VRAM is exceeded the run time does\nnot degrade gracefully — it goes from under ten minutes to three hours or more.\n\nRough scaling with resolution, from the workspace's own measurements at a 20 × 20 mesh with VRAM\nunder control: ~10 minutes at 0.1\"/pixel, ~30 minutes at 0.05\", ~1 hour at 0.03\". Benchmark both\npaths for your own data and hardware rather than trusting either default; the search-side\nsettings are [`ag_configure_search`](./ag_configure_search.md) and\n[`../wiki/core/api/searches.md`](../wiki/core/api/searches.md).\n\n## Combine — where this hands off\n\n- **Try a basis first** → [`ag_basis_profiles`](./ag_basis_profiles.md). An MGE is four\n parameters and minutes, not hours, and it genuinely resolves the shape-mismatch case a\n pixelization is often reached for by mistake.\n- **Pick and configure the search** → [`ag_configure_search`](./ag_configure_search.md), with\n `n_batch` lowered for VRAM.\n- **Run the fit** → [`ag_run_search`](./ag_run_search.md); `image/fit.png` in the output folder\n refreshes on the fly and shows the reconstruction as it converges, which is worth watching for\n a fit this long.\n- **Plot and inspect** → [`ag_plot_fit`](./ag_plot_fit.md), plus the `subplot_of_mapper`\n diagnostics above.\n- **Load a completed fit programmatically** → [`ag_load_results`](./ag_load_results.md).\n- **Over-smoothed, over-fitted or unphysical reconstruction** →\n [`ag_debug_fit_failure`](./ag_debug_fit_failure.md). The pixelization-specific causes are a\n regularization scheme too rigid for the structure, a mask that punched holes via hard masking\n where noise scaling was needed, over-sampling passed as `over_sample_size_lp` instead of\n `over_sample_size_pixelization`, and VRAM exhaustion masquerading as a hung fit.\n- **Contaminating neighbours modelled rather than scaled** →\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- **Make the fit robust and fast by starting simple** → the search-chaining skill\n (`ag_chain_searches`). This is the biggest available win for a pixelization: fit a parametric\n model first, pass its bulge as priors, and let the expensive model start from a sensible place.\n The workspace recommends it explicitly.\n- **A non-parametric shape measurement instead of a reconstruction** →\n [`ag_ellipse_fitting`](./ag_ellipse_fitting.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording the mesh and its\nshape, the regularization scheme and why, the mask radius, the hardware path, and what the\nreconstruction showed — with a pixelization the choices *are* the result, and none of them are\nrecoverable from the output folder alone.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Bayesian regularization](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb):\n why a model with hundreds of free flux values does not simply over-fit, derived from scratch;\n `tutorial_6_model_fit` then runs the full fit.\n- **General reference** — [RTD: Pixelization API](https://pyautogalaxy.readthedocs.io/en/latest/api/pixelization.html):\n every mesh, regularization scheme and the objects that combine them.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n the hybrid fit end to end, with the run-time, VRAM and GPU-versus-CPU discussion in full.\n\n## Agent procedural checklist\n\n1. Look at the residual map of a parametric or basis fit first. Shape-following residuals mean\n `ag_basis_profiles`; discrete off-centre lumps mean a pixelization. Do not skip this.\n2. Confirm the structure is resolved — at coarse pixel scales a pixelization reconstructs noise.\n3. Always pair the pixelization with a linear light profile for the smooth component; never let\n the mesh reconstruct the bulge.\n4. Fix `mesh_shape` before composing the model; it cannot be a free parameter.\n5. Pass over-sampling as `over_sample_size_pixelization`, not `over_sample_size_lp`.\n6. Start with `RectangularBilinearAdaptDensity` + `ag.reg.Constant`; move to `GaussianKernel` only when\n one smoothing strength demonstrably cannot serve both the bright and faint structure.\n7. Scale contaminant noise (`apply_noise_scaling`, `invert=True`) — never hard-mask pixels inside\n a pixelization fit — and check the signal-to-noise panel afterwards.\n8. `print(model.info)`, evaluate one likelihood, then `print_vram_use` before any GPU run; keep\n `n_batch` low.\n9. Read the reconstruction via `inversion.reconstruction` +\n `mapper.mesh_geometry.mesh_grid`; export to CSV for anything downstream.\n10. Save the script to `scripts/`, quote every plot's absolute path and offer to open it, then\n offer the `wiki/project/` entry recording mesh, regularization and hardware choices.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_3_pixelizations/tutorial_6_model_fit.ipynb b/notebooks/chapter_3_pixelizations/tutorial_6_model_fit.ipynb index 90c300f..c27ccd5 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_6_model_fit.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_6_model_fit.ipynb @@ -41,21 +41,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -399,7 +399,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_6_model_fit.ipynb in HowToGalaxy).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoGalaxy calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoGalaxy docs (https://pyautogalaxy.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_pixelization\n\n---\nname: ag_pixelization\ndescription: Reconstruct a galaxy's clumpy or irregular light directly on a regularized pixel mesh, using `ag.Pixelization` alongside a parametric `ag.lp_linear` bulge \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_6_model_fit.ipynb in HowToGalaxy).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoGalaxy calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoGalaxy docs (https://pyautogalaxy.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_pixelization\n\n---\nname: ag_pixelization\ndescription: Reconstruct a galaxy's clumpy or irregular light directly on a regularized pixel mesh, using `ag.Pixelization` alongside a parametric `ag.lp_linear` bulge — the hybrid model that gives a smooth interpretable component plus a flexible flux map for everything the profile cannot explain. Covers when a pixelization is warranted and when it is overkill, choosing an `ag.mesh` and an `ag.reg` regularization scheme and what each costs in free parameters, why `mesh_shape` must be fixed before the fit, `over_sample_size_pixelization` rather than `over_sample_size_lp`, noise scaling instead of hard masking for contaminants, the positive-only solver, reading the reconstruction and its Bayesian-evidence terms out of the `Inversion`, exporting the reconstruction to CSV for collaborators, and the GPU/VRAM versus CPU run-time trade. Use when a Sersic, MGE or shapelet basis leaves structured residuals in discrete off-centre lumps. Not for morphology a basis can still fit (`ag_basis_profiles`), not for non-parametric isophote measurement (`ag_ellipse_fitting`), and not for the basics of model composition (`ag_build_imaging_model`).\n---\n\n# Reconstructing a galaxy on a pixel mesh\n\nEvery model in this workspace so far has been a *function*: you asserted a functional form and\nthe fit found its parameters. A pixelization drops the functional form. It lays a mesh of pixels\nover the galaxy, gives each pixel its own free flux value, and solves all of them at once by\nlinear inversion — thousands of amplitudes, none of them in the non-linear search's parameter\nspace. What stops that from simply fitting the noise is **regularization**: a prior that\npenalises solutions where neighbouring mesh pixels differ sharply, so the reconstruction is as\nsmooth as the data will allow and no smoother.\n\nThe science case is specific, and it is worth being honest about how specific. Galaxies with\nspiral arms, asymmetric star-forming clumps, tidal features or low-surface-brightness\nsubstructure have light that no smooth profile — and often no basis expansion either —\nreproduces. The canonical use is therefore **hybrid**: a linear `Sersic` for the smooth central\nbulge, and a pixelization for the irregular remainder. That split is the point. It gives you a\nlow-dimensional, physically interpretable description of the bulge *and* a flux map of exactly\nwhat the bulge could not explain, which is the quantity you want if the science question is \"how\nmuch of this galaxy's light is in its irregular components?\"\n\nThis is a **direct** reconstruction. There is no second plane, no de-projection, no inversion of\na geometric mapping — the mesh sits on the image plane, over the galaxy, at the same coordinates\nthe data occupies. If you have met pixelized reconstruction before in a different context, that\nextra step is the one that is absent here, and its absence makes everything simpler: what the\nmesh reconstructs is the galaxy's own surface brightness, and its coordinates are sky\ncoordinates in arcseconds.\n\nStatistically, the fit now has two nested layers. The non-linear search explores a handful of\nparameters — the bulge's shape, the regularization strength — and for each proposal an inversion\nsolves the mesh amplitudes exactly and returns a **Bayesian evidence** rather than a plain\nlikelihood. That evidence includes terms that penalise an unnecessarily complex reconstruction,\nwhich is what lets a model with 400 free flux values not simply win by over-fitting. The theory\nis [`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md);\nchapter 3 of HowToGalaxy derives it from scratch.\n\nThe canonical scripts are\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py` (via a search),\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` (one direct fit, with the\ninversion internals walked through) and\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py` (export).\n\n## Before you reach for one — the honest gate\n\nA pixelization is the most powerful and the most expensive model here, with failure modes the\nparametric models do not have. Three questions decide whether you need it:\n\n- *\"What do the residuals actually look like?\"* Structured residuals that **follow the\n isophotes** — a twist, a four-lobed pattern, an ellipticity that changes with radius — are a\n *shape* problem, and an MGE fixes them for four free parameters\n ([`ag_basis_profiles`](./ag_basis_profiles.md)). Residuals in **discrete off-centre lumps** are\n a substructure problem, and that is what a pixelization is for. Look before you choose.\n- *\"Is the structure resolved?\"* At low resolution the irregular structure is not in the data,\n and a pixelization will reconstruct noise while telling you it fitted well. The workspace is\n blunt about this: for low-resolution data pixelizations are unnecessary.\n- *\"Do you need global quantities or the light distribution?\"* If you want a total flux, a size,\n an axis ratio, a Sersic index — a parametric profile, an MGE or shapelets are enough and far\n cheaper. If you want the morphology itself, particularly for faint or low-surface-brightness\n features, nothing else comes close.\n\nIf the answer to the first is \"lumps\" and to the second \"yes\", continue. Otherwise you will\nspend hours to learn less.\n\n## Ask\n\n- *\"What is the smooth component?\"* Almost always a linear `Sersic`, sometimes a Sersic plus an\n Exponential disk. It matters that this exists: without it the pixelization has to reconstruct\n the bright central bulge too, which wastes mesh resolution on light a six-parameter profile\n describes perfectly and makes the regularization choice much harder.\n- *\"How many mesh pixels can you afford?\"* This is a hardware question as much as a science one\n (see the run-time branch). 20 × 20 is the workspace's default for a GPU run; 28 × 28 to 30 × 30\n for a better-resolved reconstruction; higher only with a large-VRAM GPU or a many-core CPU.\n- *\"Are there neighbours inside the mask?\"* For a pixelization the answer is *never* to mask\n their pixels out — that punches holes in the mesh and produces discontinuity systematics.\n Scale their noise instead (branch below).\n- *\"GPU or CPU?\"* Genuinely depends on your pixel scale, and the answer is counter-intuitive.\n Ask before assuming.\n\n## Branch — the hybrid model\n\nThe canonical composition. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/modeling.py`.\n\n```python\n\"\"\"\nGalaxy Structure: Bulge Plus Pixelized Reconstruction\n=====================================================\n\nFit a galaxy whose light has two very different characters: a smooth central bulge, described by\na linear Sersic profile in six parameters, and asymmetric clumpy star formation, reconstructed\non a regularized rectangular mesh. The Sersic captures the smooth component interpretably; the\npixelization absorbs everything it cannot explain, and the reconstructed flux map is the\nmeasurement of the galaxy's irregular light.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the imaging, mask it, and apply pixelization over-sampling.\n- **Mesh Shape:** Fix the mesh dimensions before the model is composed.\n- **Model:** Compose the linear Sersic bulge plus the pixelization.\n- **Check:** Confirm the parameter count, evaluate one likelihood, and estimate VRAM.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPIXEL_SCALES = 0.1\nMASK_RADIUS = 2.0\n\n\"\"\"\n__Dataset__\n\nThe mask matters more than usual here. It defines the region the mesh is laid over, so a mask\nthat reaches well beyond the galaxy spends reconstruction pixels on empty sky, and one that\ntruncates the galaxy leaves its outer light unreconstructed\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe over-sampling argument changes too. A pixelization evaluates light on its *own* grid with\nits own over-sampling scheme, so the size is passed as `over_sample_size_pixelization`, not the\n`over_sample_size_lp` used for light profiles. Passing the wrong one silently leaves the\npixelization grid at its default.\n\"\"\"\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=PIXEL_SCALES,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\ndataset = dataset.apply_over_sampling(over_sample_size_pixelization=over_sample_size)\n\n\"\"\"\n__Mesh Shape__\n\nThe mesh dimensions are **fixed before the fit and cannot be a free parameter**. This is not a\nstylistic restriction: JAX compiles the likelihood against statically shaped arrays, and the\nmesh shape sets those shapes. A rectangular mesh uses the same number of pixels in y and x.\n\"\"\"\nmesh_pixels_yx = 20\nmesh_shape = (mesh_pixels_yx, mesh_pixels_yx)\n\n\"\"\"\n__Model__\n\n`ag.Pixelization` pairs a `mesh` — where the reconstruction pixels sit — with a `regularization`\nscheme — the prior that keeps the solution smooth. It is attached to the galaxy as a component\nalongside the light profiles, and the analysis knows to route it through the inversion\n(`PyAutoGalaxy:autogalaxy/galaxy/galaxy.py`).\n\nThe mesh itself contributes **zero** free parameters; the reconstruction's 400 flux values are\nsolved, not sampled. `ag.reg.GaussianKernel` contributes two (`coefficient`, `scale`). The bulge\nis `ag.lp_linear.Sersic` rather than `ag.lp.Sersic` deliberately: its `intensity` is then solved\nby the *same* inversion that solves the mesh amplitudes, which removes the degeneracy between\n\"bright bulge, faint reconstruction\" and \"faint bulge, bright reconstruction\" that a sampled\nintensity would create.\n\"\"\"\npixelization = af.Model(\n ag.Pixelization,\n mesh=ag.mesh.RectangularBilinearAdaptDensity(shape=mesh_shape),\n regularization=ag.reg.GaussianKernel,\n)\n\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n pixelization=pixelization,\n)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\nThree cheap checks, each catching a different class of mistake: the parameter count catches a\nmodel error, one likelihood evaluation catches an incompatibility between model, dataset and\nanalysis, and `print_vram_use` catches the resource error that otherwise appears as an\nout-of-memory failure mid-compile. Pixelizations use far more VRAM than profile-only models —\naround 0.05 GB per batched likelihood for 400 reconstruction pixels — which is why the\nworkspace uses a lower `n_batch` for these fits than for any other.\n\"\"\"\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\nlog_likelihood = analysis.log_likelihood_function(\n instance=model.instance_from_prior_medians()\n)\nprint(f\"log evidence at prior medians: {float(log_likelihood):.2f}\")\n```\n\n**N = 8**: the Sersic's centre (2), `ell_comps` (2), `effective_radius`, `sersic_index`, plus the\nregularization's `coefficient` and `scale`. Eight parameters, with 400 reconstruction pixels\nsolved. That is dramatically more parsimonious than stacking parametric profiles until every\nclump is described — a 20-plus-parameter approach that would still fail on genuinely irregular\nsubstructure.\n\nExtending the smooth side is exactly as you would expect — add components as further attributes\non the galaxy, keeping them linear so their intensities join the same inversion:\n\n```python\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=ag.lp_linear.Sersic,\n disk=ag.lp_linear.Exponential,\n pixelization=pixelization,\n)\n```\n\n## Branch — choosing a mesh and a regularization scheme\n\nThese are the two decisions that make or break a reconstruction, and the parameter cost is\nalmost entirely in the regularization.\n\n**Meshes** (`ag.mesh`, from `PyAutoArray:autoarray/inversion/mesh/`). All contribute zero free\nparameters, all take `shape=(y, x)`:\n\n| Mesh | Where the pixels go | Use when |\n|---|---|---|\n| `RectangularUniform` | a uniform grid over the masked region | you want the simplest, most predictable behaviour |\n| `RectangularBilinearAdaptDensity` | a rectangular grid whose spacing follows the density of image pixels mapping to it, via a rank CDF | **the default** — concentrates resolution where the data is, and the fast CPU path |\n| `RectangularBilinearAdaptImage` | adapts to the image's own brightness distribution | the irregular light is strongly concentrated |\n| `RectangularRTUAdaptDensity` / `RectangularRTUAdaptImage` | the same two adaptations through a kernel CDF | GPU, JAX gradient samplers and the interferometer sparse path — the only rectangular adaptive meshes with usable gradients |\n\n`Delaunay`, `KNearestNeighbor` and `KNNBarycentric` also exist for irregular tessellations. Start\nwith `RectangularBilinearAdaptDensity`; it is what every workspace example uses, and the\nrectangular meshes are what the fixed-`mesh_shape` JAX path is built around. (The unqualified\n`RectangularAdaptDensity` / `RectangularAdaptImage` names were split into the `Bilinear` and\n`RTU` families in PyAutoArray 2026.8.23.1 and no longer resolve.)\n\n**Regularization** (`ag.reg`, from `PyAutoArray:autoarray/inversion/regularization/`) is where\nthe free parameters are, and where the physics of \"how smooth should this be?\" lives:\n\n| Scheme | Free params | What it assumes |\n|---|---|---|\n| `ag.reg.Constant` | 1 (`coefficient`) | one smoothing strength everywhere — the simplest, and the right first try |\n| `ag.reg.GaussianKernel` | 2 (`coefficient`, `scale`) | smoothing with a Gaussian correlation length you also fit |\n| `ag.reg.MaternKernel` | 3 (`coefficient`, `scale`, `nu`) | as above, with the roughness `nu` free too |\n\nVerified counts, not guesses. `Constant` penalises the difference between neighbouring pixels\ndirectly; the kernel schemes impose a correlation *length*, which is physically closer to what a\ngalaxy's light does and generally reconstructs faint extended structure better at the cost of\none or two parameters. `ag.reg.Adapt` and its variants scale the smoothing with the\nreconstruction's own brightness — more flexible again, and requiring `adapt_images` on the\nanalysis, which is a step beyond this skill; ask if you want it.\n\nA practical route: fit once with `ag.reg.Constant`, look at the reconstruction. Over-smoothed\n(the clumps blurred into one blob) or over-fitted (isolated single-pixel spikes) both show up\nimmediately, and if `Constant` cannot get both the bright clumps and the faint envelope right at\none strength, that is the signal to move to `GaussianKernel`. Full discussion in\n[`../wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\n### The positive-only solver\n\nEvery pixelized reconstruction uses a **positive-only** linear solver: no mesh pixel may\nreconstruct negative flux. This is not a numerical nicety. A signed solver lets the\nreconstruction manufacture negative pixels that cancel positive ones to over-fit the data, and\nthat failure mode is a well-known systematic in the literature — many published methods allow\nit. Enforcing non-negativity efficiently needs bespoke linear algebra, which is why this is\nworth stating rather than assuming. You do not need to switch it on; it is the behaviour you get.\n(The one place in this workspace where you *must* disable it is a shapelet basis, which needs\nsigned amplitudes by construction — see [`ag_basis_profiles`](./ag_basis_profiles.md).)\n\n## Branch — contaminating neighbours: scale, never mask\n\nThe general advice for a neighbour inside the mask is to mask its pixels out. **For a\npixelization that advice is wrong.** Removing image pixels entirely removes their mapping into\nthe mesh, punching a hole in the reconstruction and producing discontinuities that show up as\nunexplained systematics.\n\nInstead, keep the pixels in the fit and make them contribute nothing: scale their data to zero\nand their noise to an enormous value, so the likelihood is indifferent to them while the mesh\nstays continuous. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py`.\n\n```python\n\"\"\"\n__Noise Scaling__\n\n`mask_extra_galaxies.fits` marks the contaminated pixels. It is loaded with `invert=True`\nbecause in this file `True` means \"scale this pixel\", the opposite of a modelling mask's\nconvention — getting this backwards scales the galaxy instead of the neighbour, so check the\nsubplot afterwards. `apply_noise_scaling` then zeroes those data values and inflates their\nnoise, driving their signal-to-noise to effectively zero without removing them from the mesh's\nmapping (`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nOrder matters: scale first, then apply the modelling mask.\n\"\"\"\nmask_extra_galaxies = ag.Mask2D.from_fits(\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n pixel_scales=PIXEL_SCALES,\n invert=True,\n)\n\ndataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=PIXEL_SCALES,\n centre=(0.0, 0.0),\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=\"scripts/scratch/my_galaxy/\",\n output_filename=\"noise_scaled\",\n output_format=\"png\",\n)\n```\n\nThe scaled pixels go to a noise value of order 1e8 — visibly so on the signal-to-noise panel of\nthe subplot, which is how you confirm you scaled the right region. Drawing that mask\ninteractively is `autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask_extra_galaxies.py`;\nthe modelling alternative, and when to prefer it, is\n[`ag_light_model_extras`](./ag_light_model_extras.md) and\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch — reading the reconstruction out\n\nThe reconstruction is the science product, and it lives on the `Inversion`. You can get there\nfrom a completed fit or from a single direct `ag.FitImaging` — the latter is the fast way to\nlearn the objects, and is what\n`autogalaxy_workspace:scripts/imaging/features/pixelization/fit.py` does.\n\n```python\n\"\"\"\n__Reconstruction__\n\n`inversion.linear_obj_list` holds the linear objects the fit solved. For a hybrid model that is\none `LightProfileLinearObjFuncList` per linear light profile plus one `Mapper` for the\npixelization; with a non-linear `ag.lp.Sersic` bulge the `Mapper` is the only entry. The\n`Mapper` is the object that maps image pixels onto mesh pixels, and it is mesh-specific\n(`PyAutoArray:autoarray/inversion/mappers/`).\n\nThe reconstruction is a 1D array of one flux per mesh pixel, and the (y, x) arcsecond\ncoordinates of those pixels are `mapper.mesh_geometry.mesh_grid`. Pair them by index — they are\nthe same length and the same order — and you have the flux map.\n\"\"\"\ninversion = fit.inversion\n\nmapper = inversion.linear_obj_list[0]\n\nreconstruction = inversion.reconstruction\nmesh_grid = mapper.mesh_geometry.mesh_grid\n\nprint(f\"{len(reconstruction)} mesh pixels reconstructed\")\nprint(f\"coordinates shape: {mesh_grid.shape}\")\n\n\"\"\"\nThe reconstruction's own uncertainties, and its projection back onto the image, are also on the\ninversion. `mapped_reconstructed_operated_data` contains **only** the pixelized component — any\nparametric light profile in the model is excluded — which is exactly the quantity you want when\nasking how much light is in the irregular component.\n\"\"\"\nprint(inversion.reconstruction_noise_map)\nprint(inversion.mapped_reconstructed_operated_data.native.shape)\n```\n\nA caution on the `Mapper`'s grid attributes: `mapper.image_plane_mesh_grid` is `None` for a\nrectangular mesh, so do not reach for it. `mapper.mesh_geometry.mesh_grid` is the mesh pixel\ncentres (verified on the released stack), and `mapper.image_plane_data_grid` is the centre of\nevery masked *image* pixel. Some of the `Mapper`'s attribute names carry a plane-based prefix\ninherited from the shared inversion library that also serves a multi-plane use case; in\nPyAutoGalaxy there is only the one plane, so `mesh_geometry.mesh_grid` is both the clearer name\nand the one to use.\n\n### The evidence terms\n\nThe inversion's figure of merit is a Bayesian evidence, and its components are individually\nreadable — which is how you diagnose whether regularization is doing too much or too little:\n\n```python\nprint(f\"regularization term = {inversion.regularization_term}\")\nprint(f\"log det regularization = {inversion.log_det_regularization_matrix_term}\")\nprint(f\"log det curvature + reg = {inversion.log_det_curvature_reg_matrix_term}\")\n```\n\nThe `regularization_term` measures how non-smooth the solution is; the two log-determinant\nterms are the complexity penalty that stops a 400-pixel model winning by over-fitting. The\nmatrices themselves (`curvature_matrix`, `regularization_matrix`, `curvature_reg_matrix`) are\nthere too. The derivation is in HowToGalaxy chapter 3 and the papers it cites\n(arXiv:1708.07377, arXiv:astro-ph/0601493).\n\n### Diagnostic plots\n\n`aplt.subplot_fit_imaging` includes the reconstruction on the mesh alongside the usual data /\nmodel / residual panels, and is the first thing to look at. For the inversion's own internals\nthere are dedicated functions, which live in the shared inversion library rather than on `aplt`\nand so are imported explicitly — from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/plot.py`:\n\n```python\nfrom autoarray.inversion.plot.inversion_plots import subplot_of_mapper\nfrom autoarray.inversion.plot.mapper_plots import plot_mapper, subplot_image_and_mapper\n\nPLOT_DIR = \"scripts/scratch/my_galaxy/pixelization/\"\n\naplt.subplot_fit_imaging(fit=fit, output_path=PLOT_DIR, output_format=\"png\")\n\nsubplot_of_mapper(\n inversion=inversion, mapper_index=0, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nsubplot_image_and_mapper(\n mapper=mapper, image=dataset.data, output_path=PLOT_DIR, output_format=\"png\"\n)\n\nprint(f\"Saved to: {Path(PLOT_DIR).resolve()}\")\n```\n\n`subplot_of_mapper` is the comprehensive diagnostic — reconstructed image, reconstruction, its\nnoise map and the regularization weights in one figure — and `mapper_index` selects which linear\nobject when there are several. `subplot_image_and_mapper` shows the data beside the mesh, which\nis how you check the mesh covers the structure you care about. Note that none of these three are\nexposed on the `aplt` module — `dir(aplt)` does not list them, so the explicit imports above are\nthe only route and writing them as `aplt.`-prefixed calls raises `AttributeError`. Quote the\nabsolute path back to the user and offer to open it.\n\n## Branch — exporting the reconstruction for downstream science\n\nA reconstruction that only exists inside a PyAutoGalaxy object is hard to share and hard to\nanalyse with other tools. Write it out as coordinates plus values and it becomes ordinary\ntabular data. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/pixelization/galaxy_reconstruction.py`.\n\n```python\n\"\"\"\n__Export__\n\nFour columns — y, x, reconstruction, noise — is everything needed to rebuild, plot or analyse\nthe galaxy's irregular light without PyAutoGalaxy installed. A completed model-fit also writes\nthis file into its own `image/` folder automatically; glob for `*reconstruction_0.csv` there\nrather than hard-coding the stem, which carries a prefix from the shared inversion library.\n\"\"\"\nimport csv\n\nCSV_PATH = Path(\"scripts/scratch/my_galaxy/reconstruction.csv\")\nCSV_PATH.parent.mkdir(parents=True, exist_ok=True)\n\nwith CSV_PATH.open(\"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([\"y\", \"x\", \"reconstruction\", \"noise_map\"])\n for (y, x), value, sigma in zip(\n mesh_grid, inversion.reconstruction, inversion.reconstruction_noise_map\n ):\n writer.writerow([y, x, value, sigma])\n\nprint(f\"Reconstruction written to: {CSV_PATH.resolve()}\")\n```\n\nReloading needs nothing but the standard library, and from there the mesh is ordinary scattered\ndata. Two things the workspace does with it: a Delaunay triangulation via `scipy.spatial` for\nplotting on the mesh's own geometry, and interpolation onto a regular grid via\n`scipy.interpolate.griddata` for any tool that wants an image:\n\n```python\nimport numpy as np\nfrom scipy.interpolate import griddata\n\nwith CSV_PATH.open() as f:\n reader = csv.reader(f)\n header = next(reader) # ['y', 'x', 'reconstruction', 'noise_map']\n loaded = {key: [] for key in header}\n for row in reader:\n for key, value in zip(header, row):\n loaded[key].append(float(value))\n\npoints = np.stack((np.array(loaded[\"x\"]), np.array(loaded[\"y\"])), axis=-1)\n\ninterpolation_grid = ag.Grid2D.from_extent(\n extent=(-1.0, 1.0, -1.0, 1.0), shape_native=(201, 201)\n)\n\ninterpolated = griddata(\n points=points, values=np.array(loaded[\"reconstruction\"]), xi=interpolation_grid\n)\n```\n\nPick the `extent` to cover the reconstruction without over-resolving it — the mesh has a few\nhundred pixels, so interpolating to 201 × 201 is presentation, not information.\n\n## Branch — run time, VRAM, and the GPU-versus-CPU choice\n\nThis is the branch that decides whether your fit takes twenty minutes or three hours, and the\nanswer is not \"use the GPU\".\n\nPixelized inversions do linear algebra on very large, very **sparse** matrices. JAX has no sparse\nsupport and must work densely, which scales badly; the CPU implementation exploits the sparsity\nfully via `numba`. So the trade runs against pixel scale:\n\n- **Low resolution (`pixel_scales > 0.05`, e.g. Euclid)** — fewer sparse operations, modest VRAM.\n **GPU with JAX is usually fastest.**\n- **High resolution (`pixel_scales <= 0.03`, e.g. HST or JWST)** — the linear algebra is\n sparsity-dominated. **CPU with `numba` and many cores can beat a powerful GPU.**\n\nVRAM is the hard constraint on the GPU side. JAX must hold the whole batched likelihood in GPU\nmemory, and a pixelization needs far more than a profile model: around 0.05 GB per batched\nlikelihood at 400 reconstruction pixels, and more than 1 GB — occasionally more than 10 GB — at\nhigh resolution with a fine mesh. Two consequences: keep `n_batch` low (the workspace uses 20 for\npixelizations against 50 elsewhere), and run\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nbefore committing. It takes 20–30 seconds and it is the difference between knowing your limit\nand discovering it as an out-of-memory error mid-compile. If VRAM is exceeded the run time does\nnot degrade gracefully — it goes from under ten minutes to three hours or more.\n\nRough scaling with resolution, from the workspace's own measurements at a 20 × 20 mesh with VRAM\nunder control: ~10 minutes at 0.1\"/pixel, ~30 minutes at 0.05\", ~1 hour at 0.03\". Benchmark both\npaths for your own data and hardware rather than trusting either default; the search-side\nsettings are [`ag_configure_search`](./ag_configure_search.md) and\n[`../wiki/core/api/searches.md`](../wiki/core/api/searches.md).\n\n## Combine — where this hands off\n\n- **Try a basis first** → [`ag_basis_profiles`](./ag_basis_profiles.md). An MGE is four\n parameters and minutes, not hours, and it genuinely resolves the shape-mismatch case a\n pixelization is often reached for by mistake.\n- **Pick and configure the search** → [`ag_configure_search`](./ag_configure_search.md), with\n `n_batch` lowered for VRAM.\n- **Run the fit** → [`ag_run_search`](./ag_run_search.md); `image/fit.png` in the output folder\n refreshes on the fly and shows the reconstruction as it converges, which is worth watching for\n a fit this long.\n- **Plot and inspect** → [`ag_plot_fit`](./ag_plot_fit.md), plus the `subplot_of_mapper`\n diagnostics above.\n- **Load a completed fit programmatically** → [`ag_load_results`](./ag_load_results.md).\n- **Over-smoothed, over-fitted or unphysical reconstruction** →\n [`ag_debug_fit_failure`](./ag_debug_fit_failure.md). The pixelization-specific causes are a\n regularization scheme too rigid for the structure, a mask that punched holes via hard masking\n where noise scaling was needed, over-sampling passed as `over_sample_size_lp` instead of\n `over_sample_size_pixelization`, and VRAM exhaustion masquerading as a hung fit.\n- **Contaminating neighbours modelled rather than scaled** →\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- **Make the fit robust and fast by starting simple** → the search-chaining skill\n (`ag_chain_searches`). This is the biggest available win for a pixelization: fit a parametric\n model first, pass its bulge as priors, and let the expensive model start from a sensible place.\n The workspace recommends it explicitly.\n- **A non-parametric shape measurement instead of a reconstruction** →\n [`ag_ellipse_fitting`](./ag_ellipse_fitting.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording the mesh and its\nshape, the regularization scheme and why, the mask radius, the hardware path, and what the\nreconstruction showed — with a pixelization the choices *are* the result, and none of them are\nrecoverable from the output folder alone.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Bayesian regularization](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb):\n why a model with hundreds of free flux values does not simply over-fit, derived from scratch;\n `tutorial_6_model_fit` then runs the full fit.\n- **General reference** — [RTD: Pixelization API](https://pyautogalaxy.readthedocs.io/en/latest/api/pixelization.html):\n every mesh, regularization scheme and the objects that combine them.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n the hybrid fit end to end, with the run-time, VRAM and GPU-versus-CPU discussion in full.\n\n## Agent procedural checklist\n\n1. Look at the residual map of a parametric or basis fit first. Shape-following residuals mean\n `ag_basis_profiles`; discrete off-centre lumps mean a pixelization. Do not skip this.\n2. Confirm the structure is resolved — at coarse pixel scales a pixelization reconstructs noise.\n3. Always pair the pixelization with a linear light profile for the smooth component; never let\n the mesh reconstruct the bulge.\n4. Fix `mesh_shape` before composing the model; it cannot be a free parameter.\n5. Pass over-sampling as `over_sample_size_pixelization`, not `over_sample_size_lp`.\n6. Start with `RectangularBilinearAdaptDensity` + `ag.reg.Constant`; move to `GaussianKernel` only when\n one smoothing strength demonstrably cannot serve both the bright and faint structure.\n7. Scale contaminant noise (`apply_noise_scaling`, `invert=True`) — never hard-mask pixels inside\n a pixelization fit — and check the signal-to-noise panel afterwards.\n8. `print(model.info)`, evaluate one likelihood, then `print_vram_use` before any GPU run; keep\n `n_batch` low.\n9. Read the reconstruction via `inversion.reconstruction` +\n `mapper.mesh_geometry.mesh_grid`; export to CSV for anything downstream.\n10. Save the script to `scripts/`, quote every plot's absolute path and offer to open it, then\n offer the `wiki/project/` entry recording mesh, regularization and hardware choices.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_4_scaling_up_galaxies/tutorial_1_extra_galaxies.ipynb b/notebooks/chapter_4_scaling_up_galaxies/tutorial_1_extra_galaxies.ipynb index d2c4304..280ad49 100644 --- a/notebooks/chapter_4_scaling_up_galaxies/tutorial_1_extra_galaxies.ipynb +++ b/notebooks/chapter_4_scaling_up_galaxies/tutorial_1_extra_galaxies.ipynb @@ -57,21 +57,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", diff --git a/notebooks/chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy.ipynb b/notebooks/chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy.ipynb index b32c36a..ec6fd3f 100644 --- a/notebooks/chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy.ipynb +++ b/notebooks/chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy.ipynb @@ -55,21 +55,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", diff --git a/notebooks/chapter_4_scaling_up_galaxies/tutorial_3_cluster.ipynb b/notebooks/chapter_4_scaling_up_galaxies/tutorial_3_cluster.ipynb index f875ad1..a2073ad 100644 --- a/notebooks/chapter_4_scaling_up_galaxies/tutorial_3_cluster.ipynb +++ b/notebooks/chapter_4_scaling_up_galaxies/tutorial_3_cluster.ipynb @@ -86,21 +86,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", diff --git a/notebooks/chapter_optional/tutorial_searches.ipynb b/notebooks/chapter_optional/tutorial_searches.ipynb index 671386d..60d114a 100644 --- a/notebooks/chapter_optional/tutorial_searches.ipynb +++ b/notebooks/chapter_optional/tutorial_searches.ipynb @@ -29,21 +29,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -478,7 +478,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_searches.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 \u2014 `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 \u2014 critically \u2014 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 \u2014 so it can tell you whether an inferred effective\nradius of 1.6\" is 1.6 \u00b1 0.01 or 1.6 \u00b1 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 \u2192 `Nautilus`. A quick check \u2192 `MultiStartProdigy`.\n- *\"How many free parameters does the model have?\"* \u2014 `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?\"* \u2014 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?\"* \u2014 `MultiStartProdigy` requires a JAX-traceable analysis\n (`use_jax=True`) and is not available without it.\n\n## Branch \u2014 `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 \u2014 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* \u2014 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 \u2014 which is why supercomputing\nfacilities make even large models tractable.\n\n## Branch \u2014 `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 \u2014 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 \u2014 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 \u2014 `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` \u2014 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 \u2014\ntoward the tails for a better evidence estimate, toward the bulk for better parameters \u2014\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 \u2014 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) \u2014 example: `autofit_workspace:scripts/searches/mcmc.py`\n- **Nested sampling** (`nest`): `af.DynestyStatic`, `af.DynestyDynamic`, `af.Nautilus`, `af.NSS` (experimental) \u2014 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` \u2014 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 \u2014 `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 \u2014 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 \u2014 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)` \u2014 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)` \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u2014 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 \u2014 you re-reduced it, fixed the noise-map, changed the mask,\nre-ran the simulator with different truth \u2014 **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 \u2014 `files/`, `image/`, `model.info`,\n`model.results`, `search.summary` \u2014 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 \u2014 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 \u2014 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 \u2014\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 \u2014 mapping a parameter on a grid\n\nTo scan a parameter on a fixed grid rather than marginalising over it \u2014 a light centre, a\nfixed `sersic_index`, anything you want mapped \u2014 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 \u2014 `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` \u2014 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 \u2014 where this hands off\n\n- **Run the fit** \u2192 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** \u2192 [`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** \u2192 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** \u2192 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 \u2014 `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** \u2014 [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 \u2014 parameter spaces, likelihoods, priors \u2014 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** \u2014 [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** \u2014 [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`** \u2014 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 \u2014 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_searches.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" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/simulators/cluster.ipynb b/notebooks/simulators/cluster.ipynb index 596575b..cc54187 100644 --- a/notebooks/simulators/cluster.ipynb +++ b/notebooks/simulators/cluster.ipynb @@ -39,21 +39,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", diff --git a/notebooks/simulators/extra_galaxy.ipynb b/notebooks/simulators/extra_galaxy.ipynb index e135a81..c7a23b1 100644 --- a/notebooks/simulators/extra_galaxy.ipynb +++ b/notebooks/simulators/extra_galaxy.ipynb @@ -39,21 +39,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -470,7 +470,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/simulators/extra_galaxy.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_simulate_dataset\n\n---\nname: ag_simulate_dataset\ndescription: Simulate CCD imaging (or interferometer visibilities) of a galaxy with known truth \u2014 a grid and over-sampling, a PSF, an exposure time and background sky, one or more galaxies built from light profiles, then FITS output plus a `galaxies.json` truth record. Covers targeting a signal-to-noise ratio directly with the `lp_snr` profiles, simulating a whole sample in a loop for population or machine-learning work, adding a contaminating extra galaxy with its noise-scaling mask, and the `should_simulate` auto-simulation convention every workspace script uses. Use to rehearse the modelling loop before real data, to build training sets, to test a recovery, or when a user has no data yet. Not for loading or preparing real observations (`ag_prepare_imaging_data`), and not for fitting.\n---\n\n# Simulating a galaxy dataset with known truth\n\nA simulated dataset is the only situation in galaxy modelling where you know the answer.\nThat makes it worth far more than a convenience: it is how you establish that your model\ncan recover a parameter at all, how you find out what signal-to-noise you need before you\npropose for telescope time, how you separate \"the fit is wrong\" from \"the data cannot\nconstrain this\", and how you generate the thousands of labelled images a neural network\nneeds. It is also the fastest way to rehearse the whole loop \u2014 compose, search, inspect \u2014\nbefore real data is at stake.\n\nStatistically, what you are building is a draw from the likelihood's own generative model:\ntake a noise-free galaxy image, convolve it with the PSF, scale to counts through an\nexposure time, add a background sky, and draw Poisson noise. Because that is exactly the\nforward model the likelihood inverts, a fit to simulated data tests the *inference* in\nisolation \u2014 any bias you find is yours, not the data's. Simulated data is also **exempt from\nthe real-data inspection gate** (see\n[`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md)) for the same reason: you already\nknow where every component is.\n\nThe canonical scripts are `autogalaxy_workspace:scripts/imaging/simulator.py` (bulge, disk\nand a contaminating neighbour) and `autogalaxy_workspace:scripts/imaging/simulator_sersic.py`\n(a single Sersic). What each light profile means physically is\n[`../wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md); the\ndataset objects are [`../wiki/core/api/datasets.md`](../wiki/core/api/datasets.md).\n\n## Ask\n\n- *\"What are you simulating for \u2014 rehearsing the workflow, a recovery test, a training set,\n or a signal-to-noise feasibility study?\"* This picks the branch, and the last two change\n the API you want (`lp_snr`, and the sample loop).\n- *\"One galaxy or several, and should a contaminating neighbour be included?\"* Including one\n is worth doing deliberately: it is how you rehearse the noise-scaling step you will\n certainly need on real data.\n- *\"What instrument are you standing in for?\"* \u2014 it sets `pixel_scales`, the PSF width and a\n plausible exposure time, and makes the simulation answer a question about *your* telescope\n rather than an abstract one.\n\n## Branch \u2014 a single Sersic\n\nThe smallest useful simulation, and the one to start from. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator_sersic.py`.\n\n```python\n\"\"\"\nSimulator: Single Sersic\n========================\n\nSimulate CCD imaging of a galaxy whose light is a single elliptical Sersic profile, with\nknown truth parameters recorded alongside the data. The simulation applies the same forward\nmodel a fit inverts \u2014 evaluate the profile on an over-sampled grid, convolve with the PSF,\nscale through an exposure time, add a background sky and draw Poisson noise \u2014 so a fit to\nthe output tests the inference rather than the data.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Grid:** Build the coordinate grid and its adaptive over-sampling.\n- **PSF and Simulator:** Define the optical blurring and the noise properties.\n- **Galaxies:** Define the true galaxy whose parameters we intend to recover.\n- **Output:** Write the dataset to FITS, plus a `galaxies.json` record of the truth.\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\" / \"simple_sersic\"\n\n\"\"\"\n__Grid__\n\nThe `Grid2D` is the set of (y,x) arcsecond coordinates the galaxy's light is evaluated on,\nand `pixel_scales` ties it to a detector \u2014 set it to the instrument you are standing in for.\nOver-sampling then evaluates the profile on a finer sub-grid where its intensity gradient is\nsteep: a Sersic varies enormously across the central pixel, so a single evaluation at the\npixel centre under-counts the flux and produces a subtly wrong image. Simulations use higher\nsub-sampling than fits (32x32 in the centre rather than 8x8) because the cost is paid once\nrather than at every likelihood call\n(`PyAutoArray:autoarray/operators/over_sampling/over_sample_util.py`).\n\"\"\"\ngrid = ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.1)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n\"\"\"\n__PSF and Simulator__\n\nEvery real CCD image is blurred by the telescope optics, so a simulation without a PSF is not\nimaging data. A Gaussian kernel is a reasonable stand-in when you do not have a real PSF\n(FWHM = 2.35 * sigma). The `SimulatorImaging` object then supplies the rest of what makes\ndata noisy rather than ideal: `exposure_time` converts electrons per second to counts and so\nsets the Poisson noise level, and `background_sky_level` adds the sky's contribution to the\nnoise budget (`PyAutoArray:autoarray/dataset/imaging/simulator.py`). Raising the exposure\ntime raises the signal-to-noise; the ratio of the two controls how much of the noise is\ncounting statistics versus sky.\n\"\"\"\npsf = ag.Convolver.from_gaussian(\n shape_native=(11, 11), sigma=0.1, pixel_scales=grid.pixel_scales\n)\n\nsimulator = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\n\"\"\"\n__Galaxies__\n\nThe truth. `sersic_index` sets the profile's concentration \u2014 n ~ 4 is a de Vaucouleurs-like\nspheroid, n ~ 1 an exponential disk \u2014 and `effective_radius` is the radius containing half\nthe profile's light. For a *simulation* the axis-ratio and position-angle parameterisation is\nthe intuitive one, so `ag.convert.ell_comps_from` translates it into the `ell_comps` the\nprofile actually takes; a fit uses `ell_comps` directly, because a position angle's periodic\nboundary is pathological for a non-linear search\n(`PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py`).\n\"\"\"\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.8,\n sersic_index=4.0,\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy])\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\nprint(f\"peak signal-to-noise: {float(dataset.signal_to_noise_map.max()):.1f}\")\n\n\"\"\"\n__Output__\n\nThe FITS files are written in exactly the layout `ag.Imaging.from_fits` expects, so the\nsimulated dataset is indistinguishable from real data to everything downstream. The\n`galaxies.json` record is the part people skip and regret: it stores the true light profiles\nso that months later you can still state what the fit was supposed to recover. Load it back\nwith `ag.from_json`.\n\"\"\"\naplt.fits_imaging(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n overwrite=True,\n)\n\nag.output_to_json(obj=galaxies, file_path=DATASET_PATH / \"galaxies.json\")\n\naplt.subplot_imaging_dataset(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\naplt.subplot_galaxies(\n galaxies=galaxies, grid=grid, output_path=DATASET_PATH, output_format=\"png\"\n)\n\nprint(f\"Saved to: {DATASET_PATH.resolve()}\")\n```\n\nQuote that path back and offer to open it once. The `subplot_galaxies` figure is the useful\none for a simulation: it shows the noise-free truth beside the profile's components, which\nis what you compare a fit against.\n\n## Branch \u2014 bulge, disk, and a contaminating neighbour\n\nThe realistic default. Two components let you pose the question galaxy morphology usually\ncares about \u2014 the bulge-to-total light ratio \u2014 and a faint offset neighbour lets you\nrehearse the noise-scaling step. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator.py`.\n\n```python\nextra_galaxy_centre = (2.2, 1.6)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0), extra_galaxy_centre],\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n disk=ag.lp.Exponential(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.7, angle=30.0),\n intensity=0.5,\n effective_radius=1.6,\n ),\n)\n\nextra_galaxy = ag.Galaxy(\n redshift=0.5,\n light=ag.lp.ExponentialSph(\n centre=extra_galaxy_centre, intensity=1.0, effective_radius=0.3\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy, extra_galaxy])\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\nThree details carry weight. The bulge is compact with a high `sersic_index` and the disk is\nextended with n fixed at 1 by construction \u2014 that contrast is what makes the decomposition\nidentifiable at all. The neighbour's centre appears in `centre_list` as well as in its own\nprofile, so it is over-sampled properly rather than being the one badly-evaluated object in\nthe frame. And the attribute names (`bulge`, `disk`, `light`) are arbitrary labels you choose\n\u2014 name them for what they measure.\n\nWrite the neighbour's noise-scaling mask in the same script, so the modelling examples can\nload it without a separate preparation step:\n\n```python\nmask_extra_galaxies = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n centre=extra_galaxy_centre,\n radius=3.0 * 0.3, # ~3x the neighbour's effective radius\n invert=True, # `True` inside the circle: the region whose noise is scaled.\n)\n\naplt.fits_array(\n array=mask_extra_galaxies,\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n overwrite=True,\n)\n```\n\nDeriving the radius from the neighbour's own `effective_radius` keeps the two in sync if you\nlater change it. The strategies this mask feeds into are\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch \u2014 target a signal-to-noise ratio directly\n\nOften the question is not \"what intensity?\" but \"what if this galaxy were detected at S/N =\n20?\". Choosing an `intensity` that lands there is guesswork; the `lp_snr` profiles remove it\nby solving for the intensity that achieves a requested ratio, using the simulator's\n`exposure_time` and `background_sky_level` to do so. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/simulator_manual_signal_to_noise.py`.\n\n```python\ngalaxy_0 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=20.0,\n centre=(0.0, -1.0),\n ell_comps=(0.25, 0.1),\n effective_radius=0.8,\n sersic_index=2.5,\n ),\n)\n\ngalaxy_1 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=10.0,\n centre=(0.0, 1.0),\n ell_comps=(0.0, 0.1),\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n)\n\ndataset = simulator.via_galaxies_from(\n galaxies=ag.Galaxies(galaxies=[galaxy_0, galaxy_1]), grid=grid\n)\n```\n\nNote the profiles take **no** `intensity` \u2014 that is the parameter being solved for. The\ntrade-off is that `exposure_time` and `background_sky_level` no longer set the S/N, only the\n*balance* between counting noise and sky noise. So they still matter for realism: doubling\nthe exposure time shifts the noise budget toward Poisson statistics even though the S/N is\npinned. Choose them to match your instrument if the noise character matters to the study.\n\nThis is also the profile family to reach for in a feasibility question \u2014 simulate the same\ngalaxy at S/N 10, 20 and 50, fit each, and see where the parameter you care about stops\nbeing constrained. That is a far more honest answer than a single simulation at whatever\nintensity happened to be typed.\n\n## Branch \u2014 a sample, for population or machine-learning work\n\nTo generate many galaxies, draw each one's parameters from a distribution and loop. Adapted\nfrom `autogalaxy_workspace:scripts/imaging/simulator_sample.py`, which draws directly from a\nNumPy generator \u2014 deliberately, because these are *truths* for synthetic data, not a model\nbeing fitted, so there is no reason to involve the model-composition API.\n\n```python\nimport numpy as np\n\nrng = np.random.default_rng()\n\n\ndef _clipped_ell_comp() -> float:\n return float(np.clip(rng.normal(0.0, 0.2), -1.0, 1.0))\n\n\ndef _random_galaxy() -> ag.Galaxy:\n bulge = ag.lp_snr.Sersic(\n centre=(0.0, 0.0),\n ell_comps=(_clipped_ell_comp(), _clipped_ell_comp()),\n effective_radius=float(rng.uniform(1.0, 5.0)),\n sersic_index=float(np.clip(rng.normal(4.0, 1.0), 0.8, 5.0)),\n signal_to_noise_ratio=float(rng.uniform(20.0, 60.0)),\n )\n return ag.Galaxy(redshift=0.5, bulge=bulge)\n\n\ntotal_datasets = 3\n\nfor sample_index in range(total_datasets):\n\n sample_path = DATASET_PATH / f\"dataset_{sample_index}\"\n\n galaxies = ag.Galaxies(galaxies=[_random_galaxy()])\n dataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\n aplt.fits_imaging(\n dataset=dataset,\n data_path=sample_path / \"data.fits\",\n psf_path=sample_path / \"psf.fits\",\n noise_map_path=sample_path / \"noise_map.fits\",\n overwrite=True,\n )\n ag.output_to_json(obj=galaxies, file_path=sample_path / \"galaxies.json\")\n```\n\nThe `lp_snr` bulge is what makes the loop usable: with a plain `intensity` drawn from a\ndistribution, a fraction of your sample would be invisible and another fraction saturated.\nPinning S/N per galaxy guarantees every image is detectable. Write a `galaxies.json` per\ndataset \u2014 with a sample, the truth record stops being a nicety and becomes the labels.\n\nFor a one-line random galaxy without writing your own distributions,\n`ag.model_util.random_galaxy_for_simulation_from()` returns one drawn from the library's own\nchoices, and `ag.model_util.SIMULATOR_RANDOM_GALAXY_SUMMARY` prints what those choices are \u2014\nread that summary before using it in anything you will publish, so the prior you inherited\nis one you actually endorse.\n\n## Branch \u2014 interferometer visibilities\n\nFor sub-mm and radio data (ALMA, JVLA, LOFAR) the observable is visibilities in the uv-plane,\nnot an image, and fitting them there avoids the correlated noise a dirty image carries.\nAdapted from `autogalaxy_workspace:scripts/interferometer/simulator.py`.\n\n```python\nuv_wavelengths = ag.ndarray_via_fits_from(\n file_path=Path(\"dataset\") / \"interferometer\" / \"uv_wavelengths\" / \"sma.fits\", hdu=0\n)\n\nsimulator = ag.SimulatorInterferometer(\n uv_wavelengths=uv_wavelengths,\n exposure_time=300.0,\n noise_sigma=1000.0,\n transformer_class=ag.TransformerNUFFT,\n)\n\nreal_space_grid = ag.Grid2D.uniform(shape_native=(800, 800), pixel_scales=0.05)\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=real_space_grid)\n\naplt.subplot_interferometer_dirty_images(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\n\naplt.fits_interferometer(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n uv_wavelengths_path=DATASET_PATH / \"uv_wavelengths.fits\",\n overwrite=True,\n)\n```\n\nFour differences from imaging are worth knowing. The baselines come from a real array's\n`uv_wavelengths` \u2014 the workspace ships SMA (low resolution, very fast) and ALMA files;\nswapping the file swaps the instrument. There is **no PSF and no over-sampling**: the image\nis evaluated in real space and Fourier-transformed, and interferometers do not observe in a\nway that makes over-sampling necessary. `noise_sigma` replaces the exposure-time-driven\nPoisson model. And the thing you *look at* is the dirty image, which is a diagnostic \u2014 the\nfit itself happens in the uv-plane. The physics is\n[`../wiki/core/concepts/interferometer_theory.md`](../wiki/core/concepts/interferometer_theory.md).\nFull interferometer modelling is a separate skill,\n[`ag_build_interferometer_model`](./ag_build_interferometer_model.md).\n\n## The auto-simulation convention\n\nEvery workspace script that fits a dataset first checks whether it exists and runs the\nmatching simulator if it does not, so an example can be run from a fresh clone with no\nmanual step:\n\n```python\nif ag.util.dataset.should_simulate(str(dataset_path)):\n import subprocess\n import sys\n\n subprocess.run([sys.executable, \"scripts/imaging/simulator.py\"], check=True)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py`. Adopt the same pattern in\nscripts you write, and know the sharp edge: `should_simulate` tests **existence**, not\nwhether the dataset on disk matches the simulator that would produce it. Change the\nsimulator's parameters and re-run the fit and you will silently fit the *old* data. The same\napplies to `PYAUTO_SMALL_DATASETS=1`, which caps grids and masks to a small size: a\nfull-resolution dataset already on disk will be reused and mismatch the capped grids. Delete\nthe dataset directory when you change either\n([`../wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## JAX, for many simulations\n\nFor parameter sweeps, mock-data studies or batch figure generation, build the simulator with\n`use_jax=True` \u2014 the simulation then runs on JAX arrays (and the GPU, when one is\nconfigured):\n\n```python\nsimulator_jax = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n use_jax=True,\n)\n\ndataset_jax = simulator_jax.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\n`dataset_jax.data.array` is a `jax.Array`, and the plot and FITS helpers call\n`numpy.asarray()` internally, so saving and plotting need no manual conversion.\n\nWrapping the whole simulation call in a jitted function \u2014 worth it across *many* calls \u2014\nadditionally requires registering the galaxy classes as JAX pytrees before the first jitted\ncall, and the helper that does that registration is **not in the released stack yet** (it\nlives on the libraries' development branches only). Until it ships in a release, use the\neager `use_jax=True` call above; the `__JAX Variant__` section of\n`autogalaxy_workspace:scripts/imaging/simulator.py` carries the jitted recipe for a\nsource install. **For interferometer simulations the jitted path does not work either way** \u2014\nuse the eager call; `autogalaxy_workspace:scripts/interferometer/simulator.py` documents why.\n\n## Combine \u2014 where this hands off\n\n- **Fit the dataset you just made** \u2192 [`ag_build_imaging_model`](./ag_build_imaging_model.md)\n to compose the model, then [`ag_configure_search`](./ag_configure_search.md) and the\n run-search skill (`ag_run_search`). Compose a model that *matches* the truth first: if it\n cannot recover parameters it was handed exactly, the problem is the inference, and you have\n learned that cheaply.\n- **Compare a fit against the truth** \u2192 load `galaxies.json` with `ag.from_json` and put the\n true and inferred values side by side; the results-loading and fit-plotting skills\n (`ag_load_results`, `ag_plot_fit`) do the rest.\n- **You actually have real data** \u2192 [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md),\n which also owns the inspection gate this branch is exempt from.\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry when the simulation is\npart of a study \u2014 the truth parameters and the S/N you chose *are* the experimental design,\nand a recovery test is meaningless later without them.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [HowToGalaxy: Grids and galaxies](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb):\n how a light profile becomes an image on a grid, and what each Sersic parameter changes \u2014\n the foundation under every simulation.\n- **General reference** \u2014 [RTD: Start here overview](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the core API end to end, including the simulation section, in one page.\n- **Experienced PyAutoGalaxy user** \u2014 [workspace: imaging/simulator.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/simulator.py):\n the full bulge-plus-disk simulator with the contaminant mask and the executed JAX variant.\n\n## Agent procedural checklist\n\n1. Ask what the simulation is *for*; it decides the branch and whether `lp_snr` is wanted.\n2. Set `pixel_scales`, PSF width and exposure time from a real instrument, not defaults.\n3. Over-sample with every bright centre in `centre_list` \u2014 including any neighbour.\n4. Write FITS **and** `galaxies.json`; write the neighbour's `mask_extra_galaxies.fits` in\n the same script if one exists.\n5. Plot the dataset and the noise-free galaxies subplot; print and **quote** the absolute\n path, offering to open it once.\n6. Delete the dataset directory before re-running with changed parameters or with\n `PYAUTO_SMALL_DATASETS=1` \u2014 `should_simulate` only checks existence.\n7. Hand off to `ag_build_imaging_model`, and offer the `wiki/project/` entry when the\n simulation is part of a study.\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/simulators/extra_galaxy.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_simulate_dataset\n\n---\nname: ag_simulate_dataset\ndescription: Simulate CCD imaging (or interferometer visibilities) of a galaxy with known truth — a grid and over-sampling, a PSF, an exposure time and background sky, one or more galaxies built from light profiles, then FITS output plus a `galaxies.json` truth record. Covers targeting a signal-to-noise ratio directly with the `lp_snr` profiles, simulating a whole sample in a loop for population or machine-learning work, adding a contaminating extra galaxy with its noise-scaling mask, and the `should_simulate` auto-simulation convention every workspace script uses. Use to rehearse the modelling loop before real data, to build training sets, to test a recovery, or when a user has no data yet. Not for loading or preparing real observations (`ag_prepare_imaging_data`), and not for fitting.\n---\n\n# Simulating a galaxy dataset with known truth\n\nA simulated dataset is the only situation in galaxy modelling where you know the answer.\nThat makes it worth far more than a convenience: it is how you establish that your model\ncan recover a parameter at all, how you find out what signal-to-noise you need before you\npropose for telescope time, how you separate \"the fit is wrong\" from \"the data cannot\nconstrain this\", and how you generate the thousands of labelled images a neural network\nneeds. It is also the fastest way to rehearse the whole loop — compose, search, inspect —\nbefore real data is at stake.\n\nStatistically, what you are building is a draw from the likelihood's own generative model:\ntake a noise-free galaxy image, convolve it with the PSF, scale to counts through an\nexposure time, add a background sky, and draw Poisson noise. Because that is exactly the\nforward model the likelihood inverts, a fit to simulated data tests the *inference* in\nisolation — any bias you find is yours, not the data's. Simulated data is also **exempt from\nthe real-data inspection gate** (see\n[`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md)) for the same reason: you already\nknow where every component is.\n\nThe canonical scripts are `autogalaxy_workspace:scripts/imaging/simulator.py` (bulge, disk\nand a contaminating neighbour) and `autogalaxy_workspace:scripts/imaging/simulator_sersic.py`\n(a single Sersic). What each light profile means physically is\n[`../wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md); the\ndataset objects are [`../wiki/core/api/datasets.md`](../wiki/core/api/datasets.md).\n\n## Ask\n\n- *\"What are you simulating for — rehearsing the workflow, a recovery test, a training set,\n or a signal-to-noise feasibility study?\"* This picks the branch, and the last two change\n the API you want (`lp_snr`, and the sample loop).\n- *\"One galaxy or several, and should a contaminating neighbour be included?\"* Including one\n is worth doing deliberately: it is how you rehearse the noise-scaling step you will\n certainly need on real data.\n- *\"What instrument are you standing in for?\"* — it sets `pixel_scales`, the PSF width and a\n plausible exposure time, and makes the simulation answer a question about *your* telescope\n rather than an abstract one.\n\n## Branch — a single Sersic\n\nThe smallest useful simulation, and the one to start from. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator_sersic.py`.\n\n```python\n\"\"\"\nSimulator: Single Sersic\n========================\n\nSimulate CCD imaging of a galaxy whose light is a single elliptical Sersic profile, with\nknown truth parameters recorded alongside the data. The simulation applies the same forward\nmodel a fit inverts — evaluate the profile on an over-sampled grid, convolve with the PSF,\nscale through an exposure time, add a background sky and draw Poisson noise — so a fit to\nthe output tests the inference rather than the data.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Grid:** Build the coordinate grid and its adaptive over-sampling.\n- **PSF and Simulator:** Define the optical blurring and the noise properties.\n- **Galaxies:** Define the true galaxy whose parameters we intend to recover.\n- **Output:** Write the dataset to FITS, plus a `galaxies.json` record of the truth.\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\" / \"simple_sersic\"\n\n\"\"\"\n__Grid__\n\nThe `Grid2D` is the set of (y,x) arcsecond coordinates the galaxy's light is evaluated on,\nand `pixel_scales` ties it to a detector — set it to the instrument you are standing in for.\nOver-sampling then evaluates the profile on a finer sub-grid where its intensity gradient is\nsteep: a Sersic varies enormously across the central pixel, so a single evaluation at the\npixel centre under-counts the flux and produces a subtly wrong image. Simulations use higher\nsub-sampling than fits (32x32 in the centre rather than 8x8) because the cost is paid once\nrather than at every likelihood call\n(`PyAutoArray:autoarray/operators/over_sampling/over_sample_util.py`).\n\"\"\"\ngrid = ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.1)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n\"\"\"\n__PSF and Simulator__\n\nEvery real CCD image is blurred by the telescope optics, so a simulation without a PSF is not\nimaging data. A Gaussian kernel is a reasonable stand-in when you do not have a real PSF\n(FWHM = 2.35 * sigma). The `SimulatorImaging` object then supplies the rest of what makes\ndata noisy rather than ideal: `exposure_time` converts electrons per second to counts and so\nsets the Poisson noise level, and `background_sky_level` adds the sky's contribution to the\nnoise budget (`PyAutoArray:autoarray/dataset/imaging/simulator.py`). Raising the exposure\ntime raises the signal-to-noise; the ratio of the two controls how much of the noise is\ncounting statistics versus sky.\n\"\"\"\npsf = ag.Convolver.from_gaussian(\n shape_native=(11, 11), sigma=0.1, pixel_scales=grid.pixel_scales\n)\n\nsimulator = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\n\"\"\"\n__Galaxies__\n\nThe truth. `sersic_index` sets the profile's concentration — n ~ 4 is a de Vaucouleurs-like\nspheroid, n ~ 1 an exponential disk — and `effective_radius` is the radius containing half\nthe profile's light. For a *simulation* the axis-ratio and position-angle parameterisation is\nthe intuitive one, so `ag.convert.ell_comps_from` translates it into the `ell_comps` the\nprofile actually takes; a fit uses `ell_comps` directly, because a position angle's periodic\nboundary is pathological for a non-linear search\n(`PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py`).\n\"\"\"\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.8,\n sersic_index=4.0,\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy])\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\nprint(f\"peak signal-to-noise: {float(dataset.signal_to_noise_map.max()):.1f}\")\n\n\"\"\"\n__Output__\n\nThe FITS files are written in exactly the layout `ag.Imaging.from_fits` expects, so the\nsimulated dataset is indistinguishable from real data to everything downstream. The\n`galaxies.json` record is the part people skip and regret: it stores the true light profiles\nso that months later you can still state what the fit was supposed to recover. Load it back\nwith `ag.from_json`.\n\"\"\"\naplt.fits_imaging(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n overwrite=True,\n)\n\nag.output_to_json(obj=galaxies, file_path=DATASET_PATH / \"galaxies.json\")\n\naplt.subplot_imaging_dataset(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\naplt.subplot_galaxies(\n galaxies=galaxies, grid=grid, output_path=DATASET_PATH, output_format=\"png\"\n)\n\nprint(f\"Saved to: {DATASET_PATH.resolve()}\")\n```\n\nQuote that path back and offer to open it once. The `subplot_galaxies` figure is the useful\none for a simulation: it shows the noise-free truth beside the profile's components, which\nis what you compare a fit against.\n\n## Branch — bulge, disk, and a contaminating neighbour\n\nThe realistic default. Two components let you pose the question galaxy morphology usually\ncares about — the bulge-to-total light ratio — and a faint offset neighbour lets you\nrehearse the noise-scaling step. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator.py`.\n\n```python\nextra_galaxy_centre = (2.2, 1.6)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0), extra_galaxy_centre],\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n disk=ag.lp.Exponential(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.7, angle=30.0),\n intensity=0.5,\n effective_radius=1.6,\n ),\n)\n\nextra_galaxy = ag.Galaxy(\n redshift=0.5,\n light=ag.lp.ExponentialSph(\n centre=extra_galaxy_centre, intensity=1.0, effective_radius=0.3\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy, extra_galaxy])\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\nThree details carry weight. The bulge is compact with a high `sersic_index` and the disk is\nextended with n fixed at 1 by construction — that contrast is what makes the decomposition\nidentifiable at all. The neighbour's centre appears in `centre_list` as well as in its own\nprofile, so it is over-sampled properly rather than being the one badly-evaluated object in\nthe frame. And the attribute names (`bulge`, `disk`, `light`) are arbitrary labels you choose\n— name them for what they measure.\n\nWrite the neighbour's noise-scaling mask in the same script, so the modelling examples can\nload it without a separate preparation step:\n\n```python\nmask_extra_galaxies = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n centre=extra_galaxy_centre,\n radius=3.0 * 0.3, # ~3x the neighbour's effective radius\n invert=True, # `True` inside the circle: the region whose noise is scaled.\n)\n\naplt.fits_array(\n array=mask_extra_galaxies,\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n overwrite=True,\n)\n```\n\nDeriving the radius from the neighbour's own `effective_radius` keeps the two in sync if you\nlater change it. The strategies this mask feeds into are\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch — target a signal-to-noise ratio directly\n\nOften the question is not \"what intensity?\" but \"what if this galaxy were detected at S/N =\n20?\". Choosing an `intensity` that lands there is guesswork; the `lp_snr` profiles remove it\nby solving for the intensity that achieves a requested ratio, using the simulator's\n`exposure_time` and `background_sky_level` to do so. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/simulator_manual_signal_to_noise.py`.\n\n```python\ngalaxy_0 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=20.0,\n centre=(0.0, -1.0),\n ell_comps=(0.25, 0.1),\n effective_radius=0.8,\n sersic_index=2.5,\n ),\n)\n\ngalaxy_1 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=10.0,\n centre=(0.0, 1.0),\n ell_comps=(0.0, 0.1),\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n)\n\ndataset = simulator.via_galaxies_from(\n galaxies=ag.Galaxies(galaxies=[galaxy_0, galaxy_1]), grid=grid\n)\n```\n\nNote the profiles take **no** `intensity` — that is the parameter being solved for. The\ntrade-off is that `exposure_time` and `background_sky_level` no longer set the S/N, only the\n*balance* between counting noise and sky noise. So they still matter for realism: doubling\nthe exposure time shifts the noise budget toward Poisson statistics even though the S/N is\npinned. Choose them to match your instrument if the noise character matters to the study.\n\nThis is also the profile family to reach for in a feasibility question — simulate the same\ngalaxy at S/N 10, 20 and 50, fit each, and see where the parameter you care about stops\nbeing constrained. That is a far more honest answer than a single simulation at whatever\nintensity happened to be typed.\n\n## Branch — a sample, for population or machine-learning work\n\nTo generate many galaxies, draw each one's parameters from a distribution and loop. Adapted\nfrom `autogalaxy_workspace:scripts/imaging/simulator_sample.py`, which draws directly from a\nNumPy generator — deliberately, because these are *truths* for synthetic data, not a model\nbeing fitted, so there is no reason to involve the model-composition API.\n\n```python\nimport numpy as np\n\nrng = np.random.default_rng()\n\n\ndef _clipped_ell_comp() -> float:\n return float(np.clip(rng.normal(0.0, 0.2), -1.0, 1.0))\n\n\ndef _random_galaxy() -> ag.Galaxy:\n bulge = ag.lp_snr.Sersic(\n centre=(0.0, 0.0),\n ell_comps=(_clipped_ell_comp(), _clipped_ell_comp()),\n effective_radius=float(rng.uniform(1.0, 5.0)),\n sersic_index=float(np.clip(rng.normal(4.0, 1.0), 0.8, 5.0)),\n signal_to_noise_ratio=float(rng.uniform(20.0, 60.0)),\n )\n return ag.Galaxy(redshift=0.5, bulge=bulge)\n\n\ntotal_datasets = 3\n\nfor sample_index in range(total_datasets):\n\n sample_path = DATASET_PATH / f\"dataset_{sample_index}\"\n\n galaxies = ag.Galaxies(galaxies=[_random_galaxy()])\n dataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\n aplt.fits_imaging(\n dataset=dataset,\n data_path=sample_path / \"data.fits\",\n psf_path=sample_path / \"psf.fits\",\n noise_map_path=sample_path / \"noise_map.fits\",\n overwrite=True,\n )\n ag.output_to_json(obj=galaxies, file_path=sample_path / \"galaxies.json\")\n```\n\nThe `lp_snr` bulge is what makes the loop usable: with a plain `intensity` drawn from a\ndistribution, a fraction of your sample would be invisible and another fraction saturated.\nPinning S/N per galaxy guarantees every image is detectable. Write a `galaxies.json` per\ndataset — with a sample, the truth record stops being a nicety and becomes the labels.\n\nFor a one-line random galaxy without writing your own distributions,\n`ag.model_util.random_galaxy_for_simulation_from()` returns one drawn from the library's own\nchoices, and `ag.model_util.SIMULATOR_RANDOM_GALAXY_SUMMARY` prints what those choices are —\nread that summary before using it in anything you will publish, so the prior you inherited\nis one you actually endorse.\n\n## Branch — interferometer visibilities\n\nFor sub-mm and radio data (ALMA, JVLA, LOFAR) the observable is visibilities in the uv-plane,\nnot an image, and fitting them there avoids the correlated noise a dirty image carries.\nAdapted from `autogalaxy_workspace:scripts/interferometer/simulator.py`.\n\n```python\nuv_wavelengths = ag.ndarray_via_fits_from(\n file_path=Path(\"dataset\") / \"interferometer\" / \"uv_wavelengths\" / \"sma.fits\", hdu=0\n)\n\nsimulator = ag.SimulatorInterferometer(\n uv_wavelengths=uv_wavelengths,\n exposure_time=300.0,\n noise_sigma=1000.0,\n transformer_class=ag.TransformerNUFFT,\n)\n\nreal_space_grid = ag.Grid2D.uniform(shape_native=(800, 800), pixel_scales=0.05)\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=real_space_grid)\n\naplt.subplot_interferometer_dirty_images(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\n\naplt.fits_interferometer(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n uv_wavelengths_path=DATASET_PATH / \"uv_wavelengths.fits\",\n overwrite=True,\n)\n```\n\nFour differences from imaging are worth knowing. The baselines come from a real array's\n`uv_wavelengths` — the workspace ships SMA (low resolution, very fast) and ALMA files;\nswapping the file swaps the instrument. There is **no PSF and no over-sampling**: the image\nis evaluated in real space and Fourier-transformed, and interferometers do not observe in a\nway that makes over-sampling necessary. `noise_sigma` replaces the exposure-time-driven\nPoisson model. And the thing you *look at* is the dirty image, which is a diagnostic — the\nfit itself happens in the uv-plane. The physics is\n[`../wiki/core/concepts/interferometer_theory.md`](../wiki/core/concepts/interferometer_theory.md).\nFull interferometer modelling is a separate skill,\n[`ag_build_interferometer_model`](./ag_build_interferometer_model.md).\n\n## The auto-simulation convention\n\nEvery workspace script that fits a dataset first checks whether it exists and runs the\nmatching simulator if it does not, so an example can be run from a fresh clone with no\nmanual step:\n\n```python\nif ag.util.dataset.should_simulate(str(dataset_path)):\n import subprocess\n import sys\n\n subprocess.run([sys.executable, \"scripts/imaging/simulator.py\"], check=True)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py`. Adopt the same pattern in\nscripts you write, and know the sharp edge: `should_simulate` tests **existence**, not\nwhether the dataset on disk matches the simulator that would produce it. Change the\nsimulator's parameters and re-run the fit and you will silently fit the *old* data. The same\napplies to `PYAUTO_SMALL_DATASETS=1`, which caps grids and masks to a small size: a\nfull-resolution dataset already on disk will be reused and mismatch the capped grids. Delete\nthe dataset directory when you change either\n([`../wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## JAX, for many simulations\n\nFor parameter sweeps, mock-data studies or batch figure generation, build the simulator with\n`use_jax=True` — the simulation then runs on JAX arrays (and the GPU, when one is\nconfigured):\n\n```python\nsimulator_jax = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n use_jax=True,\n)\n\ndataset_jax = simulator_jax.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\n`dataset_jax.data.array` is a `jax.Array`, and the plot and FITS helpers call\n`numpy.asarray()` internally, so saving and plotting need no manual conversion.\n\nWrapping the whole simulation call in a jitted function — worth it across *many* calls —\nadditionally requires registering the galaxy classes as JAX pytrees before the first jitted\ncall, and the helper that does that registration is **not in the released stack yet** (it\nlives on the libraries' development branches only). Until it ships in a release, use the\neager `use_jax=True` call above; the `__JAX Variant__` section of\n`autogalaxy_workspace:scripts/imaging/simulator.py` carries the jitted recipe for a\nsource install. **For interferometer simulations the jitted path does not work either way** —\nuse the eager call; `autogalaxy_workspace:scripts/interferometer/simulator.py` documents why.\n\n## Combine — where this hands off\n\n- **Fit the dataset you just made** → [`ag_build_imaging_model`](./ag_build_imaging_model.md)\n to compose the model, then [`ag_configure_search`](./ag_configure_search.md) and the\n run-search skill (`ag_run_search`). Compose a model that *matches* the truth first: if it\n cannot recover parameters it was handed exactly, the problem is the inference, and you have\n learned that cheaply.\n- **Compare a fit against the truth** → load `galaxies.json` with `ag.from_json` and put the\n true and inferred values side by side; the results-loading and fit-plotting skills\n (`ag_load_results`, `ag_plot_fit`) do the rest.\n- **You actually have real data** → [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md),\n which also owns the inspection gate this branch is exempt from.\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry when the simulation is\npart of a study — the truth parameters and the S/N you chose *are* the experimental design,\nand a recovery test is meaningless later without them.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Grids and galaxies](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb):\n how a light profile becomes an image on a grid, and what each Sersic parameter changes —\n the foundation under every simulation.\n- **General reference** — [RTD: Start here overview](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the core API end to end, including the simulation section, in one page.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/simulator.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/simulator.py):\n the full bulge-plus-disk simulator with the contaminant mask and the executed JAX variant.\n\n## Agent procedural checklist\n\n1. Ask what the simulation is *for*; it decides the branch and whether `lp_snr` is wanted.\n2. Set `pixel_scales`, PSF width and exposure time from a real instrument, not defaults.\n3. Over-sample with every bright centre in `centre_list` — including any neighbour.\n4. Write FITS **and** `galaxies.json`; write the neighbour's `mask_extra_galaxies.fits` in\n the same script if one exists.\n5. Plot the dataset and the noise-free galaxies subplot; print and **quote** the absolute\n path, offering to open it once.\n6. Delete the dataset directory before re-running with changed parameters or with\n `PYAUTO_SMALL_DATASETS=1` — `should_simulate` only checks existence.\n7. Hand off to `ag_build_imaging_model`, and offer the `wiki/project/` entry when the\n simulation is part of a study.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/simulators/interferometer.ipynb b/notebooks/simulators/interferometer.ipynb index 9944255..1f5d283 100644 --- a/notebooks/simulators/interferometer.ipynb +++ b/notebooks/simulators/interferometer.ipynb @@ -41,21 +41,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -366,7 +366,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/simulators/interferometer.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_simulate_dataset\n\n---\nname: ag_simulate_dataset\ndescription: Simulate CCD imaging (or interferometer visibilities) of a galaxy with known truth \u2014 a grid and over-sampling, a PSF, an exposure time and background sky, one or more galaxies built from light profiles, then FITS output plus a `galaxies.json` truth record. Covers targeting a signal-to-noise ratio directly with the `lp_snr` profiles, simulating a whole sample in a loop for population or machine-learning work, adding a contaminating extra galaxy with its noise-scaling mask, and the `should_simulate` auto-simulation convention every workspace script uses. Use to rehearse the modelling loop before real data, to build training sets, to test a recovery, or when a user has no data yet. Not for loading or preparing real observations (`ag_prepare_imaging_data`), and not for fitting.\n---\n\n# Simulating a galaxy dataset with known truth\n\nA simulated dataset is the only situation in galaxy modelling where you know the answer.\nThat makes it worth far more than a convenience: it is how you establish that your model\ncan recover a parameter at all, how you find out what signal-to-noise you need before you\npropose for telescope time, how you separate \"the fit is wrong\" from \"the data cannot\nconstrain this\", and how you generate the thousands of labelled images a neural network\nneeds. It is also the fastest way to rehearse the whole loop \u2014 compose, search, inspect \u2014\nbefore real data is at stake.\n\nStatistically, what you are building is a draw from the likelihood's own generative model:\ntake a noise-free galaxy image, convolve it with the PSF, scale to counts through an\nexposure time, add a background sky, and draw Poisson noise. Because that is exactly the\nforward model the likelihood inverts, a fit to simulated data tests the *inference* in\nisolation \u2014 any bias you find is yours, not the data's. Simulated data is also **exempt from\nthe real-data inspection gate** (see\n[`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md)) for the same reason: you already\nknow where every component is.\n\nThe canonical scripts are `autogalaxy_workspace:scripts/imaging/simulator.py` (bulge, disk\nand a contaminating neighbour) and `autogalaxy_workspace:scripts/imaging/simulator_sersic.py`\n(a single Sersic). What each light profile means physically is\n[`../wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md); the\ndataset objects are [`../wiki/core/api/datasets.md`](../wiki/core/api/datasets.md).\n\n## Ask\n\n- *\"What are you simulating for \u2014 rehearsing the workflow, a recovery test, a training set,\n or a signal-to-noise feasibility study?\"* This picks the branch, and the last two change\n the API you want (`lp_snr`, and the sample loop).\n- *\"One galaxy or several, and should a contaminating neighbour be included?\"* Including one\n is worth doing deliberately: it is how you rehearse the noise-scaling step you will\n certainly need on real data.\n- *\"What instrument are you standing in for?\"* \u2014 it sets `pixel_scales`, the PSF width and a\n plausible exposure time, and makes the simulation answer a question about *your* telescope\n rather than an abstract one.\n\n## Branch \u2014 a single Sersic\n\nThe smallest useful simulation, and the one to start from. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator_sersic.py`.\n\n```python\n\"\"\"\nSimulator: Single Sersic\n========================\n\nSimulate CCD imaging of a galaxy whose light is a single elliptical Sersic profile, with\nknown truth parameters recorded alongside the data. The simulation applies the same forward\nmodel a fit inverts \u2014 evaluate the profile on an over-sampled grid, convolve with the PSF,\nscale through an exposure time, add a background sky and draw Poisson noise \u2014 so a fit to\nthe output tests the inference rather than the data.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Grid:** Build the coordinate grid and its adaptive over-sampling.\n- **PSF and Simulator:** Define the optical blurring and the noise properties.\n- **Galaxies:** Define the true galaxy whose parameters we intend to recover.\n- **Output:** Write the dataset to FITS, plus a `galaxies.json` record of the truth.\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\" / \"simple_sersic\"\n\n\"\"\"\n__Grid__\n\nThe `Grid2D` is the set of (y,x) arcsecond coordinates the galaxy's light is evaluated on,\nand `pixel_scales` ties it to a detector \u2014 set it to the instrument you are standing in for.\nOver-sampling then evaluates the profile on a finer sub-grid where its intensity gradient is\nsteep: a Sersic varies enormously across the central pixel, so a single evaluation at the\npixel centre under-counts the flux and produces a subtly wrong image. Simulations use higher\nsub-sampling than fits (32x32 in the centre rather than 8x8) because the cost is paid once\nrather than at every likelihood call\n(`PyAutoArray:autoarray/operators/over_sampling/over_sample_util.py`).\n\"\"\"\ngrid = ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.1)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n\"\"\"\n__PSF and Simulator__\n\nEvery real CCD image is blurred by the telescope optics, so a simulation without a PSF is not\nimaging data. A Gaussian kernel is a reasonable stand-in when you do not have a real PSF\n(FWHM = 2.35 * sigma). The `SimulatorImaging` object then supplies the rest of what makes\ndata noisy rather than ideal: `exposure_time` converts electrons per second to counts and so\nsets the Poisson noise level, and `background_sky_level` adds the sky's contribution to the\nnoise budget (`PyAutoArray:autoarray/dataset/imaging/simulator.py`). Raising the exposure\ntime raises the signal-to-noise; the ratio of the two controls how much of the noise is\ncounting statistics versus sky.\n\"\"\"\npsf = ag.Convolver.from_gaussian(\n shape_native=(11, 11), sigma=0.1, pixel_scales=grid.pixel_scales\n)\n\nsimulator = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\n\"\"\"\n__Galaxies__\n\nThe truth. `sersic_index` sets the profile's concentration \u2014 n ~ 4 is a de Vaucouleurs-like\nspheroid, n ~ 1 an exponential disk \u2014 and `effective_radius` is the radius containing half\nthe profile's light. For a *simulation* the axis-ratio and position-angle parameterisation is\nthe intuitive one, so `ag.convert.ell_comps_from` translates it into the `ell_comps` the\nprofile actually takes; a fit uses `ell_comps` directly, because a position angle's periodic\nboundary is pathological for a non-linear search\n(`PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py`).\n\"\"\"\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.8,\n sersic_index=4.0,\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy])\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\nprint(f\"peak signal-to-noise: {float(dataset.signal_to_noise_map.max()):.1f}\")\n\n\"\"\"\n__Output__\n\nThe FITS files are written in exactly the layout `ag.Imaging.from_fits` expects, so the\nsimulated dataset is indistinguishable from real data to everything downstream. The\n`galaxies.json` record is the part people skip and regret: it stores the true light profiles\nso that months later you can still state what the fit was supposed to recover. Load it back\nwith `ag.from_json`.\n\"\"\"\naplt.fits_imaging(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n overwrite=True,\n)\n\nag.output_to_json(obj=galaxies, file_path=DATASET_PATH / \"galaxies.json\")\n\naplt.subplot_imaging_dataset(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\naplt.subplot_galaxies(\n galaxies=galaxies, grid=grid, output_path=DATASET_PATH, output_format=\"png\"\n)\n\nprint(f\"Saved to: {DATASET_PATH.resolve()}\")\n```\n\nQuote that path back and offer to open it once. The `subplot_galaxies` figure is the useful\none for a simulation: it shows the noise-free truth beside the profile's components, which\nis what you compare a fit against.\n\n## Branch \u2014 bulge, disk, and a contaminating neighbour\n\nThe realistic default. Two components let you pose the question galaxy morphology usually\ncares about \u2014 the bulge-to-total light ratio \u2014 and a faint offset neighbour lets you\nrehearse the noise-scaling step. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator.py`.\n\n```python\nextra_galaxy_centre = (2.2, 1.6)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0), extra_galaxy_centre],\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n disk=ag.lp.Exponential(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.7, angle=30.0),\n intensity=0.5,\n effective_radius=1.6,\n ),\n)\n\nextra_galaxy = ag.Galaxy(\n redshift=0.5,\n light=ag.lp.ExponentialSph(\n centre=extra_galaxy_centre, intensity=1.0, effective_radius=0.3\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy, extra_galaxy])\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\nThree details carry weight. The bulge is compact with a high `sersic_index` and the disk is\nextended with n fixed at 1 by construction \u2014 that contrast is what makes the decomposition\nidentifiable at all. The neighbour's centre appears in `centre_list` as well as in its own\nprofile, so it is over-sampled properly rather than being the one badly-evaluated object in\nthe frame. And the attribute names (`bulge`, `disk`, `light`) are arbitrary labels you choose\n\u2014 name them for what they measure.\n\nWrite the neighbour's noise-scaling mask in the same script, so the modelling examples can\nload it without a separate preparation step:\n\n```python\nmask_extra_galaxies = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n centre=extra_galaxy_centre,\n radius=3.0 * 0.3, # ~3x the neighbour's effective radius\n invert=True, # `True` inside the circle: the region whose noise is scaled.\n)\n\naplt.fits_array(\n array=mask_extra_galaxies,\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n overwrite=True,\n)\n```\n\nDeriving the radius from the neighbour's own `effective_radius` keeps the two in sync if you\nlater change it. The strategies this mask feeds into are\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch \u2014 target a signal-to-noise ratio directly\n\nOften the question is not \"what intensity?\" but \"what if this galaxy were detected at S/N =\n20?\". Choosing an `intensity` that lands there is guesswork; the `lp_snr` profiles remove it\nby solving for the intensity that achieves a requested ratio, using the simulator's\n`exposure_time` and `background_sky_level` to do so. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/simulator_manual_signal_to_noise.py`.\n\n```python\ngalaxy_0 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=20.0,\n centre=(0.0, -1.0),\n ell_comps=(0.25, 0.1),\n effective_radius=0.8,\n sersic_index=2.5,\n ),\n)\n\ngalaxy_1 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=10.0,\n centre=(0.0, 1.0),\n ell_comps=(0.0, 0.1),\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n)\n\ndataset = simulator.via_galaxies_from(\n galaxies=ag.Galaxies(galaxies=[galaxy_0, galaxy_1]), grid=grid\n)\n```\n\nNote the profiles take **no** `intensity` \u2014 that is the parameter being solved for. The\ntrade-off is that `exposure_time` and `background_sky_level` no longer set the S/N, only the\n*balance* between counting noise and sky noise. So they still matter for realism: doubling\nthe exposure time shifts the noise budget toward Poisson statistics even though the S/N is\npinned. Choose them to match your instrument if the noise character matters to the study.\n\nThis is also the profile family to reach for in a feasibility question \u2014 simulate the same\ngalaxy at S/N 10, 20 and 50, fit each, and see where the parameter you care about stops\nbeing constrained. That is a far more honest answer than a single simulation at whatever\nintensity happened to be typed.\n\n## Branch \u2014 a sample, for population or machine-learning work\n\nTo generate many galaxies, draw each one's parameters from a distribution and loop. Adapted\nfrom `autogalaxy_workspace:scripts/imaging/simulator_sample.py`, which draws directly from a\nNumPy generator \u2014 deliberately, because these are *truths* for synthetic data, not a model\nbeing fitted, so there is no reason to involve the model-composition API.\n\n```python\nimport numpy as np\n\nrng = np.random.default_rng()\n\n\ndef _clipped_ell_comp() -> float:\n return float(np.clip(rng.normal(0.0, 0.2), -1.0, 1.0))\n\n\ndef _random_galaxy() -> ag.Galaxy:\n bulge = ag.lp_snr.Sersic(\n centre=(0.0, 0.0),\n ell_comps=(_clipped_ell_comp(), _clipped_ell_comp()),\n effective_radius=float(rng.uniform(1.0, 5.0)),\n sersic_index=float(np.clip(rng.normal(4.0, 1.0), 0.8, 5.0)),\n signal_to_noise_ratio=float(rng.uniform(20.0, 60.0)),\n )\n return ag.Galaxy(redshift=0.5, bulge=bulge)\n\n\ntotal_datasets = 3\n\nfor sample_index in range(total_datasets):\n\n sample_path = DATASET_PATH / f\"dataset_{sample_index}\"\n\n galaxies = ag.Galaxies(galaxies=[_random_galaxy()])\n dataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\n aplt.fits_imaging(\n dataset=dataset,\n data_path=sample_path / \"data.fits\",\n psf_path=sample_path / \"psf.fits\",\n noise_map_path=sample_path / \"noise_map.fits\",\n overwrite=True,\n )\n ag.output_to_json(obj=galaxies, file_path=sample_path / \"galaxies.json\")\n```\n\nThe `lp_snr` bulge is what makes the loop usable: with a plain `intensity` drawn from a\ndistribution, a fraction of your sample would be invisible and another fraction saturated.\nPinning S/N per galaxy guarantees every image is detectable. Write a `galaxies.json` per\ndataset \u2014 with a sample, the truth record stops being a nicety and becomes the labels.\n\nFor a one-line random galaxy without writing your own distributions,\n`ag.model_util.random_galaxy_for_simulation_from()` returns one drawn from the library's own\nchoices, and `ag.model_util.SIMULATOR_RANDOM_GALAXY_SUMMARY` prints what those choices are \u2014\nread that summary before using it in anything you will publish, so the prior you inherited\nis one you actually endorse.\n\n## Branch \u2014 interferometer visibilities\n\nFor sub-mm and radio data (ALMA, JVLA, LOFAR) the observable is visibilities in the uv-plane,\nnot an image, and fitting them there avoids the correlated noise a dirty image carries.\nAdapted from `autogalaxy_workspace:scripts/interferometer/simulator.py`.\n\n```python\nuv_wavelengths = ag.ndarray_via_fits_from(\n file_path=Path(\"dataset\") / \"interferometer\" / \"uv_wavelengths\" / \"sma.fits\", hdu=0\n)\n\nsimulator = ag.SimulatorInterferometer(\n uv_wavelengths=uv_wavelengths,\n exposure_time=300.0,\n noise_sigma=1000.0,\n transformer_class=ag.TransformerNUFFT,\n)\n\nreal_space_grid = ag.Grid2D.uniform(shape_native=(800, 800), pixel_scales=0.05)\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=real_space_grid)\n\naplt.subplot_interferometer_dirty_images(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\n\naplt.fits_interferometer(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n uv_wavelengths_path=DATASET_PATH / \"uv_wavelengths.fits\",\n overwrite=True,\n)\n```\n\nFour differences from imaging are worth knowing. The baselines come from a real array's\n`uv_wavelengths` \u2014 the workspace ships SMA (low resolution, very fast) and ALMA files;\nswapping the file swaps the instrument. There is **no PSF and no over-sampling**: the image\nis evaluated in real space and Fourier-transformed, and interferometers do not observe in a\nway that makes over-sampling necessary. `noise_sigma` replaces the exposure-time-driven\nPoisson model. And the thing you *look at* is the dirty image, which is a diagnostic \u2014 the\nfit itself happens in the uv-plane. The physics is\n[`../wiki/core/concepts/interferometer_theory.md`](../wiki/core/concepts/interferometer_theory.md).\nFull interferometer modelling is a separate skill,\n[`ag_build_interferometer_model`](./ag_build_interferometer_model.md).\n\n## The auto-simulation convention\n\nEvery workspace script that fits a dataset first checks whether it exists and runs the\nmatching simulator if it does not, so an example can be run from a fresh clone with no\nmanual step:\n\n```python\nif ag.util.dataset.should_simulate(str(dataset_path)):\n import subprocess\n import sys\n\n subprocess.run([sys.executable, \"scripts/imaging/simulator.py\"], check=True)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py`. Adopt the same pattern in\nscripts you write, and know the sharp edge: `should_simulate` tests **existence**, not\nwhether the dataset on disk matches the simulator that would produce it. Change the\nsimulator's parameters and re-run the fit and you will silently fit the *old* data. The same\napplies to `PYAUTO_SMALL_DATASETS=1`, which caps grids and masks to a small size: a\nfull-resolution dataset already on disk will be reused and mismatch the capped grids. Delete\nthe dataset directory when you change either\n([`../wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## JAX, for many simulations\n\nFor parameter sweeps, mock-data studies or batch figure generation, build the simulator with\n`use_jax=True` \u2014 the simulation then runs on JAX arrays (and the GPU, when one is\nconfigured):\n\n```python\nsimulator_jax = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n use_jax=True,\n)\n\ndataset_jax = simulator_jax.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\n`dataset_jax.data.array` is a `jax.Array`, and the plot and FITS helpers call\n`numpy.asarray()` internally, so saving and plotting need no manual conversion.\n\nWrapping the whole simulation call in a jitted function \u2014 worth it across *many* calls \u2014\nadditionally requires registering the galaxy classes as JAX pytrees before the first jitted\ncall, and the helper that does that registration is **not in the released stack yet** (it\nlives on the libraries' development branches only). Until it ships in a release, use the\neager `use_jax=True` call above; the `__JAX Variant__` section of\n`autogalaxy_workspace:scripts/imaging/simulator.py` carries the jitted recipe for a\nsource install. **For interferometer simulations the jitted path does not work either way** \u2014\nuse the eager call; `autogalaxy_workspace:scripts/interferometer/simulator.py` documents why.\n\n## Combine \u2014 where this hands off\n\n- **Fit the dataset you just made** \u2192 [`ag_build_imaging_model`](./ag_build_imaging_model.md)\n to compose the model, then [`ag_configure_search`](./ag_configure_search.md) and the\n run-search skill (`ag_run_search`). Compose a model that *matches* the truth first: if it\n cannot recover parameters it was handed exactly, the problem is the inference, and you have\n learned that cheaply.\n- **Compare a fit against the truth** \u2192 load `galaxies.json` with `ag.from_json` and put the\n true and inferred values side by side; the results-loading and fit-plotting skills\n (`ag_load_results`, `ag_plot_fit`) do the rest.\n- **You actually have real data** \u2192 [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md),\n which also owns the inspection gate this branch is exempt from.\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry when the simulation is\npart of a study \u2014 the truth parameters and the S/N you chose *are* the experimental design,\nand a recovery test is meaningless later without them.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [HowToGalaxy: Grids and galaxies](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb):\n how a light profile becomes an image on a grid, and what each Sersic parameter changes \u2014\n the foundation under every simulation.\n- **General reference** \u2014 [RTD: Start here overview](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the core API end to end, including the simulation section, in one page.\n- **Experienced PyAutoGalaxy user** \u2014 [workspace: imaging/simulator.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/simulator.py):\n the full bulge-plus-disk simulator with the contaminant mask and the executed JAX variant.\n\n## Agent procedural checklist\n\n1. Ask what the simulation is *for*; it decides the branch and whether `lp_snr` is wanted.\n2. Set `pixel_scales`, PSF width and exposure time from a real instrument, not defaults.\n3. Over-sample with every bright centre in `centre_list` \u2014 including any neighbour.\n4. Write FITS **and** `galaxies.json`; write the neighbour's `mask_extra_galaxies.fits` in\n the same script if one exists.\n5. Plot the dataset and the noise-free galaxies subplot; print and **quote** the absolute\n path, offering to open it once.\n6. Delete the dataset directory before re-running with changed parameters or with\n `PYAUTO_SMALL_DATASETS=1` \u2014 `should_simulate` only checks existence.\n7. Hand off to `ag_build_imaging_model`, and offer the `wiki/project/` entry when the\n simulation is part of a study.\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/simulators/interferometer.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_simulate_dataset\n\n---\nname: ag_simulate_dataset\ndescription: Simulate CCD imaging (or interferometer visibilities) of a galaxy with known truth — a grid and over-sampling, a PSF, an exposure time and background sky, one or more galaxies built from light profiles, then FITS output plus a `galaxies.json` truth record. Covers targeting a signal-to-noise ratio directly with the `lp_snr` profiles, simulating a whole sample in a loop for population or machine-learning work, adding a contaminating extra galaxy with its noise-scaling mask, and the `should_simulate` auto-simulation convention every workspace script uses. Use to rehearse the modelling loop before real data, to build training sets, to test a recovery, or when a user has no data yet. Not for loading or preparing real observations (`ag_prepare_imaging_data`), and not for fitting.\n---\n\n# Simulating a galaxy dataset with known truth\n\nA simulated dataset is the only situation in galaxy modelling where you know the answer.\nThat makes it worth far more than a convenience: it is how you establish that your model\ncan recover a parameter at all, how you find out what signal-to-noise you need before you\npropose for telescope time, how you separate \"the fit is wrong\" from \"the data cannot\nconstrain this\", and how you generate the thousands of labelled images a neural network\nneeds. It is also the fastest way to rehearse the whole loop — compose, search, inspect —\nbefore real data is at stake.\n\nStatistically, what you are building is a draw from the likelihood's own generative model:\ntake a noise-free galaxy image, convolve it with the PSF, scale to counts through an\nexposure time, add a background sky, and draw Poisson noise. Because that is exactly the\nforward model the likelihood inverts, a fit to simulated data tests the *inference* in\nisolation — any bias you find is yours, not the data's. Simulated data is also **exempt from\nthe real-data inspection gate** (see\n[`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md)) for the same reason: you already\nknow where every component is.\n\nThe canonical scripts are `autogalaxy_workspace:scripts/imaging/simulator.py` (bulge, disk\nand a contaminating neighbour) and `autogalaxy_workspace:scripts/imaging/simulator_sersic.py`\n(a single Sersic). What each light profile means physically is\n[`../wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md); the\ndataset objects are [`../wiki/core/api/datasets.md`](../wiki/core/api/datasets.md).\n\n## Ask\n\n- *\"What are you simulating for — rehearsing the workflow, a recovery test, a training set,\n or a signal-to-noise feasibility study?\"* This picks the branch, and the last two change\n the API you want (`lp_snr`, and the sample loop).\n- *\"One galaxy or several, and should a contaminating neighbour be included?\"* Including one\n is worth doing deliberately: it is how you rehearse the noise-scaling step you will\n certainly need on real data.\n- *\"What instrument are you standing in for?\"* — it sets `pixel_scales`, the PSF width and a\n plausible exposure time, and makes the simulation answer a question about *your* telescope\n rather than an abstract one.\n\n## Branch — a single Sersic\n\nThe smallest useful simulation, and the one to start from. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator_sersic.py`.\n\n```python\n\"\"\"\nSimulator: Single Sersic\n========================\n\nSimulate CCD imaging of a galaxy whose light is a single elliptical Sersic profile, with\nknown truth parameters recorded alongside the data. The simulation applies the same forward\nmodel a fit inverts — evaluate the profile on an over-sampled grid, convolve with the PSF,\nscale through an exposure time, add a background sky and draw Poisson noise — so a fit to\nthe output tests the inference rather than the data.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Grid:** Build the coordinate grid and its adaptive over-sampling.\n- **PSF and Simulator:** Define the optical blurring and the noise properties.\n- **Galaxies:** Define the true galaxy whose parameters we intend to recover.\n- **Output:** Write the dataset to FITS, plus a `galaxies.json` record of the truth.\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\" / \"simple_sersic\"\n\n\"\"\"\n__Grid__\n\nThe `Grid2D` is the set of (y,x) arcsecond coordinates the galaxy's light is evaluated on,\nand `pixel_scales` ties it to a detector — set it to the instrument you are standing in for.\nOver-sampling then evaluates the profile on a finer sub-grid where its intensity gradient is\nsteep: a Sersic varies enormously across the central pixel, so a single evaluation at the\npixel centre under-counts the flux and produces a subtly wrong image. Simulations use higher\nsub-sampling than fits (32x32 in the centre rather than 8x8) because the cost is paid once\nrather than at every likelihood call\n(`PyAutoArray:autoarray/operators/over_sampling/over_sample_util.py`).\n\"\"\"\ngrid = ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.1)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n\"\"\"\n__PSF and Simulator__\n\nEvery real CCD image is blurred by the telescope optics, so a simulation without a PSF is not\nimaging data. A Gaussian kernel is a reasonable stand-in when you do not have a real PSF\n(FWHM = 2.35 * sigma). The `SimulatorImaging` object then supplies the rest of what makes\ndata noisy rather than ideal: `exposure_time` converts electrons per second to counts and so\nsets the Poisson noise level, and `background_sky_level` adds the sky's contribution to the\nnoise budget (`PyAutoArray:autoarray/dataset/imaging/simulator.py`). Raising the exposure\ntime raises the signal-to-noise; the ratio of the two controls how much of the noise is\ncounting statistics versus sky.\n\"\"\"\npsf = ag.Convolver.from_gaussian(\n shape_native=(11, 11), sigma=0.1, pixel_scales=grid.pixel_scales\n)\n\nsimulator = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\n\"\"\"\n__Galaxies__\n\nThe truth. `sersic_index` sets the profile's concentration — n ~ 4 is a de Vaucouleurs-like\nspheroid, n ~ 1 an exponential disk — and `effective_radius` is the radius containing half\nthe profile's light. For a *simulation* the axis-ratio and position-angle parameterisation is\nthe intuitive one, so `ag.convert.ell_comps_from` translates it into the `ell_comps` the\nprofile actually takes; a fit uses `ell_comps` directly, because a position angle's periodic\nboundary is pathological for a non-linear search\n(`PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py`).\n\"\"\"\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.8,\n sersic_index=4.0,\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy])\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\nprint(f\"peak signal-to-noise: {float(dataset.signal_to_noise_map.max()):.1f}\")\n\n\"\"\"\n__Output__\n\nThe FITS files are written in exactly the layout `ag.Imaging.from_fits` expects, so the\nsimulated dataset is indistinguishable from real data to everything downstream. The\n`galaxies.json` record is the part people skip and regret: it stores the true light profiles\nso that months later you can still state what the fit was supposed to recover. Load it back\nwith `ag.from_json`.\n\"\"\"\naplt.fits_imaging(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n overwrite=True,\n)\n\nag.output_to_json(obj=galaxies, file_path=DATASET_PATH / \"galaxies.json\")\n\naplt.subplot_imaging_dataset(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\naplt.subplot_galaxies(\n galaxies=galaxies, grid=grid, output_path=DATASET_PATH, output_format=\"png\"\n)\n\nprint(f\"Saved to: {DATASET_PATH.resolve()}\")\n```\n\nQuote that path back and offer to open it once. The `subplot_galaxies` figure is the useful\none for a simulation: it shows the noise-free truth beside the profile's components, which\nis what you compare a fit against.\n\n## Branch — bulge, disk, and a contaminating neighbour\n\nThe realistic default. Two components let you pose the question galaxy morphology usually\ncares about — the bulge-to-total light ratio — and a faint offset neighbour lets you\nrehearse the noise-scaling step. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator.py`.\n\n```python\nextra_galaxy_centre = (2.2, 1.6)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0), extra_galaxy_centre],\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n disk=ag.lp.Exponential(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.7, angle=30.0),\n intensity=0.5,\n effective_radius=1.6,\n ),\n)\n\nextra_galaxy = ag.Galaxy(\n redshift=0.5,\n light=ag.lp.ExponentialSph(\n centre=extra_galaxy_centre, intensity=1.0, effective_radius=0.3\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy, extra_galaxy])\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\nThree details carry weight. The bulge is compact with a high `sersic_index` and the disk is\nextended with n fixed at 1 by construction — that contrast is what makes the decomposition\nidentifiable at all. The neighbour's centre appears in `centre_list` as well as in its own\nprofile, so it is over-sampled properly rather than being the one badly-evaluated object in\nthe frame. And the attribute names (`bulge`, `disk`, `light`) are arbitrary labels you choose\n— name them for what they measure.\n\nWrite the neighbour's noise-scaling mask in the same script, so the modelling examples can\nload it without a separate preparation step:\n\n```python\nmask_extra_galaxies = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n centre=extra_galaxy_centre,\n radius=3.0 * 0.3, # ~3x the neighbour's effective radius\n invert=True, # `True` inside the circle: the region whose noise is scaled.\n)\n\naplt.fits_array(\n array=mask_extra_galaxies,\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n overwrite=True,\n)\n```\n\nDeriving the radius from the neighbour's own `effective_radius` keeps the two in sync if you\nlater change it. The strategies this mask feeds into are\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch — target a signal-to-noise ratio directly\n\nOften the question is not \"what intensity?\" but \"what if this galaxy were detected at S/N =\n20?\". Choosing an `intensity` that lands there is guesswork; the `lp_snr` profiles remove it\nby solving for the intensity that achieves a requested ratio, using the simulator's\n`exposure_time` and `background_sky_level` to do so. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/simulator_manual_signal_to_noise.py`.\n\n```python\ngalaxy_0 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=20.0,\n centre=(0.0, -1.0),\n ell_comps=(0.25, 0.1),\n effective_radius=0.8,\n sersic_index=2.5,\n ),\n)\n\ngalaxy_1 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=10.0,\n centre=(0.0, 1.0),\n ell_comps=(0.0, 0.1),\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n)\n\ndataset = simulator.via_galaxies_from(\n galaxies=ag.Galaxies(galaxies=[galaxy_0, galaxy_1]), grid=grid\n)\n```\n\nNote the profiles take **no** `intensity` — that is the parameter being solved for. The\ntrade-off is that `exposure_time` and `background_sky_level` no longer set the S/N, only the\n*balance* between counting noise and sky noise. So they still matter for realism: doubling\nthe exposure time shifts the noise budget toward Poisson statistics even though the S/N is\npinned. Choose them to match your instrument if the noise character matters to the study.\n\nThis is also the profile family to reach for in a feasibility question — simulate the same\ngalaxy at S/N 10, 20 and 50, fit each, and see where the parameter you care about stops\nbeing constrained. That is a far more honest answer than a single simulation at whatever\nintensity happened to be typed.\n\n## Branch — a sample, for population or machine-learning work\n\nTo generate many galaxies, draw each one's parameters from a distribution and loop. Adapted\nfrom `autogalaxy_workspace:scripts/imaging/simulator_sample.py`, which draws directly from a\nNumPy generator — deliberately, because these are *truths* for synthetic data, not a model\nbeing fitted, so there is no reason to involve the model-composition API.\n\n```python\nimport numpy as np\n\nrng = np.random.default_rng()\n\n\ndef _clipped_ell_comp() -> float:\n return float(np.clip(rng.normal(0.0, 0.2), -1.0, 1.0))\n\n\ndef _random_galaxy() -> ag.Galaxy:\n bulge = ag.lp_snr.Sersic(\n centre=(0.0, 0.0),\n ell_comps=(_clipped_ell_comp(), _clipped_ell_comp()),\n effective_radius=float(rng.uniform(1.0, 5.0)),\n sersic_index=float(np.clip(rng.normal(4.0, 1.0), 0.8, 5.0)),\n signal_to_noise_ratio=float(rng.uniform(20.0, 60.0)),\n )\n return ag.Galaxy(redshift=0.5, bulge=bulge)\n\n\ntotal_datasets = 3\n\nfor sample_index in range(total_datasets):\n\n sample_path = DATASET_PATH / f\"dataset_{sample_index}\"\n\n galaxies = ag.Galaxies(galaxies=[_random_galaxy()])\n dataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\n aplt.fits_imaging(\n dataset=dataset,\n data_path=sample_path / \"data.fits\",\n psf_path=sample_path / \"psf.fits\",\n noise_map_path=sample_path / \"noise_map.fits\",\n overwrite=True,\n )\n ag.output_to_json(obj=galaxies, file_path=sample_path / \"galaxies.json\")\n```\n\nThe `lp_snr` bulge is what makes the loop usable: with a plain `intensity` drawn from a\ndistribution, a fraction of your sample would be invisible and another fraction saturated.\nPinning S/N per galaxy guarantees every image is detectable. Write a `galaxies.json` per\ndataset — with a sample, the truth record stops being a nicety and becomes the labels.\n\nFor a one-line random galaxy without writing your own distributions,\n`ag.model_util.random_galaxy_for_simulation_from()` returns one drawn from the library's own\nchoices, and `ag.model_util.SIMULATOR_RANDOM_GALAXY_SUMMARY` prints what those choices are —\nread that summary before using it in anything you will publish, so the prior you inherited\nis one you actually endorse.\n\n## Branch — interferometer visibilities\n\nFor sub-mm and radio data (ALMA, JVLA, LOFAR) the observable is visibilities in the uv-plane,\nnot an image, and fitting them there avoids the correlated noise a dirty image carries.\nAdapted from `autogalaxy_workspace:scripts/interferometer/simulator.py`.\n\n```python\nuv_wavelengths = ag.ndarray_via_fits_from(\n file_path=Path(\"dataset\") / \"interferometer\" / \"uv_wavelengths\" / \"sma.fits\", hdu=0\n)\n\nsimulator = ag.SimulatorInterferometer(\n uv_wavelengths=uv_wavelengths,\n exposure_time=300.0,\n noise_sigma=1000.0,\n transformer_class=ag.TransformerNUFFT,\n)\n\nreal_space_grid = ag.Grid2D.uniform(shape_native=(800, 800), pixel_scales=0.05)\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=real_space_grid)\n\naplt.subplot_interferometer_dirty_images(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\n\naplt.fits_interferometer(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n uv_wavelengths_path=DATASET_PATH / \"uv_wavelengths.fits\",\n overwrite=True,\n)\n```\n\nFour differences from imaging are worth knowing. The baselines come from a real array's\n`uv_wavelengths` — the workspace ships SMA (low resolution, very fast) and ALMA files;\nswapping the file swaps the instrument. There is **no PSF and no over-sampling**: the image\nis evaluated in real space and Fourier-transformed, and interferometers do not observe in a\nway that makes over-sampling necessary. `noise_sigma` replaces the exposure-time-driven\nPoisson model. And the thing you *look at* is the dirty image, which is a diagnostic — the\nfit itself happens in the uv-plane. The physics is\n[`../wiki/core/concepts/interferometer_theory.md`](../wiki/core/concepts/interferometer_theory.md).\nFull interferometer modelling is a separate skill,\n[`ag_build_interferometer_model`](./ag_build_interferometer_model.md).\n\n## The auto-simulation convention\n\nEvery workspace script that fits a dataset first checks whether it exists and runs the\nmatching simulator if it does not, so an example can be run from a fresh clone with no\nmanual step:\n\n```python\nif ag.util.dataset.should_simulate(str(dataset_path)):\n import subprocess\n import sys\n\n subprocess.run([sys.executable, \"scripts/imaging/simulator.py\"], check=True)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py`. Adopt the same pattern in\nscripts you write, and know the sharp edge: `should_simulate` tests **existence**, not\nwhether the dataset on disk matches the simulator that would produce it. Change the\nsimulator's parameters and re-run the fit and you will silently fit the *old* data. The same\napplies to `PYAUTO_SMALL_DATASETS=1`, which caps grids and masks to a small size: a\nfull-resolution dataset already on disk will be reused and mismatch the capped grids. Delete\nthe dataset directory when you change either\n([`../wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## JAX, for many simulations\n\nFor parameter sweeps, mock-data studies or batch figure generation, build the simulator with\n`use_jax=True` — the simulation then runs on JAX arrays (and the GPU, when one is\nconfigured):\n\n```python\nsimulator_jax = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n use_jax=True,\n)\n\ndataset_jax = simulator_jax.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\n`dataset_jax.data.array` is a `jax.Array`, and the plot and FITS helpers call\n`numpy.asarray()` internally, so saving and plotting need no manual conversion.\n\nWrapping the whole simulation call in a jitted function — worth it across *many* calls —\nadditionally requires registering the galaxy classes as JAX pytrees before the first jitted\ncall, and the helper that does that registration is **not in the released stack yet** (it\nlives on the libraries' development branches only). Until it ships in a release, use the\neager `use_jax=True` call above; the `__JAX Variant__` section of\n`autogalaxy_workspace:scripts/imaging/simulator.py` carries the jitted recipe for a\nsource install. **For interferometer simulations the jitted path does not work either way** —\nuse the eager call; `autogalaxy_workspace:scripts/interferometer/simulator.py` documents why.\n\n## Combine — where this hands off\n\n- **Fit the dataset you just made** → [`ag_build_imaging_model`](./ag_build_imaging_model.md)\n to compose the model, then [`ag_configure_search`](./ag_configure_search.md) and the\n run-search skill (`ag_run_search`). Compose a model that *matches* the truth first: if it\n cannot recover parameters it was handed exactly, the problem is the inference, and you have\n learned that cheaply.\n- **Compare a fit against the truth** → load `galaxies.json` with `ag.from_json` and put the\n true and inferred values side by side; the results-loading and fit-plotting skills\n (`ag_load_results`, `ag_plot_fit`) do the rest.\n- **You actually have real data** → [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md),\n which also owns the inspection gate this branch is exempt from.\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry when the simulation is\npart of a study — the truth parameters and the S/N you chose *are* the experimental design,\nand a recovery test is meaningless later without them.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Grids and galaxies](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb):\n how a light profile becomes an image on a grid, and what each Sersic parameter changes —\n the foundation under every simulation.\n- **General reference** — [RTD: Start here overview](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the core API end to end, including the simulation section, in one page.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/simulator.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/simulator.py):\n the full bulge-plus-disk simulator with the contaminant mask and the executed JAX variant.\n\n## Agent procedural checklist\n\n1. Ask what the simulation is *for*; it decides the branch and whether `lp_snr` is wanted.\n2. Set `pixel_scales`, PSF width and exposure time from a real instrument, not defaults.\n3. Over-sample with every bright centre in `centre_list` — including any neighbour.\n4. Write FITS **and** `galaxies.json`; write the neighbour's `mask_extra_galaxies.fits` in\n the same script if one exists.\n5. Plot the dataset and the noise-free galaxies subplot; print and **quote** the absolute\n path, offering to open it once.\n6. Delete the dataset directory before re-running with changed parameters or with\n `PYAUTO_SMALL_DATASETS=1` — `should_simulate` only checks existence.\n7. Hand off to `ag_build_imaging_model`, and offer the `wiki/project/` entry when the\n simulation is part of a study.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/simulators/sersic.ipynb b/notebooks/simulators/sersic.ipynb index 030a87f..395f939 100644 --- a/notebooks/simulators/sersic.ipynb +++ b/notebooks/simulators/sersic.ipynb @@ -31,21 +31,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -350,7 +350,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/simulators/sersic.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_simulate_dataset\n\n---\nname: ag_simulate_dataset\ndescription: Simulate CCD imaging (or interferometer visibilities) of a galaxy with known truth \u2014 a grid and over-sampling, a PSF, an exposure time and background sky, one or more galaxies built from light profiles, then FITS output plus a `galaxies.json` truth record. Covers targeting a signal-to-noise ratio directly with the `lp_snr` profiles, simulating a whole sample in a loop for population or machine-learning work, adding a contaminating extra galaxy with its noise-scaling mask, and the `should_simulate` auto-simulation convention every workspace script uses. Use to rehearse the modelling loop before real data, to build training sets, to test a recovery, or when a user has no data yet. Not for loading or preparing real observations (`ag_prepare_imaging_data`), and not for fitting.\n---\n\n# Simulating a galaxy dataset with known truth\n\nA simulated dataset is the only situation in galaxy modelling where you know the answer.\nThat makes it worth far more than a convenience: it is how you establish that your model\ncan recover a parameter at all, how you find out what signal-to-noise you need before you\npropose for telescope time, how you separate \"the fit is wrong\" from \"the data cannot\nconstrain this\", and how you generate the thousands of labelled images a neural network\nneeds. It is also the fastest way to rehearse the whole loop \u2014 compose, search, inspect \u2014\nbefore real data is at stake.\n\nStatistically, what you are building is a draw from the likelihood's own generative model:\ntake a noise-free galaxy image, convolve it with the PSF, scale to counts through an\nexposure time, add a background sky, and draw Poisson noise. Because that is exactly the\nforward model the likelihood inverts, a fit to simulated data tests the *inference* in\nisolation \u2014 any bias you find is yours, not the data's. Simulated data is also **exempt from\nthe real-data inspection gate** (see\n[`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md)) for the same reason: you already\nknow where every component is.\n\nThe canonical scripts are `autogalaxy_workspace:scripts/imaging/simulator.py` (bulge, disk\nand a contaminating neighbour) and `autogalaxy_workspace:scripts/imaging/simulator_sersic.py`\n(a single Sersic). What each light profile means physically is\n[`../wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md); the\ndataset objects are [`../wiki/core/api/datasets.md`](../wiki/core/api/datasets.md).\n\n## Ask\n\n- *\"What are you simulating for \u2014 rehearsing the workflow, a recovery test, a training set,\n or a signal-to-noise feasibility study?\"* This picks the branch, and the last two change\n the API you want (`lp_snr`, and the sample loop).\n- *\"One galaxy or several, and should a contaminating neighbour be included?\"* Including one\n is worth doing deliberately: it is how you rehearse the noise-scaling step you will\n certainly need on real data.\n- *\"What instrument are you standing in for?\"* \u2014 it sets `pixel_scales`, the PSF width and a\n plausible exposure time, and makes the simulation answer a question about *your* telescope\n rather than an abstract one.\n\n## Branch \u2014 a single Sersic\n\nThe smallest useful simulation, and the one to start from. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator_sersic.py`.\n\n```python\n\"\"\"\nSimulator: Single Sersic\n========================\n\nSimulate CCD imaging of a galaxy whose light is a single elliptical Sersic profile, with\nknown truth parameters recorded alongside the data. The simulation applies the same forward\nmodel a fit inverts \u2014 evaluate the profile on an over-sampled grid, convolve with the PSF,\nscale through an exposure time, add a background sky and draw Poisson noise \u2014 so a fit to\nthe output tests the inference rather than the data.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Grid:** Build the coordinate grid and its adaptive over-sampling.\n- **PSF and Simulator:** Define the optical blurring and the noise properties.\n- **Galaxies:** Define the true galaxy whose parameters we intend to recover.\n- **Output:** Write the dataset to FITS, plus a `galaxies.json` record of the truth.\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\" / \"simple_sersic\"\n\n\"\"\"\n__Grid__\n\nThe `Grid2D` is the set of (y,x) arcsecond coordinates the galaxy's light is evaluated on,\nand `pixel_scales` ties it to a detector \u2014 set it to the instrument you are standing in for.\nOver-sampling then evaluates the profile on a finer sub-grid where its intensity gradient is\nsteep: a Sersic varies enormously across the central pixel, so a single evaluation at the\npixel centre under-counts the flux and produces a subtly wrong image. Simulations use higher\nsub-sampling than fits (32x32 in the centre rather than 8x8) because the cost is paid once\nrather than at every likelihood call\n(`PyAutoArray:autoarray/operators/over_sampling/over_sample_util.py`).\n\"\"\"\ngrid = ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.1)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n\"\"\"\n__PSF and Simulator__\n\nEvery real CCD image is blurred by the telescope optics, so a simulation without a PSF is not\nimaging data. A Gaussian kernel is a reasonable stand-in when you do not have a real PSF\n(FWHM = 2.35 * sigma). The `SimulatorImaging` object then supplies the rest of what makes\ndata noisy rather than ideal: `exposure_time` converts electrons per second to counts and so\nsets the Poisson noise level, and `background_sky_level` adds the sky's contribution to the\nnoise budget (`PyAutoArray:autoarray/dataset/imaging/simulator.py`). Raising the exposure\ntime raises the signal-to-noise; the ratio of the two controls how much of the noise is\ncounting statistics versus sky.\n\"\"\"\npsf = ag.Convolver.from_gaussian(\n shape_native=(11, 11), sigma=0.1, pixel_scales=grid.pixel_scales\n)\n\nsimulator = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\n\"\"\"\n__Galaxies__\n\nThe truth. `sersic_index` sets the profile's concentration \u2014 n ~ 4 is a de Vaucouleurs-like\nspheroid, n ~ 1 an exponential disk \u2014 and `effective_radius` is the radius containing half\nthe profile's light. For a *simulation* the axis-ratio and position-angle parameterisation is\nthe intuitive one, so `ag.convert.ell_comps_from` translates it into the `ell_comps` the\nprofile actually takes; a fit uses `ell_comps` directly, because a position angle's periodic\nboundary is pathological for a non-linear search\n(`PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py`).\n\"\"\"\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.8,\n sersic_index=4.0,\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy])\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\nprint(f\"peak signal-to-noise: {float(dataset.signal_to_noise_map.max()):.1f}\")\n\n\"\"\"\n__Output__\n\nThe FITS files are written in exactly the layout `ag.Imaging.from_fits` expects, so the\nsimulated dataset is indistinguishable from real data to everything downstream. The\n`galaxies.json` record is the part people skip and regret: it stores the true light profiles\nso that months later you can still state what the fit was supposed to recover. Load it back\nwith `ag.from_json`.\n\"\"\"\naplt.fits_imaging(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n overwrite=True,\n)\n\nag.output_to_json(obj=galaxies, file_path=DATASET_PATH / \"galaxies.json\")\n\naplt.subplot_imaging_dataset(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\naplt.subplot_galaxies(\n galaxies=galaxies, grid=grid, output_path=DATASET_PATH, output_format=\"png\"\n)\n\nprint(f\"Saved to: {DATASET_PATH.resolve()}\")\n```\n\nQuote that path back and offer to open it once. The `subplot_galaxies` figure is the useful\none for a simulation: it shows the noise-free truth beside the profile's components, which\nis what you compare a fit against.\n\n## Branch \u2014 bulge, disk, and a contaminating neighbour\n\nThe realistic default. Two components let you pose the question galaxy morphology usually\ncares about \u2014 the bulge-to-total light ratio \u2014 and a faint offset neighbour lets you\nrehearse the noise-scaling step. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator.py`.\n\n```python\nextra_galaxy_centre = (2.2, 1.6)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0), extra_galaxy_centre],\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n disk=ag.lp.Exponential(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.7, angle=30.0),\n intensity=0.5,\n effective_radius=1.6,\n ),\n)\n\nextra_galaxy = ag.Galaxy(\n redshift=0.5,\n light=ag.lp.ExponentialSph(\n centre=extra_galaxy_centre, intensity=1.0, effective_radius=0.3\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy, extra_galaxy])\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\nThree details carry weight. The bulge is compact with a high `sersic_index` and the disk is\nextended with n fixed at 1 by construction \u2014 that contrast is what makes the decomposition\nidentifiable at all. The neighbour's centre appears in `centre_list` as well as in its own\nprofile, so it is over-sampled properly rather than being the one badly-evaluated object in\nthe frame. And the attribute names (`bulge`, `disk`, `light`) are arbitrary labels you choose\n\u2014 name them for what they measure.\n\nWrite the neighbour's noise-scaling mask in the same script, so the modelling examples can\nload it without a separate preparation step:\n\n```python\nmask_extra_galaxies = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n centre=extra_galaxy_centre,\n radius=3.0 * 0.3, # ~3x the neighbour's effective radius\n invert=True, # `True` inside the circle: the region whose noise is scaled.\n)\n\naplt.fits_array(\n array=mask_extra_galaxies,\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n overwrite=True,\n)\n```\n\nDeriving the radius from the neighbour's own `effective_radius` keeps the two in sync if you\nlater change it. The strategies this mask feeds into are\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch \u2014 target a signal-to-noise ratio directly\n\nOften the question is not \"what intensity?\" but \"what if this galaxy were detected at S/N =\n20?\". Choosing an `intensity` that lands there is guesswork; the `lp_snr` profiles remove it\nby solving for the intensity that achieves a requested ratio, using the simulator's\n`exposure_time` and `background_sky_level` to do so. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/simulator_manual_signal_to_noise.py`.\n\n```python\ngalaxy_0 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=20.0,\n centre=(0.0, -1.0),\n ell_comps=(0.25, 0.1),\n effective_radius=0.8,\n sersic_index=2.5,\n ),\n)\n\ngalaxy_1 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=10.0,\n centre=(0.0, 1.0),\n ell_comps=(0.0, 0.1),\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n)\n\ndataset = simulator.via_galaxies_from(\n galaxies=ag.Galaxies(galaxies=[galaxy_0, galaxy_1]), grid=grid\n)\n```\n\nNote the profiles take **no** `intensity` \u2014 that is the parameter being solved for. The\ntrade-off is that `exposure_time` and `background_sky_level` no longer set the S/N, only the\n*balance* between counting noise and sky noise. So they still matter for realism: doubling\nthe exposure time shifts the noise budget toward Poisson statistics even though the S/N is\npinned. Choose them to match your instrument if the noise character matters to the study.\n\nThis is also the profile family to reach for in a feasibility question \u2014 simulate the same\ngalaxy at S/N 10, 20 and 50, fit each, and see where the parameter you care about stops\nbeing constrained. That is a far more honest answer than a single simulation at whatever\nintensity happened to be typed.\n\n## Branch \u2014 a sample, for population or machine-learning work\n\nTo generate many galaxies, draw each one's parameters from a distribution and loop. Adapted\nfrom `autogalaxy_workspace:scripts/imaging/simulator_sample.py`, which draws directly from a\nNumPy generator \u2014 deliberately, because these are *truths* for synthetic data, not a model\nbeing fitted, so there is no reason to involve the model-composition API.\n\n```python\nimport numpy as np\n\nrng = np.random.default_rng()\n\n\ndef _clipped_ell_comp() -> float:\n return float(np.clip(rng.normal(0.0, 0.2), -1.0, 1.0))\n\n\ndef _random_galaxy() -> ag.Galaxy:\n bulge = ag.lp_snr.Sersic(\n centre=(0.0, 0.0),\n ell_comps=(_clipped_ell_comp(), _clipped_ell_comp()),\n effective_radius=float(rng.uniform(1.0, 5.0)),\n sersic_index=float(np.clip(rng.normal(4.0, 1.0), 0.8, 5.0)),\n signal_to_noise_ratio=float(rng.uniform(20.0, 60.0)),\n )\n return ag.Galaxy(redshift=0.5, bulge=bulge)\n\n\ntotal_datasets = 3\n\nfor sample_index in range(total_datasets):\n\n sample_path = DATASET_PATH / f\"dataset_{sample_index}\"\n\n galaxies = ag.Galaxies(galaxies=[_random_galaxy()])\n dataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\n aplt.fits_imaging(\n dataset=dataset,\n data_path=sample_path / \"data.fits\",\n psf_path=sample_path / \"psf.fits\",\n noise_map_path=sample_path / \"noise_map.fits\",\n overwrite=True,\n )\n ag.output_to_json(obj=galaxies, file_path=sample_path / \"galaxies.json\")\n```\n\nThe `lp_snr` bulge is what makes the loop usable: with a plain `intensity` drawn from a\ndistribution, a fraction of your sample would be invisible and another fraction saturated.\nPinning S/N per galaxy guarantees every image is detectable. Write a `galaxies.json` per\ndataset \u2014 with a sample, the truth record stops being a nicety and becomes the labels.\n\nFor a one-line random galaxy without writing your own distributions,\n`ag.model_util.random_galaxy_for_simulation_from()` returns one drawn from the library's own\nchoices, and `ag.model_util.SIMULATOR_RANDOM_GALAXY_SUMMARY` prints what those choices are \u2014\nread that summary before using it in anything you will publish, so the prior you inherited\nis one you actually endorse.\n\n## Branch \u2014 interferometer visibilities\n\nFor sub-mm and radio data (ALMA, JVLA, LOFAR) the observable is visibilities in the uv-plane,\nnot an image, and fitting them there avoids the correlated noise a dirty image carries.\nAdapted from `autogalaxy_workspace:scripts/interferometer/simulator.py`.\n\n```python\nuv_wavelengths = ag.ndarray_via_fits_from(\n file_path=Path(\"dataset\") / \"interferometer\" / \"uv_wavelengths\" / \"sma.fits\", hdu=0\n)\n\nsimulator = ag.SimulatorInterferometer(\n uv_wavelengths=uv_wavelengths,\n exposure_time=300.0,\n noise_sigma=1000.0,\n transformer_class=ag.TransformerNUFFT,\n)\n\nreal_space_grid = ag.Grid2D.uniform(shape_native=(800, 800), pixel_scales=0.05)\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=real_space_grid)\n\naplt.subplot_interferometer_dirty_images(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\n\naplt.fits_interferometer(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n uv_wavelengths_path=DATASET_PATH / \"uv_wavelengths.fits\",\n overwrite=True,\n)\n```\n\nFour differences from imaging are worth knowing. The baselines come from a real array's\n`uv_wavelengths` \u2014 the workspace ships SMA (low resolution, very fast) and ALMA files;\nswapping the file swaps the instrument. There is **no PSF and no over-sampling**: the image\nis evaluated in real space and Fourier-transformed, and interferometers do not observe in a\nway that makes over-sampling necessary. `noise_sigma` replaces the exposure-time-driven\nPoisson model. And the thing you *look at* is the dirty image, which is a diagnostic \u2014 the\nfit itself happens in the uv-plane. The physics is\n[`../wiki/core/concepts/interferometer_theory.md`](../wiki/core/concepts/interferometer_theory.md).\nFull interferometer modelling is a separate skill,\n[`ag_build_interferometer_model`](./ag_build_interferometer_model.md).\n\n## The auto-simulation convention\n\nEvery workspace script that fits a dataset first checks whether it exists and runs the\nmatching simulator if it does not, so an example can be run from a fresh clone with no\nmanual step:\n\n```python\nif ag.util.dataset.should_simulate(str(dataset_path)):\n import subprocess\n import sys\n\n subprocess.run([sys.executable, \"scripts/imaging/simulator.py\"], check=True)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py`. Adopt the same pattern in\nscripts you write, and know the sharp edge: `should_simulate` tests **existence**, not\nwhether the dataset on disk matches the simulator that would produce it. Change the\nsimulator's parameters and re-run the fit and you will silently fit the *old* data. The same\napplies to `PYAUTO_SMALL_DATASETS=1`, which caps grids and masks to a small size: a\nfull-resolution dataset already on disk will be reused and mismatch the capped grids. Delete\nthe dataset directory when you change either\n([`../wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## JAX, for many simulations\n\nFor parameter sweeps, mock-data studies or batch figure generation, build the simulator with\n`use_jax=True` \u2014 the simulation then runs on JAX arrays (and the GPU, when one is\nconfigured):\n\n```python\nsimulator_jax = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n use_jax=True,\n)\n\ndataset_jax = simulator_jax.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\n`dataset_jax.data.array` is a `jax.Array`, and the plot and FITS helpers call\n`numpy.asarray()` internally, so saving and plotting need no manual conversion.\n\nWrapping the whole simulation call in a jitted function \u2014 worth it across *many* calls \u2014\nadditionally requires registering the galaxy classes as JAX pytrees before the first jitted\ncall, and the helper that does that registration is **not in the released stack yet** (it\nlives on the libraries' development branches only). Until it ships in a release, use the\neager `use_jax=True` call above; the `__JAX Variant__` section of\n`autogalaxy_workspace:scripts/imaging/simulator.py` carries the jitted recipe for a\nsource install. **For interferometer simulations the jitted path does not work either way** \u2014\nuse the eager call; `autogalaxy_workspace:scripts/interferometer/simulator.py` documents why.\n\n## Combine \u2014 where this hands off\n\n- **Fit the dataset you just made** \u2192 [`ag_build_imaging_model`](./ag_build_imaging_model.md)\n to compose the model, then [`ag_configure_search`](./ag_configure_search.md) and the\n run-search skill (`ag_run_search`). Compose a model that *matches* the truth first: if it\n cannot recover parameters it was handed exactly, the problem is the inference, and you have\n learned that cheaply.\n- **Compare a fit against the truth** \u2192 load `galaxies.json` with `ag.from_json` and put the\n true and inferred values side by side; the results-loading and fit-plotting skills\n (`ag_load_results`, `ag_plot_fit`) do the rest.\n- **You actually have real data** \u2192 [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md),\n which also owns the inspection gate this branch is exempt from.\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry when the simulation is\npart of a study \u2014 the truth parameters and the S/N you chose *are* the experimental design,\nand a recovery test is meaningless later without them.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [HowToGalaxy: Grids and galaxies](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb):\n how a light profile becomes an image on a grid, and what each Sersic parameter changes \u2014\n the foundation under every simulation.\n- **General reference** \u2014 [RTD: Start here overview](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the core API end to end, including the simulation section, in one page.\n- **Experienced PyAutoGalaxy user** \u2014 [workspace: imaging/simulator.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/simulator.py):\n the full bulge-plus-disk simulator with the contaminant mask and the executed JAX variant.\n\n## Agent procedural checklist\n\n1. Ask what the simulation is *for*; it decides the branch and whether `lp_snr` is wanted.\n2. Set `pixel_scales`, PSF width and exposure time from a real instrument, not defaults.\n3. Over-sample with every bright centre in `centre_list` \u2014 including any neighbour.\n4. Write FITS **and** `galaxies.json`; write the neighbour's `mask_extra_galaxies.fits` in\n the same script if one exists.\n5. Plot the dataset and the noise-free galaxies subplot; print and **quote** the absolute\n path, offering to open it once.\n6. Delete the dataset directory before re-running with changed parameters or with\n `PYAUTO_SMALL_DATASETS=1` \u2014 `should_simulate` only checks existence.\n7. Hand off to `ag_build_imaging_model`, and offer the `wiki/project/` entry when the\n simulation is part of a study.\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/simulators/sersic.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_simulate_dataset\n\n---\nname: ag_simulate_dataset\ndescription: Simulate CCD imaging (or interferometer visibilities) of a galaxy with known truth — a grid and over-sampling, a PSF, an exposure time and background sky, one or more galaxies built from light profiles, then FITS output plus a `galaxies.json` truth record. Covers targeting a signal-to-noise ratio directly with the `lp_snr` profiles, simulating a whole sample in a loop for population or machine-learning work, adding a contaminating extra galaxy with its noise-scaling mask, and the `should_simulate` auto-simulation convention every workspace script uses. Use to rehearse the modelling loop before real data, to build training sets, to test a recovery, or when a user has no data yet. Not for loading or preparing real observations (`ag_prepare_imaging_data`), and not for fitting.\n---\n\n# Simulating a galaxy dataset with known truth\n\nA simulated dataset is the only situation in galaxy modelling where you know the answer.\nThat makes it worth far more than a convenience: it is how you establish that your model\ncan recover a parameter at all, how you find out what signal-to-noise you need before you\npropose for telescope time, how you separate \"the fit is wrong\" from \"the data cannot\nconstrain this\", and how you generate the thousands of labelled images a neural network\nneeds. It is also the fastest way to rehearse the whole loop — compose, search, inspect —\nbefore real data is at stake.\n\nStatistically, what you are building is a draw from the likelihood's own generative model:\ntake a noise-free galaxy image, convolve it with the PSF, scale to counts through an\nexposure time, add a background sky, and draw Poisson noise. Because that is exactly the\nforward model the likelihood inverts, a fit to simulated data tests the *inference* in\nisolation — any bias you find is yours, not the data's. Simulated data is also **exempt from\nthe real-data inspection gate** (see\n[`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md)) for the same reason: you already\nknow where every component is.\n\nThe canonical scripts are `autogalaxy_workspace:scripts/imaging/simulator.py` (bulge, disk\nand a contaminating neighbour) and `autogalaxy_workspace:scripts/imaging/simulator_sersic.py`\n(a single Sersic). What each light profile means physically is\n[`../wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md); the\ndataset objects are [`../wiki/core/api/datasets.md`](../wiki/core/api/datasets.md).\n\n## Ask\n\n- *\"What are you simulating for — rehearsing the workflow, a recovery test, a training set,\n or a signal-to-noise feasibility study?\"* This picks the branch, and the last two change\n the API you want (`lp_snr`, and the sample loop).\n- *\"One galaxy or several, and should a contaminating neighbour be included?\"* Including one\n is worth doing deliberately: it is how you rehearse the noise-scaling step you will\n certainly need on real data.\n- *\"What instrument are you standing in for?\"* — it sets `pixel_scales`, the PSF width and a\n plausible exposure time, and makes the simulation answer a question about *your* telescope\n rather than an abstract one.\n\n## Branch — a single Sersic\n\nThe smallest useful simulation, and the one to start from. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator_sersic.py`.\n\n```python\n\"\"\"\nSimulator: Single Sersic\n========================\n\nSimulate CCD imaging of a galaxy whose light is a single elliptical Sersic profile, with\nknown truth parameters recorded alongside the data. The simulation applies the same forward\nmodel a fit inverts — evaluate the profile on an over-sampled grid, convolve with the PSF,\nscale through an exposure time, add a background sky and draw Poisson noise — so a fit to\nthe output tests the inference rather than the data.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Grid:** Build the coordinate grid and its adaptive over-sampling.\n- **PSF and Simulator:** Define the optical blurring and the noise properties.\n- **Galaxies:** Define the true galaxy whose parameters we intend to recover.\n- **Output:** Write the dataset to FITS, plus a `galaxies.json` record of the truth.\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\" / \"simple_sersic\"\n\n\"\"\"\n__Grid__\n\nThe `Grid2D` is the set of (y,x) arcsecond coordinates the galaxy's light is evaluated on,\nand `pixel_scales` ties it to a detector — set it to the instrument you are standing in for.\nOver-sampling then evaluates the profile on a finer sub-grid where its intensity gradient is\nsteep: a Sersic varies enormously across the central pixel, so a single evaluation at the\npixel centre under-counts the flux and produces a subtly wrong image. Simulations use higher\nsub-sampling than fits (32x32 in the centre rather than 8x8) because the cost is paid once\nrather than at every likelihood call\n(`PyAutoArray:autoarray/operators/over_sampling/over_sample_util.py`).\n\"\"\"\ngrid = ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.1)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n\"\"\"\n__PSF and Simulator__\n\nEvery real CCD image is blurred by the telescope optics, so a simulation without a PSF is not\nimaging data. A Gaussian kernel is a reasonable stand-in when you do not have a real PSF\n(FWHM = 2.35 * sigma). The `SimulatorImaging` object then supplies the rest of what makes\ndata noisy rather than ideal: `exposure_time` converts electrons per second to counts and so\nsets the Poisson noise level, and `background_sky_level` adds the sky's contribution to the\nnoise budget (`PyAutoArray:autoarray/dataset/imaging/simulator.py`). Raising the exposure\ntime raises the signal-to-noise; the ratio of the two controls how much of the noise is\ncounting statistics versus sky.\n\"\"\"\npsf = ag.Convolver.from_gaussian(\n shape_native=(11, 11), sigma=0.1, pixel_scales=grid.pixel_scales\n)\n\nsimulator = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\n\"\"\"\n__Galaxies__\n\nThe truth. `sersic_index` sets the profile's concentration — n ~ 4 is a de Vaucouleurs-like\nspheroid, n ~ 1 an exponential disk — and `effective_radius` is the radius containing half\nthe profile's light. For a *simulation* the axis-ratio and position-angle parameterisation is\nthe intuitive one, so `ag.convert.ell_comps_from` translates it into the `ell_comps` the\nprofile actually takes; a fit uses `ell_comps` directly, because a position angle's periodic\nboundary is pathological for a non-linear search\n(`PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py`).\n\"\"\"\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.8,\n sersic_index=4.0,\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy])\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\nprint(f\"peak signal-to-noise: {float(dataset.signal_to_noise_map.max()):.1f}\")\n\n\"\"\"\n__Output__\n\nThe FITS files are written in exactly the layout `ag.Imaging.from_fits` expects, so the\nsimulated dataset is indistinguishable from real data to everything downstream. The\n`galaxies.json` record is the part people skip and regret: it stores the true light profiles\nso that months later you can still state what the fit was supposed to recover. Load it back\nwith `ag.from_json`.\n\"\"\"\naplt.fits_imaging(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n overwrite=True,\n)\n\nag.output_to_json(obj=galaxies, file_path=DATASET_PATH / \"galaxies.json\")\n\naplt.subplot_imaging_dataset(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\naplt.subplot_galaxies(\n galaxies=galaxies, grid=grid, output_path=DATASET_PATH, output_format=\"png\"\n)\n\nprint(f\"Saved to: {DATASET_PATH.resolve()}\")\n```\n\nQuote that path back and offer to open it once. The `subplot_galaxies` figure is the useful\none for a simulation: it shows the noise-free truth beside the profile's components, which\nis what you compare a fit against.\n\n## Branch — bulge, disk, and a contaminating neighbour\n\nThe realistic default. Two components let you pose the question galaxy morphology usually\ncares about — the bulge-to-total light ratio — and a faint offset neighbour lets you\nrehearse the noise-scaling step. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator.py`.\n\n```python\nextra_galaxy_centre = (2.2, 1.6)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0), extra_galaxy_centre],\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n disk=ag.lp.Exponential(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.7, angle=30.0),\n intensity=0.5,\n effective_radius=1.6,\n ),\n)\n\nextra_galaxy = ag.Galaxy(\n redshift=0.5,\n light=ag.lp.ExponentialSph(\n centre=extra_galaxy_centre, intensity=1.0, effective_radius=0.3\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy, extra_galaxy])\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\nThree details carry weight. The bulge is compact with a high `sersic_index` and the disk is\nextended with n fixed at 1 by construction — that contrast is what makes the decomposition\nidentifiable at all. The neighbour's centre appears in `centre_list` as well as in its own\nprofile, so it is over-sampled properly rather than being the one badly-evaluated object in\nthe frame. And the attribute names (`bulge`, `disk`, `light`) are arbitrary labels you choose\n— name them for what they measure.\n\nWrite the neighbour's noise-scaling mask in the same script, so the modelling examples can\nload it without a separate preparation step:\n\n```python\nmask_extra_galaxies = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n centre=extra_galaxy_centre,\n radius=3.0 * 0.3, # ~3x the neighbour's effective radius\n invert=True, # `True` inside the circle: the region whose noise is scaled.\n)\n\naplt.fits_array(\n array=mask_extra_galaxies,\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n overwrite=True,\n)\n```\n\nDeriving the radius from the neighbour's own `effective_radius` keeps the two in sync if you\nlater change it. The strategies this mask feeds into are\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch — target a signal-to-noise ratio directly\n\nOften the question is not \"what intensity?\" but \"what if this galaxy were detected at S/N =\n20?\". Choosing an `intensity` that lands there is guesswork; the `lp_snr` profiles remove it\nby solving for the intensity that achieves a requested ratio, using the simulator's\n`exposure_time` and `background_sky_level` to do so. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/simulator_manual_signal_to_noise.py`.\n\n```python\ngalaxy_0 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=20.0,\n centre=(0.0, -1.0),\n ell_comps=(0.25, 0.1),\n effective_radius=0.8,\n sersic_index=2.5,\n ),\n)\n\ngalaxy_1 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=10.0,\n centre=(0.0, 1.0),\n ell_comps=(0.0, 0.1),\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n)\n\ndataset = simulator.via_galaxies_from(\n galaxies=ag.Galaxies(galaxies=[galaxy_0, galaxy_1]), grid=grid\n)\n```\n\nNote the profiles take **no** `intensity` — that is the parameter being solved for. The\ntrade-off is that `exposure_time` and `background_sky_level` no longer set the S/N, only the\n*balance* between counting noise and sky noise. So they still matter for realism: doubling\nthe exposure time shifts the noise budget toward Poisson statistics even though the S/N is\npinned. Choose them to match your instrument if the noise character matters to the study.\n\nThis is also the profile family to reach for in a feasibility question — simulate the same\ngalaxy at S/N 10, 20 and 50, fit each, and see where the parameter you care about stops\nbeing constrained. That is a far more honest answer than a single simulation at whatever\nintensity happened to be typed.\n\n## Branch — a sample, for population or machine-learning work\n\nTo generate many galaxies, draw each one's parameters from a distribution and loop. Adapted\nfrom `autogalaxy_workspace:scripts/imaging/simulator_sample.py`, which draws directly from a\nNumPy generator — deliberately, because these are *truths* for synthetic data, not a model\nbeing fitted, so there is no reason to involve the model-composition API.\n\n```python\nimport numpy as np\n\nrng = np.random.default_rng()\n\n\ndef _clipped_ell_comp() -> float:\n return float(np.clip(rng.normal(0.0, 0.2), -1.0, 1.0))\n\n\ndef _random_galaxy() -> ag.Galaxy:\n bulge = ag.lp_snr.Sersic(\n centre=(0.0, 0.0),\n ell_comps=(_clipped_ell_comp(), _clipped_ell_comp()),\n effective_radius=float(rng.uniform(1.0, 5.0)),\n sersic_index=float(np.clip(rng.normal(4.0, 1.0), 0.8, 5.0)),\n signal_to_noise_ratio=float(rng.uniform(20.0, 60.0)),\n )\n return ag.Galaxy(redshift=0.5, bulge=bulge)\n\n\ntotal_datasets = 3\n\nfor sample_index in range(total_datasets):\n\n sample_path = DATASET_PATH / f\"dataset_{sample_index}\"\n\n galaxies = ag.Galaxies(galaxies=[_random_galaxy()])\n dataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\n aplt.fits_imaging(\n dataset=dataset,\n data_path=sample_path / \"data.fits\",\n psf_path=sample_path / \"psf.fits\",\n noise_map_path=sample_path / \"noise_map.fits\",\n overwrite=True,\n )\n ag.output_to_json(obj=galaxies, file_path=sample_path / \"galaxies.json\")\n```\n\nThe `lp_snr` bulge is what makes the loop usable: with a plain `intensity` drawn from a\ndistribution, a fraction of your sample would be invisible and another fraction saturated.\nPinning S/N per galaxy guarantees every image is detectable. Write a `galaxies.json` per\ndataset — with a sample, the truth record stops being a nicety and becomes the labels.\n\nFor a one-line random galaxy without writing your own distributions,\n`ag.model_util.random_galaxy_for_simulation_from()` returns one drawn from the library's own\nchoices, and `ag.model_util.SIMULATOR_RANDOM_GALAXY_SUMMARY` prints what those choices are —\nread that summary before using it in anything you will publish, so the prior you inherited\nis one you actually endorse.\n\n## Branch — interferometer visibilities\n\nFor sub-mm and radio data (ALMA, JVLA, LOFAR) the observable is visibilities in the uv-plane,\nnot an image, and fitting them there avoids the correlated noise a dirty image carries.\nAdapted from `autogalaxy_workspace:scripts/interferometer/simulator.py`.\n\n```python\nuv_wavelengths = ag.ndarray_via_fits_from(\n file_path=Path(\"dataset\") / \"interferometer\" / \"uv_wavelengths\" / \"sma.fits\", hdu=0\n)\n\nsimulator = ag.SimulatorInterferometer(\n uv_wavelengths=uv_wavelengths,\n exposure_time=300.0,\n noise_sigma=1000.0,\n transformer_class=ag.TransformerNUFFT,\n)\n\nreal_space_grid = ag.Grid2D.uniform(shape_native=(800, 800), pixel_scales=0.05)\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=real_space_grid)\n\naplt.subplot_interferometer_dirty_images(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\n\naplt.fits_interferometer(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n uv_wavelengths_path=DATASET_PATH / \"uv_wavelengths.fits\",\n overwrite=True,\n)\n```\n\nFour differences from imaging are worth knowing. The baselines come from a real array's\n`uv_wavelengths` — the workspace ships SMA (low resolution, very fast) and ALMA files;\nswapping the file swaps the instrument. There is **no PSF and no over-sampling**: the image\nis evaluated in real space and Fourier-transformed, and interferometers do not observe in a\nway that makes over-sampling necessary. `noise_sigma` replaces the exposure-time-driven\nPoisson model. And the thing you *look at* is the dirty image, which is a diagnostic — the\nfit itself happens in the uv-plane. The physics is\n[`../wiki/core/concepts/interferometer_theory.md`](../wiki/core/concepts/interferometer_theory.md).\nFull interferometer modelling is a separate skill,\n[`ag_build_interferometer_model`](./ag_build_interferometer_model.md).\n\n## The auto-simulation convention\n\nEvery workspace script that fits a dataset first checks whether it exists and runs the\nmatching simulator if it does not, so an example can be run from a fresh clone with no\nmanual step:\n\n```python\nif ag.util.dataset.should_simulate(str(dataset_path)):\n import subprocess\n import sys\n\n subprocess.run([sys.executable, \"scripts/imaging/simulator.py\"], check=True)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py`. Adopt the same pattern in\nscripts you write, and know the sharp edge: `should_simulate` tests **existence**, not\nwhether the dataset on disk matches the simulator that would produce it. Change the\nsimulator's parameters and re-run the fit and you will silently fit the *old* data. The same\napplies to `PYAUTO_SMALL_DATASETS=1`, which caps grids and masks to a small size: a\nfull-resolution dataset already on disk will be reused and mismatch the capped grids. Delete\nthe dataset directory when you change either\n([`../wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## JAX, for many simulations\n\nFor parameter sweeps, mock-data studies or batch figure generation, build the simulator with\n`use_jax=True` — the simulation then runs on JAX arrays (and the GPU, when one is\nconfigured):\n\n```python\nsimulator_jax = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n use_jax=True,\n)\n\ndataset_jax = simulator_jax.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\n`dataset_jax.data.array` is a `jax.Array`, and the plot and FITS helpers call\n`numpy.asarray()` internally, so saving and plotting need no manual conversion.\n\nWrapping the whole simulation call in a jitted function — worth it across *many* calls —\nadditionally requires registering the galaxy classes as JAX pytrees before the first jitted\ncall, and the helper that does that registration is **not in the released stack yet** (it\nlives on the libraries' development branches only). Until it ships in a release, use the\neager `use_jax=True` call above; the `__JAX Variant__` section of\n`autogalaxy_workspace:scripts/imaging/simulator.py` carries the jitted recipe for a\nsource install. **For interferometer simulations the jitted path does not work either way** —\nuse the eager call; `autogalaxy_workspace:scripts/interferometer/simulator.py` documents why.\n\n## Combine — where this hands off\n\n- **Fit the dataset you just made** → [`ag_build_imaging_model`](./ag_build_imaging_model.md)\n to compose the model, then [`ag_configure_search`](./ag_configure_search.md) and the\n run-search skill (`ag_run_search`). Compose a model that *matches* the truth first: if it\n cannot recover parameters it was handed exactly, the problem is the inference, and you have\n learned that cheaply.\n- **Compare a fit against the truth** → load `galaxies.json` with `ag.from_json` and put the\n true and inferred values side by side; the results-loading and fit-plotting skills\n (`ag_load_results`, `ag_plot_fit`) do the rest.\n- **You actually have real data** → [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md),\n which also owns the inspection gate this branch is exempt from.\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry when the simulation is\npart of a study — the truth parameters and the S/N you chose *are* the experimental design,\nand a recovery test is meaningless later without them.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Grids and galaxies](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb):\n how a light profile becomes an image on a grid, and what each Sersic parameter changes —\n the foundation under every simulation.\n- **General reference** — [RTD: Start here overview](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the core API end to end, including the simulation section, in one page.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/simulator.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/simulator.py):\n the full bulge-plus-disk simulator with the contaminant mask and the executed JAX variant.\n\n## Agent procedural checklist\n\n1. Ask what the simulation is *for*; it decides the branch and whether `lp_snr` is wanted.\n2. Set `pixel_scales`, PSF width and exposure time from a real instrument, not defaults.\n3. Over-sample with every bright centre in `centre_list` — including any neighbour.\n4. Write FITS **and** `galaxies.json`; write the neighbour's `mask_extra_galaxies.fits` in\n the same script if one exists.\n5. Plot the dataset and the noise-free galaxies subplot; print and **quote** the absolute\n path, offering to open it once.\n6. Delete the dataset directory before re-running with changed parameters or with\n `PYAUTO_SMALL_DATASETS=1` — `should_simulate` only checks existence.\n7. Hand off to `ag_build_imaging_model`, and offer the `wiki/project/` entry when the\n simulation is part of a study.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/simulators/sersic_x2.ipynb b/notebooks/simulators/sersic_x2.ipynb index 4a631a9..98cadd2 100644 --- a/notebooks/simulators/sersic_x2.ipynb +++ b/notebooks/simulators/sersic_x2.ipynb @@ -34,21 +34,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -353,7 +353,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/simulators/sersic_x2.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_simulate_dataset\n\n---\nname: ag_simulate_dataset\ndescription: Simulate CCD imaging (or interferometer visibilities) of a galaxy with known truth \u2014 a grid and over-sampling, a PSF, an exposure time and background sky, one or more galaxies built from light profiles, then FITS output plus a `galaxies.json` truth record. Covers targeting a signal-to-noise ratio directly with the `lp_snr` profiles, simulating a whole sample in a loop for population or machine-learning work, adding a contaminating extra galaxy with its noise-scaling mask, and the `should_simulate` auto-simulation convention every workspace script uses. Use to rehearse the modelling loop before real data, to build training sets, to test a recovery, or when a user has no data yet. Not for loading or preparing real observations (`ag_prepare_imaging_data`), and not for fitting.\n---\n\n# Simulating a galaxy dataset with known truth\n\nA simulated dataset is the only situation in galaxy modelling where you know the answer.\nThat makes it worth far more than a convenience: it is how you establish that your model\ncan recover a parameter at all, how you find out what signal-to-noise you need before you\npropose for telescope time, how you separate \"the fit is wrong\" from \"the data cannot\nconstrain this\", and how you generate the thousands of labelled images a neural network\nneeds. It is also the fastest way to rehearse the whole loop \u2014 compose, search, inspect \u2014\nbefore real data is at stake.\n\nStatistically, what you are building is a draw from the likelihood's own generative model:\ntake a noise-free galaxy image, convolve it with the PSF, scale to counts through an\nexposure time, add a background sky, and draw Poisson noise. Because that is exactly the\nforward model the likelihood inverts, a fit to simulated data tests the *inference* in\nisolation \u2014 any bias you find is yours, not the data's. Simulated data is also **exempt from\nthe real-data inspection gate** (see\n[`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md)) for the same reason: you already\nknow where every component is.\n\nThe canonical scripts are `autogalaxy_workspace:scripts/imaging/simulator.py` (bulge, disk\nand a contaminating neighbour) and `autogalaxy_workspace:scripts/imaging/simulator_sersic.py`\n(a single Sersic). What each light profile means physically is\n[`../wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md); the\ndataset objects are [`../wiki/core/api/datasets.md`](../wiki/core/api/datasets.md).\n\n## Ask\n\n- *\"What are you simulating for \u2014 rehearsing the workflow, a recovery test, a training set,\n or a signal-to-noise feasibility study?\"* This picks the branch, and the last two change\n the API you want (`lp_snr`, and the sample loop).\n- *\"One galaxy or several, and should a contaminating neighbour be included?\"* Including one\n is worth doing deliberately: it is how you rehearse the noise-scaling step you will\n certainly need on real data.\n- *\"What instrument are you standing in for?\"* \u2014 it sets `pixel_scales`, the PSF width and a\n plausible exposure time, and makes the simulation answer a question about *your* telescope\n rather than an abstract one.\n\n## Branch \u2014 a single Sersic\n\nThe smallest useful simulation, and the one to start from. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator_sersic.py`.\n\n```python\n\"\"\"\nSimulator: Single Sersic\n========================\n\nSimulate CCD imaging of a galaxy whose light is a single elliptical Sersic profile, with\nknown truth parameters recorded alongside the data. The simulation applies the same forward\nmodel a fit inverts \u2014 evaluate the profile on an over-sampled grid, convolve with the PSF,\nscale through an exposure time, add a background sky and draw Poisson noise \u2014 so a fit to\nthe output tests the inference rather than the data.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Grid:** Build the coordinate grid and its adaptive over-sampling.\n- **PSF and Simulator:** Define the optical blurring and the noise properties.\n- **Galaxies:** Define the true galaxy whose parameters we intend to recover.\n- **Output:** Write the dataset to FITS, plus a `galaxies.json` record of the truth.\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\" / \"simple_sersic\"\n\n\"\"\"\n__Grid__\n\nThe `Grid2D` is the set of (y,x) arcsecond coordinates the galaxy's light is evaluated on,\nand `pixel_scales` ties it to a detector \u2014 set it to the instrument you are standing in for.\nOver-sampling then evaluates the profile on a finer sub-grid where its intensity gradient is\nsteep: a Sersic varies enormously across the central pixel, so a single evaluation at the\npixel centre under-counts the flux and produces a subtly wrong image. Simulations use higher\nsub-sampling than fits (32x32 in the centre rather than 8x8) because the cost is paid once\nrather than at every likelihood call\n(`PyAutoArray:autoarray/operators/over_sampling/over_sample_util.py`).\n\"\"\"\ngrid = ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.1)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n\"\"\"\n__PSF and Simulator__\n\nEvery real CCD image is blurred by the telescope optics, so a simulation without a PSF is not\nimaging data. A Gaussian kernel is a reasonable stand-in when you do not have a real PSF\n(FWHM = 2.35 * sigma). The `SimulatorImaging` object then supplies the rest of what makes\ndata noisy rather than ideal: `exposure_time` converts electrons per second to counts and so\nsets the Poisson noise level, and `background_sky_level` adds the sky's contribution to the\nnoise budget (`PyAutoArray:autoarray/dataset/imaging/simulator.py`). Raising the exposure\ntime raises the signal-to-noise; the ratio of the two controls how much of the noise is\ncounting statistics versus sky.\n\"\"\"\npsf = ag.Convolver.from_gaussian(\n shape_native=(11, 11), sigma=0.1, pixel_scales=grid.pixel_scales\n)\n\nsimulator = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\n\"\"\"\n__Galaxies__\n\nThe truth. `sersic_index` sets the profile's concentration \u2014 n ~ 4 is a de Vaucouleurs-like\nspheroid, n ~ 1 an exponential disk \u2014 and `effective_radius` is the radius containing half\nthe profile's light. For a *simulation* the axis-ratio and position-angle parameterisation is\nthe intuitive one, so `ag.convert.ell_comps_from` translates it into the `ell_comps` the\nprofile actually takes; a fit uses `ell_comps` directly, because a position angle's periodic\nboundary is pathological for a non-linear search\n(`PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py`).\n\"\"\"\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.8,\n sersic_index=4.0,\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy])\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\nprint(f\"peak signal-to-noise: {float(dataset.signal_to_noise_map.max()):.1f}\")\n\n\"\"\"\n__Output__\n\nThe FITS files are written in exactly the layout `ag.Imaging.from_fits` expects, so the\nsimulated dataset is indistinguishable from real data to everything downstream. The\n`galaxies.json` record is the part people skip and regret: it stores the true light profiles\nso that months later you can still state what the fit was supposed to recover. Load it back\nwith `ag.from_json`.\n\"\"\"\naplt.fits_imaging(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n overwrite=True,\n)\n\nag.output_to_json(obj=galaxies, file_path=DATASET_PATH / \"galaxies.json\")\n\naplt.subplot_imaging_dataset(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\naplt.subplot_galaxies(\n galaxies=galaxies, grid=grid, output_path=DATASET_PATH, output_format=\"png\"\n)\n\nprint(f\"Saved to: {DATASET_PATH.resolve()}\")\n```\n\nQuote that path back and offer to open it once. The `subplot_galaxies` figure is the useful\none for a simulation: it shows the noise-free truth beside the profile's components, which\nis what you compare a fit against.\n\n## Branch \u2014 bulge, disk, and a contaminating neighbour\n\nThe realistic default. Two components let you pose the question galaxy morphology usually\ncares about \u2014 the bulge-to-total light ratio \u2014 and a faint offset neighbour lets you\nrehearse the noise-scaling step. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator.py`.\n\n```python\nextra_galaxy_centre = (2.2, 1.6)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0), extra_galaxy_centre],\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n disk=ag.lp.Exponential(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.7, angle=30.0),\n intensity=0.5,\n effective_radius=1.6,\n ),\n)\n\nextra_galaxy = ag.Galaxy(\n redshift=0.5,\n light=ag.lp.ExponentialSph(\n centre=extra_galaxy_centre, intensity=1.0, effective_radius=0.3\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy, extra_galaxy])\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\nThree details carry weight. The bulge is compact with a high `sersic_index` and the disk is\nextended with n fixed at 1 by construction \u2014 that contrast is what makes the decomposition\nidentifiable at all. The neighbour's centre appears in `centre_list` as well as in its own\nprofile, so it is over-sampled properly rather than being the one badly-evaluated object in\nthe frame. And the attribute names (`bulge`, `disk`, `light`) are arbitrary labels you choose\n\u2014 name them for what they measure.\n\nWrite the neighbour's noise-scaling mask in the same script, so the modelling examples can\nload it without a separate preparation step:\n\n```python\nmask_extra_galaxies = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n centre=extra_galaxy_centre,\n radius=3.0 * 0.3, # ~3x the neighbour's effective radius\n invert=True, # `True` inside the circle: the region whose noise is scaled.\n)\n\naplt.fits_array(\n array=mask_extra_galaxies,\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n overwrite=True,\n)\n```\n\nDeriving the radius from the neighbour's own `effective_radius` keeps the two in sync if you\nlater change it. The strategies this mask feeds into are\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch \u2014 target a signal-to-noise ratio directly\n\nOften the question is not \"what intensity?\" but \"what if this galaxy were detected at S/N =\n20?\". Choosing an `intensity` that lands there is guesswork; the `lp_snr` profiles remove it\nby solving for the intensity that achieves a requested ratio, using the simulator's\n`exposure_time` and `background_sky_level` to do so. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/simulator_manual_signal_to_noise.py`.\n\n```python\ngalaxy_0 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=20.0,\n centre=(0.0, -1.0),\n ell_comps=(0.25, 0.1),\n effective_radius=0.8,\n sersic_index=2.5,\n ),\n)\n\ngalaxy_1 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=10.0,\n centre=(0.0, 1.0),\n ell_comps=(0.0, 0.1),\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n)\n\ndataset = simulator.via_galaxies_from(\n galaxies=ag.Galaxies(galaxies=[galaxy_0, galaxy_1]), grid=grid\n)\n```\n\nNote the profiles take **no** `intensity` \u2014 that is the parameter being solved for. The\ntrade-off is that `exposure_time` and `background_sky_level` no longer set the S/N, only the\n*balance* between counting noise and sky noise. So they still matter for realism: doubling\nthe exposure time shifts the noise budget toward Poisson statistics even though the S/N is\npinned. Choose them to match your instrument if the noise character matters to the study.\n\nThis is also the profile family to reach for in a feasibility question \u2014 simulate the same\ngalaxy at S/N 10, 20 and 50, fit each, and see where the parameter you care about stops\nbeing constrained. That is a far more honest answer than a single simulation at whatever\nintensity happened to be typed.\n\n## Branch \u2014 a sample, for population or machine-learning work\n\nTo generate many galaxies, draw each one's parameters from a distribution and loop. Adapted\nfrom `autogalaxy_workspace:scripts/imaging/simulator_sample.py`, which draws directly from a\nNumPy generator \u2014 deliberately, because these are *truths* for synthetic data, not a model\nbeing fitted, so there is no reason to involve the model-composition API.\n\n```python\nimport numpy as np\n\nrng = np.random.default_rng()\n\n\ndef _clipped_ell_comp() -> float:\n return float(np.clip(rng.normal(0.0, 0.2), -1.0, 1.0))\n\n\ndef _random_galaxy() -> ag.Galaxy:\n bulge = ag.lp_snr.Sersic(\n centre=(0.0, 0.0),\n ell_comps=(_clipped_ell_comp(), _clipped_ell_comp()),\n effective_radius=float(rng.uniform(1.0, 5.0)),\n sersic_index=float(np.clip(rng.normal(4.0, 1.0), 0.8, 5.0)),\n signal_to_noise_ratio=float(rng.uniform(20.0, 60.0)),\n )\n return ag.Galaxy(redshift=0.5, bulge=bulge)\n\n\ntotal_datasets = 3\n\nfor sample_index in range(total_datasets):\n\n sample_path = DATASET_PATH / f\"dataset_{sample_index}\"\n\n galaxies = ag.Galaxies(galaxies=[_random_galaxy()])\n dataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\n aplt.fits_imaging(\n dataset=dataset,\n data_path=sample_path / \"data.fits\",\n psf_path=sample_path / \"psf.fits\",\n noise_map_path=sample_path / \"noise_map.fits\",\n overwrite=True,\n )\n ag.output_to_json(obj=galaxies, file_path=sample_path / \"galaxies.json\")\n```\n\nThe `lp_snr` bulge is what makes the loop usable: with a plain `intensity` drawn from a\ndistribution, a fraction of your sample would be invisible and another fraction saturated.\nPinning S/N per galaxy guarantees every image is detectable. Write a `galaxies.json` per\ndataset \u2014 with a sample, the truth record stops being a nicety and becomes the labels.\n\nFor a one-line random galaxy without writing your own distributions,\n`ag.model_util.random_galaxy_for_simulation_from()` returns one drawn from the library's own\nchoices, and `ag.model_util.SIMULATOR_RANDOM_GALAXY_SUMMARY` prints what those choices are \u2014\nread that summary before using it in anything you will publish, so the prior you inherited\nis one you actually endorse.\n\n## Branch \u2014 interferometer visibilities\n\nFor sub-mm and radio data (ALMA, JVLA, LOFAR) the observable is visibilities in the uv-plane,\nnot an image, and fitting them there avoids the correlated noise a dirty image carries.\nAdapted from `autogalaxy_workspace:scripts/interferometer/simulator.py`.\n\n```python\nuv_wavelengths = ag.ndarray_via_fits_from(\n file_path=Path(\"dataset\") / \"interferometer\" / \"uv_wavelengths\" / \"sma.fits\", hdu=0\n)\n\nsimulator = ag.SimulatorInterferometer(\n uv_wavelengths=uv_wavelengths,\n exposure_time=300.0,\n noise_sigma=1000.0,\n transformer_class=ag.TransformerNUFFT,\n)\n\nreal_space_grid = ag.Grid2D.uniform(shape_native=(800, 800), pixel_scales=0.05)\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=real_space_grid)\n\naplt.subplot_interferometer_dirty_images(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\n\naplt.fits_interferometer(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n uv_wavelengths_path=DATASET_PATH / \"uv_wavelengths.fits\",\n overwrite=True,\n)\n```\n\nFour differences from imaging are worth knowing. The baselines come from a real array's\n`uv_wavelengths` \u2014 the workspace ships SMA (low resolution, very fast) and ALMA files;\nswapping the file swaps the instrument. There is **no PSF and no over-sampling**: the image\nis evaluated in real space and Fourier-transformed, and interferometers do not observe in a\nway that makes over-sampling necessary. `noise_sigma` replaces the exposure-time-driven\nPoisson model. And the thing you *look at* is the dirty image, which is a diagnostic \u2014 the\nfit itself happens in the uv-plane. The physics is\n[`../wiki/core/concepts/interferometer_theory.md`](../wiki/core/concepts/interferometer_theory.md).\nFull interferometer modelling is a separate skill,\n[`ag_build_interferometer_model`](./ag_build_interferometer_model.md).\n\n## The auto-simulation convention\n\nEvery workspace script that fits a dataset first checks whether it exists and runs the\nmatching simulator if it does not, so an example can be run from a fresh clone with no\nmanual step:\n\n```python\nif ag.util.dataset.should_simulate(str(dataset_path)):\n import subprocess\n import sys\n\n subprocess.run([sys.executable, \"scripts/imaging/simulator.py\"], check=True)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py`. Adopt the same pattern in\nscripts you write, and know the sharp edge: `should_simulate` tests **existence**, not\nwhether the dataset on disk matches the simulator that would produce it. Change the\nsimulator's parameters and re-run the fit and you will silently fit the *old* data. The same\napplies to `PYAUTO_SMALL_DATASETS=1`, which caps grids and masks to a small size: a\nfull-resolution dataset already on disk will be reused and mismatch the capped grids. Delete\nthe dataset directory when you change either\n([`../wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## JAX, for many simulations\n\nFor parameter sweeps, mock-data studies or batch figure generation, build the simulator with\n`use_jax=True` \u2014 the simulation then runs on JAX arrays (and the GPU, when one is\nconfigured):\n\n```python\nsimulator_jax = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n use_jax=True,\n)\n\ndataset_jax = simulator_jax.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\n`dataset_jax.data.array` is a `jax.Array`, and the plot and FITS helpers call\n`numpy.asarray()` internally, so saving and plotting need no manual conversion.\n\nWrapping the whole simulation call in a jitted function \u2014 worth it across *many* calls \u2014\nadditionally requires registering the galaxy classes as JAX pytrees before the first jitted\ncall, and the helper that does that registration is **not in the released stack yet** (it\nlives on the libraries' development branches only). Until it ships in a release, use the\neager `use_jax=True` call above; the `__JAX Variant__` section of\n`autogalaxy_workspace:scripts/imaging/simulator.py` carries the jitted recipe for a\nsource install. **For interferometer simulations the jitted path does not work either way** \u2014\nuse the eager call; `autogalaxy_workspace:scripts/interferometer/simulator.py` documents why.\n\n## Combine \u2014 where this hands off\n\n- **Fit the dataset you just made** \u2192 [`ag_build_imaging_model`](./ag_build_imaging_model.md)\n to compose the model, then [`ag_configure_search`](./ag_configure_search.md) and the\n run-search skill (`ag_run_search`). Compose a model that *matches* the truth first: if it\n cannot recover parameters it was handed exactly, the problem is the inference, and you have\n learned that cheaply.\n- **Compare a fit against the truth** \u2192 load `galaxies.json` with `ag.from_json` and put the\n true and inferred values side by side; the results-loading and fit-plotting skills\n (`ag_load_results`, `ag_plot_fit`) do the rest.\n- **You actually have real data** \u2192 [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md),\n which also owns the inspection gate this branch is exempt from.\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry when the simulation is\npart of a study \u2014 the truth parameters and the S/N you chose *are* the experimental design,\nand a recovery test is meaningless later without them.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [HowToGalaxy: Grids and galaxies](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb):\n how a light profile becomes an image on a grid, and what each Sersic parameter changes \u2014\n the foundation under every simulation.\n- **General reference** \u2014 [RTD: Start here overview](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the core API end to end, including the simulation section, in one page.\n- **Experienced PyAutoGalaxy user** \u2014 [workspace: imaging/simulator.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/simulator.py):\n the full bulge-plus-disk simulator with the contaminant mask and the executed JAX variant.\n\n## Agent procedural checklist\n\n1. Ask what the simulation is *for*; it decides the branch and whether `lp_snr` is wanted.\n2. Set `pixel_scales`, PSF width and exposure time from a real instrument, not defaults.\n3. Over-sample with every bright centre in `centre_list` \u2014 including any neighbour.\n4. Write FITS **and** `galaxies.json`; write the neighbour's `mask_extra_galaxies.fits` in\n the same script if one exists.\n5. Plot the dataset and the noise-free galaxies subplot; print and **quote** the absolute\n path, offering to open it once.\n6. Delete the dataset directory before re-running with changed parameters or with\n `PYAUTO_SMALL_DATASETS=1` \u2014 `should_simulate` only checks existence.\n7. Hand off to `ag_build_imaging_model`, and offer the `wiki/project/` entry when the\n simulation is part of a study.\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/simulators/sersic_x2.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_simulate_dataset\n\n---\nname: ag_simulate_dataset\ndescription: Simulate CCD imaging (or interferometer visibilities) of a galaxy with known truth — a grid and over-sampling, a PSF, an exposure time and background sky, one or more galaxies built from light profiles, then FITS output plus a `galaxies.json` truth record. Covers targeting a signal-to-noise ratio directly with the `lp_snr` profiles, simulating a whole sample in a loop for population or machine-learning work, adding a contaminating extra galaxy with its noise-scaling mask, and the `should_simulate` auto-simulation convention every workspace script uses. Use to rehearse the modelling loop before real data, to build training sets, to test a recovery, or when a user has no data yet. Not for loading or preparing real observations (`ag_prepare_imaging_data`), and not for fitting.\n---\n\n# Simulating a galaxy dataset with known truth\n\nA simulated dataset is the only situation in galaxy modelling where you know the answer.\nThat makes it worth far more than a convenience: it is how you establish that your model\ncan recover a parameter at all, how you find out what signal-to-noise you need before you\npropose for telescope time, how you separate \"the fit is wrong\" from \"the data cannot\nconstrain this\", and how you generate the thousands of labelled images a neural network\nneeds. It is also the fastest way to rehearse the whole loop — compose, search, inspect —\nbefore real data is at stake.\n\nStatistically, what you are building is a draw from the likelihood's own generative model:\ntake a noise-free galaxy image, convolve it with the PSF, scale to counts through an\nexposure time, add a background sky, and draw Poisson noise. Because that is exactly the\nforward model the likelihood inverts, a fit to simulated data tests the *inference* in\nisolation — any bias you find is yours, not the data's. Simulated data is also **exempt from\nthe real-data inspection gate** (see\n[`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md)) for the same reason: you already\nknow where every component is.\n\nThe canonical scripts are `autogalaxy_workspace:scripts/imaging/simulator.py` (bulge, disk\nand a contaminating neighbour) and `autogalaxy_workspace:scripts/imaging/simulator_sersic.py`\n(a single Sersic). What each light profile means physically is\n[`../wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md); the\ndataset objects are [`../wiki/core/api/datasets.md`](../wiki/core/api/datasets.md).\n\n## Ask\n\n- *\"What are you simulating for — rehearsing the workflow, a recovery test, a training set,\n or a signal-to-noise feasibility study?\"* This picks the branch, and the last two change\n the API you want (`lp_snr`, and the sample loop).\n- *\"One galaxy or several, and should a contaminating neighbour be included?\"* Including one\n is worth doing deliberately: it is how you rehearse the noise-scaling step you will\n certainly need on real data.\n- *\"What instrument are you standing in for?\"* — it sets `pixel_scales`, the PSF width and a\n plausible exposure time, and makes the simulation answer a question about *your* telescope\n rather than an abstract one.\n\n## Branch — a single Sersic\n\nThe smallest useful simulation, and the one to start from. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator_sersic.py`.\n\n```python\n\"\"\"\nSimulator: Single Sersic\n========================\n\nSimulate CCD imaging of a galaxy whose light is a single elliptical Sersic profile, with\nknown truth parameters recorded alongside the data. The simulation applies the same forward\nmodel a fit inverts — evaluate the profile on an over-sampled grid, convolve with the PSF,\nscale through an exposure time, add a background sky and draw Poisson noise — so a fit to\nthe output tests the inference rather than the data.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Grid:** Build the coordinate grid and its adaptive over-sampling.\n- **PSF and Simulator:** Define the optical blurring and the noise properties.\n- **Galaxies:** Define the true galaxy whose parameters we intend to recover.\n- **Output:** Write the dataset to FITS, plus a `galaxies.json` record of the truth.\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\" / \"simple_sersic\"\n\n\"\"\"\n__Grid__\n\nThe `Grid2D` is the set of (y,x) arcsecond coordinates the galaxy's light is evaluated on,\nand `pixel_scales` ties it to a detector — set it to the instrument you are standing in for.\nOver-sampling then evaluates the profile on a finer sub-grid where its intensity gradient is\nsteep: a Sersic varies enormously across the central pixel, so a single evaluation at the\npixel centre under-counts the flux and produces a subtly wrong image. Simulations use higher\nsub-sampling than fits (32x32 in the centre rather than 8x8) because the cost is paid once\nrather than at every likelihood call\n(`PyAutoArray:autoarray/operators/over_sampling/over_sample_util.py`).\n\"\"\"\ngrid = ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.1)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n\"\"\"\n__PSF and Simulator__\n\nEvery real CCD image is blurred by the telescope optics, so a simulation without a PSF is not\nimaging data. A Gaussian kernel is a reasonable stand-in when you do not have a real PSF\n(FWHM = 2.35 * sigma). The `SimulatorImaging` object then supplies the rest of what makes\ndata noisy rather than ideal: `exposure_time` converts electrons per second to counts and so\nsets the Poisson noise level, and `background_sky_level` adds the sky's contribution to the\nnoise budget (`PyAutoArray:autoarray/dataset/imaging/simulator.py`). Raising the exposure\ntime raises the signal-to-noise; the ratio of the two controls how much of the noise is\ncounting statistics versus sky.\n\"\"\"\npsf = ag.Convolver.from_gaussian(\n shape_native=(11, 11), sigma=0.1, pixel_scales=grid.pixel_scales\n)\n\nsimulator = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\n\"\"\"\n__Galaxies__\n\nThe truth. `sersic_index` sets the profile's concentration — n ~ 4 is a de Vaucouleurs-like\nspheroid, n ~ 1 an exponential disk — and `effective_radius` is the radius containing half\nthe profile's light. For a *simulation* the axis-ratio and position-angle parameterisation is\nthe intuitive one, so `ag.convert.ell_comps_from` translates it into the `ell_comps` the\nprofile actually takes; a fit uses `ell_comps` directly, because a position angle's periodic\nboundary is pathological for a non-linear search\n(`PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py`).\n\"\"\"\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.8,\n sersic_index=4.0,\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy])\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\nprint(f\"peak signal-to-noise: {float(dataset.signal_to_noise_map.max()):.1f}\")\n\n\"\"\"\n__Output__\n\nThe FITS files are written in exactly the layout `ag.Imaging.from_fits` expects, so the\nsimulated dataset is indistinguishable from real data to everything downstream. The\n`galaxies.json` record is the part people skip and regret: it stores the true light profiles\nso that months later you can still state what the fit was supposed to recover. Load it back\nwith `ag.from_json`.\n\"\"\"\naplt.fits_imaging(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n overwrite=True,\n)\n\nag.output_to_json(obj=galaxies, file_path=DATASET_PATH / \"galaxies.json\")\n\naplt.subplot_imaging_dataset(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\naplt.subplot_galaxies(\n galaxies=galaxies, grid=grid, output_path=DATASET_PATH, output_format=\"png\"\n)\n\nprint(f\"Saved to: {DATASET_PATH.resolve()}\")\n```\n\nQuote that path back and offer to open it once. The `subplot_galaxies` figure is the useful\none for a simulation: it shows the noise-free truth beside the profile's components, which\nis what you compare a fit against.\n\n## Branch — bulge, disk, and a contaminating neighbour\n\nThe realistic default. Two components let you pose the question galaxy morphology usually\ncares about — the bulge-to-total light ratio — and a faint offset neighbour lets you\nrehearse the noise-scaling step. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator.py`.\n\n```python\nextra_galaxy_centre = (2.2, 1.6)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0), extra_galaxy_centre],\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n disk=ag.lp.Exponential(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.7, angle=30.0),\n intensity=0.5,\n effective_radius=1.6,\n ),\n)\n\nextra_galaxy = ag.Galaxy(\n redshift=0.5,\n light=ag.lp.ExponentialSph(\n centre=extra_galaxy_centre, intensity=1.0, effective_radius=0.3\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy, extra_galaxy])\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\nThree details carry weight. The bulge is compact with a high `sersic_index` and the disk is\nextended with n fixed at 1 by construction — that contrast is what makes the decomposition\nidentifiable at all. The neighbour's centre appears in `centre_list` as well as in its own\nprofile, so it is over-sampled properly rather than being the one badly-evaluated object in\nthe frame. And the attribute names (`bulge`, `disk`, `light`) are arbitrary labels you choose\n— name them for what they measure.\n\nWrite the neighbour's noise-scaling mask in the same script, so the modelling examples can\nload it without a separate preparation step:\n\n```python\nmask_extra_galaxies = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n centre=extra_galaxy_centre,\n radius=3.0 * 0.3, # ~3x the neighbour's effective radius\n invert=True, # `True` inside the circle: the region whose noise is scaled.\n)\n\naplt.fits_array(\n array=mask_extra_galaxies,\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n overwrite=True,\n)\n```\n\nDeriving the radius from the neighbour's own `effective_radius` keeps the two in sync if you\nlater change it. The strategies this mask feeds into are\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch — target a signal-to-noise ratio directly\n\nOften the question is not \"what intensity?\" but \"what if this galaxy were detected at S/N =\n20?\". Choosing an `intensity` that lands there is guesswork; the `lp_snr` profiles remove it\nby solving for the intensity that achieves a requested ratio, using the simulator's\n`exposure_time` and `background_sky_level` to do so. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/simulator_manual_signal_to_noise.py`.\n\n```python\ngalaxy_0 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=20.0,\n centre=(0.0, -1.0),\n ell_comps=(0.25, 0.1),\n effective_radius=0.8,\n sersic_index=2.5,\n ),\n)\n\ngalaxy_1 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=10.0,\n centre=(0.0, 1.0),\n ell_comps=(0.0, 0.1),\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n)\n\ndataset = simulator.via_galaxies_from(\n galaxies=ag.Galaxies(galaxies=[galaxy_0, galaxy_1]), grid=grid\n)\n```\n\nNote the profiles take **no** `intensity` — that is the parameter being solved for. The\ntrade-off is that `exposure_time` and `background_sky_level` no longer set the S/N, only the\n*balance* between counting noise and sky noise. So they still matter for realism: doubling\nthe exposure time shifts the noise budget toward Poisson statistics even though the S/N is\npinned. Choose them to match your instrument if the noise character matters to the study.\n\nThis is also the profile family to reach for in a feasibility question — simulate the same\ngalaxy at S/N 10, 20 and 50, fit each, and see where the parameter you care about stops\nbeing constrained. That is a far more honest answer than a single simulation at whatever\nintensity happened to be typed.\n\n## Branch — a sample, for population or machine-learning work\n\nTo generate many galaxies, draw each one's parameters from a distribution and loop. Adapted\nfrom `autogalaxy_workspace:scripts/imaging/simulator_sample.py`, which draws directly from a\nNumPy generator — deliberately, because these are *truths* for synthetic data, not a model\nbeing fitted, so there is no reason to involve the model-composition API.\n\n```python\nimport numpy as np\n\nrng = np.random.default_rng()\n\n\ndef _clipped_ell_comp() -> float:\n return float(np.clip(rng.normal(0.0, 0.2), -1.0, 1.0))\n\n\ndef _random_galaxy() -> ag.Galaxy:\n bulge = ag.lp_snr.Sersic(\n centre=(0.0, 0.0),\n ell_comps=(_clipped_ell_comp(), _clipped_ell_comp()),\n effective_radius=float(rng.uniform(1.0, 5.0)),\n sersic_index=float(np.clip(rng.normal(4.0, 1.0), 0.8, 5.0)),\n signal_to_noise_ratio=float(rng.uniform(20.0, 60.0)),\n )\n return ag.Galaxy(redshift=0.5, bulge=bulge)\n\n\ntotal_datasets = 3\n\nfor sample_index in range(total_datasets):\n\n sample_path = DATASET_PATH / f\"dataset_{sample_index}\"\n\n galaxies = ag.Galaxies(galaxies=[_random_galaxy()])\n dataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\n aplt.fits_imaging(\n dataset=dataset,\n data_path=sample_path / \"data.fits\",\n psf_path=sample_path / \"psf.fits\",\n noise_map_path=sample_path / \"noise_map.fits\",\n overwrite=True,\n )\n ag.output_to_json(obj=galaxies, file_path=sample_path / \"galaxies.json\")\n```\n\nThe `lp_snr` bulge is what makes the loop usable: with a plain `intensity` drawn from a\ndistribution, a fraction of your sample would be invisible and another fraction saturated.\nPinning S/N per galaxy guarantees every image is detectable. Write a `galaxies.json` per\ndataset — with a sample, the truth record stops being a nicety and becomes the labels.\n\nFor a one-line random galaxy without writing your own distributions,\n`ag.model_util.random_galaxy_for_simulation_from()` returns one drawn from the library's own\nchoices, and `ag.model_util.SIMULATOR_RANDOM_GALAXY_SUMMARY` prints what those choices are —\nread that summary before using it in anything you will publish, so the prior you inherited\nis one you actually endorse.\n\n## Branch — interferometer visibilities\n\nFor sub-mm and radio data (ALMA, JVLA, LOFAR) the observable is visibilities in the uv-plane,\nnot an image, and fitting them there avoids the correlated noise a dirty image carries.\nAdapted from `autogalaxy_workspace:scripts/interferometer/simulator.py`.\n\n```python\nuv_wavelengths = ag.ndarray_via_fits_from(\n file_path=Path(\"dataset\") / \"interferometer\" / \"uv_wavelengths\" / \"sma.fits\", hdu=0\n)\n\nsimulator = ag.SimulatorInterferometer(\n uv_wavelengths=uv_wavelengths,\n exposure_time=300.0,\n noise_sigma=1000.0,\n transformer_class=ag.TransformerNUFFT,\n)\n\nreal_space_grid = ag.Grid2D.uniform(shape_native=(800, 800), pixel_scales=0.05)\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=real_space_grid)\n\naplt.subplot_interferometer_dirty_images(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\n\naplt.fits_interferometer(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n uv_wavelengths_path=DATASET_PATH / \"uv_wavelengths.fits\",\n overwrite=True,\n)\n```\n\nFour differences from imaging are worth knowing. The baselines come from a real array's\n`uv_wavelengths` — the workspace ships SMA (low resolution, very fast) and ALMA files;\nswapping the file swaps the instrument. There is **no PSF and no over-sampling**: the image\nis evaluated in real space and Fourier-transformed, and interferometers do not observe in a\nway that makes over-sampling necessary. `noise_sigma` replaces the exposure-time-driven\nPoisson model. And the thing you *look at* is the dirty image, which is a diagnostic — the\nfit itself happens in the uv-plane. The physics is\n[`../wiki/core/concepts/interferometer_theory.md`](../wiki/core/concepts/interferometer_theory.md).\nFull interferometer modelling is a separate skill,\n[`ag_build_interferometer_model`](./ag_build_interferometer_model.md).\n\n## The auto-simulation convention\n\nEvery workspace script that fits a dataset first checks whether it exists and runs the\nmatching simulator if it does not, so an example can be run from a fresh clone with no\nmanual step:\n\n```python\nif ag.util.dataset.should_simulate(str(dataset_path)):\n import subprocess\n import sys\n\n subprocess.run([sys.executable, \"scripts/imaging/simulator.py\"], check=True)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py`. Adopt the same pattern in\nscripts you write, and know the sharp edge: `should_simulate` tests **existence**, not\nwhether the dataset on disk matches the simulator that would produce it. Change the\nsimulator's parameters and re-run the fit and you will silently fit the *old* data. The same\napplies to `PYAUTO_SMALL_DATASETS=1`, which caps grids and masks to a small size: a\nfull-resolution dataset already on disk will be reused and mismatch the capped grids. Delete\nthe dataset directory when you change either\n([`../wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## JAX, for many simulations\n\nFor parameter sweeps, mock-data studies or batch figure generation, build the simulator with\n`use_jax=True` — the simulation then runs on JAX arrays (and the GPU, when one is\nconfigured):\n\n```python\nsimulator_jax = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n use_jax=True,\n)\n\ndataset_jax = simulator_jax.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\n`dataset_jax.data.array` is a `jax.Array`, and the plot and FITS helpers call\n`numpy.asarray()` internally, so saving and plotting need no manual conversion.\n\nWrapping the whole simulation call in a jitted function — worth it across *many* calls —\nadditionally requires registering the galaxy classes as JAX pytrees before the first jitted\ncall, and the helper that does that registration is **not in the released stack yet** (it\nlives on the libraries' development branches only). Until it ships in a release, use the\neager `use_jax=True` call above; the `__JAX Variant__` section of\n`autogalaxy_workspace:scripts/imaging/simulator.py` carries the jitted recipe for a\nsource install. **For interferometer simulations the jitted path does not work either way** —\nuse the eager call; `autogalaxy_workspace:scripts/interferometer/simulator.py` documents why.\n\n## Combine — where this hands off\n\n- **Fit the dataset you just made** → [`ag_build_imaging_model`](./ag_build_imaging_model.md)\n to compose the model, then [`ag_configure_search`](./ag_configure_search.md) and the\n run-search skill (`ag_run_search`). Compose a model that *matches* the truth first: if it\n cannot recover parameters it was handed exactly, the problem is the inference, and you have\n learned that cheaply.\n- **Compare a fit against the truth** → load `galaxies.json` with `ag.from_json` and put the\n true and inferred values side by side; the results-loading and fit-plotting skills\n (`ag_load_results`, `ag_plot_fit`) do the rest.\n- **You actually have real data** → [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md),\n which also owns the inspection gate this branch is exempt from.\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry when the simulation is\npart of a study — the truth parameters and the S/N you chose *are* the experimental design,\nand a recovery test is meaningless later without them.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Grids and galaxies](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb):\n how a light profile becomes an image on a grid, and what each Sersic parameter changes —\n the foundation under every simulation.\n- **General reference** — [RTD: Start here overview](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the core API end to end, including the simulation section, in one page.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/simulator.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/simulator.py):\n the full bulge-plus-disk simulator with the contaminant mask and the executed JAX variant.\n\n## Agent procedural checklist\n\n1. Ask what the simulation is *for*; it decides the branch and whether `lp_snr` is wanted.\n2. Set `pixel_scales`, PSF width and exposure time from a real instrument, not defaults.\n3. Over-sample with every bright centre in `centre_list` — including any neighbour.\n4. Write FITS **and** `galaxies.json`; write the neighbour's `mask_extra_galaxies.fits` in\n the same script if one exists.\n5. Plot the dataset and the noise-free galaxies subplot; print and **quote** the absolute\n path, offering to open it once.\n6. Delete the dataset directory before re-running with changed parameters or with\n `PYAUTO_SMALL_DATASETS=1` — `should_simulate` only checks existence.\n7. Hand off to `ag_build_imaging_model`, and offer the `wiki/project/` entry when the\n simulation is part of a study.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/simulators/simple.ipynb b/notebooks/simulators/simple.ipynb index 535341a..dff632d 100644 --- a/notebooks/simulators/simple.ipynb +++ b/notebooks/simulators/simple.ipynb @@ -29,21 +29,21 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n", @@ -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/simulators/simple.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_simulate_dataset\n\n---\nname: ag_simulate_dataset\ndescription: Simulate CCD imaging (or interferometer visibilities) of a galaxy with known truth \u2014 a grid and over-sampling, a PSF, an exposure time and background sky, one or more galaxies built from light profiles, then FITS output plus a `galaxies.json` truth record. Covers targeting a signal-to-noise ratio directly with the `lp_snr` profiles, simulating a whole sample in a loop for population or machine-learning work, adding a contaminating extra galaxy with its noise-scaling mask, and the `should_simulate` auto-simulation convention every workspace script uses. Use to rehearse the modelling loop before real data, to build training sets, to test a recovery, or when a user has no data yet. Not for loading or preparing real observations (`ag_prepare_imaging_data`), and not for fitting.\n---\n\n# Simulating a galaxy dataset with known truth\n\nA simulated dataset is the only situation in galaxy modelling where you know the answer.\nThat makes it worth far more than a convenience: it is how you establish that your model\ncan recover a parameter at all, how you find out what signal-to-noise you need before you\npropose for telescope time, how you separate \"the fit is wrong\" from \"the data cannot\nconstrain this\", and how you generate the thousands of labelled images a neural network\nneeds. It is also the fastest way to rehearse the whole loop \u2014 compose, search, inspect \u2014\nbefore real data is at stake.\n\nStatistically, what you are building is a draw from the likelihood's own generative model:\ntake a noise-free galaxy image, convolve it with the PSF, scale to counts through an\nexposure time, add a background sky, and draw Poisson noise. Because that is exactly the\nforward model the likelihood inverts, a fit to simulated data tests the *inference* in\nisolation \u2014 any bias you find is yours, not the data's. Simulated data is also **exempt from\nthe real-data inspection gate** (see\n[`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md)) for the same reason: you already\nknow where every component is.\n\nThe canonical scripts are `autogalaxy_workspace:scripts/imaging/simulator.py` (bulge, disk\nand a contaminating neighbour) and `autogalaxy_workspace:scripts/imaging/simulator_sersic.py`\n(a single Sersic). What each light profile means physically is\n[`../wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md); the\ndataset objects are [`../wiki/core/api/datasets.md`](../wiki/core/api/datasets.md).\n\n## Ask\n\n- *\"What are you simulating for \u2014 rehearsing the workflow, a recovery test, a training set,\n or a signal-to-noise feasibility study?\"* This picks the branch, and the last two change\n the API you want (`lp_snr`, and the sample loop).\n- *\"One galaxy or several, and should a contaminating neighbour be included?\"* Including one\n is worth doing deliberately: it is how you rehearse the noise-scaling step you will\n certainly need on real data.\n- *\"What instrument are you standing in for?\"* \u2014 it sets `pixel_scales`, the PSF width and a\n plausible exposure time, and makes the simulation answer a question about *your* telescope\n rather than an abstract one.\n\n## Branch \u2014 a single Sersic\n\nThe smallest useful simulation, and the one to start from. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator_sersic.py`.\n\n```python\n\"\"\"\nSimulator: Single Sersic\n========================\n\nSimulate CCD imaging of a galaxy whose light is a single elliptical Sersic profile, with\nknown truth parameters recorded alongside the data. The simulation applies the same forward\nmodel a fit inverts \u2014 evaluate the profile on an over-sampled grid, convolve with the PSF,\nscale through an exposure time, add a background sky and draw Poisson noise \u2014 so a fit to\nthe output tests the inference rather than the data.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Grid:** Build the coordinate grid and its adaptive over-sampling.\n- **PSF and Simulator:** Define the optical blurring and the noise properties.\n- **Galaxies:** Define the true galaxy whose parameters we intend to recover.\n- **Output:** Write the dataset to FITS, plus a `galaxies.json` record of the truth.\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\" / \"simple_sersic\"\n\n\"\"\"\n__Grid__\n\nThe `Grid2D` is the set of (y,x) arcsecond coordinates the galaxy's light is evaluated on,\nand `pixel_scales` ties it to a detector \u2014 set it to the instrument you are standing in for.\nOver-sampling then evaluates the profile on a finer sub-grid where its intensity gradient is\nsteep: a Sersic varies enormously across the central pixel, so a single evaluation at the\npixel centre under-counts the flux and produces a subtly wrong image. Simulations use higher\nsub-sampling than fits (32x32 in the centre rather than 8x8) because the cost is paid once\nrather than at every likelihood call\n(`PyAutoArray:autoarray/operators/over_sampling/over_sample_util.py`).\n\"\"\"\ngrid = ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.1)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n\"\"\"\n__PSF and Simulator__\n\nEvery real CCD image is blurred by the telescope optics, so a simulation without a PSF is not\nimaging data. A Gaussian kernel is a reasonable stand-in when you do not have a real PSF\n(FWHM = 2.35 * sigma). The `SimulatorImaging` object then supplies the rest of what makes\ndata noisy rather than ideal: `exposure_time` converts electrons per second to counts and so\nsets the Poisson noise level, and `background_sky_level` adds the sky's contribution to the\nnoise budget (`PyAutoArray:autoarray/dataset/imaging/simulator.py`). Raising the exposure\ntime raises the signal-to-noise; the ratio of the two controls how much of the noise is\ncounting statistics versus sky.\n\"\"\"\npsf = ag.Convolver.from_gaussian(\n shape_native=(11, 11), sigma=0.1, pixel_scales=grid.pixel_scales\n)\n\nsimulator = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\n\"\"\"\n__Galaxies__\n\nThe truth. `sersic_index` sets the profile's concentration \u2014 n ~ 4 is a de Vaucouleurs-like\nspheroid, n ~ 1 an exponential disk \u2014 and `effective_radius` is the radius containing half\nthe profile's light. For a *simulation* the axis-ratio and position-angle parameterisation is\nthe intuitive one, so `ag.convert.ell_comps_from` translates it into the `ell_comps` the\nprofile actually takes; a fit uses `ell_comps` directly, because a position angle's periodic\nboundary is pathological for a non-linear search\n(`PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py`).\n\"\"\"\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.8,\n sersic_index=4.0,\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy])\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\nprint(f\"peak signal-to-noise: {float(dataset.signal_to_noise_map.max()):.1f}\")\n\n\"\"\"\n__Output__\n\nThe FITS files are written in exactly the layout `ag.Imaging.from_fits` expects, so the\nsimulated dataset is indistinguishable from real data to everything downstream. The\n`galaxies.json` record is the part people skip and regret: it stores the true light profiles\nso that months later you can still state what the fit was supposed to recover. Load it back\nwith `ag.from_json`.\n\"\"\"\naplt.fits_imaging(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n overwrite=True,\n)\n\nag.output_to_json(obj=galaxies, file_path=DATASET_PATH / \"galaxies.json\")\n\naplt.subplot_imaging_dataset(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\naplt.subplot_galaxies(\n galaxies=galaxies, grid=grid, output_path=DATASET_PATH, output_format=\"png\"\n)\n\nprint(f\"Saved to: {DATASET_PATH.resolve()}\")\n```\n\nQuote that path back and offer to open it once. The `subplot_galaxies` figure is the useful\none for a simulation: it shows the noise-free truth beside the profile's components, which\nis what you compare a fit against.\n\n## Branch \u2014 bulge, disk, and a contaminating neighbour\n\nThe realistic default. Two components let you pose the question galaxy morphology usually\ncares about \u2014 the bulge-to-total light ratio \u2014 and a faint offset neighbour lets you\nrehearse the noise-scaling step. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator.py`.\n\n```python\nextra_galaxy_centre = (2.2, 1.6)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0), extra_galaxy_centre],\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n disk=ag.lp.Exponential(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.7, angle=30.0),\n intensity=0.5,\n effective_radius=1.6,\n ),\n)\n\nextra_galaxy = ag.Galaxy(\n redshift=0.5,\n light=ag.lp.ExponentialSph(\n centre=extra_galaxy_centre, intensity=1.0, effective_radius=0.3\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy, extra_galaxy])\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\nThree details carry weight. The bulge is compact with a high `sersic_index` and the disk is\nextended with n fixed at 1 by construction \u2014 that contrast is what makes the decomposition\nidentifiable at all. The neighbour's centre appears in `centre_list` as well as in its own\nprofile, so it is over-sampled properly rather than being the one badly-evaluated object in\nthe frame. And the attribute names (`bulge`, `disk`, `light`) are arbitrary labels you choose\n\u2014 name them for what they measure.\n\nWrite the neighbour's noise-scaling mask in the same script, so the modelling examples can\nload it without a separate preparation step:\n\n```python\nmask_extra_galaxies = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n centre=extra_galaxy_centre,\n radius=3.0 * 0.3, # ~3x the neighbour's effective radius\n invert=True, # `True` inside the circle: the region whose noise is scaled.\n)\n\naplt.fits_array(\n array=mask_extra_galaxies,\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n overwrite=True,\n)\n```\n\nDeriving the radius from the neighbour's own `effective_radius` keeps the two in sync if you\nlater change it. The strategies this mask feeds into are\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch \u2014 target a signal-to-noise ratio directly\n\nOften the question is not \"what intensity?\" but \"what if this galaxy were detected at S/N =\n20?\". Choosing an `intensity` that lands there is guesswork; the `lp_snr` profiles remove it\nby solving for the intensity that achieves a requested ratio, using the simulator's\n`exposure_time` and `background_sky_level` to do so. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/simulator_manual_signal_to_noise.py`.\n\n```python\ngalaxy_0 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=20.0,\n centre=(0.0, -1.0),\n ell_comps=(0.25, 0.1),\n effective_radius=0.8,\n sersic_index=2.5,\n ),\n)\n\ngalaxy_1 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=10.0,\n centre=(0.0, 1.0),\n ell_comps=(0.0, 0.1),\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n)\n\ndataset = simulator.via_galaxies_from(\n galaxies=ag.Galaxies(galaxies=[galaxy_0, galaxy_1]), grid=grid\n)\n```\n\nNote the profiles take **no** `intensity` \u2014 that is the parameter being solved for. The\ntrade-off is that `exposure_time` and `background_sky_level` no longer set the S/N, only the\n*balance* between counting noise and sky noise. So they still matter for realism: doubling\nthe exposure time shifts the noise budget toward Poisson statistics even though the S/N is\npinned. Choose them to match your instrument if the noise character matters to the study.\n\nThis is also the profile family to reach for in a feasibility question \u2014 simulate the same\ngalaxy at S/N 10, 20 and 50, fit each, and see where the parameter you care about stops\nbeing constrained. That is a far more honest answer than a single simulation at whatever\nintensity happened to be typed.\n\n## Branch \u2014 a sample, for population or machine-learning work\n\nTo generate many galaxies, draw each one's parameters from a distribution and loop. Adapted\nfrom `autogalaxy_workspace:scripts/imaging/simulator_sample.py`, which draws directly from a\nNumPy generator \u2014 deliberately, because these are *truths* for synthetic data, not a model\nbeing fitted, so there is no reason to involve the model-composition API.\n\n```python\nimport numpy as np\n\nrng = np.random.default_rng()\n\n\ndef _clipped_ell_comp() -> float:\n return float(np.clip(rng.normal(0.0, 0.2), -1.0, 1.0))\n\n\ndef _random_galaxy() -> ag.Galaxy:\n bulge = ag.lp_snr.Sersic(\n centre=(0.0, 0.0),\n ell_comps=(_clipped_ell_comp(), _clipped_ell_comp()),\n effective_radius=float(rng.uniform(1.0, 5.0)),\n sersic_index=float(np.clip(rng.normal(4.0, 1.0), 0.8, 5.0)),\n signal_to_noise_ratio=float(rng.uniform(20.0, 60.0)),\n )\n return ag.Galaxy(redshift=0.5, bulge=bulge)\n\n\ntotal_datasets = 3\n\nfor sample_index in range(total_datasets):\n\n sample_path = DATASET_PATH / f\"dataset_{sample_index}\"\n\n galaxies = ag.Galaxies(galaxies=[_random_galaxy()])\n dataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\n aplt.fits_imaging(\n dataset=dataset,\n data_path=sample_path / \"data.fits\",\n psf_path=sample_path / \"psf.fits\",\n noise_map_path=sample_path / \"noise_map.fits\",\n overwrite=True,\n )\n ag.output_to_json(obj=galaxies, file_path=sample_path / \"galaxies.json\")\n```\n\nThe `lp_snr` bulge is what makes the loop usable: with a plain `intensity` drawn from a\ndistribution, a fraction of your sample would be invisible and another fraction saturated.\nPinning S/N per galaxy guarantees every image is detectable. Write a `galaxies.json` per\ndataset \u2014 with a sample, the truth record stops being a nicety and becomes the labels.\n\nFor a one-line random galaxy without writing your own distributions,\n`ag.model_util.random_galaxy_for_simulation_from()` returns one drawn from the library's own\nchoices, and `ag.model_util.SIMULATOR_RANDOM_GALAXY_SUMMARY` prints what those choices are \u2014\nread that summary before using it in anything you will publish, so the prior you inherited\nis one you actually endorse.\n\n## Branch \u2014 interferometer visibilities\n\nFor sub-mm and radio data (ALMA, JVLA, LOFAR) the observable is visibilities in the uv-plane,\nnot an image, and fitting them there avoids the correlated noise a dirty image carries.\nAdapted from `autogalaxy_workspace:scripts/interferometer/simulator.py`.\n\n```python\nuv_wavelengths = ag.ndarray_via_fits_from(\n file_path=Path(\"dataset\") / \"interferometer\" / \"uv_wavelengths\" / \"sma.fits\", hdu=0\n)\n\nsimulator = ag.SimulatorInterferometer(\n uv_wavelengths=uv_wavelengths,\n exposure_time=300.0,\n noise_sigma=1000.0,\n transformer_class=ag.TransformerNUFFT,\n)\n\nreal_space_grid = ag.Grid2D.uniform(shape_native=(800, 800), pixel_scales=0.05)\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=real_space_grid)\n\naplt.subplot_interferometer_dirty_images(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\n\naplt.fits_interferometer(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n uv_wavelengths_path=DATASET_PATH / \"uv_wavelengths.fits\",\n overwrite=True,\n)\n```\n\nFour differences from imaging are worth knowing. The baselines come from a real array's\n`uv_wavelengths` \u2014 the workspace ships SMA (low resolution, very fast) and ALMA files;\nswapping the file swaps the instrument. There is **no PSF and no over-sampling**: the image\nis evaluated in real space and Fourier-transformed, and interferometers do not observe in a\nway that makes over-sampling necessary. `noise_sigma` replaces the exposure-time-driven\nPoisson model. And the thing you *look at* is the dirty image, which is a diagnostic \u2014 the\nfit itself happens in the uv-plane. The physics is\n[`../wiki/core/concepts/interferometer_theory.md`](../wiki/core/concepts/interferometer_theory.md).\nFull interferometer modelling is a separate skill,\n[`ag_build_interferometer_model`](./ag_build_interferometer_model.md).\n\n## The auto-simulation convention\n\nEvery workspace script that fits a dataset first checks whether it exists and runs the\nmatching simulator if it does not, so an example can be run from a fresh clone with no\nmanual step:\n\n```python\nif ag.util.dataset.should_simulate(str(dataset_path)):\n import subprocess\n import sys\n\n subprocess.run([sys.executable, \"scripts/imaging/simulator.py\"], check=True)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py`. Adopt the same pattern in\nscripts you write, and know the sharp edge: `should_simulate` tests **existence**, not\nwhether the dataset on disk matches the simulator that would produce it. Change the\nsimulator's parameters and re-run the fit and you will silently fit the *old* data. The same\napplies to `PYAUTO_SMALL_DATASETS=1`, which caps grids and masks to a small size: a\nfull-resolution dataset already on disk will be reused and mismatch the capped grids. Delete\nthe dataset directory when you change either\n([`../wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## JAX, for many simulations\n\nFor parameter sweeps, mock-data studies or batch figure generation, build the simulator with\n`use_jax=True` \u2014 the simulation then runs on JAX arrays (and the GPU, when one is\nconfigured):\n\n```python\nsimulator_jax = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n use_jax=True,\n)\n\ndataset_jax = simulator_jax.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\n`dataset_jax.data.array` is a `jax.Array`, and the plot and FITS helpers call\n`numpy.asarray()` internally, so saving and plotting need no manual conversion.\n\nWrapping the whole simulation call in a jitted function \u2014 worth it across *many* calls \u2014\nadditionally requires registering the galaxy classes as JAX pytrees before the first jitted\ncall, and the helper that does that registration is **not in the released stack yet** (it\nlives on the libraries' development branches only). Until it ships in a release, use the\neager `use_jax=True` call above; the `__JAX Variant__` section of\n`autogalaxy_workspace:scripts/imaging/simulator.py` carries the jitted recipe for a\nsource install. **For interferometer simulations the jitted path does not work either way** \u2014\nuse the eager call; `autogalaxy_workspace:scripts/interferometer/simulator.py` documents why.\n\n## Combine \u2014 where this hands off\n\n- **Fit the dataset you just made** \u2192 [`ag_build_imaging_model`](./ag_build_imaging_model.md)\n to compose the model, then [`ag_configure_search`](./ag_configure_search.md) and the\n run-search skill (`ag_run_search`). Compose a model that *matches* the truth first: if it\n cannot recover parameters it was handed exactly, the problem is the inference, and you have\n learned that cheaply.\n- **Compare a fit against the truth** \u2192 load `galaxies.json` with `ag.from_json` and put the\n true and inferred values side by side; the results-loading and fit-plotting skills\n (`ag_load_results`, `ag_plot_fit`) do the rest.\n- **You actually have real data** \u2192 [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md),\n which also owns the inspection gate this branch is exempt from.\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry when the simulation is\npart of a study \u2014 the truth parameters and the S/N you chose *are* the experimental design,\nand a recovery test is meaningless later without them.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [HowToGalaxy: Grids and galaxies](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb):\n how a light profile becomes an image on a grid, and what each Sersic parameter changes \u2014\n the foundation under every simulation.\n- **General reference** \u2014 [RTD: Start here overview](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the core API end to end, including the simulation section, in one page.\n- **Experienced PyAutoGalaxy user** \u2014 [workspace: imaging/simulator.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/simulator.py):\n the full bulge-plus-disk simulator with the contaminant mask and the executed JAX variant.\n\n## Agent procedural checklist\n\n1. Ask what the simulation is *for*; it decides the branch and whether `lp_snr` is wanted.\n2. Set `pixel_scales`, PSF width and exposure time from a real instrument, not defaults.\n3. Over-sample with every bright centre in `centre_list` \u2014 including any neighbour.\n4. Write FITS **and** `galaxies.json`; write the neighbour's `mask_extra_galaxies.fits` in\n the same script if one exists.\n5. Plot the dataset and the noise-free galaxies subplot; print and **quote** the absolute\n path, offering to open it once.\n6. Delete the dataset directory before re-running with changed parameters or with\n `PYAUTO_SMALL_DATASETS=1` \u2014 `should_simulate` only checks existence.\n7. Hand off to `ag_build_imaging_model`, and offer the `wiki/project/` entry when the\n simulation is part of a study.\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/simulators/simple.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_simulate_dataset\n\n---\nname: ag_simulate_dataset\ndescription: Simulate CCD imaging (or interferometer visibilities) of a galaxy with known truth — a grid and over-sampling, a PSF, an exposure time and background sky, one or more galaxies built from light profiles, then FITS output plus a `galaxies.json` truth record. Covers targeting a signal-to-noise ratio directly with the `lp_snr` profiles, simulating a whole sample in a loop for population or machine-learning work, adding a contaminating extra galaxy with its noise-scaling mask, and the `should_simulate` auto-simulation convention every workspace script uses. Use to rehearse the modelling loop before real data, to build training sets, to test a recovery, or when a user has no data yet. Not for loading or preparing real observations (`ag_prepare_imaging_data`), and not for fitting.\n---\n\n# Simulating a galaxy dataset with known truth\n\nA simulated dataset is the only situation in galaxy modelling where you know the answer.\nThat makes it worth far more than a convenience: it is how you establish that your model\ncan recover a parameter at all, how you find out what signal-to-noise you need before you\npropose for telescope time, how you separate \"the fit is wrong\" from \"the data cannot\nconstrain this\", and how you generate the thousands of labelled images a neural network\nneeds. It is also the fastest way to rehearse the whole loop — compose, search, inspect —\nbefore real data is at stake.\n\nStatistically, what you are building is a draw from the likelihood's own generative model:\ntake a noise-free galaxy image, convolve it with the PSF, scale to counts through an\nexposure time, add a background sky, and draw Poisson noise. Because that is exactly the\nforward model the likelihood inverts, a fit to simulated data tests the *inference* in\nisolation — any bias you find is yours, not the data's. Simulated data is also **exempt from\nthe real-data inspection gate** (see\n[`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md)) for the same reason: you already\nknow where every component is.\n\nThe canonical scripts are `autogalaxy_workspace:scripts/imaging/simulator.py` (bulge, disk\nand a contaminating neighbour) and `autogalaxy_workspace:scripts/imaging/simulator_sersic.py`\n(a single Sersic). What each light profile means physically is\n[`../wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md); the\ndataset objects are [`../wiki/core/api/datasets.md`](../wiki/core/api/datasets.md).\n\n## Ask\n\n- *\"What are you simulating for — rehearsing the workflow, a recovery test, a training set,\n or a signal-to-noise feasibility study?\"* This picks the branch, and the last two change\n the API you want (`lp_snr`, and the sample loop).\n- *\"One galaxy or several, and should a contaminating neighbour be included?\"* Including one\n is worth doing deliberately: it is how you rehearse the noise-scaling step you will\n certainly need on real data.\n- *\"What instrument are you standing in for?\"* — it sets `pixel_scales`, the PSF width and a\n plausible exposure time, and makes the simulation answer a question about *your* telescope\n rather than an abstract one.\n\n## Branch — a single Sersic\n\nThe smallest useful simulation, and the one to start from. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator_sersic.py`.\n\n```python\n\"\"\"\nSimulator: Single Sersic\n========================\n\nSimulate CCD imaging of a galaxy whose light is a single elliptical Sersic profile, with\nknown truth parameters recorded alongside the data. The simulation applies the same forward\nmodel a fit inverts — evaluate the profile on an over-sampled grid, convolve with the PSF,\nscale through an exposure time, add a background sky and draw Poisson noise — so a fit to\nthe output tests the inference rather than the data.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Grid:** Build the coordinate grid and its adaptive over-sampling.\n- **PSF and Simulator:** Define the optical blurring and the noise properties.\n- **Galaxies:** Define the true galaxy whose parameters we intend to recover.\n- **Output:** Write the dataset to FITS, plus a `galaxies.json` record of the truth.\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\" / \"simple_sersic\"\n\n\"\"\"\n__Grid__\n\nThe `Grid2D` is the set of (y,x) arcsecond coordinates the galaxy's light is evaluated on,\nand `pixel_scales` ties it to a detector — set it to the instrument you are standing in for.\nOver-sampling then evaluates the profile on a finer sub-grid where its intensity gradient is\nsteep: a Sersic varies enormously across the central pixel, so a single evaluation at the\npixel centre under-counts the flux and produces a subtly wrong image. Simulations use higher\nsub-sampling than fits (32x32 in the centre rather than 8x8) because the cost is paid once\nrather than at every likelihood call\n(`PyAutoArray:autoarray/operators/over_sampling/over_sample_util.py`).\n\"\"\"\ngrid = ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.1)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n\"\"\"\n__PSF and Simulator__\n\nEvery real CCD image is blurred by the telescope optics, so a simulation without a PSF is not\nimaging data. A Gaussian kernel is a reasonable stand-in when you do not have a real PSF\n(FWHM = 2.35 * sigma). The `SimulatorImaging` object then supplies the rest of what makes\ndata noisy rather than ideal: `exposure_time` converts electrons per second to counts and so\nsets the Poisson noise level, and `background_sky_level` adds the sky's contribution to the\nnoise budget (`PyAutoArray:autoarray/dataset/imaging/simulator.py`). Raising the exposure\ntime raises the signal-to-noise; the ratio of the two controls how much of the noise is\ncounting statistics versus sky.\n\"\"\"\npsf = ag.Convolver.from_gaussian(\n shape_native=(11, 11), sigma=0.1, pixel_scales=grid.pixel_scales\n)\n\nsimulator = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\n\"\"\"\n__Galaxies__\n\nThe truth. `sersic_index` sets the profile's concentration — n ~ 4 is a de Vaucouleurs-like\nspheroid, n ~ 1 an exponential disk — and `effective_radius` is the radius containing half\nthe profile's light. For a *simulation* the axis-ratio and position-angle parameterisation is\nthe intuitive one, so `ag.convert.ell_comps_from` translates it into the `ell_comps` the\nprofile actually takes; a fit uses `ell_comps` directly, because a position angle's periodic\nboundary is pathological for a non-linear search\n(`PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py`).\n\"\"\"\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.8,\n sersic_index=4.0,\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy])\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\nprint(f\"peak signal-to-noise: {float(dataset.signal_to_noise_map.max()):.1f}\")\n\n\"\"\"\n__Output__\n\nThe FITS files are written in exactly the layout `ag.Imaging.from_fits` expects, so the\nsimulated dataset is indistinguishable from real data to everything downstream. The\n`galaxies.json` record is the part people skip and regret: it stores the true light profiles\nso that months later you can still state what the fit was supposed to recover. Load it back\nwith `ag.from_json`.\n\"\"\"\naplt.fits_imaging(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n overwrite=True,\n)\n\nag.output_to_json(obj=galaxies, file_path=DATASET_PATH / \"galaxies.json\")\n\naplt.subplot_imaging_dataset(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\naplt.subplot_galaxies(\n galaxies=galaxies, grid=grid, output_path=DATASET_PATH, output_format=\"png\"\n)\n\nprint(f\"Saved to: {DATASET_PATH.resolve()}\")\n```\n\nQuote that path back and offer to open it once. The `subplot_galaxies` figure is the useful\none for a simulation: it shows the noise-free truth beside the profile's components, which\nis what you compare a fit against.\n\n## Branch — bulge, disk, and a contaminating neighbour\n\nThe realistic default. Two components let you pose the question galaxy morphology usually\ncares about — the bulge-to-total light ratio — and a faint offset neighbour lets you\nrehearse the noise-scaling step. Adapted from\n`autogalaxy_workspace:scripts/imaging/simulator.py`.\n\n```python\nextra_galaxy_centre = (2.2, 1.6)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid,\n sub_size_list=[32, 8, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0), extra_galaxy_centre],\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\ngalaxy = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp.Sersic(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0),\n intensity=1.0,\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n disk=ag.lp.Exponential(\n centre=(0.0, 0.0),\n ell_comps=ag.convert.ell_comps_from(axis_ratio=0.7, angle=30.0),\n intensity=0.5,\n effective_radius=1.6,\n ),\n)\n\nextra_galaxy = ag.Galaxy(\n redshift=0.5,\n light=ag.lp.ExponentialSph(\n centre=extra_galaxy_centre, intensity=1.0, effective_radius=0.3\n ),\n)\n\ngalaxies = ag.Galaxies(galaxies=[galaxy, extra_galaxy])\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\nThree details carry weight. The bulge is compact with a high `sersic_index` and the disk is\nextended with n fixed at 1 by construction — that contrast is what makes the decomposition\nidentifiable at all. The neighbour's centre appears in `centre_list` as well as in its own\nprofile, so it is over-sampled properly rather than being the one badly-evaluated object in\nthe frame. And the attribute names (`bulge`, `disk`, `light`) are arbitrary labels you choose\n— name them for what they measure.\n\nWrite the neighbour's noise-scaling mask in the same script, so the modelling examples can\nload it without a separate preparation step:\n\n```python\nmask_extra_galaxies = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n centre=extra_galaxy_centre,\n radius=3.0 * 0.3, # ~3x the neighbour's effective radius\n invert=True, # `True` inside the circle: the region whose noise is scaled.\n)\n\naplt.fits_array(\n array=mask_extra_galaxies,\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n overwrite=True,\n)\n```\n\nDeriving the radius from the neighbour's own `effective_radius` keeps the two in sync if you\nlater change it. The strategies this mask feeds into are\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch — target a signal-to-noise ratio directly\n\nOften the question is not \"what intensity?\" but \"what if this galaxy were detected at S/N =\n20?\". Choosing an `intensity` that lands there is guesswork; the `lp_snr` profiles remove it\nby solving for the intensity that achieves a requested ratio, using the simulator's\n`exposure_time` and `background_sky_level` to do so. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/simulator_manual_signal_to_noise.py`.\n\n```python\ngalaxy_0 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=20.0,\n centre=(0.0, -1.0),\n ell_comps=(0.25, 0.1),\n effective_radius=0.8,\n sersic_index=2.5,\n ),\n)\n\ngalaxy_1 = ag.Galaxy(\n redshift=0.5,\n bulge=ag.lp_snr.Sersic(\n signal_to_noise_ratio=10.0,\n centre=(0.0, 1.0),\n ell_comps=(0.0, 0.1),\n effective_radius=0.6,\n sersic_index=3.0,\n ),\n)\n\ndataset = simulator.via_galaxies_from(\n galaxies=ag.Galaxies(galaxies=[galaxy_0, galaxy_1]), grid=grid\n)\n```\n\nNote the profiles take **no** `intensity` — that is the parameter being solved for. The\ntrade-off is that `exposure_time` and `background_sky_level` no longer set the S/N, only the\n*balance* between counting noise and sky noise. So they still matter for realism: doubling\nthe exposure time shifts the noise budget toward Poisson statistics even though the S/N is\npinned. Choose them to match your instrument if the noise character matters to the study.\n\nThis is also the profile family to reach for in a feasibility question — simulate the same\ngalaxy at S/N 10, 20 and 50, fit each, and see where the parameter you care about stops\nbeing constrained. That is a far more honest answer than a single simulation at whatever\nintensity happened to be typed.\n\n## Branch — a sample, for population or machine-learning work\n\nTo generate many galaxies, draw each one's parameters from a distribution and loop. Adapted\nfrom `autogalaxy_workspace:scripts/imaging/simulator_sample.py`, which draws directly from a\nNumPy generator — deliberately, because these are *truths* for synthetic data, not a model\nbeing fitted, so there is no reason to involve the model-composition API.\n\n```python\nimport numpy as np\n\nrng = np.random.default_rng()\n\n\ndef _clipped_ell_comp() -> float:\n return float(np.clip(rng.normal(0.0, 0.2), -1.0, 1.0))\n\n\ndef _random_galaxy() -> ag.Galaxy:\n bulge = ag.lp_snr.Sersic(\n centre=(0.0, 0.0),\n ell_comps=(_clipped_ell_comp(), _clipped_ell_comp()),\n effective_radius=float(rng.uniform(1.0, 5.0)),\n sersic_index=float(np.clip(rng.normal(4.0, 1.0), 0.8, 5.0)),\n signal_to_noise_ratio=float(rng.uniform(20.0, 60.0)),\n )\n return ag.Galaxy(redshift=0.5, bulge=bulge)\n\n\ntotal_datasets = 3\n\nfor sample_index in range(total_datasets):\n\n sample_path = DATASET_PATH / f\"dataset_{sample_index}\"\n\n galaxies = ag.Galaxies(galaxies=[_random_galaxy()])\n dataset = simulator.via_galaxies_from(galaxies=galaxies, grid=grid)\n\n aplt.fits_imaging(\n dataset=dataset,\n data_path=sample_path / \"data.fits\",\n psf_path=sample_path / \"psf.fits\",\n noise_map_path=sample_path / \"noise_map.fits\",\n overwrite=True,\n )\n ag.output_to_json(obj=galaxies, file_path=sample_path / \"galaxies.json\")\n```\n\nThe `lp_snr` bulge is what makes the loop usable: with a plain `intensity` drawn from a\ndistribution, a fraction of your sample would be invisible and another fraction saturated.\nPinning S/N per galaxy guarantees every image is detectable. Write a `galaxies.json` per\ndataset — with a sample, the truth record stops being a nicety and becomes the labels.\n\nFor a one-line random galaxy without writing your own distributions,\n`ag.model_util.random_galaxy_for_simulation_from()` returns one drawn from the library's own\nchoices, and `ag.model_util.SIMULATOR_RANDOM_GALAXY_SUMMARY` prints what those choices are —\nread that summary before using it in anything you will publish, so the prior you inherited\nis one you actually endorse.\n\n## Branch — interferometer visibilities\n\nFor sub-mm and radio data (ALMA, JVLA, LOFAR) the observable is visibilities in the uv-plane,\nnot an image, and fitting them there avoids the correlated noise a dirty image carries.\nAdapted from `autogalaxy_workspace:scripts/interferometer/simulator.py`.\n\n```python\nuv_wavelengths = ag.ndarray_via_fits_from(\n file_path=Path(\"dataset\") / \"interferometer\" / \"uv_wavelengths\" / \"sma.fits\", hdu=0\n)\n\nsimulator = ag.SimulatorInterferometer(\n uv_wavelengths=uv_wavelengths,\n exposure_time=300.0,\n noise_sigma=1000.0,\n transformer_class=ag.TransformerNUFFT,\n)\n\nreal_space_grid = ag.Grid2D.uniform(shape_native=(800, 800), pixel_scales=0.05)\n\ndataset = simulator.via_galaxies_from(galaxies=galaxies, grid=real_space_grid)\n\naplt.subplot_interferometer_dirty_images(\n dataset=dataset, output_path=DATASET_PATH, output_format=\"png\"\n)\n\naplt.fits_interferometer(\n dataset=dataset,\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n uv_wavelengths_path=DATASET_PATH / \"uv_wavelengths.fits\",\n overwrite=True,\n)\n```\n\nFour differences from imaging are worth knowing. The baselines come from a real array's\n`uv_wavelengths` — the workspace ships SMA (low resolution, very fast) and ALMA files;\nswapping the file swaps the instrument. There is **no PSF and no over-sampling**: the image\nis evaluated in real space and Fourier-transformed, and interferometers do not observe in a\nway that makes over-sampling necessary. `noise_sigma` replaces the exposure-time-driven\nPoisson model. And the thing you *look at* is the dirty image, which is a diagnostic — the\nfit itself happens in the uv-plane. The physics is\n[`../wiki/core/concepts/interferometer_theory.md`](../wiki/core/concepts/interferometer_theory.md).\nFull interferometer modelling is a separate skill,\n[`ag_build_interferometer_model`](./ag_build_interferometer_model.md).\n\n## The auto-simulation convention\n\nEvery workspace script that fits a dataset first checks whether it exists and runs the\nmatching simulator if it does not, so an example can be run from a fresh clone with no\nmanual step:\n\n```python\nif ag.util.dataset.should_simulate(str(dataset_path)):\n import subprocess\n import sys\n\n subprocess.run([sys.executable, \"scripts/imaging/simulator.py\"], check=True)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py`. Adopt the same pattern in\nscripts you write, and know the sharp edge: `should_simulate` tests **existence**, not\nwhether the dataset on disk matches the simulator that would produce it. Change the\nsimulator's parameters and re-run the fit and you will silently fit the *old* data. The same\napplies to `PYAUTO_SMALL_DATASETS=1`, which caps grids and masks to a small size: a\nfull-resolution dataset already on disk will be reused and mismatch the capped grids. Delete\nthe dataset directory when you change either\n([`../wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## JAX, for many simulations\n\nFor parameter sweeps, mock-data studies or batch figure generation, build the simulator with\n`use_jax=True` — the simulation then runs on JAX arrays (and the GPU, when one is\nconfigured):\n\n```python\nsimulator_jax = ag.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n use_jax=True,\n)\n\ndataset_jax = simulator_jax.via_galaxies_from(galaxies=galaxies, grid=grid)\n```\n\n`dataset_jax.data.array` is a `jax.Array`, and the plot and FITS helpers call\n`numpy.asarray()` internally, so saving and plotting need no manual conversion.\n\nWrapping the whole simulation call in a jitted function — worth it across *many* calls —\nadditionally requires registering the galaxy classes as JAX pytrees before the first jitted\ncall, and the helper that does that registration is **not in the released stack yet** (it\nlives on the libraries' development branches only). Until it ships in a release, use the\neager `use_jax=True` call above; the `__JAX Variant__` section of\n`autogalaxy_workspace:scripts/imaging/simulator.py` carries the jitted recipe for a\nsource install. **For interferometer simulations the jitted path does not work either way** —\nuse the eager call; `autogalaxy_workspace:scripts/interferometer/simulator.py` documents why.\n\n## Combine — where this hands off\n\n- **Fit the dataset you just made** → [`ag_build_imaging_model`](./ag_build_imaging_model.md)\n to compose the model, then [`ag_configure_search`](./ag_configure_search.md) and the\n run-search skill (`ag_run_search`). Compose a model that *matches* the truth first: if it\n cannot recover parameters it was handed exactly, the problem is the inference, and you have\n learned that cheaply.\n- **Compare a fit against the truth** → load `galaxies.json` with `ag.from_json` and put the\n true and inferred values side by side; the results-loading and fit-plotting skills\n (`ag_load_results`, `ag_plot_fit`) do the rest.\n- **You actually have real data** → [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md),\n which also owns the inspection gate this branch is exempt from.\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry when the simulation is\npart of a study — the truth parameters and the S/N you chose *are* the experimental design,\nand a recovery test is meaningless later without them.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Grids and galaxies](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb):\n how a light profile becomes an image on a grid, and what each Sersic parameter changes —\n the foundation under every simulation.\n- **General reference** — [RTD: Start here overview](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the core API end to end, including the simulation section, in one page.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/simulator.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/simulator.py):\n the full bulge-plus-disk simulator with the contaminant mask and the executed JAX variant.\n\n## Agent procedural checklist\n\n1. Ask what the simulation is *for*; it decides the branch and whether `lp_snr` is wanted.\n2. Set `pixel_scales`, PSF width and exposure time from a real instrument, not defaults.\n3. Over-sample with every bright centre in `centre_list` — including any neighbour.\n4. Write FITS **and** `galaxies.json`; write the neighbour's `mask_extra_galaxies.fits` in\n the same script if one exists.\n5. Plot the dataset and the noise-free galaxies subplot; print and **quote** the absolute\n path, offering to open it once.\n6. Delete the dataset directory before re-running with changed parameters or with\n `PYAUTO_SMALL_DATASETS=1` — `should_simulate` only checks existence.\n7. Hand off to `ag_build_imaging_model`, and offer the `wiki/project/` entry when the\n simulation is part of a study.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/start_here.ipynb b/start_here.ipynb index 719147c..9f996c2 100644 --- a/start_here.ipynb +++ b/start_here.ipynb @@ -61,21 +61,22 @@ "source": [ "__Google Colab Setup__\n", "\n", - "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", - "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", - "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", - "your own installation) it does nothing, and you can run it safely.\n", - "\n", - "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", - "type\" -> \"Hardware accelerator\" before running the notebook." + "Run this cell to install PyAutoGalaxy and download the files needed for this notebook on Google Colab.\n", + "If you\u2019re running locally or in HTML, it leaves your installation unchanged.\n" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, "outputs": [], "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", "try:\n", " import google.colab\n", "except ImportError:\n",