diff --git a/notebooks/chapter_1_introduction/tutorial_0_visualization.ipynb b/notebooks/chapter_1_introduction/tutorial_0_visualization.ipynb index cef6fb6..ee700c3 100644 --- a/notebooks/chapter_1_introduction/tutorial_0_visualization.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_0_visualization.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/HowToLens/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 49686e3..b16005f 100644 --- a/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb @@ -74,21 +74,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 PyAutoLens 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_ray_tracing.ipynb b/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb index de1920d..010efd3 100644 --- a/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb @@ -79,21 +79,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/HowToLens/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_more_ray_tracing.ipynb b/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb index 8682625..e3e3015 100644 --- a/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb @@ -46,21 +46,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/HowToLens/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", @@ -643,7 +643,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` \u2014 image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* \u2014 pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* \u2014 if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual \u2014 what convergence is, why caustics matter, what\na critical curve traces \u2014 see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions \u2014\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch \u2014 quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch \u2014 single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly \u2014 build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch \u2014 multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI \u2014 extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) \u2014 multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) \u2014 for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot \u2014 how light deflects, how critical curves and\n caustics arise.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action \u2014 building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` \u2014 ray tracing, profiles, numpy\n arrays, visualization.\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth \u2014 or build a\ntraining set for neural-network classifiers \u2014 you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating \u2014 single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* \u2014 chooses the branch.\n- *\"What's the ground truth?\"* \u2014 lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* \u2014 pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch \u2014 galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid \u2014 defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer \u2014 lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_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 overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot \u2014 saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` \u2014 `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch \u2014 many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch \u2014 interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n \u2192 [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour \u2014 see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates \u2014 the forward physics\n the simulator runs.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice \u2014 grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` — image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* — pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* — if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual — what convergence is, why caustics matter, what\na critical curve traces — see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions —\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch — quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch — single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly — build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch — multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI — extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) — multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) — for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot — how light deflects, how critical curves and\n caustics arise.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action — building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** — [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` — ray tracing, profiles, numpy\n arrays, visualization.\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth — or build a\ntraining set for neural-network classifiers — you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating — single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* — chooses the branch.\n- *\"What's the ground truth?\"* — lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* — pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch — galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid — defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer — lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_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 overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot — saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` — `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch — many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch — interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n → [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour — see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates — the forward physics\n the simulator runs.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice — grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_1_introduction/tutorial_4_point_sources.ipynb b/notebooks/chapter_1_introduction/tutorial_4_point_sources.ipynb index b2096e2..97a73e4 100644 --- a/notebooks/chapter_1_introduction/tutorial_4_point_sources.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_4_point_sources.ipynb @@ -75,21 +75,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/HowToLens/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_5_lensing_formalism.ipynb b/notebooks/chapter_1_introduction/tutorial_5_lensing_formalism.ipynb index cdd8dcf..b7dee11 100644 --- a/notebooks/chapter_1_introduction/tutorial_5_lensing_formalism.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_5_lensing_formalism.ipynb @@ -47,21 +47,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/HowToLens/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_6_data.ipynb b/notebooks/chapter_1_introduction/tutorial_6_data.ipynb index 6708dc1..9db0087 100644 --- a/notebooks/chapter_1_introduction/tutorial_6_data.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_6_data.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/HowToLens/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_7_fitting.ipynb b/notebooks/chapter_1_introduction/tutorial_7_fitting.ipynb index 9be89c7..0a372e3 100644 --- a/notebooks/chapter_1_introduction/tutorial_7_fitting.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_7_fitting.ipynb @@ -54,21 +54,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/HowToLens/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_8_summary.ipynb b/notebooks/chapter_1_introduction/tutorial_8_summary.ipynb index e521de4..c58f2cd 100644 --- a/notebooks/chapter_1_introduction/tutorial_8_summary.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_8_summary.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/HowToLens/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", @@ -338,7 +338,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_1_introduction/tutorial_8_summary.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` \u2014 image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* \u2014 pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* \u2014 if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual \u2014 what convergence is, why caustics matter, what\na critical curve traces \u2014 see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions \u2014\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch \u2014 quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch \u2014 single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly \u2014 build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch \u2014 multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI \u2014 extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) \u2014 multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) \u2014 for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot \u2014 how light deflects, how critical curves and\n caustics arise.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action \u2014 building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` \u2014 ray tracing, profiles, numpy\n arrays, visualization.\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth \u2014 or build a\ntraining set for neural-network classifiers \u2014 you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating \u2014 single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* \u2014 chooses the branch.\n- *\"What's the ground truth?\"* \u2014 lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* \u2014 pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch \u2014 galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid \u2014 defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer \u2014 lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_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 overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot \u2014 saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` \u2014 `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch \u2014 many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch \u2014 interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n \u2192 [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour \u2014 see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates \u2014 the forward physics\n the simulator runs.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice \u2014 grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_1_introduction/tutorial_8_summary.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` — image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* — pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* — if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual — what convergence is, why caustics matter, what\na critical curve traces — see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions —\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch — quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch — single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly — build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch — multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI — extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) — multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) — for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot — how light deflects, how critical curves and\n caustics arise.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action — building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** — [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` — ray tracing, profiles, numpy\n arrays, visualization.\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth — or build a\ntraining set for neural-network classifiers — you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating — single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* — chooses the branch.\n- *\"What's the ground truth?\"* — lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* — pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch — galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid — defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer — lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_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 overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot — saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` — `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch — many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch — interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n → [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour — see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates — the forward physics\n the simulator runs.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice — grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_2_lens_modeling/tutorial_10_prior_passing.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_10_prior_passing.ipynb index ba84b2b..90f204a 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_10_prior_passing.ipynb +++ b/notebooks/chapter_2_lens_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/HowToLens/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_lens_modeling/tutorial_11_slam.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_11_slam.ipynb index 8e59035..cbdba94 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_11_slam.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_11_slam.ipynb @@ -77,21 +77,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/HowToLens/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_lens_modeling/tutorial_1_non_linear_search.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb index 358be7e..2c7ea8d 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb +++ b/notebooks/chapter_2_lens_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/HowToLens/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_lens_modeling/tutorial_2_practicalities.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb index eba2e2f..e48248e 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb @@ -87,21 +87,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/HowToLens/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_lens_modeling/tutorial_3_realism_and_complexity.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_3_realism_and_complexity.ipynb index e8d0c0d..46a39e0 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_3_realism_and_complexity.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_3_realism_and_complexity.ipynb @@ -46,21 +46,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/HowToLens/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", @@ -508,7 +508,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_2_lens_modeling/tutorial_3_realism_and_complexity.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_build_imaging_model\n\n---\nname: al_build_imaging_model\ndescription: Compose a strong-lens model for imaging data \u2014 galaxies with light + mass profiles, prior customisation, and an `al.AnalysisImaging` ready to hand to a non-linear search. Writes a runnable Python script in scripts/. Pairs with `al_prepare_imaging_data` (which loads + masks the dataset) and `al_run_search` (which executes the fit). For visibility-plane data see `al_build_interferometer_model`.\n---\n\n# Composing an imaging lens model\n\nThe model is the PyAuto\\* representation of *what kind of lens you think this is* \u2014 how\nmany galaxies, at what redshifts, with what light and mass parameterisations, with\nwhich parameters free and which fixed. Building one is the step between \"I have a\nloaded `Imaging` dataset\" and \"I'm running a non-linear search\".\n\nThe canonical example is `autolens_workspace:scripts/imaging/modeling.py`. This skill\ngenerates the equivalent for the user's lens.\n\nThis skill assumes the imaging data is already preprocessing-ready. For real\nobservational data, confirm first that the user has **inspected `dataset.png`** and\nthought through mask extent, contaminating objects, and any regions to exclude \u2014 in\nparticular that any **extra galaxies** have been handled (noise-scaled via a\n`mask_extra_galaxies.fits`, or excluded by shrinking the circular mask). If not, route\nthem back to [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) before building the\nmodel \u2014 don't compose a model over data with an unaddressed contaminant.\n\n## Ask\n\n- *\"If this is real observational data, have you inspected `dataset.png`, decided the\n mask extent, and handled any extra galaxies (noise-scaled a `mask_extra_galaxies.fits`,\n or shrunk the mask to exclude them)?\"* \u2014 if not, stop and do that in\n [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) first.\n- *\"How many galaxies in the model \u2014 single galaxy-scale, multi-galaxy (2+ co-dominant, no host halo), group (2\u201310, optional group halo), cluster?\"* \u2014\n this is the only structural choice. Skill below assumes galaxy-scale; bootstrap a\n variant for groups/clusters via `_bootstrap_skill` if needed.\n- *\"What's the lens light parameterisation \u2014 a single Sersic, MGE (multi-Gaussian\n expansion), bulge + disk, or no lens light at all (mass-only)?\"*\n- *\"What's the lens mass \u2014 Isothermal (SIE) + ExternalShear is the standard starting\n point; PowerLaw or NFW for total or dark-matter-only models.\"*\n- *\"What's the source \u2014 parametric Sersic, MGE, or pixelised inversion?\"* \u2014 pixelised\n needs a different `Analysis` wiring; see [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md).\n- *\"What are the lens and source redshifts?\"* \u2014 needed for distance ratios; even a\n ballpark value works for relative-comparison runs.\n\n## Branch \u2014 galaxy-scale, Sersic light + SIE mass + Sersic source\n\nThe minimum viable model. Save to `scripts/build_model.py`:\n\n```python\n# scripts/build_model.py\nfrom autonerves import jax_wrapper\nimport autofit as af\nimport autolens as al\n\n# Lens light \u2014 a Sersic for the bulge.\nlens_bulge = af.Model(al.lp.Sersic)\n\n# Lens mass \u2014 SIE plus a separate external field.\nlens_mass = af.Model(al.mp.Isothermal)\nlens_shear = af.Model(al.mp.ExternalShear)\n\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=lens_bulge,\n mass=lens_mass,\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=lens_shear)\n\n# Source light \u2014 a single Sersic.\nsource = af.Model(\n al.Galaxy,\n redshift=1.0,\n bulge=af.Model(al.lp.SersicCore),\n)\n\n# Compose into a Collection.\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# Optional: customise priors. E.g. tighten the lens centre.\nlens_mass.centre.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\nlens_mass.centre.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n\n# On real data, bound the Einstein radius from the ring you can see in the image\n# (the default prior is uniform over 0-8\"). A maximum-likelihood optimiser such as\n# MultiStartProdigy otherwise finds degenerate basins where theta_E exceeds the mask,\n# the \"source\" lands on a neighbouring galaxy and the ring is left in the residuals\n# (this is exactly what happened on the bundled COSMOS-Web Ring: theta_E 2.4\" vs 0.8\").\nlens_mass.einstein_radius = af.UniformPrior(lower_limit=0.3, upper_limit=1.5)\n\nprint(model.info)\n```\n\nSource citations:\n- `PyAutoGalaxy:autogalaxy/galaxy/galaxy.py` \u2014 `Galaxy`.\n- `PyAutoGalaxy:autogalaxy/galaxy/mass_field.py` \u2014 `MassField`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 `Sersic`, `SersicCore`.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 `Isothermal`.\n- `PyAutoFit:autofit/mapper/prior_model/prior_model.py` \u2014 `af.Model`.\n- `PyAutoFit:autofit/mapper/prior_model/collection.py` \u2014 `af.Collection`.\n\nWiki:\n- [`wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md) \u2014 what each\n light profile represents and when to pick which.\n- [`wiki/core/concepts/mass_profiles.md`](../wiki/core/concepts/mass_profiles.md) \u2014 same for mass.\n- [`wiki/core/concepts/galaxy_and_plane.md`](../wiki/core/concepts/galaxy_and_plane.md) \u2014 how\n galaxies, redshifts, and the `Tracer` fit together.\n\n## Branch \u2014 linear (MGE) lens light\n\nFor complex lens galaxy morphologies, replace the single Sersic bulge with a Multi-\nGaussian Expansion of *linear* light profiles. Linear profiles have their\n*intensities* solved analytically inside the fit, so the search only varies\nshape parameters \u2014 far fewer dimensions, much better convergence.\n\n```python\nn_gaussians = 30\ngaussian_per_basis = [\n af.Model(al.lp_linear.Gaussian) for _ in range(n_gaussians)\n]\n# Tie centres + ellipticities across the basis; let only sigma + intensity vary.\nfor g in gaussian_per_basis[1:]:\n g.centre = gaussian_per_basis[0].centre\n g.ell_comps = gaussian_per_basis[0].ell_comps\n\nlens_bulge = af.Model(al.lp_basis.Basis, profile_list=gaussian_per_basis)\n```\n\nSee `PyAutoGalaxy:autogalaxy/profiles/light/linear/` for the linear-profile classes.\n\n## Branch \u2014 pixelised source\n\nFor sources with complex morphology (lensed arcs, multiple components), reconstruct\nthe source on a pixel grid rather than as a parametric Sersic. The model wiring is\ndifferent: the source `Galaxy` carries a `Pixelization`, and the `Analysis` needs a\npositions likelihood penalty to keep the inversion well-posed.\n\nSee [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) for\nthe full pattern.\n\n## Wrap with an analysis\n\nOnce the model is built, wrap your loaded `dataset` (from `al_prepare_imaging_data`)\nin an analysis object:\n\n```python\nanalysis = al.AnalysisImaging(dataset=dataset)\n```\n\nSource: `PyAutoLens:autolens/imaging/model/analysis.py`.\n\n`analysis` + `model` are the two inputs to the non-linear search. Pass them to\n[`al_run_search`](./al_run_search.md).\n\n## Combine\n\nNatural next steps:\n\n- [`al_configure_search`](./al_configure_search.md) \u2014 pick Nautilus (default), Dynesty,\n Emcee, or another search; tune live points / walkers.\n- [`al_run_search`](./al_run_search.md) \u2014 `search.fit(model=model, analysis=analysis)`.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 chain a fast Sersic source fit into\n a slower pixelised one, inheriting priors.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Non-linear searches and parameter\n inference](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb):\n how non-linear searches find a best-fit model \u2014 parameter spaces, likelihoods,\n priors. The statistical foundation under model composition.\n- **General reference** \u2014 [RTD: Model cookbook](https://pyautolens.readthedocs.io/en/latest/general/model_cookbook.html):\n systematic reference for building lens models with `Model` and `Collection` \u2014\n two-component to multi-galaxy, prior customisation, parameter pairing, MGE.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/modeling/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling/start_here.py):\n the canonical imaging-modeling script \u2014 light-profile choice (Sersic vs. MGE),\n non-linear-search configuration, JAX/GPU fitting.\n\n## Skill: al_run_search\n\n---\nname: al_run_search\ndescription: Execute a non-linear search on a configured model + analysis. Calls `search.fit(model=model, analysis=analysis)` and monitors progress to the search's `path_prefix/name/unique_id/` output folder. Includes the sandbox / test-mode wrapper so smoke tests don't burn hours on real sampling. Use after `al_build_imaging_model` (or interferometer) and `al_configure_search` have produced `model`, `analysis`, and `search` objects.\n---\n\n# Running a non-linear search\n\nThe actual fit. Inputs: a model, an analysis (which knows the dataset and how to\ncompute a log-likelihood), and a search (which knows how to explore parameter space).\nThe single call `search.fit(model=model, analysis=analysis)` does the work.\n\nThis skill assembles those three pieces into a runnable script, then runs it \u2014 either\nin `PYAUTO_TEST_MODE=1` for a smoke test or in production mode for the real fit.\n\n## Ask\n\n- *\"Have you built `model` and `analysis` (from `al_build_imaging_model`) and\n configured `search` (from `al_configure_search`)?\"* If not, route to those first.\n- *\"Smoke test or production run?\"* Smoke test runs in seconds with `PYAUTO_TEST_MODE=1`\n and a tiny dataset, just to prove the wiring is correct. Production run takes hours\n to a day depending on model complexity and number of likelihood evals.\n- *\"How long can the fit run?\"* Sets expectations and decides whether to launch it as\n a foreground or backgrounded process.\n\n## Branch \u2014 production run\n\nOperational reminder: if the search was configured with `live_visual_update=True`\n(`al_configure_search` \"Live visual updates\"), a foreground script opens a matplotlib viewer\nand a notebook cell refreshes in place \u2014 don't re-ask when the search configuration already\nrecords the choice, and keep it `False` for HPC/headless/background runs. `fit.png` is\nwritten to disk on every quick update either way.\n\nAssemble everything into one script (`scripts/run_fit.py`):\n\n```python\n# scripts/run_fit.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autofit as af\nimport autolens as al\n\n# --- Dataset (from al_prepare_imaging_data) ---\ndataset_path = Path(\"dataset/imaging/\")\ndataset = al.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.06,\n)\nmask = al.Mask2D.circular(\n shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5\n)\ndataset = dataset.apply_mask(mask=mask)\n\n# --- Model (from al_build_imaging_model) ---\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=af.Model(al.lp.Sersic),\n mass=af.Model(al.mp.Isothermal),\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=af.Model(al.mp.ExternalShear))\nsource = af.Model(al.Galaxy, redshift=1.0, bulge=af.Model(al.lp.SersicCore))\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# --- Analysis ---\nanalysis = al.AnalysisImaging(dataset=dataset)\n\n# --- Search (from al_configure_search) ---\nsearch = af.Nautilus(\n path_prefix=\"imaging/\",\n name=\"sie_sersic\",\n n_live=200,\n number_of_cores=4,\n)\n\n# --- Fit ---\nresult = search.fit(model=model, analysis=analysis)\nprint(result.max_log_likelihood_instance)\n```\n\nRun with sandbox cache overrides if needed:\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/abstract_search.py` (the `fit` method).\nThe returned `Result` object is documented in `PyAutoFit:autofit/non_linear/result.py`.\n\n## Branch \u2014 smoke test (`PYAUTO_TEST_MODE=1`)\n\nWhen you've just written the script and want to know it runs end-to-end *without*\nwaiting for real sampling, set `PYAUTO_TEST_MODE=1`:\n\n```bash\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\nThe search will short-circuit after a small number of likelihood evaluations and\nreturn a `Result` so the script completes. Use this on every script you write, before\nlaunching a real run.\n\nFor an even faster smoke (sub-second per step), combine with PyAutoLens's small-dataset\nflags:\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\nSee [`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md) for the full flag list.\n\n## Output\n\nThe fit writes to `output////` (see\n`al_configure_search` for the layout). Tail the search log live:\n\n```bash\ntail -f output/imaging//sie_sersic/*/search.log\n```\n\nSay this out loud the moment a production fit starts: results are written **on the fly**\nfrom the best model so far, so `model.results` and `image/fit.png` are already worth\nopening \u2014 no need to wait for the search to terminate. For a newcomer, or in teacher\nmode, tour the folder per `_style.md` \"Output folder announcement\" and point at\n`__Output Folder Layout__` in\n[`autolens_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling.py),\nwhich annotates every file the fit writes.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 once the fit completes (or even mid-run),\n load and inspect.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 visualise model vs data.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 feed the result into a follow-up\n search with tighter priors.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) \u2014 if the fit converged badly.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Output management and result\n interpretation](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running fits \u2014 output structure, reviewing results,\n managing run times.\n- **General reference** \u2014 [RTD: New user guide](https://pyautolens.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n decision-tree routing for a new user about which fit to run first.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit on GPU \u2014 production pattern this skill mirrors.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_2_lens_modeling/tutorial_3_realism_and_complexity.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_build_imaging_model\n\n---\nname: al_build_imaging_model\ndescription: Compose a strong-lens model for imaging data — galaxies with light + mass profiles, prior customisation, and an `al.AnalysisImaging` ready to hand to a non-linear search. Writes a runnable Python script in scripts/. Pairs with `al_prepare_imaging_data` (which loads + masks the dataset) and `al_run_search` (which executes the fit). For visibility-plane data see `al_build_interferometer_model`.\n---\n\n# Composing an imaging lens model\n\nThe model is the PyAuto\\* representation of *what kind of lens you think this is* — how\nmany galaxies, at what redshifts, with what light and mass parameterisations, with\nwhich parameters free and which fixed. Building one is the step between \"I have a\nloaded `Imaging` dataset\" and \"I'm running a non-linear search\".\n\nThe canonical example is `autolens_workspace:scripts/imaging/modeling.py`. This skill\ngenerates the equivalent for the user's lens.\n\nThis skill assumes the imaging data is already preprocessing-ready. For real\nobservational data, confirm first that the user has **inspected `dataset.png`** and\nthought through mask extent, contaminating objects, and any regions to exclude — in\nparticular that any **extra galaxies** have been handled (noise-scaled via a\n`mask_extra_galaxies.fits`, or excluded by shrinking the circular mask). If not, route\nthem back to [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) before building the\nmodel — don't compose a model over data with an unaddressed contaminant.\n\n## Ask\n\n- *\"If this is real observational data, have you inspected `dataset.png`, decided the\n mask extent, and handled any extra galaxies (noise-scaled a `mask_extra_galaxies.fits`,\n or shrunk the mask to exclude them)?\"* — if not, stop and do that in\n [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) first.\n- *\"How many galaxies in the model — single galaxy-scale, multi-galaxy (2+ co-dominant, no host halo), group (2–10, optional group halo), cluster?\"* —\n this is the only structural choice. Skill below assumes galaxy-scale; bootstrap a\n variant for groups/clusters via `_bootstrap_skill` if needed.\n- *\"What's the lens light parameterisation — a single Sersic, MGE (multi-Gaussian\n expansion), bulge + disk, or no lens light at all (mass-only)?\"*\n- *\"What's the lens mass — Isothermal (SIE) + ExternalShear is the standard starting\n point; PowerLaw or NFW for total or dark-matter-only models.\"*\n- *\"What's the source — parametric Sersic, MGE, or pixelised inversion?\"* — pixelised\n needs a different `Analysis` wiring; see [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md).\n- *\"What are the lens and source redshifts?\"* — needed for distance ratios; even a\n ballpark value works for relative-comparison runs.\n\n## Branch — galaxy-scale, Sersic light + SIE mass + Sersic source\n\nThe minimum viable model. Save to `scripts/build_model.py`:\n\n```python\n# scripts/build_model.py\nfrom autonerves import jax_wrapper\nimport autofit as af\nimport autolens as al\n\n# Lens light — a Sersic for the bulge.\nlens_bulge = af.Model(al.lp.Sersic)\n\n# Lens mass — SIE plus a separate external field.\nlens_mass = af.Model(al.mp.Isothermal)\nlens_shear = af.Model(al.mp.ExternalShear)\n\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=lens_bulge,\n mass=lens_mass,\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=lens_shear)\n\n# Source light — a single Sersic.\nsource = af.Model(\n al.Galaxy,\n redshift=1.0,\n bulge=af.Model(al.lp.SersicCore),\n)\n\n# Compose into a Collection.\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# Optional: customise priors. E.g. tighten the lens centre.\nlens_mass.centre.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\nlens_mass.centre.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n\n# On real data, bound the Einstein radius from the ring you can see in the image\n# (the default prior is uniform over 0-8\"). A maximum-likelihood optimiser such as\n# MultiStartProdigy otherwise finds degenerate basins where theta_E exceeds the mask,\n# the \"source\" lands on a neighbouring galaxy and the ring is left in the residuals\n# (this is exactly what happened on the bundled COSMOS-Web Ring: theta_E 2.4\" vs 0.8\").\nlens_mass.einstein_radius = af.UniformPrior(lower_limit=0.3, upper_limit=1.5)\n\nprint(model.info)\n```\n\nSource citations:\n- `PyAutoGalaxy:autogalaxy/galaxy/galaxy.py` — `Galaxy`.\n- `PyAutoGalaxy:autogalaxy/galaxy/mass_field.py` — `MassField`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — `Sersic`, `SersicCore`.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — `Isothermal`.\n- `PyAutoFit:autofit/mapper/prior_model/prior_model.py` — `af.Model`.\n- `PyAutoFit:autofit/mapper/prior_model/collection.py` — `af.Collection`.\n\nWiki:\n- [`wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md) — what each\n light profile represents and when to pick which.\n- [`wiki/core/concepts/mass_profiles.md`](../wiki/core/concepts/mass_profiles.md) — same for mass.\n- [`wiki/core/concepts/galaxy_and_plane.md`](../wiki/core/concepts/galaxy_and_plane.md) — how\n galaxies, redshifts, and the `Tracer` fit together.\n\n## Branch — linear (MGE) lens light\n\nFor complex lens galaxy morphologies, replace the single Sersic bulge with a Multi-\nGaussian Expansion of *linear* light profiles. Linear profiles have their\n*intensities* solved analytically inside the fit, so the search only varies\nshape parameters — far fewer dimensions, much better convergence.\n\n```python\nn_gaussians = 30\ngaussian_per_basis = [\n af.Model(al.lp_linear.Gaussian) for _ in range(n_gaussians)\n]\n# Tie centres + ellipticities across the basis; let only sigma + intensity vary.\nfor g in gaussian_per_basis[1:]:\n g.centre = gaussian_per_basis[0].centre\n g.ell_comps = gaussian_per_basis[0].ell_comps\n\nlens_bulge = af.Model(al.lp_basis.Basis, profile_list=gaussian_per_basis)\n```\n\nSee `PyAutoGalaxy:autogalaxy/profiles/light/linear/` for the linear-profile classes.\n\n## Branch — pixelised source\n\nFor sources with complex morphology (lensed arcs, multiple components), reconstruct\nthe source on a pixel grid rather than as a parametric Sersic. The model wiring is\ndifferent: the source `Galaxy` carries a `Pixelization`, and the `Analysis` needs a\npositions likelihood penalty to keep the inversion well-posed.\n\nSee [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) for\nthe full pattern.\n\n## Wrap with an analysis\n\nOnce the model is built, wrap your loaded `dataset` (from `al_prepare_imaging_data`)\nin an analysis object:\n\n```python\nanalysis = al.AnalysisImaging(dataset=dataset)\n```\n\nSource: `PyAutoLens:autolens/imaging/model/analysis.py`.\n\n`analysis` + `model` are the two inputs to the non-linear search. Pass them to\n[`al_run_search`](./al_run_search.md).\n\n## Combine\n\nNatural next steps:\n\n- [`al_configure_search`](./al_configure_search.md) — pick Nautilus (default), Dynesty,\n Emcee, or another search; tune live points / walkers.\n- [`al_run_search`](./al_run_search.md) — `search.fit(model=model, analysis=analysis)`.\n- [`al_chain_searches`](./al_chain_searches.md) — chain a fast Sersic source fit into\n a slower pixelised one, inheriting priors.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Non-linear searches and parameter\n inference](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb):\n how non-linear searches find a best-fit model — parameter spaces, likelihoods,\n priors. The statistical foundation under model composition.\n- **General reference** — [RTD: Model cookbook](https://pyautolens.readthedocs.io/en/latest/general/model_cookbook.html):\n systematic reference for building lens models with `Model` and `Collection` —\n two-component to multi-galaxy, prior customisation, parameter pairing, MGE.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/modeling/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling/start_here.py):\n the canonical imaging-modeling script — light-profile choice (Sersic vs. MGE),\n non-linear-search configuration, JAX/GPU fitting.\n\n## Skill: al_run_search\n\n---\nname: al_run_search\ndescription: Execute a non-linear search on a configured model + analysis. Calls `search.fit(model=model, analysis=analysis)` and monitors progress to the search's `path_prefix/name/unique_id/` output folder. Includes the sandbox / test-mode wrapper so smoke tests don't burn hours on real sampling. Use after `al_build_imaging_model` (or interferometer) and `al_configure_search` have produced `model`, `analysis`, and `search` objects.\n---\n\n# Running a non-linear search\n\nThe actual fit. Inputs: a model, an analysis (which knows the dataset and how to\ncompute a log-likelihood), and a search (which knows how to explore parameter space).\nThe single call `search.fit(model=model, analysis=analysis)` does the work.\n\nThis skill assembles those three pieces into a runnable script, then runs it — either\nin `PYAUTO_TEST_MODE=1` for a smoke test or in production mode for the real fit.\n\n## Ask\n\n- *\"Have you built `model` and `analysis` (from `al_build_imaging_model`) and\n configured `search` (from `al_configure_search`)?\"* If not, route to those first.\n- *\"Smoke test or production run?\"* Smoke test runs in seconds with `PYAUTO_TEST_MODE=1`\n and a tiny dataset, just to prove the wiring is correct. Production run takes hours\n to a day depending on model complexity and number of likelihood evals.\n- *\"How long can the fit run?\"* Sets expectations and decides whether to launch it as\n a foreground or backgrounded process.\n\n## Branch — production run\n\nOperational reminder: if the search was configured with `live_visual_update=True`\n(`al_configure_search` \"Live visual updates\"), a foreground script opens a matplotlib viewer\nand a notebook cell refreshes in place — don't re-ask when the search configuration already\nrecords the choice, and keep it `False` for HPC/headless/background runs. `fit.png` is\nwritten to disk on every quick update either way.\n\nAssemble everything into one script (`scripts/run_fit.py`):\n\n```python\n# scripts/run_fit.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autofit as af\nimport autolens as al\n\n# --- Dataset (from al_prepare_imaging_data) ---\ndataset_path = Path(\"dataset/imaging/\")\ndataset = al.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.06,\n)\nmask = al.Mask2D.circular(\n shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5\n)\ndataset = dataset.apply_mask(mask=mask)\n\n# --- Model (from al_build_imaging_model) ---\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=af.Model(al.lp.Sersic),\n mass=af.Model(al.mp.Isothermal),\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=af.Model(al.mp.ExternalShear))\nsource = af.Model(al.Galaxy, redshift=1.0, bulge=af.Model(al.lp.SersicCore))\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# --- Analysis ---\nanalysis = al.AnalysisImaging(dataset=dataset)\n\n# --- Search (from al_configure_search) ---\nsearch = af.Nautilus(\n path_prefix=\"imaging/\",\n name=\"sie_sersic\",\n n_live=200,\n number_of_cores=4,\n)\n\n# --- Fit ---\nresult = search.fit(model=model, analysis=analysis)\nprint(result.max_log_likelihood_instance)\n```\n\nRun with sandbox cache overrides if needed:\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/abstract_search.py` (the `fit` method).\nThe returned `Result` object is documented in `PyAutoFit:autofit/non_linear/result.py`.\n\n## Branch — smoke test (`PYAUTO_TEST_MODE=1`)\n\nWhen you've just written the script and want to know it runs end-to-end *without*\nwaiting for real sampling, set `PYAUTO_TEST_MODE=1`:\n\n```bash\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\nThe search will short-circuit after a small number of likelihood evaluations and\nreturn a `Result` so the script completes. Use this on every script you write, before\nlaunching a real run.\n\nFor an even faster smoke (sub-second per step), combine with PyAutoLens's small-dataset\nflags:\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\nSee [`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md) for the full flag list.\n\n## Output\n\nThe fit writes to `output////` (see\n`al_configure_search` for the layout). Tail the search log live:\n\n```bash\ntail -f output/imaging//sie_sersic/*/search.log\n```\n\nSay this out loud the moment a production fit starts: results are written **on the fly**\nfrom the best model so far, so `model.results` and `image/fit.png` are already worth\nopening — no need to wait for the search to terminate. For a newcomer, or in teacher\nmode, tour the folder per `_style.md` \"Output folder announcement\" and point at\n`__Output Folder Layout__` in\n[`autolens_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling.py),\nwhich annotates every file the fit writes.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — once the fit completes (or even mid-run),\n load and inspect.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — visualise model vs data.\n- [`al_chain_searches`](./al_chain_searches.md) — feed the result into a follow-up\n search with tighter priors.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) — if the fit converged badly.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Output management and result\n interpretation](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running fits — output structure, reviewing results,\n managing run times.\n- **General reference** — [RTD: New user guide](https://pyautolens.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n decision-tree routing for a new user about which fit to run first.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit on GPU — production pattern this skill mirrors.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.ipynb index 8104e72..62d2ebb 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.ipynb @@ -43,21 +43,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/HowToLens/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_lens_modeling/tutorial_5_linear_profiles.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_5_linear_profiles.ipynb index 87dad55..3a3df78 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_5_linear_profiles.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_5_linear_profiles.ipynb @@ -54,21 +54,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/HowToLens/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_lens_modeling/tutorial_6_masking_and_positions.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_6_masking_and_positions.ipynb index 4a584a2..2b5c36e 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_6_masking_and_positions.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_6_masking_and_positions.ipynb @@ -30,21 +30,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/HowToLens/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", @@ -477,7 +477,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_2_lens_modeling/tutorial_6_masking_and_positions.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_build_imaging_model\n\n---\nname: al_build_imaging_model\ndescription: Compose a strong-lens model for imaging data \u2014 galaxies with light + mass profiles, prior customisation, and an `al.AnalysisImaging` ready to hand to a non-linear search. Writes a runnable Python script in scripts/. Pairs with `al_prepare_imaging_data` (which loads + masks the dataset) and `al_run_search` (which executes the fit). For visibility-plane data see `al_build_interferometer_model`.\n---\n\n# Composing an imaging lens model\n\nThe model is the PyAuto\\* representation of *what kind of lens you think this is* \u2014 how\nmany galaxies, at what redshifts, with what light and mass parameterisations, with\nwhich parameters free and which fixed. Building one is the step between \"I have a\nloaded `Imaging` dataset\" and \"I'm running a non-linear search\".\n\nThe canonical example is `autolens_workspace:scripts/imaging/modeling.py`. This skill\ngenerates the equivalent for the user's lens.\n\nThis skill assumes the imaging data is already preprocessing-ready. For real\nobservational data, confirm first that the user has **inspected `dataset.png`** and\nthought through mask extent, contaminating objects, and any regions to exclude \u2014 in\nparticular that any **extra galaxies** have been handled (noise-scaled via a\n`mask_extra_galaxies.fits`, or excluded by shrinking the circular mask). If not, route\nthem back to [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) before building the\nmodel \u2014 don't compose a model over data with an unaddressed contaminant.\n\n## Ask\n\n- *\"If this is real observational data, have you inspected `dataset.png`, decided the\n mask extent, and handled any extra galaxies (noise-scaled a `mask_extra_galaxies.fits`,\n or shrunk the mask to exclude them)?\"* \u2014 if not, stop and do that in\n [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) first.\n- *\"How many galaxies in the model \u2014 single galaxy-scale, multi-galaxy (2+ co-dominant, no host halo), group (2\u201310, optional group halo), cluster?\"* \u2014\n this is the only structural choice. Skill below assumes galaxy-scale; bootstrap a\n variant for groups/clusters via `_bootstrap_skill` if needed.\n- *\"What's the lens light parameterisation \u2014 a single Sersic, MGE (multi-Gaussian\n expansion), bulge + disk, or no lens light at all (mass-only)?\"*\n- *\"What's the lens mass \u2014 Isothermal (SIE) + ExternalShear is the standard starting\n point; PowerLaw or NFW for total or dark-matter-only models.\"*\n- *\"What's the source \u2014 parametric Sersic, MGE, or pixelised inversion?\"* \u2014 pixelised\n needs a different `Analysis` wiring; see [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md).\n- *\"What are the lens and source redshifts?\"* \u2014 needed for distance ratios; even a\n ballpark value works for relative-comparison runs.\n\n## Branch \u2014 galaxy-scale, Sersic light + SIE mass + Sersic source\n\nThe minimum viable model. Save to `scripts/build_model.py`:\n\n```python\n# scripts/build_model.py\nfrom autonerves import jax_wrapper\nimport autofit as af\nimport autolens as al\n\n# Lens light \u2014 a Sersic for the bulge.\nlens_bulge = af.Model(al.lp.Sersic)\n\n# Lens mass \u2014 SIE plus a separate external field.\nlens_mass = af.Model(al.mp.Isothermal)\nlens_shear = af.Model(al.mp.ExternalShear)\n\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=lens_bulge,\n mass=lens_mass,\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=lens_shear)\n\n# Source light \u2014 a single Sersic.\nsource = af.Model(\n al.Galaxy,\n redshift=1.0,\n bulge=af.Model(al.lp.SersicCore),\n)\n\n# Compose into a Collection.\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# Optional: customise priors. E.g. tighten the lens centre.\nlens_mass.centre.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\nlens_mass.centre.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n\n# On real data, bound the Einstein radius from the ring you can see in the image\n# (the default prior is uniform over 0-8\"). A maximum-likelihood optimiser such as\n# MultiStartProdigy otherwise finds degenerate basins where theta_E exceeds the mask,\n# the \"source\" lands on a neighbouring galaxy and the ring is left in the residuals\n# (this is exactly what happened on the bundled COSMOS-Web Ring: theta_E 2.4\" vs 0.8\").\nlens_mass.einstein_radius = af.UniformPrior(lower_limit=0.3, upper_limit=1.5)\n\nprint(model.info)\n```\n\nSource citations:\n- `PyAutoGalaxy:autogalaxy/galaxy/galaxy.py` \u2014 `Galaxy`.\n- `PyAutoGalaxy:autogalaxy/galaxy/mass_field.py` \u2014 `MassField`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 `Sersic`, `SersicCore`.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 `Isothermal`.\n- `PyAutoFit:autofit/mapper/prior_model/prior_model.py` \u2014 `af.Model`.\n- `PyAutoFit:autofit/mapper/prior_model/collection.py` \u2014 `af.Collection`.\n\nWiki:\n- [`wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md) \u2014 what each\n light profile represents and when to pick which.\n- [`wiki/core/concepts/mass_profiles.md`](../wiki/core/concepts/mass_profiles.md) \u2014 same for mass.\n- [`wiki/core/concepts/galaxy_and_plane.md`](../wiki/core/concepts/galaxy_and_plane.md) \u2014 how\n galaxies, redshifts, and the `Tracer` fit together.\n\n## Branch \u2014 linear (MGE) lens light\n\nFor complex lens galaxy morphologies, replace the single Sersic bulge with a Multi-\nGaussian Expansion of *linear* light profiles. Linear profiles have their\n*intensities* solved analytically inside the fit, so the search only varies\nshape parameters \u2014 far fewer dimensions, much better convergence.\n\n```python\nn_gaussians = 30\ngaussian_per_basis = [\n af.Model(al.lp_linear.Gaussian) for _ in range(n_gaussians)\n]\n# Tie centres + ellipticities across the basis; let only sigma + intensity vary.\nfor g in gaussian_per_basis[1:]:\n g.centre = gaussian_per_basis[0].centre\n g.ell_comps = gaussian_per_basis[0].ell_comps\n\nlens_bulge = af.Model(al.lp_basis.Basis, profile_list=gaussian_per_basis)\n```\n\nSee `PyAutoGalaxy:autogalaxy/profiles/light/linear/` for the linear-profile classes.\n\n## Branch \u2014 pixelised source\n\nFor sources with complex morphology (lensed arcs, multiple components), reconstruct\nthe source on a pixel grid rather than as a parametric Sersic. The model wiring is\ndifferent: the source `Galaxy` carries a `Pixelization`, and the `Analysis` needs a\npositions likelihood penalty to keep the inversion well-posed.\n\nSee [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) for\nthe full pattern.\n\n## Wrap with an analysis\n\nOnce the model is built, wrap your loaded `dataset` (from `al_prepare_imaging_data`)\nin an analysis object:\n\n```python\nanalysis = al.AnalysisImaging(dataset=dataset)\n```\n\nSource: `PyAutoLens:autolens/imaging/model/analysis.py`.\n\n`analysis` + `model` are the two inputs to the non-linear search. Pass them to\n[`al_run_search`](./al_run_search.md).\n\n## Combine\n\nNatural next steps:\n\n- [`al_configure_search`](./al_configure_search.md) \u2014 pick Nautilus (default), Dynesty,\n Emcee, or another search; tune live points / walkers.\n- [`al_run_search`](./al_run_search.md) \u2014 `search.fit(model=model, analysis=analysis)`.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 chain a fast Sersic source fit into\n a slower pixelised one, inheriting priors.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Non-linear searches and parameter\n inference](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb):\n how non-linear searches find a best-fit model \u2014 parameter spaces, likelihoods,\n priors. The statistical foundation under model composition.\n- **General reference** \u2014 [RTD: Model cookbook](https://pyautolens.readthedocs.io/en/latest/general/model_cookbook.html):\n systematic reference for building lens models with `Model` and `Collection` \u2014\n two-component to multi-galaxy, prior customisation, parameter pairing, MGE.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/modeling/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling/start_here.py):\n the canonical imaging-modeling script \u2014 light-profile choice (Sersic vs. MGE),\n non-linear-search configuration, JAX/GPU fitting.\n\n## Skill: al_run_search\n\n---\nname: al_run_search\ndescription: Execute a non-linear search on a configured model + analysis. Calls `search.fit(model=model, analysis=analysis)` and monitors progress to the search's `path_prefix/name/unique_id/` output folder. Includes the sandbox / test-mode wrapper so smoke tests don't burn hours on real sampling. Use after `al_build_imaging_model` (or interferometer) and `al_configure_search` have produced `model`, `analysis`, and `search` objects.\n---\n\n# Running a non-linear search\n\nThe actual fit. Inputs: a model, an analysis (which knows the dataset and how to\ncompute a log-likelihood), and a search (which knows how to explore parameter space).\nThe single call `search.fit(model=model, analysis=analysis)` does the work.\n\nThis skill assembles those three pieces into a runnable script, then runs it \u2014 either\nin `PYAUTO_TEST_MODE=1` for a smoke test or in production mode for the real fit.\n\n## Ask\n\n- *\"Have you built `model` and `analysis` (from `al_build_imaging_model`) and\n configured `search` (from `al_configure_search`)?\"* If not, route to those first.\n- *\"Smoke test or production run?\"* Smoke test runs in seconds with `PYAUTO_TEST_MODE=1`\n and a tiny dataset, just to prove the wiring is correct. Production run takes hours\n to a day depending on model complexity and number of likelihood evals.\n- *\"How long can the fit run?\"* Sets expectations and decides whether to launch it as\n a foreground or backgrounded process.\n\n## Branch \u2014 production run\n\nOperational reminder: if the search was configured with `live_visual_update=True`\n(`al_configure_search` \"Live visual updates\"), a foreground script opens a matplotlib viewer\nand a notebook cell refreshes in place \u2014 don't re-ask when the search configuration already\nrecords the choice, and keep it `False` for HPC/headless/background runs. `fit.png` is\nwritten to disk on every quick update either way.\n\nAssemble everything into one script (`scripts/run_fit.py`):\n\n```python\n# scripts/run_fit.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autofit as af\nimport autolens as al\n\n# --- Dataset (from al_prepare_imaging_data) ---\ndataset_path = Path(\"dataset/imaging/\")\ndataset = al.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.06,\n)\nmask = al.Mask2D.circular(\n shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5\n)\ndataset = dataset.apply_mask(mask=mask)\n\n# --- Model (from al_build_imaging_model) ---\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=af.Model(al.lp.Sersic),\n mass=af.Model(al.mp.Isothermal),\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=af.Model(al.mp.ExternalShear))\nsource = af.Model(al.Galaxy, redshift=1.0, bulge=af.Model(al.lp.SersicCore))\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# --- Analysis ---\nanalysis = al.AnalysisImaging(dataset=dataset)\n\n# --- Search (from al_configure_search) ---\nsearch = af.Nautilus(\n path_prefix=\"imaging/\",\n name=\"sie_sersic\",\n n_live=200,\n number_of_cores=4,\n)\n\n# --- Fit ---\nresult = search.fit(model=model, analysis=analysis)\nprint(result.max_log_likelihood_instance)\n```\n\nRun with sandbox cache overrides if needed:\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/abstract_search.py` (the `fit` method).\nThe returned `Result` object is documented in `PyAutoFit:autofit/non_linear/result.py`.\n\n## Branch \u2014 smoke test (`PYAUTO_TEST_MODE=1`)\n\nWhen you've just written the script and want to know it runs end-to-end *without*\nwaiting for real sampling, set `PYAUTO_TEST_MODE=1`:\n\n```bash\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\nThe search will short-circuit after a small number of likelihood evaluations and\nreturn a `Result` so the script completes. Use this on every script you write, before\nlaunching a real run.\n\nFor an even faster smoke (sub-second per step), combine with PyAutoLens's small-dataset\nflags:\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\nSee [`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md) for the full flag list.\n\n## Output\n\nThe fit writes to `output////` (see\n`al_configure_search` for the layout). Tail the search log live:\n\n```bash\ntail -f output/imaging//sie_sersic/*/search.log\n```\n\nSay this out loud the moment a production fit starts: results are written **on the fly**\nfrom the best model so far, so `model.results` and `image/fit.png` are already worth\nopening \u2014 no need to wait for the search to terminate. For a newcomer, or in teacher\nmode, tour the folder per `_style.md` \"Output folder announcement\" and point at\n`__Output Folder Layout__` in\n[`autolens_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling.py),\nwhich annotates every file the fit writes.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 once the fit completes (or even mid-run),\n load and inspect.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 visualise model vs data.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 feed the result into a follow-up\n search with tighter priors.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) \u2014 if the fit converged badly.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Output management and result\n interpretation](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running fits \u2014 output structure, reviewing results,\n managing run times.\n- **General reference** \u2014 [RTD: New user guide](https://pyautolens.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n decision-tree routing for a new user about which fit to run first.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit on GPU \u2014 production pattern this skill mirrors.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_2_lens_modeling/tutorial_6_masking_and_positions.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_build_imaging_model\n\n---\nname: al_build_imaging_model\ndescription: Compose a strong-lens model for imaging data — galaxies with light + mass profiles, prior customisation, and an `al.AnalysisImaging` ready to hand to a non-linear search. Writes a runnable Python script in scripts/. Pairs with `al_prepare_imaging_data` (which loads + masks the dataset) and `al_run_search` (which executes the fit). For visibility-plane data see `al_build_interferometer_model`.\n---\n\n# Composing an imaging lens model\n\nThe model is the PyAuto\\* representation of *what kind of lens you think this is* — how\nmany galaxies, at what redshifts, with what light and mass parameterisations, with\nwhich parameters free and which fixed. Building one is the step between \"I have a\nloaded `Imaging` dataset\" and \"I'm running a non-linear search\".\n\nThe canonical example is `autolens_workspace:scripts/imaging/modeling.py`. This skill\ngenerates the equivalent for the user's lens.\n\nThis skill assumes the imaging data is already preprocessing-ready. For real\nobservational data, confirm first that the user has **inspected `dataset.png`** and\nthought through mask extent, contaminating objects, and any regions to exclude — in\nparticular that any **extra galaxies** have been handled (noise-scaled via a\n`mask_extra_galaxies.fits`, or excluded by shrinking the circular mask). If not, route\nthem back to [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) before building the\nmodel — don't compose a model over data with an unaddressed contaminant.\n\n## Ask\n\n- *\"If this is real observational data, have you inspected `dataset.png`, decided the\n mask extent, and handled any extra galaxies (noise-scaled a `mask_extra_galaxies.fits`,\n or shrunk the mask to exclude them)?\"* — if not, stop and do that in\n [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) first.\n- *\"How many galaxies in the model — single galaxy-scale, multi-galaxy (2+ co-dominant, no host halo), group (2–10, optional group halo), cluster?\"* —\n this is the only structural choice. Skill below assumes galaxy-scale; bootstrap a\n variant for groups/clusters via `_bootstrap_skill` if needed.\n- *\"What's the lens light parameterisation — a single Sersic, MGE (multi-Gaussian\n expansion), bulge + disk, or no lens light at all (mass-only)?\"*\n- *\"What's the lens mass — Isothermal (SIE) + ExternalShear is the standard starting\n point; PowerLaw or NFW for total or dark-matter-only models.\"*\n- *\"What's the source — parametric Sersic, MGE, or pixelised inversion?\"* — pixelised\n needs a different `Analysis` wiring; see [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md).\n- *\"What are the lens and source redshifts?\"* — needed for distance ratios; even a\n ballpark value works for relative-comparison runs.\n\n## Branch — galaxy-scale, Sersic light + SIE mass + Sersic source\n\nThe minimum viable model. Save to `scripts/build_model.py`:\n\n```python\n# scripts/build_model.py\nfrom autonerves import jax_wrapper\nimport autofit as af\nimport autolens as al\n\n# Lens light — a Sersic for the bulge.\nlens_bulge = af.Model(al.lp.Sersic)\n\n# Lens mass — SIE plus a separate external field.\nlens_mass = af.Model(al.mp.Isothermal)\nlens_shear = af.Model(al.mp.ExternalShear)\n\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=lens_bulge,\n mass=lens_mass,\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=lens_shear)\n\n# Source light — a single Sersic.\nsource = af.Model(\n al.Galaxy,\n redshift=1.0,\n bulge=af.Model(al.lp.SersicCore),\n)\n\n# Compose into a Collection.\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# Optional: customise priors. E.g. tighten the lens centre.\nlens_mass.centre.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\nlens_mass.centre.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n\n# On real data, bound the Einstein radius from the ring you can see in the image\n# (the default prior is uniform over 0-8\"). A maximum-likelihood optimiser such as\n# MultiStartProdigy otherwise finds degenerate basins where theta_E exceeds the mask,\n# the \"source\" lands on a neighbouring galaxy and the ring is left in the residuals\n# (this is exactly what happened on the bundled COSMOS-Web Ring: theta_E 2.4\" vs 0.8\").\nlens_mass.einstein_radius = af.UniformPrior(lower_limit=0.3, upper_limit=1.5)\n\nprint(model.info)\n```\n\nSource citations:\n- `PyAutoGalaxy:autogalaxy/galaxy/galaxy.py` — `Galaxy`.\n- `PyAutoGalaxy:autogalaxy/galaxy/mass_field.py` — `MassField`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — `Sersic`, `SersicCore`.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — `Isothermal`.\n- `PyAutoFit:autofit/mapper/prior_model/prior_model.py` — `af.Model`.\n- `PyAutoFit:autofit/mapper/prior_model/collection.py` — `af.Collection`.\n\nWiki:\n- [`wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md) — what each\n light profile represents and when to pick which.\n- [`wiki/core/concepts/mass_profiles.md`](../wiki/core/concepts/mass_profiles.md) — same for mass.\n- [`wiki/core/concepts/galaxy_and_plane.md`](../wiki/core/concepts/galaxy_and_plane.md) — how\n galaxies, redshifts, and the `Tracer` fit together.\n\n## Branch — linear (MGE) lens light\n\nFor complex lens galaxy morphologies, replace the single Sersic bulge with a Multi-\nGaussian Expansion of *linear* light profiles. Linear profiles have their\n*intensities* solved analytically inside the fit, so the search only varies\nshape parameters — far fewer dimensions, much better convergence.\n\n```python\nn_gaussians = 30\ngaussian_per_basis = [\n af.Model(al.lp_linear.Gaussian) for _ in range(n_gaussians)\n]\n# Tie centres + ellipticities across the basis; let only sigma + intensity vary.\nfor g in gaussian_per_basis[1:]:\n g.centre = gaussian_per_basis[0].centre\n g.ell_comps = gaussian_per_basis[0].ell_comps\n\nlens_bulge = af.Model(al.lp_basis.Basis, profile_list=gaussian_per_basis)\n```\n\nSee `PyAutoGalaxy:autogalaxy/profiles/light/linear/` for the linear-profile classes.\n\n## Branch — pixelised source\n\nFor sources with complex morphology (lensed arcs, multiple components), reconstruct\nthe source on a pixel grid rather than as a parametric Sersic. The model wiring is\ndifferent: the source `Galaxy` carries a `Pixelization`, and the `Analysis` needs a\npositions likelihood penalty to keep the inversion well-posed.\n\nSee [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) for\nthe full pattern.\n\n## Wrap with an analysis\n\nOnce the model is built, wrap your loaded `dataset` (from `al_prepare_imaging_data`)\nin an analysis object:\n\n```python\nanalysis = al.AnalysisImaging(dataset=dataset)\n```\n\nSource: `PyAutoLens:autolens/imaging/model/analysis.py`.\n\n`analysis` + `model` are the two inputs to the non-linear search. Pass them to\n[`al_run_search`](./al_run_search.md).\n\n## Combine\n\nNatural next steps:\n\n- [`al_configure_search`](./al_configure_search.md) — pick Nautilus (default), Dynesty,\n Emcee, or another search; tune live points / walkers.\n- [`al_run_search`](./al_run_search.md) — `search.fit(model=model, analysis=analysis)`.\n- [`al_chain_searches`](./al_chain_searches.md) — chain a fast Sersic source fit into\n a slower pixelised one, inheriting priors.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Non-linear searches and parameter\n inference](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb):\n how non-linear searches find a best-fit model — parameter spaces, likelihoods,\n priors. The statistical foundation under model composition.\n- **General reference** — [RTD: Model cookbook](https://pyautolens.readthedocs.io/en/latest/general/model_cookbook.html):\n systematic reference for building lens models with `Model` and `Collection` —\n two-component to multi-galaxy, prior customisation, parameter pairing, MGE.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/modeling/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling/start_here.py):\n the canonical imaging-modeling script — light-profile choice (Sersic vs. MGE),\n non-linear-search configuration, JAX/GPU fitting.\n\n## Skill: al_run_search\n\n---\nname: al_run_search\ndescription: Execute a non-linear search on a configured model + analysis. Calls `search.fit(model=model, analysis=analysis)` and monitors progress to the search's `path_prefix/name/unique_id/` output folder. Includes the sandbox / test-mode wrapper so smoke tests don't burn hours on real sampling. Use after `al_build_imaging_model` (or interferometer) and `al_configure_search` have produced `model`, `analysis`, and `search` objects.\n---\n\n# Running a non-linear search\n\nThe actual fit. Inputs: a model, an analysis (which knows the dataset and how to\ncompute a log-likelihood), and a search (which knows how to explore parameter space).\nThe single call `search.fit(model=model, analysis=analysis)` does the work.\n\nThis skill assembles those three pieces into a runnable script, then runs it — either\nin `PYAUTO_TEST_MODE=1` for a smoke test or in production mode for the real fit.\n\n## Ask\n\n- *\"Have you built `model` and `analysis` (from `al_build_imaging_model`) and\n configured `search` (from `al_configure_search`)?\"* If not, route to those first.\n- *\"Smoke test or production run?\"* Smoke test runs in seconds with `PYAUTO_TEST_MODE=1`\n and a tiny dataset, just to prove the wiring is correct. Production run takes hours\n to a day depending on model complexity and number of likelihood evals.\n- *\"How long can the fit run?\"* Sets expectations and decides whether to launch it as\n a foreground or backgrounded process.\n\n## Branch — production run\n\nOperational reminder: if the search was configured with `live_visual_update=True`\n(`al_configure_search` \"Live visual updates\"), a foreground script opens a matplotlib viewer\nand a notebook cell refreshes in place — don't re-ask when the search configuration already\nrecords the choice, and keep it `False` for HPC/headless/background runs. `fit.png` is\nwritten to disk on every quick update either way.\n\nAssemble everything into one script (`scripts/run_fit.py`):\n\n```python\n# scripts/run_fit.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autofit as af\nimport autolens as al\n\n# --- Dataset (from al_prepare_imaging_data) ---\ndataset_path = Path(\"dataset/imaging/\")\ndataset = al.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.06,\n)\nmask = al.Mask2D.circular(\n shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5\n)\ndataset = dataset.apply_mask(mask=mask)\n\n# --- Model (from al_build_imaging_model) ---\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=af.Model(al.lp.Sersic),\n mass=af.Model(al.mp.Isothermal),\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=af.Model(al.mp.ExternalShear))\nsource = af.Model(al.Galaxy, redshift=1.0, bulge=af.Model(al.lp.SersicCore))\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# --- Analysis ---\nanalysis = al.AnalysisImaging(dataset=dataset)\n\n# --- Search (from al_configure_search) ---\nsearch = af.Nautilus(\n path_prefix=\"imaging/\",\n name=\"sie_sersic\",\n n_live=200,\n number_of_cores=4,\n)\n\n# --- Fit ---\nresult = search.fit(model=model, analysis=analysis)\nprint(result.max_log_likelihood_instance)\n```\n\nRun with sandbox cache overrides if needed:\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/abstract_search.py` (the `fit` method).\nThe returned `Result` object is documented in `PyAutoFit:autofit/non_linear/result.py`.\n\n## Branch — smoke test (`PYAUTO_TEST_MODE=1`)\n\nWhen you've just written the script and want to know it runs end-to-end *without*\nwaiting for real sampling, set `PYAUTO_TEST_MODE=1`:\n\n```bash\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\nThe search will short-circuit after a small number of likelihood evaluations and\nreturn a `Result` so the script completes. Use this on every script you write, before\nlaunching a real run.\n\nFor an even faster smoke (sub-second per step), combine with PyAutoLens's small-dataset\nflags:\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\nSee [`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md) for the full flag list.\n\n## Output\n\nThe fit writes to `output////` (see\n`al_configure_search` for the layout). Tail the search log live:\n\n```bash\ntail -f output/imaging//sie_sersic/*/search.log\n```\n\nSay this out loud the moment a production fit starts: results are written **on the fly**\nfrom the best model so far, so `model.results` and `image/fit.png` are already worth\nopening — no need to wait for the search to terminate. For a newcomer, or in teacher\nmode, tour the folder per `_style.md` \"Output folder announcement\" and point at\n`__Output Folder Layout__` in\n[`autolens_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling.py),\nwhich annotates every file the fit writes.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — once the fit completes (or even mid-run),\n load and inspect.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — visualise model vs data.\n- [`al_chain_searches`](./al_chain_searches.md) — feed the result into a follow-up\n search with tighter priors.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) — if the fit converged badly.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Output management and result\n interpretation](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running fits — output structure, reviewing results,\n managing run times.\n- **General reference** — [RTD: New user guide](https://pyautolens.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n decision-tree routing for a new user about which fit to run first.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit on GPU — production pattern this skill mirrors.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_2_lens_modeling/tutorial_7_results.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_7_results.ipynb index abe015a..52e0a4d 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_7_results.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_7_results.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/HowToLens/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", @@ -286,7 +286,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_2_lens_modeling/tutorial_7_results.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_build_imaging_model\n\n---\nname: al_build_imaging_model\ndescription: Compose a strong-lens model for imaging data \u2014 galaxies with light + mass profiles, prior customisation, and an `al.AnalysisImaging` ready to hand to a non-linear search. Writes a runnable Python script in scripts/. Pairs with `al_prepare_imaging_data` (which loads + masks the dataset) and `al_run_search` (which executes the fit). For visibility-plane data see `al_build_interferometer_model`.\n---\n\n# Composing an imaging lens model\n\nThe model is the PyAuto\\* representation of *what kind of lens you think this is* \u2014 how\nmany galaxies, at what redshifts, with what light and mass parameterisations, with\nwhich parameters free and which fixed. Building one is the step between \"I have a\nloaded `Imaging` dataset\" and \"I'm running a non-linear search\".\n\nThe canonical example is `autolens_workspace:scripts/imaging/modeling.py`. This skill\ngenerates the equivalent for the user's lens.\n\nThis skill assumes the imaging data is already preprocessing-ready. For real\nobservational data, confirm first that the user has **inspected `dataset.png`** and\nthought through mask extent, contaminating objects, and any regions to exclude \u2014 in\nparticular that any **extra galaxies** have been handled (noise-scaled via a\n`mask_extra_galaxies.fits`, or excluded by shrinking the circular mask). If not, route\nthem back to [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) before building the\nmodel \u2014 don't compose a model over data with an unaddressed contaminant.\n\n## Ask\n\n- *\"If this is real observational data, have you inspected `dataset.png`, decided the\n mask extent, and handled any extra galaxies (noise-scaled a `mask_extra_galaxies.fits`,\n or shrunk the mask to exclude them)?\"* \u2014 if not, stop and do that in\n [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) first.\n- *\"How many galaxies in the model \u2014 single galaxy-scale, multi-galaxy (2+ co-dominant, no host halo), group (2\u201310, optional group halo), cluster?\"* \u2014\n this is the only structural choice. Skill below assumes galaxy-scale; bootstrap a\n variant for groups/clusters via `_bootstrap_skill` if needed.\n- *\"What's the lens light parameterisation \u2014 a single Sersic, MGE (multi-Gaussian\n expansion), bulge + disk, or no lens light at all (mass-only)?\"*\n- *\"What's the lens mass \u2014 Isothermal (SIE) + ExternalShear is the standard starting\n point; PowerLaw or NFW for total or dark-matter-only models.\"*\n- *\"What's the source \u2014 parametric Sersic, MGE, or pixelised inversion?\"* \u2014 pixelised\n needs a different `Analysis` wiring; see [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md).\n- *\"What are the lens and source redshifts?\"* \u2014 needed for distance ratios; even a\n ballpark value works for relative-comparison runs.\n\n## Branch \u2014 galaxy-scale, Sersic light + SIE mass + Sersic source\n\nThe minimum viable model. Save to `scripts/build_model.py`:\n\n```python\n# scripts/build_model.py\nfrom autonerves import jax_wrapper\nimport autofit as af\nimport autolens as al\n\n# Lens light \u2014 a Sersic for the bulge.\nlens_bulge = af.Model(al.lp.Sersic)\n\n# Lens mass \u2014 SIE plus a separate external field.\nlens_mass = af.Model(al.mp.Isothermal)\nlens_shear = af.Model(al.mp.ExternalShear)\n\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=lens_bulge,\n mass=lens_mass,\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=lens_shear)\n\n# Source light \u2014 a single Sersic.\nsource = af.Model(\n al.Galaxy,\n redshift=1.0,\n bulge=af.Model(al.lp.SersicCore),\n)\n\n# Compose into a Collection.\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# Optional: customise priors. E.g. tighten the lens centre.\nlens_mass.centre.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\nlens_mass.centre.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n\n# On real data, bound the Einstein radius from the ring you can see in the image\n# (the default prior is uniform over 0-8\"). A maximum-likelihood optimiser such as\n# MultiStartProdigy otherwise finds degenerate basins where theta_E exceeds the mask,\n# the \"source\" lands on a neighbouring galaxy and the ring is left in the residuals\n# (this is exactly what happened on the bundled COSMOS-Web Ring: theta_E 2.4\" vs 0.8\").\nlens_mass.einstein_radius = af.UniformPrior(lower_limit=0.3, upper_limit=1.5)\n\nprint(model.info)\n```\n\nSource citations:\n- `PyAutoGalaxy:autogalaxy/galaxy/galaxy.py` \u2014 `Galaxy`.\n- `PyAutoGalaxy:autogalaxy/galaxy/mass_field.py` \u2014 `MassField`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 `Sersic`, `SersicCore`.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 `Isothermal`.\n- `PyAutoFit:autofit/mapper/prior_model/prior_model.py` \u2014 `af.Model`.\n- `PyAutoFit:autofit/mapper/prior_model/collection.py` \u2014 `af.Collection`.\n\nWiki:\n- [`wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md) \u2014 what each\n light profile represents and when to pick which.\n- [`wiki/core/concepts/mass_profiles.md`](../wiki/core/concepts/mass_profiles.md) \u2014 same for mass.\n- [`wiki/core/concepts/galaxy_and_plane.md`](../wiki/core/concepts/galaxy_and_plane.md) \u2014 how\n galaxies, redshifts, and the `Tracer` fit together.\n\n## Branch \u2014 linear (MGE) lens light\n\nFor complex lens galaxy morphologies, replace the single Sersic bulge with a Multi-\nGaussian Expansion of *linear* light profiles. Linear profiles have their\n*intensities* solved analytically inside the fit, so the search only varies\nshape parameters \u2014 far fewer dimensions, much better convergence.\n\n```python\nn_gaussians = 30\ngaussian_per_basis = [\n af.Model(al.lp_linear.Gaussian) for _ in range(n_gaussians)\n]\n# Tie centres + ellipticities across the basis; let only sigma + intensity vary.\nfor g in gaussian_per_basis[1:]:\n g.centre = gaussian_per_basis[0].centre\n g.ell_comps = gaussian_per_basis[0].ell_comps\n\nlens_bulge = af.Model(al.lp_basis.Basis, profile_list=gaussian_per_basis)\n```\n\nSee `PyAutoGalaxy:autogalaxy/profiles/light/linear/` for the linear-profile classes.\n\n## Branch \u2014 pixelised source\n\nFor sources with complex morphology (lensed arcs, multiple components), reconstruct\nthe source on a pixel grid rather than as a parametric Sersic. The model wiring is\ndifferent: the source `Galaxy` carries a `Pixelization`, and the `Analysis` needs a\npositions likelihood penalty to keep the inversion well-posed.\n\nSee [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) for\nthe full pattern.\n\n## Wrap with an analysis\n\nOnce the model is built, wrap your loaded `dataset` (from `al_prepare_imaging_data`)\nin an analysis object:\n\n```python\nanalysis = al.AnalysisImaging(dataset=dataset)\n```\n\nSource: `PyAutoLens:autolens/imaging/model/analysis.py`.\n\n`analysis` + `model` are the two inputs to the non-linear search. Pass them to\n[`al_run_search`](./al_run_search.md).\n\n## Combine\n\nNatural next steps:\n\n- [`al_configure_search`](./al_configure_search.md) \u2014 pick Nautilus (default), Dynesty,\n Emcee, or another search; tune live points / walkers.\n- [`al_run_search`](./al_run_search.md) \u2014 `search.fit(model=model, analysis=analysis)`.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 chain a fast Sersic source fit into\n a slower pixelised one, inheriting priors.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Non-linear searches and parameter\n inference](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb):\n how non-linear searches find a best-fit model \u2014 parameter spaces, likelihoods,\n priors. The statistical foundation under model composition.\n- **General reference** \u2014 [RTD: Model cookbook](https://pyautolens.readthedocs.io/en/latest/general/model_cookbook.html):\n systematic reference for building lens models with `Model` and `Collection` \u2014\n two-component to multi-galaxy, prior customisation, parameter pairing, MGE.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/modeling/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling/start_here.py):\n the canonical imaging-modeling script \u2014 light-profile choice (Sersic vs. MGE),\n non-linear-search configuration, JAX/GPU fitting.\n\n## Skill: al_run_search\n\n---\nname: al_run_search\ndescription: Execute a non-linear search on a configured model + analysis. Calls `search.fit(model=model, analysis=analysis)` and monitors progress to the search's `path_prefix/name/unique_id/` output folder. Includes the sandbox / test-mode wrapper so smoke tests don't burn hours on real sampling. Use after `al_build_imaging_model` (or interferometer) and `al_configure_search` have produced `model`, `analysis`, and `search` objects.\n---\n\n# Running a non-linear search\n\nThe actual fit. Inputs: a model, an analysis (which knows the dataset and how to\ncompute a log-likelihood), and a search (which knows how to explore parameter space).\nThe single call `search.fit(model=model, analysis=analysis)` does the work.\n\nThis skill assembles those three pieces into a runnable script, then runs it \u2014 either\nin `PYAUTO_TEST_MODE=1` for a smoke test or in production mode for the real fit.\n\n## Ask\n\n- *\"Have you built `model` and `analysis` (from `al_build_imaging_model`) and\n configured `search` (from `al_configure_search`)?\"* If not, route to those first.\n- *\"Smoke test or production run?\"* Smoke test runs in seconds with `PYAUTO_TEST_MODE=1`\n and a tiny dataset, just to prove the wiring is correct. Production run takes hours\n to a day depending on model complexity and number of likelihood evals.\n- *\"How long can the fit run?\"* Sets expectations and decides whether to launch it as\n a foreground or backgrounded process.\n\n## Branch \u2014 production run\n\nOperational reminder: if the search was configured with `live_visual_update=True`\n(`al_configure_search` \"Live visual updates\"), a foreground script opens a matplotlib viewer\nand a notebook cell refreshes in place \u2014 don't re-ask when the search configuration already\nrecords the choice, and keep it `False` for HPC/headless/background runs. `fit.png` is\nwritten to disk on every quick update either way.\n\nAssemble everything into one script (`scripts/run_fit.py`):\n\n```python\n# scripts/run_fit.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autofit as af\nimport autolens as al\n\n# --- Dataset (from al_prepare_imaging_data) ---\ndataset_path = Path(\"dataset/imaging/\")\ndataset = al.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.06,\n)\nmask = al.Mask2D.circular(\n shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5\n)\ndataset = dataset.apply_mask(mask=mask)\n\n# --- Model (from al_build_imaging_model) ---\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=af.Model(al.lp.Sersic),\n mass=af.Model(al.mp.Isothermal),\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=af.Model(al.mp.ExternalShear))\nsource = af.Model(al.Galaxy, redshift=1.0, bulge=af.Model(al.lp.SersicCore))\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# --- Analysis ---\nanalysis = al.AnalysisImaging(dataset=dataset)\n\n# --- Search (from al_configure_search) ---\nsearch = af.Nautilus(\n path_prefix=\"imaging/\",\n name=\"sie_sersic\",\n n_live=200,\n number_of_cores=4,\n)\n\n# --- Fit ---\nresult = search.fit(model=model, analysis=analysis)\nprint(result.max_log_likelihood_instance)\n```\n\nRun with sandbox cache overrides if needed:\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/abstract_search.py` (the `fit` method).\nThe returned `Result` object is documented in `PyAutoFit:autofit/non_linear/result.py`.\n\n## Branch \u2014 smoke test (`PYAUTO_TEST_MODE=1`)\n\nWhen you've just written the script and want to know it runs end-to-end *without*\nwaiting for real sampling, set `PYAUTO_TEST_MODE=1`:\n\n```bash\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\nThe search will short-circuit after a small number of likelihood evaluations and\nreturn a `Result` so the script completes. Use this on every script you write, before\nlaunching a real run.\n\nFor an even faster smoke (sub-second per step), combine with PyAutoLens's small-dataset\nflags:\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\nSee [`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md) for the full flag list.\n\n## Output\n\nThe fit writes to `output////` (see\n`al_configure_search` for the layout). Tail the search log live:\n\n```bash\ntail -f output/imaging//sie_sersic/*/search.log\n```\n\nSay this out loud the moment a production fit starts: results are written **on the fly**\nfrom the best model so far, so `model.results` and `image/fit.png` are already worth\nopening \u2014 no need to wait for the search to terminate. For a newcomer, or in teacher\nmode, tour the folder per `_style.md` \"Output folder announcement\" and point at\n`__Output Folder Layout__` in\n[`autolens_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling.py),\nwhich annotates every file the fit writes.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 once the fit completes (or even mid-run),\n load and inspect.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 visualise model vs data.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 feed the result into a follow-up\n search with tighter priors.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) \u2014 if the fit converged badly.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Output management and result\n interpretation](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running fits \u2014 output structure, reviewing results,\n managing run times.\n- **General reference** \u2014 [RTD: New user guide](https://pyautolens.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n decision-tree routing for a new user about which fit to run first.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit on GPU \u2014 production pattern this skill mirrors.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_2_lens_modeling/tutorial_7_results.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_build_imaging_model\n\n---\nname: al_build_imaging_model\ndescription: Compose a strong-lens model for imaging data — galaxies with light + mass profiles, prior customisation, and an `al.AnalysisImaging` ready to hand to a non-linear search. Writes a runnable Python script in scripts/. Pairs with `al_prepare_imaging_data` (which loads + masks the dataset) and `al_run_search` (which executes the fit). For visibility-plane data see `al_build_interferometer_model`.\n---\n\n# Composing an imaging lens model\n\nThe model is the PyAuto\\* representation of *what kind of lens you think this is* — how\nmany galaxies, at what redshifts, with what light and mass parameterisations, with\nwhich parameters free and which fixed. Building one is the step between \"I have a\nloaded `Imaging` dataset\" and \"I'm running a non-linear search\".\n\nThe canonical example is `autolens_workspace:scripts/imaging/modeling.py`. This skill\ngenerates the equivalent for the user's lens.\n\nThis skill assumes the imaging data is already preprocessing-ready. For real\nobservational data, confirm first that the user has **inspected `dataset.png`** and\nthought through mask extent, contaminating objects, and any regions to exclude — in\nparticular that any **extra galaxies** have been handled (noise-scaled via a\n`mask_extra_galaxies.fits`, or excluded by shrinking the circular mask). If not, route\nthem back to [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) before building the\nmodel — don't compose a model over data with an unaddressed contaminant.\n\n## Ask\n\n- *\"If this is real observational data, have you inspected `dataset.png`, decided the\n mask extent, and handled any extra galaxies (noise-scaled a `mask_extra_galaxies.fits`,\n or shrunk the mask to exclude them)?\"* — if not, stop and do that in\n [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) first.\n- *\"How many galaxies in the model — single galaxy-scale, multi-galaxy (2+ co-dominant, no host halo), group (2–10, optional group halo), cluster?\"* —\n this is the only structural choice. Skill below assumes galaxy-scale; bootstrap a\n variant for groups/clusters via `_bootstrap_skill` if needed.\n- *\"What's the lens light parameterisation — a single Sersic, MGE (multi-Gaussian\n expansion), bulge + disk, or no lens light at all (mass-only)?\"*\n- *\"What's the lens mass — Isothermal (SIE) + ExternalShear is the standard starting\n point; PowerLaw or NFW for total or dark-matter-only models.\"*\n- *\"What's the source — parametric Sersic, MGE, or pixelised inversion?\"* — pixelised\n needs a different `Analysis` wiring; see [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md).\n- *\"What are the lens and source redshifts?\"* — needed for distance ratios; even a\n ballpark value works for relative-comparison runs.\n\n## Branch — galaxy-scale, Sersic light + SIE mass + Sersic source\n\nThe minimum viable model. Save to `scripts/build_model.py`:\n\n```python\n# scripts/build_model.py\nfrom autonerves import jax_wrapper\nimport autofit as af\nimport autolens as al\n\n# Lens light — a Sersic for the bulge.\nlens_bulge = af.Model(al.lp.Sersic)\n\n# Lens mass — SIE plus a separate external field.\nlens_mass = af.Model(al.mp.Isothermal)\nlens_shear = af.Model(al.mp.ExternalShear)\n\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=lens_bulge,\n mass=lens_mass,\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=lens_shear)\n\n# Source light — a single Sersic.\nsource = af.Model(\n al.Galaxy,\n redshift=1.0,\n bulge=af.Model(al.lp.SersicCore),\n)\n\n# Compose into a Collection.\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# Optional: customise priors. E.g. tighten the lens centre.\nlens_mass.centre.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\nlens_mass.centre.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n\n# On real data, bound the Einstein radius from the ring you can see in the image\n# (the default prior is uniform over 0-8\"). A maximum-likelihood optimiser such as\n# MultiStartProdigy otherwise finds degenerate basins where theta_E exceeds the mask,\n# the \"source\" lands on a neighbouring galaxy and the ring is left in the residuals\n# (this is exactly what happened on the bundled COSMOS-Web Ring: theta_E 2.4\" vs 0.8\").\nlens_mass.einstein_radius = af.UniformPrior(lower_limit=0.3, upper_limit=1.5)\n\nprint(model.info)\n```\n\nSource citations:\n- `PyAutoGalaxy:autogalaxy/galaxy/galaxy.py` — `Galaxy`.\n- `PyAutoGalaxy:autogalaxy/galaxy/mass_field.py` — `MassField`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — `Sersic`, `SersicCore`.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — `Isothermal`.\n- `PyAutoFit:autofit/mapper/prior_model/prior_model.py` — `af.Model`.\n- `PyAutoFit:autofit/mapper/prior_model/collection.py` — `af.Collection`.\n\nWiki:\n- [`wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md) — what each\n light profile represents and when to pick which.\n- [`wiki/core/concepts/mass_profiles.md`](../wiki/core/concepts/mass_profiles.md) — same for mass.\n- [`wiki/core/concepts/galaxy_and_plane.md`](../wiki/core/concepts/galaxy_and_plane.md) — how\n galaxies, redshifts, and the `Tracer` fit together.\n\n## Branch — linear (MGE) lens light\n\nFor complex lens galaxy morphologies, replace the single Sersic bulge with a Multi-\nGaussian Expansion of *linear* light profiles. Linear profiles have their\n*intensities* solved analytically inside the fit, so the search only varies\nshape parameters — far fewer dimensions, much better convergence.\n\n```python\nn_gaussians = 30\ngaussian_per_basis = [\n af.Model(al.lp_linear.Gaussian) for _ in range(n_gaussians)\n]\n# Tie centres + ellipticities across the basis; let only sigma + intensity vary.\nfor g in gaussian_per_basis[1:]:\n g.centre = gaussian_per_basis[0].centre\n g.ell_comps = gaussian_per_basis[0].ell_comps\n\nlens_bulge = af.Model(al.lp_basis.Basis, profile_list=gaussian_per_basis)\n```\n\nSee `PyAutoGalaxy:autogalaxy/profiles/light/linear/` for the linear-profile classes.\n\n## Branch — pixelised source\n\nFor sources with complex morphology (lensed arcs, multiple components), reconstruct\nthe source on a pixel grid rather than as a parametric Sersic. The model wiring is\ndifferent: the source `Galaxy` carries a `Pixelization`, and the `Analysis` needs a\npositions likelihood penalty to keep the inversion well-posed.\n\nSee [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) for\nthe full pattern.\n\n## Wrap with an analysis\n\nOnce the model is built, wrap your loaded `dataset` (from `al_prepare_imaging_data`)\nin an analysis object:\n\n```python\nanalysis = al.AnalysisImaging(dataset=dataset)\n```\n\nSource: `PyAutoLens:autolens/imaging/model/analysis.py`.\n\n`analysis` + `model` are the two inputs to the non-linear search. Pass them to\n[`al_run_search`](./al_run_search.md).\n\n## Combine\n\nNatural next steps:\n\n- [`al_configure_search`](./al_configure_search.md) — pick Nautilus (default), Dynesty,\n Emcee, or another search; tune live points / walkers.\n- [`al_run_search`](./al_run_search.md) — `search.fit(model=model, analysis=analysis)`.\n- [`al_chain_searches`](./al_chain_searches.md) — chain a fast Sersic source fit into\n a slower pixelised one, inheriting priors.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Non-linear searches and parameter\n inference](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb):\n how non-linear searches find a best-fit model — parameter spaces, likelihoods,\n priors. The statistical foundation under model composition.\n- **General reference** — [RTD: Model cookbook](https://pyautolens.readthedocs.io/en/latest/general/model_cookbook.html):\n systematic reference for building lens models with `Model` and `Collection` —\n two-component to multi-galaxy, prior customisation, parameter pairing, MGE.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/modeling/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling/start_here.py):\n the canonical imaging-modeling script — light-profile choice (Sersic vs. MGE),\n non-linear-search configuration, JAX/GPU fitting.\n\n## Skill: al_run_search\n\n---\nname: al_run_search\ndescription: Execute a non-linear search on a configured model + analysis. Calls `search.fit(model=model, analysis=analysis)` and monitors progress to the search's `path_prefix/name/unique_id/` output folder. Includes the sandbox / test-mode wrapper so smoke tests don't burn hours on real sampling. Use after `al_build_imaging_model` (or interferometer) and `al_configure_search` have produced `model`, `analysis`, and `search` objects.\n---\n\n# Running a non-linear search\n\nThe actual fit. Inputs: a model, an analysis (which knows the dataset and how to\ncompute a log-likelihood), and a search (which knows how to explore parameter space).\nThe single call `search.fit(model=model, analysis=analysis)` does the work.\n\nThis skill assembles those three pieces into a runnable script, then runs it — either\nin `PYAUTO_TEST_MODE=1` for a smoke test or in production mode for the real fit.\n\n## Ask\n\n- *\"Have you built `model` and `analysis` (from `al_build_imaging_model`) and\n configured `search` (from `al_configure_search`)?\"* If not, route to those first.\n- *\"Smoke test or production run?\"* Smoke test runs in seconds with `PYAUTO_TEST_MODE=1`\n and a tiny dataset, just to prove the wiring is correct. Production run takes hours\n to a day depending on model complexity and number of likelihood evals.\n- *\"How long can the fit run?\"* Sets expectations and decides whether to launch it as\n a foreground or backgrounded process.\n\n## Branch — production run\n\nOperational reminder: if the search was configured with `live_visual_update=True`\n(`al_configure_search` \"Live visual updates\"), a foreground script opens a matplotlib viewer\nand a notebook cell refreshes in place — don't re-ask when the search configuration already\nrecords the choice, and keep it `False` for HPC/headless/background runs. `fit.png` is\nwritten to disk on every quick update either way.\n\nAssemble everything into one script (`scripts/run_fit.py`):\n\n```python\n# scripts/run_fit.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autofit as af\nimport autolens as al\n\n# --- Dataset (from al_prepare_imaging_data) ---\ndataset_path = Path(\"dataset/imaging/\")\ndataset = al.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.06,\n)\nmask = al.Mask2D.circular(\n shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5\n)\ndataset = dataset.apply_mask(mask=mask)\n\n# --- Model (from al_build_imaging_model) ---\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=af.Model(al.lp.Sersic),\n mass=af.Model(al.mp.Isothermal),\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=af.Model(al.mp.ExternalShear))\nsource = af.Model(al.Galaxy, redshift=1.0, bulge=af.Model(al.lp.SersicCore))\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# --- Analysis ---\nanalysis = al.AnalysisImaging(dataset=dataset)\n\n# --- Search (from al_configure_search) ---\nsearch = af.Nautilus(\n path_prefix=\"imaging/\",\n name=\"sie_sersic\",\n n_live=200,\n number_of_cores=4,\n)\n\n# --- Fit ---\nresult = search.fit(model=model, analysis=analysis)\nprint(result.max_log_likelihood_instance)\n```\n\nRun with sandbox cache overrides if needed:\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/abstract_search.py` (the `fit` method).\nThe returned `Result` object is documented in `PyAutoFit:autofit/non_linear/result.py`.\n\n## Branch — smoke test (`PYAUTO_TEST_MODE=1`)\n\nWhen you've just written the script and want to know it runs end-to-end *without*\nwaiting for real sampling, set `PYAUTO_TEST_MODE=1`:\n\n```bash\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\nThe search will short-circuit after a small number of likelihood evaluations and\nreturn a `Result` so the script completes. Use this on every script you write, before\nlaunching a real run.\n\nFor an even faster smoke (sub-second per step), combine with PyAutoLens's small-dataset\nflags:\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\nSee [`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md) for the full flag list.\n\n## Output\n\nThe fit writes to `output////` (see\n`al_configure_search` for the layout). Tail the search log live:\n\n```bash\ntail -f output/imaging//sie_sersic/*/search.log\n```\n\nSay this out loud the moment a production fit starts: results are written **on the fly**\nfrom the best model so far, so `model.results` and `image/fit.png` are already worth\nopening — no need to wait for the search to terminate. For a newcomer, or in teacher\nmode, tour the folder per `_style.md` \"Output folder announcement\" and point at\n`__Output Folder Layout__` in\n[`autolens_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling.py),\nwhich annotates every file the fit writes.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — once the fit completes (or even mid-run),\n load and inspect.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — visualise model vs data.\n- [`al_chain_searches`](./al_chain_searches.md) — feed the result into a follow-up\n search with tighter priors.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) — if the fit converged badly.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Output management and result\n interpretation](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running fits — output structure, reviewing results,\n managing run times.\n- **General reference** — [RTD: New user guide](https://pyautolens.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n decision-tree routing for a new user about which fit to run first.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit on GPU — production pattern this skill mirrors.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_2_lens_modeling/tutorial_8_need_for_speed.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_8_need_for_speed.ipynb index b52fe63..2397469 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_8_need_for_speed.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_8_need_for_speed.ipynb @@ -175,21 +175,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/HowToLens/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", @@ -242,7 +242,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_2_lens_modeling/tutorial_8_need_for_speed.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_build_imaging_model\n\n---\nname: al_build_imaging_model\ndescription: Compose a strong-lens model for imaging data \u2014 galaxies with light + mass profiles, prior customisation, and an `al.AnalysisImaging` ready to hand to a non-linear search. Writes a runnable Python script in scripts/. Pairs with `al_prepare_imaging_data` (which loads + masks the dataset) and `al_run_search` (which executes the fit). For visibility-plane data see `al_build_interferometer_model`.\n---\n\n# Composing an imaging lens model\n\nThe model is the PyAuto\\* representation of *what kind of lens you think this is* \u2014 how\nmany galaxies, at what redshifts, with what light and mass parameterisations, with\nwhich parameters free and which fixed. Building one is the step between \"I have a\nloaded `Imaging` dataset\" and \"I'm running a non-linear search\".\n\nThe canonical example is `autolens_workspace:scripts/imaging/modeling.py`. This skill\ngenerates the equivalent for the user's lens.\n\nThis skill assumes the imaging data is already preprocessing-ready. For real\nobservational data, confirm first that the user has **inspected `dataset.png`** and\nthought through mask extent, contaminating objects, and any regions to exclude \u2014 in\nparticular that any **extra galaxies** have been handled (noise-scaled via a\n`mask_extra_galaxies.fits`, or excluded by shrinking the circular mask). If not, route\nthem back to [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) before building the\nmodel \u2014 don't compose a model over data with an unaddressed contaminant.\n\n## Ask\n\n- *\"If this is real observational data, have you inspected `dataset.png`, decided the\n mask extent, and handled any extra galaxies (noise-scaled a `mask_extra_galaxies.fits`,\n or shrunk the mask to exclude them)?\"* \u2014 if not, stop and do that in\n [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) first.\n- *\"How many galaxies in the model \u2014 single galaxy-scale, multi-galaxy (2+ co-dominant, no host halo), group (2\u201310, optional group halo), cluster?\"* \u2014\n this is the only structural choice. Skill below assumes galaxy-scale; bootstrap a\n variant for groups/clusters via `_bootstrap_skill` if needed.\n- *\"What's the lens light parameterisation \u2014 a single Sersic, MGE (multi-Gaussian\n expansion), bulge + disk, or no lens light at all (mass-only)?\"*\n- *\"What's the lens mass \u2014 Isothermal (SIE) + ExternalShear is the standard starting\n point; PowerLaw or NFW for total or dark-matter-only models.\"*\n- *\"What's the source \u2014 parametric Sersic, MGE, or pixelised inversion?\"* \u2014 pixelised\n needs a different `Analysis` wiring; see [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md).\n- *\"What are the lens and source redshifts?\"* \u2014 needed for distance ratios; even a\n ballpark value works for relative-comparison runs.\n\n## Branch \u2014 galaxy-scale, Sersic light + SIE mass + Sersic source\n\nThe minimum viable model. Save to `scripts/build_model.py`:\n\n```python\n# scripts/build_model.py\nfrom autonerves import jax_wrapper\nimport autofit as af\nimport autolens as al\n\n# Lens light \u2014 a Sersic for the bulge.\nlens_bulge = af.Model(al.lp.Sersic)\n\n# Lens mass \u2014 SIE plus a separate external field.\nlens_mass = af.Model(al.mp.Isothermal)\nlens_shear = af.Model(al.mp.ExternalShear)\n\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=lens_bulge,\n mass=lens_mass,\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=lens_shear)\n\n# Source light \u2014 a single Sersic.\nsource = af.Model(\n al.Galaxy,\n redshift=1.0,\n bulge=af.Model(al.lp.SersicCore),\n)\n\n# Compose into a Collection.\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# Optional: customise priors. E.g. tighten the lens centre.\nlens_mass.centre.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\nlens_mass.centre.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n\n# On real data, bound the Einstein radius from the ring you can see in the image\n# (the default prior is uniform over 0-8\"). A maximum-likelihood optimiser such as\n# MultiStartProdigy otherwise finds degenerate basins where theta_E exceeds the mask,\n# the \"source\" lands on a neighbouring galaxy and the ring is left in the residuals\n# (this is exactly what happened on the bundled COSMOS-Web Ring: theta_E 2.4\" vs 0.8\").\nlens_mass.einstein_radius = af.UniformPrior(lower_limit=0.3, upper_limit=1.5)\n\nprint(model.info)\n```\n\nSource citations:\n- `PyAutoGalaxy:autogalaxy/galaxy/galaxy.py` \u2014 `Galaxy`.\n- `PyAutoGalaxy:autogalaxy/galaxy/mass_field.py` \u2014 `MassField`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 `Sersic`, `SersicCore`.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 `Isothermal`.\n- `PyAutoFit:autofit/mapper/prior_model/prior_model.py` \u2014 `af.Model`.\n- `PyAutoFit:autofit/mapper/prior_model/collection.py` \u2014 `af.Collection`.\n\nWiki:\n- [`wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md) \u2014 what each\n light profile represents and when to pick which.\n- [`wiki/core/concepts/mass_profiles.md`](../wiki/core/concepts/mass_profiles.md) \u2014 same for mass.\n- [`wiki/core/concepts/galaxy_and_plane.md`](../wiki/core/concepts/galaxy_and_plane.md) \u2014 how\n galaxies, redshifts, and the `Tracer` fit together.\n\n## Branch \u2014 linear (MGE) lens light\n\nFor complex lens galaxy morphologies, replace the single Sersic bulge with a Multi-\nGaussian Expansion of *linear* light profiles. Linear profiles have their\n*intensities* solved analytically inside the fit, so the search only varies\nshape parameters \u2014 far fewer dimensions, much better convergence.\n\n```python\nn_gaussians = 30\ngaussian_per_basis = [\n af.Model(al.lp_linear.Gaussian) for _ in range(n_gaussians)\n]\n# Tie centres + ellipticities across the basis; let only sigma + intensity vary.\nfor g in gaussian_per_basis[1:]:\n g.centre = gaussian_per_basis[0].centre\n g.ell_comps = gaussian_per_basis[0].ell_comps\n\nlens_bulge = af.Model(al.lp_basis.Basis, profile_list=gaussian_per_basis)\n```\n\nSee `PyAutoGalaxy:autogalaxy/profiles/light/linear/` for the linear-profile classes.\n\n## Branch \u2014 pixelised source\n\nFor sources with complex morphology (lensed arcs, multiple components), reconstruct\nthe source on a pixel grid rather than as a parametric Sersic. The model wiring is\ndifferent: the source `Galaxy` carries a `Pixelization`, and the `Analysis` needs a\npositions likelihood penalty to keep the inversion well-posed.\n\nSee [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) for\nthe full pattern.\n\n## Wrap with an analysis\n\nOnce the model is built, wrap your loaded `dataset` (from `al_prepare_imaging_data`)\nin an analysis object:\n\n```python\nanalysis = al.AnalysisImaging(dataset=dataset)\n```\n\nSource: `PyAutoLens:autolens/imaging/model/analysis.py`.\n\n`analysis` + `model` are the two inputs to the non-linear search. Pass them to\n[`al_run_search`](./al_run_search.md).\n\n## Combine\n\nNatural next steps:\n\n- [`al_configure_search`](./al_configure_search.md) \u2014 pick Nautilus (default), Dynesty,\n Emcee, or another search; tune live points / walkers.\n- [`al_run_search`](./al_run_search.md) \u2014 `search.fit(model=model, analysis=analysis)`.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 chain a fast Sersic source fit into\n a slower pixelised one, inheriting priors.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Non-linear searches and parameter\n inference](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb):\n how non-linear searches find a best-fit model \u2014 parameter spaces, likelihoods,\n priors. The statistical foundation under model composition.\n- **General reference** \u2014 [RTD: Model cookbook](https://pyautolens.readthedocs.io/en/latest/general/model_cookbook.html):\n systematic reference for building lens models with `Model` and `Collection` \u2014\n two-component to multi-galaxy, prior customisation, parameter pairing, MGE.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/modeling/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling/start_here.py):\n the canonical imaging-modeling script \u2014 light-profile choice (Sersic vs. MGE),\n non-linear-search configuration, JAX/GPU fitting.\n\n## Skill: al_run_search\n\n---\nname: al_run_search\ndescription: Execute a non-linear search on a configured model + analysis. Calls `search.fit(model=model, analysis=analysis)` and monitors progress to the search's `path_prefix/name/unique_id/` output folder. Includes the sandbox / test-mode wrapper so smoke tests don't burn hours on real sampling. Use after `al_build_imaging_model` (or interferometer) and `al_configure_search` have produced `model`, `analysis`, and `search` objects.\n---\n\n# Running a non-linear search\n\nThe actual fit. Inputs: a model, an analysis (which knows the dataset and how to\ncompute a log-likelihood), and a search (which knows how to explore parameter space).\nThe single call `search.fit(model=model, analysis=analysis)` does the work.\n\nThis skill assembles those three pieces into a runnable script, then runs it \u2014 either\nin `PYAUTO_TEST_MODE=1` for a smoke test or in production mode for the real fit.\n\n## Ask\n\n- *\"Have you built `model` and `analysis` (from `al_build_imaging_model`) and\n configured `search` (from `al_configure_search`)?\"* If not, route to those first.\n- *\"Smoke test or production run?\"* Smoke test runs in seconds with `PYAUTO_TEST_MODE=1`\n and a tiny dataset, just to prove the wiring is correct. Production run takes hours\n to a day depending on model complexity and number of likelihood evals.\n- *\"How long can the fit run?\"* Sets expectations and decides whether to launch it as\n a foreground or backgrounded process.\n\n## Branch \u2014 production run\n\nOperational reminder: if the search was configured with `live_visual_update=True`\n(`al_configure_search` \"Live visual updates\"), a foreground script opens a matplotlib viewer\nand a notebook cell refreshes in place \u2014 don't re-ask when the search configuration already\nrecords the choice, and keep it `False` for HPC/headless/background runs. `fit.png` is\nwritten to disk on every quick update either way.\n\nAssemble everything into one script (`scripts/run_fit.py`):\n\n```python\n# scripts/run_fit.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autofit as af\nimport autolens as al\n\n# --- Dataset (from al_prepare_imaging_data) ---\ndataset_path = Path(\"dataset/imaging/\")\ndataset = al.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.06,\n)\nmask = al.Mask2D.circular(\n shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5\n)\ndataset = dataset.apply_mask(mask=mask)\n\n# --- Model (from al_build_imaging_model) ---\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=af.Model(al.lp.Sersic),\n mass=af.Model(al.mp.Isothermal),\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=af.Model(al.mp.ExternalShear))\nsource = af.Model(al.Galaxy, redshift=1.0, bulge=af.Model(al.lp.SersicCore))\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# --- Analysis ---\nanalysis = al.AnalysisImaging(dataset=dataset)\n\n# --- Search (from al_configure_search) ---\nsearch = af.Nautilus(\n path_prefix=\"imaging/\",\n name=\"sie_sersic\",\n n_live=200,\n number_of_cores=4,\n)\n\n# --- Fit ---\nresult = search.fit(model=model, analysis=analysis)\nprint(result.max_log_likelihood_instance)\n```\n\nRun with sandbox cache overrides if needed:\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/abstract_search.py` (the `fit` method).\nThe returned `Result` object is documented in `PyAutoFit:autofit/non_linear/result.py`.\n\n## Branch \u2014 smoke test (`PYAUTO_TEST_MODE=1`)\n\nWhen you've just written the script and want to know it runs end-to-end *without*\nwaiting for real sampling, set `PYAUTO_TEST_MODE=1`:\n\n```bash\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\nThe search will short-circuit after a small number of likelihood evaluations and\nreturn a `Result` so the script completes. Use this on every script you write, before\nlaunching a real run.\n\nFor an even faster smoke (sub-second per step), combine with PyAutoLens's small-dataset\nflags:\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\nSee [`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md) for the full flag list.\n\n## Output\n\nThe fit writes to `output////` (see\n`al_configure_search` for the layout). Tail the search log live:\n\n```bash\ntail -f output/imaging//sie_sersic/*/search.log\n```\n\nSay this out loud the moment a production fit starts: results are written **on the fly**\nfrom the best model so far, so `model.results` and `image/fit.png` are already worth\nopening \u2014 no need to wait for the search to terminate. For a newcomer, or in teacher\nmode, tour the folder per `_style.md` \"Output folder announcement\" and point at\n`__Output Folder Layout__` in\n[`autolens_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling.py),\nwhich annotates every file the fit writes.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 once the fit completes (or even mid-run),\n load and inspect.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 visualise model vs data.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 feed the result into a follow-up\n search with tighter priors.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) \u2014 if the fit converged badly.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Output management and result\n interpretation](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running fits \u2014 output structure, reviewing results,\n managing run times.\n- **General reference** \u2014 [RTD: New user guide](https://pyautolens.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n decision-tree routing for a new user about which fit to run first.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit on GPU \u2014 production pattern this skill mirrors.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_2_lens_modeling/tutorial_8_need_for_speed.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_build_imaging_model\n\n---\nname: al_build_imaging_model\ndescription: Compose a strong-lens model for imaging data — galaxies with light + mass profiles, prior customisation, and an `al.AnalysisImaging` ready to hand to a non-linear search. Writes a runnable Python script in scripts/. Pairs with `al_prepare_imaging_data` (which loads + masks the dataset) and `al_run_search` (which executes the fit). For visibility-plane data see `al_build_interferometer_model`.\n---\n\n# Composing an imaging lens model\n\nThe model is the PyAuto\\* representation of *what kind of lens you think this is* — how\nmany galaxies, at what redshifts, with what light and mass parameterisations, with\nwhich parameters free and which fixed. Building one is the step between \"I have a\nloaded `Imaging` dataset\" and \"I'm running a non-linear search\".\n\nThe canonical example is `autolens_workspace:scripts/imaging/modeling.py`. This skill\ngenerates the equivalent for the user's lens.\n\nThis skill assumes the imaging data is already preprocessing-ready. For real\nobservational data, confirm first that the user has **inspected `dataset.png`** and\nthought through mask extent, contaminating objects, and any regions to exclude — in\nparticular that any **extra galaxies** have been handled (noise-scaled via a\n`mask_extra_galaxies.fits`, or excluded by shrinking the circular mask). If not, route\nthem back to [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) before building the\nmodel — don't compose a model over data with an unaddressed contaminant.\n\n## Ask\n\n- *\"If this is real observational data, have you inspected `dataset.png`, decided the\n mask extent, and handled any extra galaxies (noise-scaled a `mask_extra_galaxies.fits`,\n or shrunk the mask to exclude them)?\"* — if not, stop and do that in\n [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) first.\n- *\"How many galaxies in the model — single galaxy-scale, multi-galaxy (2+ co-dominant, no host halo), group (2–10, optional group halo), cluster?\"* —\n this is the only structural choice. Skill below assumes galaxy-scale; bootstrap a\n variant for groups/clusters via `_bootstrap_skill` if needed.\n- *\"What's the lens light parameterisation — a single Sersic, MGE (multi-Gaussian\n expansion), bulge + disk, or no lens light at all (mass-only)?\"*\n- *\"What's the lens mass — Isothermal (SIE) + ExternalShear is the standard starting\n point; PowerLaw or NFW for total or dark-matter-only models.\"*\n- *\"What's the source — parametric Sersic, MGE, or pixelised inversion?\"* — pixelised\n needs a different `Analysis` wiring; see [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md).\n- *\"What are the lens and source redshifts?\"* — needed for distance ratios; even a\n ballpark value works for relative-comparison runs.\n\n## Branch — galaxy-scale, Sersic light + SIE mass + Sersic source\n\nThe minimum viable model. Save to `scripts/build_model.py`:\n\n```python\n# scripts/build_model.py\nfrom autonerves import jax_wrapper\nimport autofit as af\nimport autolens as al\n\n# Lens light — a Sersic for the bulge.\nlens_bulge = af.Model(al.lp.Sersic)\n\n# Lens mass — SIE plus a separate external field.\nlens_mass = af.Model(al.mp.Isothermal)\nlens_shear = af.Model(al.mp.ExternalShear)\n\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=lens_bulge,\n mass=lens_mass,\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=lens_shear)\n\n# Source light — a single Sersic.\nsource = af.Model(\n al.Galaxy,\n redshift=1.0,\n bulge=af.Model(al.lp.SersicCore),\n)\n\n# Compose into a Collection.\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# Optional: customise priors. E.g. tighten the lens centre.\nlens_mass.centre.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\nlens_mass.centre.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n\n# On real data, bound the Einstein radius from the ring you can see in the image\n# (the default prior is uniform over 0-8\"). A maximum-likelihood optimiser such as\n# MultiStartProdigy otherwise finds degenerate basins where theta_E exceeds the mask,\n# the \"source\" lands on a neighbouring galaxy and the ring is left in the residuals\n# (this is exactly what happened on the bundled COSMOS-Web Ring: theta_E 2.4\" vs 0.8\").\nlens_mass.einstein_radius = af.UniformPrior(lower_limit=0.3, upper_limit=1.5)\n\nprint(model.info)\n```\n\nSource citations:\n- `PyAutoGalaxy:autogalaxy/galaxy/galaxy.py` — `Galaxy`.\n- `PyAutoGalaxy:autogalaxy/galaxy/mass_field.py` — `MassField`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — `Sersic`, `SersicCore`.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — `Isothermal`.\n- `PyAutoFit:autofit/mapper/prior_model/prior_model.py` — `af.Model`.\n- `PyAutoFit:autofit/mapper/prior_model/collection.py` — `af.Collection`.\n\nWiki:\n- [`wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md) — what each\n light profile represents and when to pick which.\n- [`wiki/core/concepts/mass_profiles.md`](../wiki/core/concepts/mass_profiles.md) — same for mass.\n- [`wiki/core/concepts/galaxy_and_plane.md`](../wiki/core/concepts/galaxy_and_plane.md) — how\n galaxies, redshifts, and the `Tracer` fit together.\n\n## Branch — linear (MGE) lens light\n\nFor complex lens galaxy morphologies, replace the single Sersic bulge with a Multi-\nGaussian Expansion of *linear* light profiles. Linear profiles have their\n*intensities* solved analytically inside the fit, so the search only varies\nshape parameters — far fewer dimensions, much better convergence.\n\n```python\nn_gaussians = 30\ngaussian_per_basis = [\n af.Model(al.lp_linear.Gaussian) for _ in range(n_gaussians)\n]\n# Tie centres + ellipticities across the basis; let only sigma + intensity vary.\nfor g in gaussian_per_basis[1:]:\n g.centre = gaussian_per_basis[0].centre\n g.ell_comps = gaussian_per_basis[0].ell_comps\n\nlens_bulge = af.Model(al.lp_basis.Basis, profile_list=gaussian_per_basis)\n```\n\nSee `PyAutoGalaxy:autogalaxy/profiles/light/linear/` for the linear-profile classes.\n\n## Branch — pixelised source\n\nFor sources with complex morphology (lensed arcs, multiple components), reconstruct\nthe source on a pixel grid rather than as a parametric Sersic. The model wiring is\ndifferent: the source `Galaxy` carries a `Pixelization`, and the `Analysis` needs a\npositions likelihood penalty to keep the inversion well-posed.\n\nSee [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) for\nthe full pattern.\n\n## Wrap with an analysis\n\nOnce the model is built, wrap your loaded `dataset` (from `al_prepare_imaging_data`)\nin an analysis object:\n\n```python\nanalysis = al.AnalysisImaging(dataset=dataset)\n```\n\nSource: `PyAutoLens:autolens/imaging/model/analysis.py`.\n\n`analysis` + `model` are the two inputs to the non-linear search. Pass them to\n[`al_run_search`](./al_run_search.md).\n\n## Combine\n\nNatural next steps:\n\n- [`al_configure_search`](./al_configure_search.md) — pick Nautilus (default), Dynesty,\n Emcee, or another search; tune live points / walkers.\n- [`al_run_search`](./al_run_search.md) — `search.fit(model=model, analysis=analysis)`.\n- [`al_chain_searches`](./al_chain_searches.md) — chain a fast Sersic source fit into\n a slower pixelised one, inheriting priors.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Non-linear searches and parameter\n inference](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb):\n how non-linear searches find a best-fit model — parameter spaces, likelihoods,\n priors. The statistical foundation under model composition.\n- **General reference** — [RTD: Model cookbook](https://pyautolens.readthedocs.io/en/latest/general/model_cookbook.html):\n systematic reference for building lens models with `Model` and `Collection` —\n two-component to multi-galaxy, prior customisation, parameter pairing, MGE.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/modeling/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling/start_here.py):\n the canonical imaging-modeling script — light-profile choice (Sersic vs. MGE),\n non-linear-search configuration, JAX/GPU fitting.\n\n## Skill: al_run_search\n\n---\nname: al_run_search\ndescription: Execute a non-linear search on a configured model + analysis. Calls `search.fit(model=model, analysis=analysis)` and monitors progress to the search's `path_prefix/name/unique_id/` output folder. Includes the sandbox / test-mode wrapper so smoke tests don't burn hours on real sampling. Use after `al_build_imaging_model` (or interferometer) and `al_configure_search` have produced `model`, `analysis`, and `search` objects.\n---\n\n# Running a non-linear search\n\nThe actual fit. Inputs: a model, an analysis (which knows the dataset and how to\ncompute a log-likelihood), and a search (which knows how to explore parameter space).\nThe single call `search.fit(model=model, analysis=analysis)` does the work.\n\nThis skill assembles those three pieces into a runnable script, then runs it — either\nin `PYAUTO_TEST_MODE=1` for a smoke test or in production mode for the real fit.\n\n## Ask\n\n- *\"Have you built `model` and `analysis` (from `al_build_imaging_model`) and\n configured `search` (from `al_configure_search`)?\"* If not, route to those first.\n- *\"Smoke test or production run?\"* Smoke test runs in seconds with `PYAUTO_TEST_MODE=1`\n and a tiny dataset, just to prove the wiring is correct. Production run takes hours\n to a day depending on model complexity and number of likelihood evals.\n- *\"How long can the fit run?\"* Sets expectations and decides whether to launch it as\n a foreground or backgrounded process.\n\n## Branch — production run\n\nOperational reminder: if the search was configured with `live_visual_update=True`\n(`al_configure_search` \"Live visual updates\"), a foreground script opens a matplotlib viewer\nand a notebook cell refreshes in place — don't re-ask when the search configuration already\nrecords the choice, and keep it `False` for HPC/headless/background runs. `fit.png` is\nwritten to disk on every quick update either way.\n\nAssemble everything into one script (`scripts/run_fit.py`):\n\n```python\n# scripts/run_fit.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autofit as af\nimport autolens as al\n\n# --- Dataset (from al_prepare_imaging_data) ---\ndataset_path = Path(\"dataset/imaging/\")\ndataset = al.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.06,\n)\nmask = al.Mask2D.circular(\n shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5\n)\ndataset = dataset.apply_mask(mask=mask)\n\n# --- Model (from al_build_imaging_model) ---\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=af.Model(al.lp.Sersic),\n mass=af.Model(al.mp.Isothermal),\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=af.Model(al.mp.ExternalShear))\nsource = af.Model(al.Galaxy, redshift=1.0, bulge=af.Model(al.lp.SersicCore))\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# --- Analysis ---\nanalysis = al.AnalysisImaging(dataset=dataset)\n\n# --- Search (from al_configure_search) ---\nsearch = af.Nautilus(\n path_prefix=\"imaging/\",\n name=\"sie_sersic\",\n n_live=200,\n number_of_cores=4,\n)\n\n# --- Fit ---\nresult = search.fit(model=model, analysis=analysis)\nprint(result.max_log_likelihood_instance)\n```\n\nRun with sandbox cache overrides if needed:\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/abstract_search.py` (the `fit` method).\nThe returned `Result` object is documented in `PyAutoFit:autofit/non_linear/result.py`.\n\n## Branch — smoke test (`PYAUTO_TEST_MODE=1`)\n\nWhen you've just written the script and want to know it runs end-to-end *without*\nwaiting for real sampling, set `PYAUTO_TEST_MODE=1`:\n\n```bash\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\nThe search will short-circuit after a small number of likelihood evaluations and\nreturn a `Result` so the script completes. Use this on every script you write, before\nlaunching a real run.\n\nFor an even faster smoke (sub-second per step), combine with PyAutoLens's small-dataset\nflags:\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\nSee [`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md) for the full flag list.\n\n## Output\n\nThe fit writes to `output////` (see\n`al_configure_search` for the layout). Tail the search log live:\n\n```bash\ntail -f output/imaging//sie_sersic/*/search.log\n```\n\nSay this out loud the moment a production fit starts: results are written **on the fly**\nfrom the best model so far, so `model.results` and `image/fit.png` are already worth\nopening — no need to wait for the search to terminate. For a newcomer, or in teacher\nmode, tour the folder per `_style.md` \"Output folder announcement\" and point at\n`__Output Folder Layout__` in\n[`autolens_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling.py),\nwhich annotates every file the fit writes.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — once the fit completes (or even mid-run),\n load and inspect.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — visualise model vs data.\n- [`al_chain_searches`](./al_chain_searches.md) — feed the result into a follow-up\n search with tighter priors.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) — if the fit converged badly.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Output management and result\n interpretation](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running fits — output structure, reviewing results,\n managing run times.\n- **General reference** — [RTD: New user guide](https://pyautolens.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n decision-tree routing for a new user about which fit to run first.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit on GPU — production pattern this skill mirrors.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_2_lens_modeling/tutorial_9_search_chaining.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_9_search_chaining.ipynb index e68d60c..b84cf1d 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_9_search_chaining.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_9_search_chaining.ipynb @@ -66,21 +66,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/HowToLens/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", @@ -740,7 +740,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_2_lens_modeling/tutorial_9_search_chaining.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_chain_searches\n\n---\nname: al_chain_searches\ndescription: Run a sequence of non-linear searches where each later search inherits priors from the previous result. Standard pattern for moving from simple parametric models (fast, easy) to complex pixelised or chained models (slow, sensitive to initial position). Pairs with `al_run_slam_pipeline` (which is itself the canonical multi-stage chain) and `al_build_imaging_model`.\n---\n\n# Chaining searches\n\nA lens model with 20+ free parameters and a pixelised source is hard to fit from\nbroad priors. The robust approach is to run a *sequence* of searches: a fast simple\nfit first (Sersic source, broad priors), then a more complex fit (pixelised source)\nwhose priors are seeded from the earlier result.\n\nPyAutoFit's prior-chaining API lets the second search reuse the first's posterior as\nits prior, narrowing parameter space dramatically.\n\nCanonical reference: `autolens_workspace:scripts/guides/modeling/chaining.py`.\n\n## Ask\n\n- *\"What's the simple-first model that you trust to converge?\"* \u2014 usually a Sersic\n source + SIE lens.\n- *\"What's the more complex model you ultimately want?\"* \u2014 pixelised source, MGE lens\n light, PowerLaw mass, etc.\n- *\"How much do you want to lock down between phases?\"* \u2014 full posterior inheritance\n (tight) vs. mean-only with widened uncertainties (loose).\n\n## Branch \u2014 two-phase chain (parametric \u2192 pixelised source)\n\n```python\n# scripts/chain.py\n\"\"\"\nChain Searches: Parametric -> Pixelised Source\n==============================================\n\nChain two non-linear searches: a fast parametric fit that locks down the lens mass, then a\npixelised-source fit that inherits the mass posterior as its prior. Chaining keeps the\nexpensive flexible model from having to explore the full prior volume from scratch.\n\n__Contents__\n\n- **Setup:** Imports (assumes `dataset` is already loaded \u2014 see al_prepare_imaging_data).\n- **Phase 1:** SIE + Sersic source, fast initial fit.\n- **Phase 2:** Pixelised source, priors inherited from phase 1.\n\"\"\"\n\n\"\"\"\n__Setup__\n\nAssumes `dataset` is already loaded (see al_prepare_imaging_data). The `jax_wrapper` import\nmust precede the other PyAuto* imports so the JAX environment is configured first.\n\"\"\"\nfrom autonerves import jax_wrapper\nimport autofit as af\nimport autolens as al\n\n\"\"\"\n__Phase 1__\n\nA fast initial fit with an SIE + external-shear mass and a parametric Sersic source\n(`al.mp.Isothermal`, `al.mp.ExternalShear`, `al.lp.SersicCore`). This pins down the lens\nmass cheaply before we pay for a pixelised source.\n\"\"\"\nlens_1 = af.Model(\n al.Galaxy,\n redshift=0.5,\n mass=af.Model(al.mp.Isothermal),\n)\nfield_1 = af.Model(al.MassField, redshift=0.5, shear=af.Model(al.mp.ExternalShear))\nsource_1 = af.Model(al.Galaxy, redshift=1.0, bulge=af.Model(al.lp.SersicCore))\nmodel_1 = af.Collection(galaxies=af.Collection(lens=lens_1, source=source_1), fields=field_1)\n\nanalysis = al.AnalysisImaging(dataset=dataset)\nsearch_1 = af.Nautilus(path_prefix=\"chain_demo\", name=\"phase_1_parametric\", n_live=100)\n\nresult_1 = search_1.fit(model=model_1, analysis=analysis)\n\n\"\"\"\n__Phase 2__\n\nSwap in a pixelised source for maximum source flexibility,\ninheriting the lens mass and shear from phase 1's posterior so the search\nstarts from a good region of parameter space rather than the prior. `result_1.model`\nreturns a new `af.Model` whose priors are the previous search's posterior, keeping the\nparameters free to vary.\n\"\"\"\nlens_2 = af.Model(\n al.Galaxy,\n redshift=0.5,\n mass=result_1.model.galaxies.lens.mass, # inherits the posterior as prior\n)\nfield_2 = result_1.model.fields\n\nsource_2 = af.Model(\n al.Galaxy,\n redshift=1.0,\n pixelization=af.Model(\n al.Pixelization,\n # NOTE: Delaunay + ConstantSplit is the standard production choice, but a\n # known regression (PyAutoArray #332, still open) crashes Delaunay inside\n # FitImaging and breaks ConstantSplit on RectangularUniform. Until it is\n # fixed, use the combination below.\n mesh=al.mesh.RectangularUniform,\n regularization=al.reg.Constant,\n ),\n)\nmodel_2 = af.Collection(galaxies=af.Collection(lens=lens_2, source=source_2), fields=field_2)\n\nsearch_2 = af.Nautilus(path_prefix=\"chain_demo\", name=\"phase_2_pixelized\", n_live=150)\nresult_2 = search_2.fit(model=model_2, analysis=analysis)\n```\n\nThe key lines carry both `mass=result_1.model.galaxies.lens.mass` and\n`field_2 = result_1.model.fields`. `result_1.model` returns a\nnew `af.Model` whose priors are the previous search's posterior \u2014 Gaussian-bounded\naround the maximum likelihood, with widths from the posterior. To use the\n*instance* values (locked) instead of the model: `result_1.instance.galaxies.lens.mass`.\n\nSource citations:\n- `PyAutoFit:autofit/non_linear/result.py` \u2014 `result.model` vs `result.instance`.\n- `PyAutoFit:autofit/mapper/prior_model/prior_model.py` \u2014 `af.Model` with inherited\n priors.\n\nWiki:\n- [`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md) \u2014 what\n prior inheritance does mechanically.\n- [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\n \u2014 the pixelised-source side of phase 2.\n\n## Branch \u2014 N-phase pipeline\n\nFor 3+ phases, the same pattern repeats: each phase inherits selectively from earlier\nones. The fully-automated version of this is the SLaM (Source-Light-Mass) pipeline \u2014\nsee [`al_run_slam_pipeline`](./al_run_slam_pipeline.md). Roll your own chain when SLaM\ndoesn't match your problem.\n\n## Combine\n\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) \u2014 the canonical 4\u20136 phase chain.\n- [`al_load_results`](./al_load_results.md) \u2014 load any phase's results independently.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) \u2014 if a later phase fails because\n earlier-phase priors were too tight.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Breaking modeling into sequential\n searches](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_9_search_chaining.ipynb):\n introduces chaining \u2014 why a sequence of fits beats a single high-dimensional one.\n The end of chapter 2 (tutorials 9-11) develops the pattern.\n- **General reference** \u2014 [RTD: Model cookbook](https://pyautolens.readthedocs.io/en/latest/general/model_cookbook.html):\n systematic reference for inheriting and adjusting priors between models, the\n mechanical core of chaining.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/modeling/slam_start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/modeling/slam_start_here.py):\n SLaM is the canonical multi-phase chain; this script overviews it stage-by-stage.\n\n## Skill: al_run_search\n\n---\nname: al_run_search\ndescription: Execute a non-linear search on a configured model + analysis. Calls `search.fit(model=model, analysis=analysis)` and monitors progress to the search's `path_prefix/name/unique_id/` output folder. Includes the sandbox / test-mode wrapper so smoke tests don't burn hours on real sampling. Use after `al_build_imaging_model` (or interferometer) and `al_configure_search` have produced `model`, `analysis`, and `search` objects.\n---\n\n# Running a non-linear search\n\nThe actual fit. Inputs: a model, an analysis (which knows the dataset and how to\ncompute a log-likelihood), and a search (which knows how to explore parameter space).\nThe single call `search.fit(model=model, analysis=analysis)` does the work.\n\nThis skill assembles those three pieces into a runnable script, then runs it \u2014 either\nin `PYAUTO_TEST_MODE=1` for a smoke test or in production mode for the real fit.\n\n## Ask\n\n- *\"Have you built `model` and `analysis` (from `al_build_imaging_model`) and\n configured `search` (from `al_configure_search`)?\"* If not, route to those first.\n- *\"Smoke test or production run?\"* Smoke test runs in seconds with `PYAUTO_TEST_MODE=1`\n and a tiny dataset, just to prove the wiring is correct. Production run takes hours\n to a day depending on model complexity and number of likelihood evals.\n- *\"How long can the fit run?\"* Sets expectations and decides whether to launch it as\n a foreground or backgrounded process.\n\n## Branch \u2014 production run\n\nOperational reminder: if the search was configured with `live_visual_update=True`\n(`al_configure_search` \"Live visual updates\"), a foreground script opens a matplotlib viewer\nand a notebook cell refreshes in place \u2014 don't re-ask when the search configuration already\nrecords the choice, and keep it `False` for HPC/headless/background runs. `fit.png` is\nwritten to disk on every quick update either way.\n\nAssemble everything into one script (`scripts/run_fit.py`):\n\n```python\n# scripts/run_fit.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autofit as af\nimport autolens as al\n\n# --- Dataset (from al_prepare_imaging_data) ---\ndataset_path = Path(\"dataset/imaging/\")\ndataset = al.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.06,\n)\nmask = al.Mask2D.circular(\n shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5\n)\ndataset = dataset.apply_mask(mask=mask)\n\n# --- Model (from al_build_imaging_model) ---\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=af.Model(al.lp.Sersic),\n mass=af.Model(al.mp.Isothermal),\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=af.Model(al.mp.ExternalShear))\nsource = af.Model(al.Galaxy, redshift=1.0, bulge=af.Model(al.lp.SersicCore))\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# --- Analysis ---\nanalysis = al.AnalysisImaging(dataset=dataset)\n\n# --- Search (from al_configure_search) ---\nsearch = af.Nautilus(\n path_prefix=\"imaging/\",\n name=\"sie_sersic\",\n n_live=200,\n number_of_cores=4,\n)\n\n# --- Fit ---\nresult = search.fit(model=model, analysis=analysis)\nprint(result.max_log_likelihood_instance)\n```\n\nRun with sandbox cache overrides if needed:\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/abstract_search.py` (the `fit` method).\nThe returned `Result` object is documented in `PyAutoFit:autofit/non_linear/result.py`.\n\n## Branch \u2014 smoke test (`PYAUTO_TEST_MODE=1`)\n\nWhen you've just written the script and want to know it runs end-to-end *without*\nwaiting for real sampling, set `PYAUTO_TEST_MODE=1`:\n\n```bash\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\nThe search will short-circuit after a small number of likelihood evaluations and\nreturn a `Result` so the script completes. Use this on every script you write, before\nlaunching a real run.\n\nFor an even faster smoke (sub-second per step), combine with PyAutoLens's small-dataset\nflags:\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\nSee [`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md) for the full flag list.\n\n## Output\n\nThe fit writes to `output////` (see\n`al_configure_search` for the layout). Tail the search log live:\n\n```bash\ntail -f output/imaging//sie_sersic/*/search.log\n```\n\nSay this out loud the moment a production fit starts: results are written **on the fly**\nfrom the best model so far, so `model.results` and `image/fit.png` are already worth\nopening \u2014 no need to wait for the search to terminate. For a newcomer, or in teacher\nmode, tour the folder per `_style.md` \"Output folder announcement\" and point at\n`__Output Folder Layout__` in\n[`autolens_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling.py),\nwhich annotates every file the fit writes.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 once the fit completes (or even mid-run),\n load and inspect.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 visualise model vs data.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 feed the result into a follow-up\n search with tighter priors.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) \u2014 if the fit converged badly.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Output management and result\n interpretation](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running fits \u2014 output structure, reviewing results,\n managing run times.\n- **General reference** \u2014 [RTD: New user guide](https://pyautolens.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n decision-tree routing for a new user about which fit to run first.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit on GPU \u2014 production pattern this skill mirrors.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_2_lens_modeling/tutorial_9_search_chaining.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_chain_searches\n\n---\nname: al_chain_searches\ndescription: Run a sequence of non-linear searches where each later search inherits priors from the previous result. Standard pattern for moving from simple parametric models (fast, easy) to complex pixelised or chained models (slow, sensitive to initial position). Pairs with `al_run_slam_pipeline` (which is itself the canonical multi-stage chain) and `al_build_imaging_model`.\n---\n\n# Chaining searches\n\nA lens model with 20+ free parameters and a pixelised source is hard to fit from\nbroad priors. The robust approach is to run a *sequence* of searches: a fast simple\nfit first (Sersic source, broad priors), then a more complex fit (pixelised source)\nwhose priors are seeded from the earlier result.\n\nPyAutoFit's prior-chaining API lets the second search reuse the first's posterior as\nits prior, narrowing parameter space dramatically.\n\nCanonical reference: `autolens_workspace:scripts/guides/modeling/chaining.py`.\n\n## Ask\n\n- *\"What's the simple-first model that you trust to converge?\"* — usually a Sersic\n source + SIE lens.\n- *\"What's the more complex model you ultimately want?\"* — pixelised source, MGE lens\n light, PowerLaw mass, etc.\n- *\"How much do you want to lock down between phases?\"* — full posterior inheritance\n (tight) vs. mean-only with widened uncertainties (loose).\n\n## Branch — two-phase chain (parametric → pixelised source)\n\n```python\n# scripts/chain.py\n\"\"\"\nChain Searches: Parametric -> Pixelised Source\n==============================================\n\nChain two non-linear searches: a fast parametric fit that locks down the lens mass, then a\npixelised-source fit that inherits the mass posterior as its prior. Chaining keeps the\nexpensive flexible model from having to explore the full prior volume from scratch.\n\n__Contents__\n\n- **Setup:** Imports (assumes `dataset` is already loaded — see al_prepare_imaging_data).\n- **Phase 1:** SIE + Sersic source, fast initial fit.\n- **Phase 2:** Pixelised source, priors inherited from phase 1.\n\"\"\"\n\n\"\"\"\n__Setup__\n\nAssumes `dataset` is already loaded (see al_prepare_imaging_data). The `jax_wrapper` import\nmust precede the other PyAuto* imports so the JAX environment is configured first.\n\"\"\"\nfrom autonerves import jax_wrapper\nimport autofit as af\nimport autolens as al\n\n\"\"\"\n__Phase 1__\n\nA fast initial fit with an SIE + external-shear mass and a parametric Sersic source\n(`al.mp.Isothermal`, `al.mp.ExternalShear`, `al.lp.SersicCore`). This pins down the lens\nmass cheaply before we pay for a pixelised source.\n\"\"\"\nlens_1 = af.Model(\n al.Galaxy,\n redshift=0.5,\n mass=af.Model(al.mp.Isothermal),\n)\nfield_1 = af.Model(al.MassField, redshift=0.5, shear=af.Model(al.mp.ExternalShear))\nsource_1 = af.Model(al.Galaxy, redshift=1.0, bulge=af.Model(al.lp.SersicCore))\nmodel_1 = af.Collection(galaxies=af.Collection(lens=lens_1, source=source_1), fields=field_1)\n\nanalysis = al.AnalysisImaging(dataset=dataset)\nsearch_1 = af.Nautilus(path_prefix=\"chain_demo\", name=\"phase_1_parametric\", n_live=100)\n\nresult_1 = search_1.fit(model=model_1, analysis=analysis)\n\n\"\"\"\n__Phase 2__\n\nSwap in a pixelised source for maximum source flexibility,\ninheriting the lens mass and shear from phase 1's posterior so the search\nstarts from a good region of parameter space rather than the prior. `result_1.model`\nreturns a new `af.Model` whose priors are the previous search's posterior, keeping the\nparameters free to vary.\n\"\"\"\nlens_2 = af.Model(\n al.Galaxy,\n redshift=0.5,\n mass=result_1.model.galaxies.lens.mass, # inherits the posterior as prior\n)\nfield_2 = result_1.model.fields\n\nsource_2 = af.Model(\n al.Galaxy,\n redshift=1.0,\n pixelization=af.Model(\n al.Pixelization,\n # NOTE: Delaunay + ConstantSplit is the standard production choice, but a\n # known regression (PyAutoArray #332, still open) crashes Delaunay inside\n # FitImaging and breaks ConstantSplit on RectangularUniform. Until it is\n # fixed, use the combination below.\n mesh=al.mesh.RectangularUniform,\n regularization=al.reg.Constant,\n ),\n)\nmodel_2 = af.Collection(galaxies=af.Collection(lens=lens_2, source=source_2), fields=field_2)\n\nsearch_2 = af.Nautilus(path_prefix=\"chain_demo\", name=\"phase_2_pixelized\", n_live=150)\nresult_2 = search_2.fit(model=model_2, analysis=analysis)\n```\n\nThe key lines carry both `mass=result_1.model.galaxies.lens.mass` and\n`field_2 = result_1.model.fields`. `result_1.model` returns a\nnew `af.Model` whose priors are the previous search's posterior — Gaussian-bounded\naround the maximum likelihood, with widths from the posterior. To use the\n*instance* values (locked) instead of the model: `result_1.instance.galaxies.lens.mass`.\n\nSource citations:\n- `PyAutoFit:autofit/non_linear/result.py` — `result.model` vs `result.instance`.\n- `PyAutoFit:autofit/mapper/prior_model/prior_model.py` — `af.Model` with inherited\n priors.\n\nWiki:\n- [`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md) — what\n prior inheritance does mechanically.\n- [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\n — the pixelised-source side of phase 2.\n\n## Branch — N-phase pipeline\n\nFor 3+ phases, the same pattern repeats: each phase inherits selectively from earlier\nones. The fully-automated version of this is the SLaM (Source-Light-Mass) pipeline —\nsee [`al_run_slam_pipeline`](./al_run_slam_pipeline.md). Roll your own chain when SLaM\ndoesn't match your problem.\n\n## Combine\n\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) — the canonical 4–6 phase chain.\n- [`al_load_results`](./al_load_results.md) — load any phase's results independently.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) — if a later phase fails because\n earlier-phase priors were too tight.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Breaking modeling into sequential\n searches](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_9_search_chaining.ipynb):\n introduces chaining — why a sequence of fits beats a single high-dimensional one.\n The end of chapter 2 (tutorials 9-11) develops the pattern.\n- **General reference** — [RTD: Model cookbook](https://pyautolens.readthedocs.io/en/latest/general/model_cookbook.html):\n systematic reference for inheriting and adjusting priors between models, the\n mechanical core of chaining.\n- **Experienced PyAutoLens user** — [workspace/lens: guides/modeling/slam_start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/modeling/slam_start_here.py):\n SLaM is the canonical multi-phase chain; this script overviews it stage-by-stage.\n\n## Skill: al_run_search\n\n---\nname: al_run_search\ndescription: Execute a non-linear search on a configured model + analysis. Calls `search.fit(model=model, analysis=analysis)` and monitors progress to the search's `path_prefix/name/unique_id/` output folder. Includes the sandbox / test-mode wrapper so smoke tests don't burn hours on real sampling. Use after `al_build_imaging_model` (or interferometer) and `al_configure_search` have produced `model`, `analysis`, and `search` objects.\n---\n\n# Running a non-linear search\n\nThe actual fit. Inputs: a model, an analysis (which knows the dataset and how to\ncompute a log-likelihood), and a search (which knows how to explore parameter space).\nThe single call `search.fit(model=model, analysis=analysis)` does the work.\n\nThis skill assembles those three pieces into a runnable script, then runs it — either\nin `PYAUTO_TEST_MODE=1` for a smoke test or in production mode for the real fit.\n\n## Ask\n\n- *\"Have you built `model` and `analysis` (from `al_build_imaging_model`) and\n configured `search` (from `al_configure_search`)?\"* If not, route to those first.\n- *\"Smoke test or production run?\"* Smoke test runs in seconds with `PYAUTO_TEST_MODE=1`\n and a tiny dataset, just to prove the wiring is correct. Production run takes hours\n to a day depending on model complexity and number of likelihood evals.\n- *\"How long can the fit run?\"* Sets expectations and decides whether to launch it as\n a foreground or backgrounded process.\n\n## Branch — production run\n\nOperational reminder: if the search was configured with `live_visual_update=True`\n(`al_configure_search` \"Live visual updates\"), a foreground script opens a matplotlib viewer\nand a notebook cell refreshes in place — don't re-ask when the search configuration already\nrecords the choice, and keep it `False` for HPC/headless/background runs. `fit.png` is\nwritten to disk on every quick update either way.\n\nAssemble everything into one script (`scripts/run_fit.py`):\n\n```python\n# scripts/run_fit.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autofit as af\nimport autolens as al\n\n# --- Dataset (from al_prepare_imaging_data) ---\ndataset_path = Path(\"dataset/imaging/\")\ndataset = al.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.06,\n)\nmask = al.Mask2D.circular(\n shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5\n)\ndataset = dataset.apply_mask(mask=mask)\n\n# --- Model (from al_build_imaging_model) ---\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=af.Model(al.lp.Sersic),\n mass=af.Model(al.mp.Isothermal),\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=af.Model(al.mp.ExternalShear))\nsource = af.Model(al.Galaxy, redshift=1.0, bulge=af.Model(al.lp.SersicCore))\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# --- Analysis ---\nanalysis = al.AnalysisImaging(dataset=dataset)\n\n# --- Search (from al_configure_search) ---\nsearch = af.Nautilus(\n path_prefix=\"imaging/\",\n name=\"sie_sersic\",\n n_live=200,\n number_of_cores=4,\n)\n\n# --- Fit ---\nresult = search.fit(model=model, analysis=analysis)\nprint(result.max_log_likelihood_instance)\n```\n\nRun with sandbox cache overrides if needed:\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/abstract_search.py` (the `fit` method).\nThe returned `Result` object is documented in `PyAutoFit:autofit/non_linear/result.py`.\n\n## Branch — smoke test (`PYAUTO_TEST_MODE=1`)\n\nWhen you've just written the script and want to know it runs end-to-end *without*\nwaiting for real sampling, set `PYAUTO_TEST_MODE=1`:\n\n```bash\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\nThe search will short-circuit after a small number of likelihood evaluations and\nreturn a `Result` so the script completes. Use this on every script you write, before\nlaunching a real run.\n\nFor an even faster smoke (sub-second per step), combine with PyAutoLens's small-dataset\nflags:\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\nSee [`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md) for the full flag list.\n\n## Output\n\nThe fit writes to `output////` (see\n`al_configure_search` for the layout). Tail the search log live:\n\n```bash\ntail -f output/imaging//sie_sersic/*/search.log\n```\n\nSay this out loud the moment a production fit starts: results are written **on the fly**\nfrom the best model so far, so `model.results` and `image/fit.png` are already worth\nopening — no need to wait for the search to terminate. For a newcomer, or in teacher\nmode, tour the folder per `_style.md` \"Output folder announcement\" and point at\n`__Output Folder Layout__` in\n[`autolens_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling.py),\nwhich annotates every file the fit writes.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — once the fit completes (or even mid-run),\n load and inspect.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — visualise model vs data.\n- [`al_chain_searches`](./al_chain_searches.md) — feed the result into a follow-up\n search with tighter priors.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) — if the fit converged badly.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Output management and result\n interpretation](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running fits — output structure, reviewing results,\n managing run times.\n- **General reference** — [RTD: New user guide](https://pyautolens.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n decision-tree routing for a new user about which fit to run first.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit on GPU — production pattern this skill mirrors.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_3_pixelizations/tutorial_10_fit_problems.ipynb b/notebooks/chapter_3_pixelizations/tutorial_10_fit_problems.ipynb index 876f3b7..d21612e 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_10_fit_problems.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_10_fit_problems.ipynb @@ -67,21 +67,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/HowToLens/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", @@ -503,7 +503,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_10_fit_problems.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones \u2014 common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially \u2014 both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type \u2014 Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation \u2014 constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source \u2014 do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* \u2014 either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised \u2014 `(adapt_image / max) ** power` \u2014 so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** \u2014 `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, \u2026).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead \u2014 transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` \u2014 the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` \u2014 the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` \u2014 the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline \u2014 imaging, group, multi-galaxy, multi-dataset \u2014 over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data \u2014 ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** \u2014 it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** \u2014 a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch \u2014 Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch \u2014 bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n \u2014 post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) \u2014 datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** \u2014 [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit \u2014 source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** \u2014 the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory \u2014 what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty \u2014\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at \u2014 the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* \u2014 if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions \u2014 the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> \u26a0\ufe0f **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch \u2014 source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot \u2014 when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D \u2014 plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch \u2014 mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch \u2014 double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel \u2014 the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map \u2014 regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic \u2014 mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) \u2014 overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) \u2014 automated pipeline that\n handles the parametric \u2192 pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart \u2014 least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** \u2014 [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets \u2014\n links into deeper docs.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model \u2014 production\n pattern for extended-arc sources.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_10_fit_problems.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones — common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially — both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type — Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation — constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source — do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* — either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised — `(adapt_image / max) ** power` — so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** — `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, …).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead — transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` — the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` — the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` — the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline — imaging, group, multi-galaxy, multi-dataset — over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data — ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** — it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** — a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch — Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch — bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n — post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) — the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) — datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** — [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit — source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** — the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory — what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty —\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at — the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* — if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions — the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> ⚠️ **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch — source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot — when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D — plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch — mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch — double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel — the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map — regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic — mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) — overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) — the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) — automated pipeline that\n handles the parametric → pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart — least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** — [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets —\n links into deeper docs.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model — production\n pattern for extended-arc sources.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_3_pixelizations/tutorial_11_brightness_adaption.ipynb b/notebooks/chapter_3_pixelizations/tutorial_11_brightness_adaption.ipynb index 71fb36f..e832b37 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_11_brightness_adaption.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_11_brightness_adaption.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/HowToLens/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", @@ -588,7 +588,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_11_brightness_adaption.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones \u2014 common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially \u2014 both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type \u2014 Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation \u2014 constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source \u2014 do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* \u2014 either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised \u2014 `(adapt_image / max) ** power` \u2014 so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** \u2014 `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, \u2026).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead \u2014 transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` \u2014 the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` \u2014 the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` \u2014 the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline \u2014 imaging, group, multi-galaxy, multi-dataset \u2014 over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data \u2014 ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** \u2014 it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** \u2014 a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch \u2014 Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch \u2014 bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n \u2014 post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) \u2014 datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** \u2014 [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit \u2014 source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** \u2014 the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory \u2014 what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty \u2014\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at \u2014 the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* \u2014 if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions \u2014 the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> \u26a0\ufe0f **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch \u2014 source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot \u2014 when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D \u2014 plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch \u2014 mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch \u2014 double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel \u2014 the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map \u2014 regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic \u2014 mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) \u2014 overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) \u2014 automated pipeline that\n handles the parametric \u2192 pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart \u2014 least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** \u2014 [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets \u2014\n links into deeper docs.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model \u2014 production\n pattern for extended-arc sources.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_11_brightness_adaption.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones — common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially — both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type — Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation — constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source — do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* — either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised — `(adapt_image / max) ** power` — so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** — `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, …).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead — transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` — the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` — the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` — the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline — imaging, group, multi-galaxy, multi-dataset — over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data — ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** — it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** — a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch — Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch — bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n — post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) — the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) — datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** — [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit — source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** — the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory — what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty —\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at — the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* — if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions — the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> ⚠️ **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch — source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot — when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D — plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch — mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch — double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel — the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map — regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic — mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) — overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) — the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) — automated pipeline that\n handles the parametric → pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart — least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** — [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets —\n links into deeper docs.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model — production\n pattern for extended-arc sources.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_3_pixelizations/tutorial_12_adaptive_regularization.ipynb b/notebooks/chapter_3_pixelizations/tutorial_12_adaptive_regularization.ipynb index f91659a..20b62fe 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_12_adaptive_regularization.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_12_adaptive_regularization.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/HowToLens/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", @@ -468,7 +468,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_12_adaptive_regularization.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones \u2014 common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially \u2014 both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type \u2014 Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation \u2014 constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source \u2014 do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* \u2014 either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised \u2014 `(adapt_image / max) ** power` \u2014 so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** \u2014 `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, \u2026).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead \u2014 transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` \u2014 the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` \u2014 the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` \u2014 the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline \u2014 imaging, group, multi-galaxy, multi-dataset \u2014 over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data \u2014 ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** \u2014 it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** \u2014 a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch \u2014 Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch \u2014 bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n \u2014 post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) \u2014 datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** \u2014 [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit \u2014 source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** \u2014 the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory \u2014 what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty \u2014\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at \u2014 the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* \u2014 if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions \u2014 the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> \u26a0\ufe0f **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch \u2014 source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot \u2014 when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D \u2014 plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch \u2014 mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch \u2014 double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel \u2014 the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map \u2014 regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic \u2014 mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) \u2014 overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) \u2014 automated pipeline that\n handles the parametric \u2192 pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart \u2014 least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** \u2014 [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets \u2014\n links into deeper docs.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model \u2014 production\n pattern for extended-arc sources.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_12_adaptive_regularization.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones — common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially — both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type — Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation — constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source — do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* — either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised — `(adapt_image / max) ** power` — so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** — `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, …).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead — transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` — the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` — the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` — the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline — imaging, group, multi-galaxy, multi-dataset — over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data — ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** — it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** — a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch — Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch — bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n — post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) — the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) — datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** — [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit — source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** — the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory — what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty —\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at — the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* — if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions — the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> ⚠️ **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch — source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot — when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D — plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch — mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch — double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel — the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map — regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic — mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) — overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) — the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) — automated pipeline that\n handles the parametric → pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart — least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** — [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets —\n links into deeper docs.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model — production\n pattern for extended-arc sources.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb b/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb index efdac11..3507add 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb @@ -25,21 +25,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/HowToLens/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", @@ -354,7 +354,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones \u2014 common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially \u2014 both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type \u2014 Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation \u2014 constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source \u2014 do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* \u2014 either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised \u2014 `(adapt_image / max) ** power` \u2014 so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** \u2014 `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, \u2026).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead \u2014 transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` \u2014 the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` \u2014 the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` \u2014 the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline \u2014 imaging, group, multi-galaxy, multi-dataset \u2014 over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data \u2014 ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** \u2014 it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** \u2014 a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch \u2014 Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch \u2014 bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n \u2014 post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) \u2014 datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** \u2014 [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit \u2014 source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** \u2014 the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory \u2014 what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty \u2014\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at \u2014 the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* \u2014 if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions \u2014 the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> \u26a0\ufe0f **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch \u2014 source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot \u2014 when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D \u2014 plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch \u2014 mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch \u2014 double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel \u2014 the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map \u2014 regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic \u2014 mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) \u2014 overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) \u2014 automated pipeline that\n handles the parametric \u2192 pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart \u2014 least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** \u2014 [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets \u2014\n links into deeper docs.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model \u2014 production\n pattern for extended-arc sources.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones — common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially — both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type — Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation — constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source — do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* — either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised — `(adapt_image / max) ** power` — so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** — `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, …).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead — transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` — the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` — the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` — the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline — imaging, group, multi-galaxy, multi-dataset — over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data — ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** — it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** — a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch — Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch — bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n — post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) — the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) — datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** — [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit — source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** — the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory — what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty —\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at — the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* — if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions — the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> ⚠️ **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch — source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot — when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D — plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch — mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch — double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel — the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map — regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic — mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) — overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) — the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) — automated pipeline that\n handles the parametric → pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart — least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** — [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets —\n links into deeper docs.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model — production\n pattern for extended-arc sources.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_3_pixelizations/tutorial_2_mappers.ipynb b/notebooks/chapter_3_pixelizations/tutorial_2_mappers.ipynb index 06fe9c8..8e0b1f8 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_2_mappers.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_2_mappers.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/HowToLens/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", @@ -594,7 +594,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_2_mappers.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones \u2014 common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially \u2014 both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type \u2014 Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation \u2014 constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source \u2014 do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* \u2014 either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised \u2014 `(adapt_image / max) ** power` \u2014 so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** \u2014 `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, \u2026).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead \u2014 transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` \u2014 the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` \u2014 the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` \u2014 the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline \u2014 imaging, group, multi-galaxy, multi-dataset \u2014 over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data \u2014 ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** \u2014 it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** \u2014 a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch \u2014 Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch \u2014 bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n \u2014 post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) \u2014 datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** \u2014 [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit \u2014 source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** \u2014 the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory \u2014 what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty \u2014\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at \u2014 the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* \u2014 if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions \u2014 the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> \u26a0\ufe0f **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch \u2014 source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot \u2014 when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D \u2014 plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch \u2014 mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch \u2014 double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel \u2014 the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map \u2014 regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic \u2014 mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) \u2014 overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) \u2014 automated pipeline that\n handles the parametric \u2192 pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart \u2014 least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** \u2014 [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets \u2014\n links into deeper docs.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model \u2014 production\n pattern for extended-arc sources.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_2_mappers.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones — common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially — both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type — Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation — constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source — do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* — either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised — `(adapt_image / max) ** power` — so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** — `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, …).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead — transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` — the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` — the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` — the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline — imaging, group, multi-galaxy, multi-dataset — over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data — ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** — it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** — a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch — Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch — bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n — post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) — the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) — datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** — [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit — source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** — the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory — what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty —\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at — the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* — if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions — the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> ⚠️ **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch — source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot — when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D — plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch — mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch — double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel — the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map — regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic — mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) — overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) — the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) — automated pipeline that\n handles the parametric → pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart — least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** — [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets —\n links into deeper docs.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model — production\n pattern for extended-arc sources.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb b/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb index 5cd6479..43272eb 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb @@ -30,21 +30,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/HowToLens/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", @@ -604,7 +604,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones \u2014 common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially \u2014 both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type \u2014 Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation \u2014 constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source \u2014 do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* \u2014 either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised \u2014 `(adapt_image / max) ** power` \u2014 so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** \u2014 `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, \u2026).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead \u2014 transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` \u2014 the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` \u2014 the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` \u2014 the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline \u2014 imaging, group, multi-galaxy, multi-dataset \u2014 over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data \u2014 ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** \u2014 it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** \u2014 a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch \u2014 Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch \u2014 bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n \u2014 post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) \u2014 datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** \u2014 [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit \u2014 source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** \u2014 the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory \u2014 what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty \u2014\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at \u2014 the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* \u2014 if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions \u2014 the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> \u26a0\ufe0f **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch \u2014 source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot \u2014 when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D \u2014 plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch \u2014 mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch \u2014 double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel \u2014 the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map \u2014 regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic \u2014 mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) \u2014 overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) \u2014 automated pipeline that\n handles the parametric \u2192 pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart \u2014 least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** \u2014 [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets \u2014\n links into deeper docs.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model \u2014 production\n pattern for extended-arc sources.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones — common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially — both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type — Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation — constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source — do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* — either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised — `(adapt_image / max) ** power` — so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** — `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, …).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead — transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` — the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` — the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` — the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline — imaging, group, multi-galaxy, multi-dataset — over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data — ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** — it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** — a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch — Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch — bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n — post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) — the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) — datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** — [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit — source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** — the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory — what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty —\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at — the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* — if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions — the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> ⚠️ **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch — source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot — when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D — plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch — mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch — double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel — the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map — regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic — mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) — overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) — the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) — automated pipeline that\n handles the parametric → pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart — least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** — [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets —\n links into deeper docs.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model — production\n pattern for extended-arc sources.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb b/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb index 8286d2b..50b9b9c 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_4_bayesian_regularization.ipynb @@ -33,21 +33,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/HowToLens/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 c41160e..9ec4671 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb @@ -59,21 +59,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/HowToLens/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", @@ -1012,7 +1012,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones \u2014 common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially \u2014 both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type \u2014 Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation \u2014 constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source \u2014 do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* \u2014 either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised \u2014 `(adapt_image / max) ** power` \u2014 so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** \u2014 `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, \u2026).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead \u2014 transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` \u2014 the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` \u2014 the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` \u2014 the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline \u2014 imaging, group, multi-galaxy, multi-dataset \u2014 over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data \u2014 ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** \u2014 it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** \u2014 a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch \u2014 Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch \u2014 bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n \u2014 post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) \u2014 datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** \u2014 [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit \u2014 source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** \u2014 the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory \u2014 what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty \u2014\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at \u2014 the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* \u2014 if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions \u2014 the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> \u26a0\ufe0f **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch \u2014 source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot \u2014 when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D \u2014 plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch \u2014 mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch \u2014 double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel \u2014 the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map \u2014 regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic \u2014 mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) \u2014 overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) \u2014 automated pipeline that\n handles the parametric \u2192 pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart \u2014 least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** \u2014 [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets \u2014\n links into deeper docs.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model \u2014 production\n pattern for extended-arc sources.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones — common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially — both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type — Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation — constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source — do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* — either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised — `(adapt_image / max) ** power` — so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** — `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, …).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead — transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` — the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` — the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` — the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline — imaging, group, multi-galaxy, multi-dataset — over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data — ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** — it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** — a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch — Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch — bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n — post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) — the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) — datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** — [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit — source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** — the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory — what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty —\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at — the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* — if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions — the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> ⚠️ **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch — source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot — when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D — plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch — mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch — double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel — the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map — regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic — mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) — overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) — the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) — automated pipeline that\n handles the parametric → pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart — least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** — [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets —\n links into deeper docs.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model — production\n pattern for extended-arc sources.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_3_pixelizations/tutorial_6_borders.ipynb b/notebooks/chapter_3_pixelizations/tutorial_6_borders.ipynb index 85f399a..2b1c8e5 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_6_borders.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_6_borders.ipynb @@ -28,21 +28,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/HowToLens/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", @@ -777,7 +777,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_6_borders.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones \u2014 common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially \u2014 both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type \u2014 Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation \u2014 constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source \u2014 do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* \u2014 either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised \u2014 `(adapt_image / max) ** power` \u2014 so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** \u2014 `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, \u2026).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead \u2014 transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` \u2014 the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` \u2014 the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` \u2014 the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline \u2014 imaging, group, multi-galaxy, multi-dataset \u2014 over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data \u2014 ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** \u2014 it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** \u2014 a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch \u2014 Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch \u2014 bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n \u2014 post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) \u2014 datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** \u2014 [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit \u2014 source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** \u2014 the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory \u2014 what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty \u2014\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at \u2014 the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* \u2014 if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions \u2014 the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> \u26a0\ufe0f **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch \u2014 source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot \u2014 when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D \u2014 plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch \u2014 mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch \u2014 double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel \u2014 the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map \u2014 regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic \u2014 mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) \u2014 overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) \u2014 automated pipeline that\n handles the parametric \u2192 pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart \u2014 least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** \u2014 [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets \u2014\n links into deeper docs.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model \u2014 production\n pattern for extended-arc sources.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_6_borders.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones — common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially — both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type — Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation — constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source — do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* — either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised — `(adapt_image / max) ** power` — so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** — `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, …).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead — transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` — the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` — the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` — the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline — imaging, group, multi-galaxy, multi-dataset — over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data — ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** — it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** — a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch — Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch — bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n — post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) — the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) — datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** — [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit — source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** — the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory — what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty —\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at — the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* — if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions — the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> ⚠️ **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch — source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot — when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D — plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch — mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch — double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel — the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map — regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic — mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) — overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) — the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) — automated pipeline that\n handles the parametric → pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart — least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** — [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets —\n links into deeper docs.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model — production\n pattern for extended-arc sources.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_3_pixelizations/tutorial_7_lens_modeling.ipynb b/notebooks/chapter_3_pixelizations/tutorial_7_lens_modeling.ipynb index d5d16e0..873775f 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_7_lens_modeling.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_7_lens_modeling.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/HowToLens/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", @@ -504,7 +504,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_7_lens_modeling.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones \u2014 common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially \u2014 both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type \u2014 Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation \u2014 constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source \u2014 do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* \u2014 either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised \u2014 `(adapt_image / max) ** power` \u2014 so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** \u2014 `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, \u2026).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead \u2014 transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` \u2014 the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` \u2014 the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` \u2014 the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline \u2014 imaging, group, multi-galaxy, multi-dataset \u2014 over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data \u2014 ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** \u2014 it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** \u2014 a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch \u2014 Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch \u2014 bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n \u2014 post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) \u2014 datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** \u2014 [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit \u2014 source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** \u2014 the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory \u2014 what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty \u2014\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at \u2014 the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* \u2014 if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions \u2014 the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> \u26a0\ufe0f **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch \u2014 source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot \u2014 when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D \u2014 plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch \u2014 mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch \u2014 double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel \u2014 the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map \u2014 regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic \u2014 mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) \u2014 overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) \u2014 automated pipeline that\n handles the parametric \u2192 pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart \u2014 least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** \u2014 [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets \u2014\n links into deeper docs.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model \u2014 production\n pattern for extended-arc sources.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_7_lens_modeling.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones — common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially — both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type — Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation — constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source — do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* — either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised — `(adapt_image / max) ** power` — so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** — `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, …).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead — transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` — the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` — the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` — the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline — imaging, group, multi-galaxy, multi-dataset — over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data — ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** — it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** — a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch — Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch — bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n — post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) — the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) — datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** — [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit — source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** — the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory — what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty —\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at — the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* — if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions — the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> ⚠️ **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch — source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot — when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D — plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch — mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch — double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel — the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map — regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic — mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) — overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) — the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) — automated pipeline that\n handles the parametric → pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart — least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** — [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets —\n links into deeper docs.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model — production\n pattern for extended-arc sources.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb b/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb index 79a5531..3edd987 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.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/HowToLens/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", @@ -407,7 +407,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones \u2014 common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially \u2014 both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type \u2014 Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation \u2014 constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source \u2014 do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* \u2014 either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised \u2014 `(adapt_image / max) ** power` \u2014 so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** \u2014 `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, \u2026).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead \u2014 transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` \u2014 the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` \u2014 the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` \u2014 the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline \u2014 imaging, group, multi-galaxy, multi-dataset \u2014 over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data \u2014 ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** \u2014 it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** \u2014 a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch \u2014 Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch \u2014 bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n \u2014 post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) \u2014 datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** \u2014 [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit \u2014 source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** \u2014 the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory \u2014 what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty \u2014\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at \u2014 the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* \u2014 if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions \u2014 the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> \u26a0\ufe0f **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch \u2014 source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot \u2014 when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D \u2014 plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch \u2014 mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch \u2014 double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel \u2014 the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map \u2014 regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic \u2014 mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) \u2014 overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) \u2014 automated pipeline that\n handles the parametric \u2192 pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart \u2014 least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** \u2014 [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets \u2014\n links into deeper docs.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model \u2014 production\n pattern for extended-arc sources.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones — common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially — both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type — Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation — constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source — do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* — either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised — `(adapt_image / max) ** power` — so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** — `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, …).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead — transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` — the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` — the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` — the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline — imaging, group, multi-galaxy, multi-dataset — over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data — ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** — it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** — a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch — Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch — bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n — post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) — the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) — datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** — [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit — source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** — the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory — what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty —\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at — the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* — if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions — the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> ⚠️ **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch — source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot — when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D — plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch — mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch — double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel — the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map — regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic — mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) — overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) — the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) — automated pipeline that\n handles the parametric → pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart — least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** — [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets —\n links into deeper docs.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model — production\n pattern for extended-arc sources.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_3_pixelizations/tutorial_9_model_fit.ipynb b/notebooks/chapter_3_pixelizations/tutorial_9_model_fit.ipynb index 7ae1634..96fff82 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_9_model_fit.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_9_model_fit.ipynb @@ -23,21 +23,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/HowToLens/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", @@ -90,7 +90,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_9_model_fit.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones \u2014 common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially \u2014 both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type \u2014 Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation \u2014 constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source \u2014 do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* \u2014 either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised \u2014 `(adapt_image / max) ** power` \u2014 so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** \u2014 `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, \u2026).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead \u2014 transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` \u2014 the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` \u2014 the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` \u2014 the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline \u2014 imaging, group, multi-galaxy, multi-dataset \u2014 over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data \u2014 ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** \u2014 it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** \u2014 a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch \u2014 Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch \u2014 bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n \u2014 post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) \u2014 datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** \u2014 [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit \u2014 source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** \u2014 the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory \u2014 what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty \u2014\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at \u2014 the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* \u2014 if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions \u2014 the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> \u26a0\ufe0f **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch \u2014 source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot \u2014 when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D \u2014 plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch \u2014 mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch \u2014 double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel \u2014 the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map \u2014 regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic \u2014 mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) \u2014 overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) \u2014 automated pipeline that\n handles the parametric \u2192 pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart \u2014 least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** \u2014 [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets \u2014\n links into deeper docs.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model \u2014 production\n pattern for extended-arc sources.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_3_pixelizations/tutorial_9_model_fit.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_adaptive_pixelization\n\n---\nname: al_adaptive_pixelization\ndescription: Build a model whose source reconstruction uses an adaptive pixelisation (mesh density tracks source brightness or surface density) and adaptive regularisation (smoothing strength inferred from data, not fixed). Use when a uniform mesh wastes resolution on dim regions and under-resolves bright ones — common for complex arcs and ALMA data. More expressive than `al_build_imaging_model`'s \"pixelised source\" branch, at the cost of more knobs. Pairs with `al_inspect_source_reconstruction` (post-fit inspection). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Adaptive pixelisation + adaptive regularisation\n\nA fixed-resolution pixelised source treats every region of the source\nplane the same. An adaptive pixelisation concentrates pixels where the\nflux concentrates, and adaptive regularisation lets the smoothness\nstrength vary spatially — both inferred jointly with the lens parameters.\n\nThe wins are sharper at high signal-to-noise and especially for\ninterferometer data where rectangular meshes waste capacity on empty\nsky.\n\nWorkspace path: `autolens_workspace:scripts/imaging/features/pixelization/adaptive.py`,\n`scripts/imaging/features/pixelization/delaunay.py`.\n\n## Ask\n\n- *\"Mesh type — Delaunay (default adaptive), KMeans-Voronoi, Hilbert\n (memory-efficient for groups), rectangular adaptive?\"*\n- *\"Regularisation — constant (single strength), split (different per\n region), brightness-adaptive (strength scales with local source\n flux)?\"*\n- *\"Adapt-image source — do you have a converged base fit to use as the\n adapt-image, or should we bootstrap from a parametric source fit\n first?\"* — either way the source adapt image is capped at S/N 3.0\n before use (see below); the cap applies regardless of which fit it\n came from.\n\n## Adapt image S/N cap (always)\n\nThe Hilbert image-mesh weights and the adaptive regularization pixel signals are both\nmax-normalised — `(adapt_image / max) ** power` — so the brightest peak of a raw\nsignal-to-noise adapt image sets the scale for everything else. Fainter multiply-imaged\nfeatures fall to a few percent of that weight and lose both source-pixel density and\nregularization weight, so the source adapt image is capped at S/N 3.0 wherever it is\nbuilt. The library applies no cap; it is the script's job at every site.\n\nApply it immediately after the dict is built, before `al.AdaptImages(...)` or a Hilbert\n`image_plane_mesh_grid_from(adapt_data=...)`:\n\n```python\ngalaxy_image_name_dict = al.galaxy_name_image_dict_via_result_from(result=result)\n\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsource_adapt_image[source_adapt_image > adapt_image_snr_cap] = adapt_image_snr_cap\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\nRules:\n\n- **Cap a copy, never the dict entry in place.** `.copy()` keeps the class and mask; an\n in-place cap would silently truncate the raw image every later consumer shares.\n- **Anything that needs the raw image binds it before the cap.** The adaptive\n over-sampling map (`np.where(source_image_raw > 3.0, 4, 2)`, see \"Adaptive pixelization\n over-sampling\" below) reads a\n `source_image_raw = galaxy_image_name_dict[\"('galaxies', 'source')\"]` bound above the cap\n block, because the capped image never exceeds the threshold.\n- **Every stage that builds `AdaptImages` from a source image gets the cap** — `source_lp`,\n `source_pix_*`, `light_lp` and `mass_total` alike; the three lines repeat per stage.\n- Scripts with more than one source cap every source key present\n (`\"('galaxies', 'source_0')\"`, `\"('galaxies', 'source_1')\"`, …).\n\n### Interferometer\n\nInterferometer adapt images are real-space *model* images in flux units\n(`use_model_images=True`): the interferometer dirty noise map is a dirty beam rather than a\nnoise map, so dividing by it does not give a usable S/N image. Derive the clip level from a\nbeam-smoothed S/N instead — transform the model image to a dirty image, divide by the\nhomogeneous image-plane noise, and clip the copy at the flux where that S/N crosses 3.0:\n\n```python\nadapt_image_snr_cap = 3.0\n\nsource_adapt_image = galaxy_image_name_dict[\"('galaxies', 'source')\"].copy()\nsigma_pix = np.sqrt(0.5 * np.sum(np.abs(dataset.noise_map.array) ** 2))\ndirty_source = dataset.transformer.image_from(\n visibilities=dataset.transformer.visibilities_from(image=source_adapt_image)\n)\nabove_cap = source_adapt_image.array[\n dirty_source.array / sigma_pix > adapt_image_snr_cap\n]\nif above_cap.size:\n source_adapt_image[source_adapt_image > above_cap.min()] = above_cap.min()\nelse:\n print(\n \"Adapt image S/N cap not applied: no pixel reaches S/N 3.0 in the dirty image.\"\n )\ngalaxy_image_name_dict[\"('galaxies', 'source')\"] = source_adapt_image\n```\n\n`sigma_pix` is the square root of *half* the summed visibility variances, because the dirty\nimage is the real part of the transform.\n\nWorked sites to copy from:\n\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` — the canonical SLaM\n template, capped at every stage.\n- `autolens_workspace:scripts/imaging/features/pixelization/delaunay.py` — the cap feeding\n a Hilbert image mesh.\n- `autolens_workspace:scripts/interferometer/features/pixelization/slam.py` — the\n interferometer form above.\n\n## Adaptive pixelization over-sampling (from `source_pix_2`)\n\nEvery SLaM pipeline — imaging, group, multi-galaxy, multi-dataset — over-samples the\npixelization grid adaptively from `source_pix_2` onwards: sub-size 4 where the source is\ndetected, 2 elsewhere. Build the map from the *raw* (pre-cap) source entry and re-apply the\ndataset before the fit is composed; `source_pix_2` and every later stage receive that\ndataset.\n\n```python\nsignal_to_noise_threshold = 3.0\n\nsource_image_raw = al.galaxy_name_image_dict_via_result_from(result=source_pix_result_1)[\n \"('galaxies', 'source')\"\n]\n\nover_sample_size_pixelization = al.Array2D(\n values=np.where(source_image_raw > signal_to_noise_threshold, 4, 2), mask=dataset.mask\n)\n\ndataset = dataset.apply_over_sampling(\n over_sample_size_pixelization=over_sample_size_pixelization\n)\n```\n\n- **The dict entry is already a signal-to-noise map**, so it is thresholded directly.\n `al.galaxy_name_image_dict_via_result_from` with its default `use_model_images=False`\n returns `subtracted_image / noise_map` (its on-disk cache is literally\n `galaxy_images_snr.fits`); only `use_model_images=True` returns flux-unit model images.\n The function's docstring says \"model-image\" and is misleading.\n- **Never do this:** `al.util.over_sample.over_sample_size_via_adapt_from(data=,\n noise_map=...)`. That helper divides by the noise itself, so feeding it an S/N map divides\n twice (~18x inflation on HST-depth data — ~90 % of the mask at sub-size 4 instead of\n ~30 %), and its `signal_to_noise_cut` defaults to 5.0 and silently drops to `max / 2` when\n the map's maximum is below `2 * cut`. The workspace no longer calls it anywhere.\n- **`source_pix_1` is exempt** — it keeps the library default uniform sub-size (4), because\n its adapt image comes from the parametric SOURCE LP fit and is not yet reliable enough to\n steer over-sampling.\n- **Interferometer SLaM does not do this** — a pixelization fit to visibilities cannot be\n over-sampled.\n\n## Branch — Delaunay mesh + adaptive brightness regularisation\n\n> TODO: recipe. Pattern: `pix = al.Pixelization(mesh=al.mesh.Delaunay(...),\n> regularization=al.reg.AdaptiveBrightnessSplit(...))` ; wrap in a\n> `Galaxy`; analysis needs `adapt_images` set from the bootstrap fit.\n> See `PyAutoArray:autoarray/inversion/...` and\n> `PyAutoLens:autolens/imaging/...`.\n\n## Branch — bootstrap workflow\n\nTwo-stage: (1) fit with a parametric source to produce an adapt image,\n(2) refit with the adaptive pixelisation, using the parametric model\nimage as the adapt source.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n — post-fit inspection of the reconstructed source + regularisation\n state.\n- [`al_chain_searches`](./al_chain_searches.md) — the bootstrap is a\n classic two-search chain.\n- [`al_datacube_modeling`](./al_datacube_modeling.md) — datacube\n pixelisation is similar but spectrally extended.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: chapter_3 tutorial_8 adaptive](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb):\n pedagogical adaptive-pixelisation walkthrough.\n- **General reference** — [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n pixelisation feature section.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/adaptive.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/adaptive.py):\n the canonical adaptive setup.\n\nSee also [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\nfor the underlying inversion theory.\n\n## Skill: al_inspect_source_reconstruction\n\n---\nname: al_inspect_source_reconstruction\ndescription: Inspect a pixelised source reconstruction from a completed fit — source-plane image, mesh / regularisation state, reconstruction error, and the inversion's linear solution. Pixelised sources are common for complex arcs and for ALMA/JVLA visibilities. Use after `al_load_results` has handed you the dataset + tracer; needs to rebuild the `FitImaging` because pixelisation state isn't stored in `tracer.json`.\n---\n\n# Inspecting a pixelised source reconstruction\n\nWhen the source has been reconstructed on a pixel grid (Delaunay / Voronoi /\nrectangular mesh) rather than as a parametric Sersic, the interesting object is the\n**inversion** — the linear solution that mapped source-plane pixels to image-plane\ncounts. Pixelised reconstructions live in `FitImaging.inversion`, *not* in the\nsaved `tracer.json`. To see them you have to rebuild the fit.\n\nFor the theory — what regularisation does, what makes a pixelisation adaptive vs.\nfixed, why the inversion can demagnify pathologically without a positions penalty —\nread [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\nCanonical reference:\n`autolens_workspace:scripts/imaging/features/pixelization/plot.py`.\n\n## Ask\n\n- *\"What do you want to look at — the source image on its mesh, the regularisation\n matrix structure, the reconstruction error, the data-mapping matrix?\"*\n- *\"Was this a parametric or pixelised fit?\"* — if parametric, this skill doesn't\n apply; use [`al_plot_tracer`](./al_plot_tracer.md) for the source-plane image.\n\n## Saving plots\n\n`autolens.plot` in `2026.5.21+` is a flat module of free functions — the old\n`InversionPlotter` / `MatPlot2D` / `Output` classes are gone. Plot the\ninversion's component arrays directly via `aplt.plot_array`:\n\n```python\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n> ⚠️ **Known regression (still open as of `2026.7.6`).** `Delaunay` and\n> `KNNBarycentric` crash inside `FitImaging` (`'NoneType' object has no attribute\n> 'array'`), and `ConstantSplit` is broken on `RectangularUniform`. Use\n> `al.mesh.RectangularUniform` + `al.reg.Constant` for now; tracking:\n> .\n\n## Branch — source-plane reconstruction\n\nRebuild the fit so the inversion is computed, then plot the components:\n\nThe quickest full view is the fit subplot — when the fit uses an inversion its\nfinal panel *is* the source-plane reconstruction:\n\n```python\n# `dataset` from al_prepare_imaging_data, `tracer` from al_load_results.\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\n\naplt.subplot_fit_imaging(\n fit=fit, output_path=str(PLOT_DIR), output_format=\"png\",\n)\n```\n\nFor component-level access, the inversion exposes (names verified against the\n2026.7 stack):\n\n```python\ninv = fit.inversion\n\n# Image-plane image the linear solution reconstructs (Array2D — plottable):\naplt.plot_array(array=inv.mapped_reconstructed_data,\n output_path=str(PLOT_DIR),\n output_filename=\"mapped_reconstruction\",\n output_format=\"png\")\n\n# Source-plane solution: a 1D vector of per-source-pixel intensities\n# (keyed per mapper in inv.reconstruction_dict). For a RectangularUniform\n# mesh, reshape to the mesh's native 2D shape to plot it.\nreconstruction = inv.reconstruction\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoArray:autoarray/inversion/inversion/`.\n\n## Branch — mesh + regularisation diagnostics\n\nThe previous object-oriented inversion plotter API is removed.\nThe closest current entry point is `aplt.subplot_basis_image`, which renders\nthe mapper's pixelisation overlaid on the image:\n\n```python\naplt.subplot_basis_image(\n inversion=fit.inversion,\n output_path=str(PLOT_DIR), output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThe mesh-triangulation and regularisation-neighbour graphs no longer have\ndirect plot helpers; build them with NumPy and `aplt.plot_grid` if needed.\n\n## Branch — double source-plane lens (DSPL) / multi-plane pixelisations\n\nFor systems with two source planes (each pixelised independently), the\n`pixelization_index` argument indexes into the planes. See\n`autolens_workspace:scripts/imaging/features/advanced/double_source_plane_lens/plot.py`.\n\n## Quality checks\n\nA healthy pixelised reconstruction:\n\n- Source-plane reconstruction shows recognisable structure (clumps, arms), not white\n noise.\n- Reconstruction error / signal-to-noise is positive across the source.\n- Regularisation weights smoothly decrease toward the edges (for adaptive variants).\n- The reconstructed image-plane model matches the data with featureless residuals\n (see [`al_plot_fit_residuals`](./al_plot_fit_residuals.md)).\n\nPathological signs:\n\n- Source-plane is a single bright pixel — the inversion has demagnified. Add image\n positions and refit.\n- Reconstruction looks like the noise map — regularisation is too low. Raise the\n regularisation coefficient range.\n- Source is unphysically extended beyond the caustic — mass model is wrong; the\n positions penalty isn't holding it in.\n\nConnect to [`al_debug_fit_failure`](./al_debug_fit_failure.md) when any of these\nappear.\n\n## Combine\n\n- [`al_plot_tracer`](./al_plot_tracer.md) — overlay caustics on the source-plane\n reconstruction to confirm signal is inside the caustic.\n- [`al_chain_searches`](./al_chain_searches.md) — the canonical chain for moving from\n a parametric source fit to a pixelised one.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) — automated pipeline that\n handles the parametric → pixelised transition.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Reconstructing source light via\n least-squares](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_3_inversions.ipynb):\n the inversion at its heart — least-squares solution for source-plane pixel\n intensities. Chapter 3 as a whole covers mappers, regularization, adaptive grids.\n- **General reference** — [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n the pixelization feature sits here alongside MGE / interferometry / shapelets —\n links into deeper docs.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/features/pixelization/modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/modeling.py):\n rectangular-mesh + constant-regularization pixelization model — production\n pattern for extended-arc sources.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.ipynb b/notebooks/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.ipynb index a2c490a..46b0203 100644 --- a/notebooks/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.ipynb +++ b/notebooks/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.ipynb @@ -63,21 +63,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/HowToLens/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", @@ -768,7 +768,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_group_lensing\n\n---\nname: al_group_lensing\ndescription: Model a group-scale strong lens \u2014 one or two main lens galaxies plus a population of companion (\"extra\") galaxies whose light + mass must also be modelled. Two strategies: (a) free per-companion profiles for small N, (b) \"scaling-relation\" galaxies tied to a luminosity-to-mass relation for larger N. Pairs with `al_cluster_csv_api` (when N is large enough that inline Python composition becomes unwieldy). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Group-scale lensing \u2014 companion galaxies and scaling relations\n\nA galaxy-scale model assumes one dominant lens. A group-scale lens has\nmultiple deflectors: a primary galaxy plus companions whose mass cannot be\nignored. With ~3\u201310 companions you can give each its own light + mass\nprofile (free). Past that, parameter count explodes and you instead tie\neach companion's mass to its observed luminosity via a scaling relation.\n\nWorkspace path: `autolens_workspace:scripts/group/start_here.py` and\n`scripts/group/features/scaling_relation/modeling.py`.\n\n## Ask\n\n- *\"How many lens galaxies \u2014 main + how many companions?\"* This picks the\n branch.\n- *\"Do you have light + position measurements for the companions, or just\n positions?\"* Scaling relations need a measured luminosity per\n companion.\n- *\"Source \u2014 single or multiple?\"* Group lenses sometimes have multiple\n background sources at different redshifts.\n- *\"Parametric or pixelised source?\"* Same trade-off as galaxy-scale.\n\n## Branch \u2014 small N: free per-companion mass profiles\n\n> TODO: recipe. Pattern: each companion gets its own `Galaxy` with light\n> + mass; centres are fixed from imaging measurements; mass-profile\n> normalisations are free. Bundle into a single `af.Collection`.\n\n## Branch \u2014 large N: scaling-relation companions\n\n> TODO: recipe. Pattern: a single set of shared scaling-relation\n> parameters (slope, normalisation, scatter) governs the mass of every\n> companion as a function of its measured luminosity. See\n> `PyAutoGalaxy:autogalaxy/galaxy/...` for the scaling-relation\n> machinery.\n\n## Branch \u2014 group with extra + scaling galaxies together\n\nSome companions are bright enough to deserve free mass; the rest follow\nthe scaling relation. Composed in one model.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_cluster_csv_api`](./al_cluster_csv_api.md) \u2014 for very large N\n (cluster-scale), spreadsheet-driven composition.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) \u2014 group SLaM\n variant exists in the workspace.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n \u2014 pixelised sources are common in group lenses.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 _ (no direct HowToLens chapter; group\n lensing is an advanced topic).\n- **General reference** \u2014 [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n group lensing in the feature tour.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: group/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/group/start_here.py):\n the canonical group fit \u2014 extra galaxies, scaling relations, group\n SLaM.\n\nSee also [`wiki/core/concepts/group_and_cluster_lensing.md`](../wiki/core/concepts/group_and_cluster_lensing.md)\nfor the physics (group mass scale, cluster member kinematics, the\nextra-galaxy vs. scaling-relation choice).\n\n## Skill: al_build_imaging_model\n\n---\nname: al_build_imaging_model\ndescription: Compose a strong-lens model for imaging data \u2014 galaxies with light + mass profiles, prior customisation, and an `al.AnalysisImaging` ready to hand to a non-linear search. Writes a runnable Python script in scripts/. Pairs with `al_prepare_imaging_data` (which loads + masks the dataset) and `al_run_search` (which executes the fit). For visibility-plane data see `al_build_interferometer_model`.\n---\n\n# Composing an imaging lens model\n\nThe model is the PyAuto\\* representation of *what kind of lens you think this is* \u2014 how\nmany galaxies, at what redshifts, with what light and mass parameterisations, with\nwhich parameters free and which fixed. Building one is the step between \"I have a\nloaded `Imaging` dataset\" and \"I'm running a non-linear search\".\n\nThe canonical example is `autolens_workspace:scripts/imaging/modeling.py`. This skill\ngenerates the equivalent for the user's lens.\n\nThis skill assumes the imaging data is already preprocessing-ready. For real\nobservational data, confirm first that the user has **inspected `dataset.png`** and\nthought through mask extent, contaminating objects, and any regions to exclude \u2014 in\nparticular that any **extra galaxies** have been handled (noise-scaled via a\n`mask_extra_galaxies.fits`, or excluded by shrinking the circular mask). If not, route\nthem back to [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) before building the\nmodel \u2014 don't compose a model over data with an unaddressed contaminant.\n\n## Ask\n\n- *\"If this is real observational data, have you inspected `dataset.png`, decided the\n mask extent, and handled any extra galaxies (noise-scaled a `mask_extra_galaxies.fits`,\n or shrunk the mask to exclude them)?\"* \u2014 if not, stop and do that in\n [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) first.\n- *\"How many galaxies in the model \u2014 single galaxy-scale, multi-galaxy (2+ co-dominant, no host halo), group (2\u201310, optional group halo), cluster?\"* \u2014\n this is the only structural choice. Skill below assumes galaxy-scale; bootstrap a\n variant for groups/clusters via `_bootstrap_skill` if needed.\n- *\"What's the lens light parameterisation \u2014 a single Sersic, MGE (multi-Gaussian\n expansion), bulge + disk, or no lens light at all (mass-only)?\"*\n- *\"What's the lens mass \u2014 Isothermal (SIE) + ExternalShear is the standard starting\n point; PowerLaw or NFW for total or dark-matter-only models.\"*\n- *\"What's the source \u2014 parametric Sersic, MGE, or pixelised inversion?\"* \u2014 pixelised\n needs a different `Analysis` wiring; see [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md).\n- *\"What are the lens and source redshifts?\"* \u2014 needed for distance ratios; even a\n ballpark value works for relative-comparison runs.\n\n## Branch \u2014 galaxy-scale, Sersic light + SIE mass + Sersic source\n\nThe minimum viable model. Save to `scripts/build_model.py`:\n\n```python\n# scripts/build_model.py\nfrom autonerves import jax_wrapper\nimport autofit as af\nimport autolens as al\n\n# Lens light \u2014 a Sersic for the bulge.\nlens_bulge = af.Model(al.lp.Sersic)\n\n# Lens mass \u2014 SIE plus a separate external field.\nlens_mass = af.Model(al.mp.Isothermal)\nlens_shear = af.Model(al.mp.ExternalShear)\n\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=lens_bulge,\n mass=lens_mass,\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=lens_shear)\n\n# Source light \u2014 a single Sersic.\nsource = af.Model(\n al.Galaxy,\n redshift=1.0,\n bulge=af.Model(al.lp.SersicCore),\n)\n\n# Compose into a Collection.\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# Optional: customise priors. E.g. tighten the lens centre.\nlens_mass.centre.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\nlens_mass.centre.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n\n# On real data, bound the Einstein radius from the ring you can see in the image\n# (the default prior is uniform over 0-8\"). A maximum-likelihood optimiser such as\n# MultiStartProdigy otherwise finds degenerate basins where theta_E exceeds the mask,\n# the \"source\" lands on a neighbouring galaxy and the ring is left in the residuals\n# (this is exactly what happened on the bundled COSMOS-Web Ring: theta_E 2.4\" vs 0.8\").\nlens_mass.einstein_radius = af.UniformPrior(lower_limit=0.3, upper_limit=1.5)\n\nprint(model.info)\n```\n\nSource citations:\n- `PyAutoGalaxy:autogalaxy/galaxy/galaxy.py` \u2014 `Galaxy`.\n- `PyAutoGalaxy:autogalaxy/galaxy/mass_field.py` \u2014 `MassField`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 `Sersic`, `SersicCore`.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 `Isothermal`.\n- `PyAutoFit:autofit/mapper/prior_model/prior_model.py` \u2014 `af.Model`.\n- `PyAutoFit:autofit/mapper/prior_model/collection.py` \u2014 `af.Collection`.\n\nWiki:\n- [`wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md) \u2014 what each\n light profile represents and when to pick which.\n- [`wiki/core/concepts/mass_profiles.md`](../wiki/core/concepts/mass_profiles.md) \u2014 same for mass.\n- [`wiki/core/concepts/galaxy_and_plane.md`](../wiki/core/concepts/galaxy_and_plane.md) \u2014 how\n galaxies, redshifts, and the `Tracer` fit together.\n\n## Branch \u2014 linear (MGE) lens light\n\nFor complex lens galaxy morphologies, replace the single Sersic bulge with a Multi-\nGaussian Expansion of *linear* light profiles. Linear profiles have their\n*intensities* solved analytically inside the fit, so the search only varies\nshape parameters \u2014 far fewer dimensions, much better convergence.\n\n```python\nn_gaussians = 30\ngaussian_per_basis = [\n af.Model(al.lp_linear.Gaussian) for _ in range(n_gaussians)\n]\n# Tie centres + ellipticities across the basis; let only sigma + intensity vary.\nfor g in gaussian_per_basis[1:]:\n g.centre = gaussian_per_basis[0].centre\n g.ell_comps = gaussian_per_basis[0].ell_comps\n\nlens_bulge = af.Model(al.lp_basis.Basis, profile_list=gaussian_per_basis)\n```\n\nSee `PyAutoGalaxy:autogalaxy/profiles/light/linear/` for the linear-profile classes.\n\n## Branch \u2014 pixelised source\n\nFor sources with complex morphology (lensed arcs, multiple components), reconstruct\nthe source on a pixel grid rather than as a parametric Sersic. The model wiring is\ndifferent: the source `Galaxy` carries a `Pixelization`, and the `Analysis` needs a\npositions likelihood penalty to keep the inversion well-posed.\n\nSee [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) for\nthe full pattern.\n\n## Wrap with an analysis\n\nOnce the model is built, wrap your loaded `dataset` (from `al_prepare_imaging_data`)\nin an analysis object:\n\n```python\nanalysis = al.AnalysisImaging(dataset=dataset)\n```\n\nSource: `PyAutoLens:autolens/imaging/model/analysis.py`.\n\n`analysis` + `model` are the two inputs to the non-linear search. Pass them to\n[`al_run_search`](./al_run_search.md).\n\n## Combine\n\nNatural next steps:\n\n- [`al_configure_search`](./al_configure_search.md) \u2014 pick Nautilus (default), Dynesty,\n Emcee, or another search; tune live points / walkers.\n- [`al_run_search`](./al_run_search.md) \u2014 `search.fit(model=model, analysis=analysis)`.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 chain a fast Sersic source fit into\n a slower pixelised one, inheriting priors.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Non-linear searches and parameter\n inference](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb):\n how non-linear searches find a best-fit model \u2014 parameter spaces, likelihoods,\n priors. The statistical foundation under model composition.\n- **General reference** \u2014 [RTD: Model cookbook](https://pyautolens.readthedocs.io/en/latest/general/model_cookbook.html):\n systematic reference for building lens models with `Model` and `Collection` \u2014\n two-component to multi-galaxy, prior customisation, parameter pairing, MGE.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/modeling/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling/start_here.py):\n the canonical imaging-modeling script \u2014 light-profile choice (Sersic vs. MGE),\n non-linear-search configuration, JAX/GPU fitting.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_group_lensing\n\n---\nname: al_group_lensing\ndescription: Model a group-scale strong lens — one or two main lens galaxies plus a population of companion (\"extra\") galaxies whose light + mass must also be modelled. Two strategies: (a) free per-companion profiles for small N, (b) \"scaling-relation\" galaxies tied to a luminosity-to-mass relation for larger N. Pairs with `al_cluster_csv_api` (when N is large enough that inline Python composition becomes unwieldy). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Group-scale lensing — companion galaxies and scaling relations\n\nA galaxy-scale model assumes one dominant lens. A group-scale lens has\nmultiple deflectors: a primary galaxy plus companions whose mass cannot be\nignored. With ~3–10 companions you can give each its own light + mass\nprofile (free). Past that, parameter count explodes and you instead tie\neach companion's mass to its observed luminosity via a scaling relation.\n\nWorkspace path: `autolens_workspace:scripts/group/start_here.py` and\n`scripts/group/features/scaling_relation/modeling.py`.\n\n## Ask\n\n- *\"How many lens galaxies — main + how many companions?\"* This picks the\n branch.\n- *\"Do you have light + position measurements for the companions, or just\n positions?\"* Scaling relations need a measured luminosity per\n companion.\n- *\"Source — single or multiple?\"* Group lenses sometimes have multiple\n background sources at different redshifts.\n- *\"Parametric or pixelised source?\"* Same trade-off as galaxy-scale.\n\n## Branch — small N: free per-companion mass profiles\n\n> TODO: recipe. Pattern: each companion gets its own `Galaxy` with light\n> + mass; centres are fixed from imaging measurements; mass-profile\n> normalisations are free. Bundle into a single `af.Collection`.\n\n## Branch — large N: scaling-relation companions\n\n> TODO: recipe. Pattern: a single set of shared scaling-relation\n> parameters (slope, normalisation, scatter) governs the mass of every\n> companion as a function of its measured luminosity. See\n> `PyAutoGalaxy:autogalaxy/galaxy/...` for the scaling-relation\n> machinery.\n\n## Branch — group with extra + scaling galaxies together\n\nSome companions are bright enough to deserve free mass; the rest follow\nthe scaling relation. Composed in one model.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_cluster_csv_api`](./al_cluster_csv_api.md) — for very large N\n (cluster-scale), spreadsheet-driven composition.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) — group SLaM\n variant exists in the workspace.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n — pixelised sources are common in group lenses.\n\n## Further reading\n\n- **Student / new to lensing** — _ (no direct HowToLens chapter; group\n lensing is an advanced topic).\n- **General reference** — [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n group lensing in the feature tour.\n- **Experienced PyAutoLens user** — [workspace/lens: group/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/group/start_here.py):\n the canonical group fit — extra galaxies, scaling relations, group\n SLaM.\n\nSee also [`wiki/core/concepts/group_and_cluster_lensing.md`](../wiki/core/concepts/group_and_cluster_lensing.md)\nfor the physics (group mass scale, cluster member kinematics, the\nextra-galaxy vs. scaling-relation choice).\n\n## Skill: al_build_imaging_model\n\n---\nname: al_build_imaging_model\ndescription: Compose a strong-lens model for imaging data — galaxies with light + mass profiles, prior customisation, and an `al.AnalysisImaging` ready to hand to a non-linear search. Writes a runnable Python script in scripts/. Pairs with `al_prepare_imaging_data` (which loads + masks the dataset) and `al_run_search` (which executes the fit). For visibility-plane data see `al_build_interferometer_model`.\n---\n\n# Composing an imaging lens model\n\nThe model is the PyAuto\\* representation of *what kind of lens you think this is* — how\nmany galaxies, at what redshifts, with what light and mass parameterisations, with\nwhich parameters free and which fixed. Building one is the step between \"I have a\nloaded `Imaging` dataset\" and \"I'm running a non-linear search\".\n\nThe canonical example is `autolens_workspace:scripts/imaging/modeling.py`. This skill\ngenerates the equivalent for the user's lens.\n\nThis skill assumes the imaging data is already preprocessing-ready. For real\nobservational data, confirm first that the user has **inspected `dataset.png`** and\nthought through mask extent, contaminating objects, and any regions to exclude — in\nparticular that any **extra galaxies** have been handled (noise-scaled via a\n`mask_extra_galaxies.fits`, or excluded by shrinking the circular mask). If not, route\nthem back to [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) before building the\nmodel — don't compose a model over data with an unaddressed contaminant.\n\n## Ask\n\n- *\"If this is real observational data, have you inspected `dataset.png`, decided the\n mask extent, and handled any extra galaxies (noise-scaled a `mask_extra_galaxies.fits`,\n or shrunk the mask to exclude them)?\"* — if not, stop and do that in\n [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) first.\n- *\"How many galaxies in the model — single galaxy-scale, multi-galaxy (2+ co-dominant, no host halo), group (2–10, optional group halo), cluster?\"* —\n this is the only structural choice. Skill below assumes galaxy-scale; bootstrap a\n variant for groups/clusters via `_bootstrap_skill` if needed.\n- *\"What's the lens light parameterisation — a single Sersic, MGE (multi-Gaussian\n expansion), bulge + disk, or no lens light at all (mass-only)?\"*\n- *\"What's the lens mass — Isothermal (SIE) + ExternalShear is the standard starting\n point; PowerLaw or NFW for total or dark-matter-only models.\"*\n- *\"What's the source — parametric Sersic, MGE, or pixelised inversion?\"* — pixelised\n needs a different `Analysis` wiring; see [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md).\n- *\"What are the lens and source redshifts?\"* — needed for distance ratios; even a\n ballpark value works for relative-comparison runs.\n\n## Branch — galaxy-scale, Sersic light + SIE mass + Sersic source\n\nThe minimum viable model. Save to `scripts/build_model.py`:\n\n```python\n# scripts/build_model.py\nfrom autonerves import jax_wrapper\nimport autofit as af\nimport autolens as al\n\n# Lens light — a Sersic for the bulge.\nlens_bulge = af.Model(al.lp.Sersic)\n\n# Lens mass — SIE plus a separate external field.\nlens_mass = af.Model(al.mp.Isothermal)\nlens_shear = af.Model(al.mp.ExternalShear)\n\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=lens_bulge,\n mass=lens_mass,\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=lens_shear)\n\n# Source light — a single Sersic.\nsource = af.Model(\n al.Galaxy,\n redshift=1.0,\n bulge=af.Model(al.lp.SersicCore),\n)\n\n# Compose into a Collection.\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# Optional: customise priors. E.g. tighten the lens centre.\nlens_mass.centre.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\nlens_mass.centre.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n\n# On real data, bound the Einstein radius from the ring you can see in the image\n# (the default prior is uniform over 0-8\"). A maximum-likelihood optimiser such as\n# MultiStartProdigy otherwise finds degenerate basins where theta_E exceeds the mask,\n# the \"source\" lands on a neighbouring galaxy and the ring is left in the residuals\n# (this is exactly what happened on the bundled COSMOS-Web Ring: theta_E 2.4\" vs 0.8\").\nlens_mass.einstein_radius = af.UniformPrior(lower_limit=0.3, upper_limit=1.5)\n\nprint(model.info)\n```\n\nSource citations:\n- `PyAutoGalaxy:autogalaxy/galaxy/galaxy.py` — `Galaxy`.\n- `PyAutoGalaxy:autogalaxy/galaxy/mass_field.py` — `MassField`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — `Sersic`, `SersicCore`.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — `Isothermal`.\n- `PyAutoFit:autofit/mapper/prior_model/prior_model.py` — `af.Model`.\n- `PyAutoFit:autofit/mapper/prior_model/collection.py` — `af.Collection`.\n\nWiki:\n- [`wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md) — what each\n light profile represents and when to pick which.\n- [`wiki/core/concepts/mass_profiles.md`](../wiki/core/concepts/mass_profiles.md) — same for mass.\n- [`wiki/core/concepts/galaxy_and_plane.md`](../wiki/core/concepts/galaxy_and_plane.md) — how\n galaxies, redshifts, and the `Tracer` fit together.\n\n## Branch — linear (MGE) lens light\n\nFor complex lens galaxy morphologies, replace the single Sersic bulge with a Multi-\nGaussian Expansion of *linear* light profiles. Linear profiles have their\n*intensities* solved analytically inside the fit, so the search only varies\nshape parameters — far fewer dimensions, much better convergence.\n\n```python\nn_gaussians = 30\ngaussian_per_basis = [\n af.Model(al.lp_linear.Gaussian) for _ in range(n_gaussians)\n]\n# Tie centres + ellipticities across the basis; let only sigma + intensity vary.\nfor g in gaussian_per_basis[1:]:\n g.centre = gaussian_per_basis[0].centre\n g.ell_comps = gaussian_per_basis[0].ell_comps\n\nlens_bulge = af.Model(al.lp_basis.Basis, profile_list=gaussian_per_basis)\n```\n\nSee `PyAutoGalaxy:autogalaxy/profiles/light/linear/` for the linear-profile classes.\n\n## Branch — pixelised source\n\nFor sources with complex morphology (lensed arcs, multiple components), reconstruct\nthe source on a pixel grid rather than as a parametric Sersic. The model wiring is\ndifferent: the source `Galaxy` carries a `Pixelization`, and the `Analysis` needs a\npositions likelihood penalty to keep the inversion well-posed.\n\nSee [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) for\nthe full pattern.\n\n## Wrap with an analysis\n\nOnce the model is built, wrap your loaded `dataset` (from `al_prepare_imaging_data`)\nin an analysis object:\n\n```python\nanalysis = al.AnalysisImaging(dataset=dataset)\n```\n\nSource: `PyAutoLens:autolens/imaging/model/analysis.py`.\n\n`analysis` + `model` are the two inputs to the non-linear search. Pass them to\n[`al_run_search`](./al_run_search.md).\n\n## Combine\n\nNatural next steps:\n\n- [`al_configure_search`](./al_configure_search.md) — pick Nautilus (default), Dynesty,\n Emcee, or another search; tune live points / walkers.\n- [`al_run_search`](./al_run_search.md) — `search.fit(model=model, analysis=analysis)`.\n- [`al_chain_searches`](./al_chain_searches.md) — chain a fast Sersic source fit into\n a slower pixelised one, inheriting priors.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Non-linear searches and parameter\n inference](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb):\n how non-linear searches find a best-fit model — parameter spaces, likelihoods,\n priors. The statistical foundation under model composition.\n- **General reference** — [RTD: Model cookbook](https://pyautolens.readthedocs.io/en/latest/general/model_cookbook.html):\n systematic reference for building lens models with `Model` and `Collection` —\n two-component to multi-galaxy, prior customisation, parameter pairing, MGE.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/modeling/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling/start_here.py):\n the canonical imaging-modeling script — light-profile choice (Sersic vs. MGE),\n non-linear-search configuration, JAX/GPU fitting.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_4_scaling_up_lensing/tutorial_2_multi_galaxy.ipynb b/notebooks/chapter_4_scaling_up_lensing/tutorial_2_multi_galaxy.ipynb index 4617e03..09320f8 100644 --- a/notebooks/chapter_4_scaling_up_lensing/tutorial_2_multi_galaxy.ipynb +++ b/notebooks/chapter_4_scaling_up_lensing/tutorial_2_multi_galaxy.ipynb @@ -54,21 +54,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/HowToLens/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_lensing/tutorial_3_scaling_relation.ipynb b/notebooks/chapter_4_scaling_up_lensing/tutorial_3_scaling_relation.ipynb index 7f6365e..e8dbca9 100644 --- a/notebooks/chapter_4_scaling_up_lensing/tutorial_3_scaling_relation.ipynb +++ b/notebooks/chapter_4_scaling_up_lensing/tutorial_3_scaling_relation.ipynb @@ -111,21 +111,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/HowToLens/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_lensing/tutorial_4_group_scale.ipynb b/notebooks/chapter_4_scaling_up_lensing/tutorial_4_group_scale.ipynb index 916d633..3d463c4 100644 --- a/notebooks/chapter_4_scaling_up_lensing/tutorial_4_group_scale.ipynb +++ b/notebooks/chapter_4_scaling_up_lensing/tutorial_4_group_scale.ipynb @@ -74,21 +74,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/HowToLens/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_lensing/tutorial_5_cluster_scale.ipynb b/notebooks/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.ipynb index 2492da7..3403eae 100644 --- a/notebooks/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.ipynb +++ b/notebooks/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.ipynb @@ -96,21 +96,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/HowToLens/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_lensing/tutorial_6_weak_lensing.ipynb b/notebooks/chapter_4_scaling_up_lensing/tutorial_6_weak_lensing.ipynb index 6a65ca6..ceafb7e 100644 --- a/notebooks/chapter_4_scaling_up_lensing/tutorial_6_weak_lensing.ipynb +++ b/notebooks/chapter_4_scaling_up_lensing/tutorial_6_weak_lensing.ipynb @@ -67,21 +67,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/HowToLens/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 0f4f60f..9a02540 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/HowToLens/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", @@ -511,7 +511,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_optional/tutorial_searches.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_configure_search\n\n---\nname: al_configure_search\ndescription: Pick and tune a non-linear search for a lens-modelling fit. Defaults to Nautilus (nested sampling, the recommended choice); covers Dynesty, Emcee, Zeus, and the JAX multi-start gradient optimizers (MultiStartProdigy recommended when a fast MAP point estimate on a parametric source is wanted \u2014 not pixelized). Sets sampler-specific knobs (live points, walkers, tolerance) and the output `path_prefix` / `name` that determine where results land. Pairs with `al_run_search`, which actually calls `search.fit`.\n---\n\n# Configuring a non-linear search\n\nThe non-linear search is *how* PyAutoFit explores the model's parameter space. PyAutoLens\nexposes the same searches PyAutoFit ships, with Nautilus as the default. Picking the\nright one \u2014 and tuning its knobs sensibly \u2014 is often the difference between a fit that\nconverges in hours and one that doesn't converge at all.\n\nFor the catalogue of available searches and when to use each,\n[`wiki/core/api/searches.md`](../wiki/core/api/searches.md). For the *concept* of a non-linear\nsearch (what nested sampling does, what MCMC does, what gradient descent does),\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md).\n\n## Ask\n\n- *\"How complex is the model?\"* \u2014 number of free parameters and whether any are\n expected to be multi-modal. Multi-modality strongly favours nested sampling\n (Nautilus / Dynesty) over MCMC.\n- *\"How fast does the likelihood evaluate?\"* \u2014 fast (<1s with JAX) \u2192 can afford more\n live points or walkers. Slow \u2192 tighten the search.\n- *\"Is this a first exploratory fit, or a final production run?\"* \u2014 exploratory fits\n use fewer live points and looser tolerance to fail fast.\n- *\"Where should the output go?\"* \u2014 `output//modeling///` is the\n convention; the user chooses `` and ``.\n\n## Branch \u2014 Nautilus (recommended default)\n\nFor most lens models \u2014 parametric, pixelised, simple, complex \u2014 Nautilus is the right\nfirst pick. It handles multi-modal posteriors and is fast enough on modern CPUs.\n\n```python\n# scripts/configure_search.py\nimport autofit as af\n\nsearch = af.Nautilus(\n path_prefix=\"imaging/\",\n name=\"modeling_sie_sersic\",\n unique_tag=\"\",\n n_live=200, # 100 for exploration, 200 for production, 400+ for complex models\n iterations_per_full_update=2500,\n number_of_cores=4, # parallel likelihood evaluations\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/nautilus/`.\n\nKnobs to know:\n- `n_live` \u2014 more = more accurate posterior, slower. Start at 200; go to 400+ only if\n the posterior looks multi-modal or thin.\n- `number_of_cores` \u2014 parallel likelihood evaluations via Python multiprocessing, **only when\n JAX is off**. JAX disables multiprocessing, so a JAX fit gains nothing from it \u2014 leave it\n unset there (it defaults to 1; passing `1` explicitly just implies a parallelism that isn't\n there). Set it to your core count only for non-JAX CPU fits \u2014 see\n \"Branch \u2014 CPU acceleration\" below, which decides *which* regime a fit belongs to.\n- `iterations_per_full_update` / `iterations_per_quick_update` \u2014 how often the search\n writes full output (samples, visualisation) vs quick intermediate updates to disk.\n **Actively choose `iterations_per_quick_update` so the user always has quick access to\n result inspection** \u2014 don't just take the default. Judge it against the likelihood cost so\n the first on-the-fly `fit.png` / `samples` lands within a few minutes and refreshes\n regularly, but not so often that per-update visualisation overhead eats into throughput.\n Rules of thumb: ~500\u20131000 is a good interactive default; **lower it for a slow/expensive\n likelihood** (large MGE, pixelised source, GPU-batched fit, high `n_live`) so an inspection\n point still appears early; only **raise it** (\u22482500\u20135000) when the likelihood is very fast\n and frequent updates would measurably dominate runtime. A common failure is leaving it high\n on a heavy fit, so the run shows *nothing* to inspect for an hour \u2014 avoid that. On HPC/batch\n runs the same value governs what a `sync pull` surfaces, so pick it before submitting.\n - **Set it the right way \u2014 directly on the search.** Pass `iterations_per_quick_update=\u2026`\n straight to the search constructor, e.g. `af.Nautilus(..., iterations_per_quick_update=\u2026)`\n (the idiom used throughout `autolens_workspace`, e.g. `point_source/modeling.py`,\n `weak/modeling.py`). Do **not** try to set it via `settings_search.search_dict[...] = \u2026`:\n `SettingsSearch.search_dict` is a fixed-key property (`path_prefix`, `unique_tag`,\n `number_of_cores`, `session`, `use_jax_vmap`), so assigning a new key to it is a **silent\n no-op** \u2014 the value never reaches the search and the config default (often `1e99`, i.e.\n *never* quick-update) silently wins. To set it globally for a whole pipeline without\n editing every search, write it to the live config once after `conf.instance.push(...)`:\n `conf.instance[\"general\"][\"updates\"][\"iterations_per_quick_update\"] = N`.\n\n## Branch \u2014 CPU acceleration (JAX vs sparse operators)\n\nOn CPU the right accelerator depends on the **source model**. This is the single biggest CPU\nruntime lever in lens modelling, and getting it backwards costs days, not minutes \u2014 a full SLaM\nrun misconfigured here spends >12 h stuck in its first search.\n\n| Fit type | Accelerator | `use_jax` | `number_of_cores` | Dataset |\n|---|---|---|---|---|\n| **Parametric source** (`source_lp`, most non-pixelised fits) | JAX \u2014 vectorises the likelihood, parallelises well **on CPU** | `True` | leave unset (JAX disables multiprocessing) | plain |\n| **Pixelised source** (`source_pix`, `light`, `mass` \u2014 any fit with a `Pixelization`) | Sparse operator formalism (numba) | `False` | your core count | `dataset.apply_sparse_operator_cpu()` |\n\nTwo rules that are easy to get wrong:\n\n- **JAX is not GPU-only.** It is the correct accelerator for *parametric* fits on CPU too. Do\n not reach for `use_jax=False` + many cores just because there is no GPU.\n- **The sparse operator does not support JAX.** It is numba-based, so never combine them: a\n pixelised CPU fit is `apply_sparse_operator_cpu()` + `use_jax=False` + `number_of_cores=N`.\n `apply_sparse_operator_cpu()` precomputes operator matrices once (seconds to minutes) and\n every later pixelised fit reuses them, exploiting the sparsity of the pixelisation linear\n algebra for a large CPU speed-up.\n\n```python\n# Parametric source on CPU \u2014 JAX, no number_of_cores.\nanalysis = al.AnalysisImaging(dataset=dataset, use_jax=True)\nsettings_search = af.SettingsSearch(path_prefix=..., unique_tag=..., session=None)\n\n# Pixelised source on CPU \u2014 sparse operators, JAX off, multiprocessing on.\ndataset_pix = dataset.apply_sparse_operator_cpu()\nanalysis = al.AnalysisImaging(dataset=dataset_pix, use_jax=False)\nsettings_search = af.SettingsSearch(\n path_prefix=..., unique_tag=..., session=None, number_of_cores=8\n)\n```\n\n`number_of_cores` reaches the search through `af.SettingsSearch` (it is one of `search_dict`'s\nfixed keys), so pass it there rather than to the search constructor.\n\n**A SLaM pipeline spans both regimes.** SOURCE LP is parametric (JAX); every stage after it uses\na pixelised source (sparse/CPU). So build **two** `af.SettingsSearch` objects \u2014 one without\n`number_of_cores` for SOURCE LP, one with N for the pixelised stages \u2014 and hand each stage the\nright dataset (`dataset` vs `dataset_pix`). On **GPU**, JAX is used throughout and the sparse\noperator is not applied at all.\n\nSource / worked example:\n`autolens_workspace:scripts/imaging/features/pixelization/cpu_fast_modeling.py`.\n\n## Branch \u2014 MultiStartProdigy (JAX gradient optimizer, parametric sources)\n\nWhen the user explicitly wants a **JAX gradient optimizer** \u2014 a fast maximum-a-posteriori (MAP)\n*point* estimate rather than a full posterior \u2014 the recommended default is `MultiStartProdigy`.\nReach for it when the goal is speed to a best-fit model on a **parametric source** (MGE, Sersic)\nand errors are not yet needed; otherwise keep Nautilus.\n\n```python\nimport autofit as af\n\nsearch = af.MultiStartProdigy(\n path_prefix=\"imaging/\",\n name=\"modeling_sie_sersic\",\n unique_tag=\"\",\n n_starts=50, # broad starts run in parallel via jax.vmap\n n_steps=500,\n)\n```\n\nRequires a JAX-traceable analysis: `al.AnalysisImaging(dataset=dataset, use_jax=True)` (the\nparametric-source regime of \"Branch \u2014 CPU acceleration\" above).\n\nWhy Prodigy, and what the family is:\n\n- The **multi-start** approach \u2014 launch many broad starts in parallel and keep the best \u2014 was\n introduced for strong-lens modelling by **GIGA-Lens** (Gu, Huang et al. 2022, arXiv:2202.07663;\n GIGA-Lens 2.0, arXiv:2606.30633). It is what makes a gradient optimizer robust on the\n multi-modal lens likelihood, where a single-start optimizer gets stuck.\n- **`MultiStartProdigy`** uses the *learning-rate free* Prodigy rule (Mishchenko & Defazio 2024,\n arXiv:2306.06101): it tunes its own step size, so there is no `learning_rate` to set, and it\n reaches the same maximum as a hand-tuned `MultiStartAdam`. Recommend it as the default.\n- **`MultiStartAdam`** is the GIGA-Lens original (needs a chosen `learning_rate`);\n **`MultiStartADABelief`** is a drop-in Adam-variant alternative. (`MultiStartLion` is a further\n sign-based option that prefers a ~10x smaller `learning_rate`.)\n\n**Parametric sources only, for now.** These optimizers are validated and recommended for\nparametric sources. For a **pixelised source** (any fit with a `Pixelization`) they do **not**\nyet reliably work: the pixelised likelihood has regions where the gradient becomes non-finite,\nso the optimizer stalls short of the best fit, and `Nautilus` is both more reliable and faster\nthere. Making the JAX multi-start optimizers work on pixelised sources is ongoing work \u2014 so for\nany pixelised fit recommend Nautilus (with the sparse-operator CPU regime above), not a gradient\noptimizer.\n\nLike every optimizer it returns a single best-fit model, no errors \u2014 hand it to Nautilus / MCMC\nafterwards if a posterior is needed.\n\nSource: `PyAutoFit:autofit/non_linear/search/mle/multi_start_gradient/`.\n\n## Branch \u2014 Dynesty\n\nUse Dynesty for problems where you specifically want its dynamic sampling features\n(e.g. focusing samples in the posterior tails for precise evidence estimation).\n\n```python\nsearch = af.DynestyStatic(\n path_prefix=\"...\",\n name=\"...\",\n nlive=150,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/dynesty/`.\n\n## Branch \u2014 Emcee (MCMC)\n\nUse Emcee for posterior characterisation on a *known unimodal* posterior, when you\nalready have a tight initial guess (e.g. from a chained earlier fit). Don't use for\nexploration of multi-modal spaces.\n\n```python\nsearch = af.Emcee(\n path_prefix=\"...\",\n name=\"...\",\n nwalkers=50,\n nsteps=10000,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/mcmc/emcee/`.\n\n## Branch \u2014 Other searches\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\nZeus (ensemble slice MCMC), DynestyDynamic (dynamic nested sampling), NSS (JAX nested slice\nsampling), BlackJAXNUTS and SMC (JAX gradient MCMC; SMC also returns the evidence), BFGS / LBFGS\n(single-start gradient descent for MLE), Drawer (random prior draws \u2014 debugging only). NSS,\nBlackJAXNUTS and SMC need a JAX-traceable analysis (`use_jax=True`). See\n[`wiki/core/api/searches.md`](../wiki/core/api/searches.md) for the comparison table. For a\n*JAX* gradient optimizer, prefer the multi-start family (`MultiStartProdigy` and friends) in\n\"Branch \u2014 MultiStartProdigy\" above over single-start `BFGS`/`LBFGS`.\n\n## Branch \u2014 Live visual updates\n\nWhen configuring an **interactive production fit** (foreground script or notebook), ask once:\n*watch the fit update live?* The quick-update image (`fit.png`) is **always written to disk**\nevery `iterations_per_quick_update` iterations regardless; `live_visual_update=True` (default\n`False`) additionally pushes it to a live display surface:\n\n- **foreground Python script** \u2014 a matplotlib viewer opens and refreshes with each quick\n update;\n- **Jupyter / Colab** \u2014 the cell that ran `search.fit(...)` refreshes one image in place;\n- **HPC, headless, background, or unattended runs** \u2014 keep it `False` (nothing to attach to;\n HPC mode disables it in config).\n\n```python\nsearch = af.Nautilus(\n ...,\n iterations_per_quick_update=1000, # quick-update (and live refresh) cadence\n live_visual_update=True, # script: matplotlib viewer; notebook: in-place cell\n)\n```\n\nBoth are shared search options (accepted by every search via the common base class), with\nconfig fallbacks in `config/general.yaml` `updates:`. Don't re-ask on later runs \u2014 the\nchoice is recorded in the search configuration.\n\nSource: `PyAutoFit:autofit/non_linear/search/abstract_search.py`.\n\n## Output folder layout\n\nAfter `search.fit(...)` runs, results land at:\n\n```\noutput////\n files/\n tracer.json\n model.json\n samples.csv\n samples_summary.json\n search.json\n image/\n dataset.fits\n fit.fits\n ...\n model.info\n model.results\n```\n\nThe `unique_id` hash is derived from the model + dataset + search settings, so identical\nre-runs land in the same folder (and resume from where they stopped).\n\nThe abbreviated tree above is enough to configure a search; the fuller, always-current\nannotation of every file \u2014 plus the fact that all of it is written **on the fly** while\nthe search runs \u2014 is `__Output Folder Layout__` in\n[`autolens_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling.py).\nPoint a newcomer (or a teacher-mode session) there rather than expanding this block \u2014\n`_style.md` \"Output folder announcement\" has the rule.\n\nSee [`al_load_results`](./al_load_results.md) for the inverse \u2014 loading what\n`search.fit` writes.\n\n## Combine\n\n- [`al_run_search`](./al_run_search.md) \u2014 call `search.fit(model=..., analysis=...)`.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 feed this search's result into a\n follow-up.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) \u2014 when the search runs but the\n result is wrong.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens (optional): Alternative non-linear search\n algorithms](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_searches.ipynb):\n the menu of searches beyond Nautilus (MCMC, optimizers) and how to think about\n tuning them.\n- **General reference** \u2014 [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n tour of advanced capabilities; search configuration interacts directly with most\n of them (especially pixelization, MGE, point-source).\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/modeling/slam_start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/modeling/slam_start_here.py):\n the SLaM pipeline pre-configures sensible searches per stage \u2014 a reference for\n *which* knobs matter at *which* phase.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_optional/tutorial_searches.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_configure_search\n\n---\nname: al_configure_search\ndescription: Pick and tune a non-linear search for a lens-modelling fit. Defaults to Nautilus (nested sampling, the recommended choice); covers Dynesty, Emcee, Zeus, and the JAX multi-start gradient optimizers (MultiStartProdigy recommended when a fast MAP point estimate on a parametric source is wanted — not pixelized). Sets sampler-specific knobs (live points, walkers, tolerance) and the output `path_prefix` / `name` that determine where results land. Pairs with `al_run_search`, which actually calls `search.fit`.\n---\n\n# Configuring a non-linear search\n\nThe non-linear search is *how* PyAutoFit explores the model's parameter space. PyAutoLens\nexposes the same searches PyAutoFit ships, with Nautilus as the default. Picking the\nright one — and tuning its knobs sensibly — is often the difference between a fit that\nconverges in hours and one that doesn't converge at all.\n\nFor the catalogue of available searches and when to use each,\n[`wiki/core/api/searches.md`](../wiki/core/api/searches.md). For the *concept* of a non-linear\nsearch (what nested sampling does, what MCMC does, what gradient descent does),\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md).\n\n## Ask\n\n- *\"How complex is the model?\"* — number of free parameters and whether any are\n expected to be multi-modal. Multi-modality strongly favours nested sampling\n (Nautilus / Dynesty) over MCMC.\n- *\"How fast does the likelihood evaluate?\"* — fast (<1s with JAX) → can afford more\n live points or walkers. Slow → tighten the search.\n- *\"Is this a first exploratory fit, or a final production run?\"* — exploratory fits\n use fewer live points and looser tolerance to fail fast.\n- *\"Where should the output go?\"* — `output//modeling///` is the\n convention; the user chooses `` and ``.\n\n## Branch — Nautilus (recommended default)\n\nFor most lens models — parametric, pixelised, simple, complex — Nautilus is the right\nfirst pick. It handles multi-modal posteriors and is fast enough on modern CPUs.\n\n```python\n# scripts/configure_search.py\nimport autofit as af\n\nsearch = af.Nautilus(\n path_prefix=\"imaging/\",\n name=\"modeling_sie_sersic\",\n unique_tag=\"\",\n n_live=200, # 100 for exploration, 200 for production, 400+ for complex models\n iterations_per_full_update=2500,\n number_of_cores=4, # parallel likelihood evaluations\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/nautilus/`.\n\nKnobs to know:\n- `n_live` — more = more accurate posterior, slower. Start at 200; go to 400+ only if\n the posterior looks multi-modal or thin.\n- `number_of_cores` — parallel likelihood evaluations via Python multiprocessing, **only when\n JAX is off**. JAX disables multiprocessing, so a JAX fit gains nothing from it — leave it\n unset there (it defaults to 1; passing `1` explicitly just implies a parallelism that isn't\n there). Set it to your core count only for non-JAX CPU fits — see\n \"Branch — CPU acceleration\" below, which decides *which* regime a fit belongs to.\n- `iterations_per_full_update` / `iterations_per_quick_update` — how often the search\n writes full output (samples, visualisation) vs quick intermediate updates to disk.\n **Actively choose `iterations_per_quick_update` so the user always has quick access to\n result inspection** — don't just take the default. Judge it against the likelihood cost so\n the first on-the-fly `fit.png` / `samples` lands within a few minutes and refreshes\n regularly, but not so often that per-update visualisation overhead eats into throughput.\n Rules of thumb: ~500–1000 is a good interactive default; **lower it for a slow/expensive\n likelihood** (large MGE, pixelised source, GPU-batched fit, high `n_live`) so an inspection\n point still appears early; only **raise it** (≈2500–5000) when the likelihood is very fast\n and frequent updates would measurably dominate runtime. A common failure is leaving it high\n on a heavy fit, so the run shows *nothing* to inspect for an hour — avoid that. On HPC/batch\n runs the same value governs what a `sync pull` surfaces, so pick it before submitting.\n - **Set it the right way — directly on the search.** Pass `iterations_per_quick_update=…`\n straight to the search constructor, e.g. `af.Nautilus(..., iterations_per_quick_update=…)`\n (the idiom used throughout `autolens_workspace`, e.g. `point_source/modeling.py`,\n `weak/modeling.py`). Do **not** try to set it via `settings_search.search_dict[...] = …`:\n `SettingsSearch.search_dict` is a fixed-key property (`path_prefix`, `unique_tag`,\n `number_of_cores`, `session`, `use_jax_vmap`), so assigning a new key to it is a **silent\n no-op** — the value never reaches the search and the config default (often `1e99`, i.e.\n *never* quick-update) silently wins. To set it globally for a whole pipeline without\n editing every search, write it to the live config once after `conf.instance.push(...)`:\n `conf.instance[\"general\"][\"updates\"][\"iterations_per_quick_update\"] = N`.\n\n## Branch — CPU acceleration (JAX vs sparse operators)\n\nOn CPU the right accelerator depends on the **source model**. This is the single biggest CPU\nruntime lever in lens modelling, and getting it backwards costs days, not minutes — a full SLaM\nrun misconfigured here spends >12 h stuck in its first search.\n\n| Fit type | Accelerator | `use_jax` | `number_of_cores` | Dataset |\n|---|---|---|---|---|\n| **Parametric source** (`source_lp`, most non-pixelised fits) | JAX — vectorises the likelihood, parallelises well **on CPU** | `True` | leave unset (JAX disables multiprocessing) | plain |\n| **Pixelised source** (`source_pix`, `light`, `mass` — any fit with a `Pixelization`) | Sparse operator formalism (numba) | `False` | your core count | `dataset.apply_sparse_operator_cpu()` |\n\nTwo rules that are easy to get wrong:\n\n- **JAX is not GPU-only.** It is the correct accelerator for *parametric* fits on CPU too. Do\n not reach for `use_jax=False` + many cores just because there is no GPU.\n- **The sparse operator does not support JAX.** It is numba-based, so never combine them: a\n pixelised CPU fit is `apply_sparse_operator_cpu()` + `use_jax=False` + `number_of_cores=N`.\n `apply_sparse_operator_cpu()` precomputes operator matrices once (seconds to minutes) and\n every later pixelised fit reuses them, exploiting the sparsity of the pixelisation linear\n algebra for a large CPU speed-up.\n\n```python\n# Parametric source on CPU — JAX, no number_of_cores.\nanalysis = al.AnalysisImaging(dataset=dataset, use_jax=True)\nsettings_search = af.SettingsSearch(path_prefix=..., unique_tag=..., session=None)\n\n# Pixelised source on CPU — sparse operators, JAX off, multiprocessing on.\ndataset_pix = dataset.apply_sparse_operator_cpu()\nanalysis = al.AnalysisImaging(dataset=dataset_pix, use_jax=False)\nsettings_search = af.SettingsSearch(\n path_prefix=..., unique_tag=..., session=None, number_of_cores=8\n)\n```\n\n`number_of_cores` reaches the search through `af.SettingsSearch` (it is one of `search_dict`'s\nfixed keys), so pass it there rather than to the search constructor.\n\n**A SLaM pipeline spans both regimes.** SOURCE LP is parametric (JAX); every stage after it uses\na pixelised source (sparse/CPU). So build **two** `af.SettingsSearch` objects — one without\n`number_of_cores` for SOURCE LP, one with N for the pixelised stages — and hand each stage the\nright dataset (`dataset` vs `dataset_pix`). On **GPU**, JAX is used throughout and the sparse\noperator is not applied at all.\n\nSource / worked example:\n`autolens_workspace:scripts/imaging/features/pixelization/cpu_fast_modeling.py`.\n\n## Branch — MultiStartProdigy (JAX gradient optimizer, parametric sources)\n\nWhen the user explicitly wants a **JAX gradient optimizer** — a fast maximum-a-posteriori (MAP)\n*point* estimate rather than a full posterior — the recommended default is `MultiStartProdigy`.\nReach for it when the goal is speed to a best-fit model on a **parametric source** (MGE, Sersic)\nand errors are not yet needed; otherwise keep Nautilus.\n\n```python\nimport autofit as af\n\nsearch = af.MultiStartProdigy(\n path_prefix=\"imaging/\",\n name=\"modeling_sie_sersic\",\n unique_tag=\"\",\n n_starts=50, # broad starts run in parallel via jax.vmap\n n_steps=500,\n)\n```\n\nRequires a JAX-traceable analysis: `al.AnalysisImaging(dataset=dataset, use_jax=True)` (the\nparametric-source regime of \"Branch — CPU acceleration\" above).\n\nWhy Prodigy, and what the family is:\n\n- The **multi-start** approach — launch many broad starts in parallel and keep the best — was\n introduced for strong-lens modelling by **GIGA-Lens** (Gu, Huang et al. 2022, arXiv:2202.07663;\n GIGA-Lens 2.0, arXiv:2606.30633). It is what makes a gradient optimizer robust on the\n multi-modal lens likelihood, where a single-start optimizer gets stuck.\n- **`MultiStartProdigy`** uses the *learning-rate free* Prodigy rule (Mishchenko & Defazio 2024,\n arXiv:2306.06101): it tunes its own step size, so there is no `learning_rate` to set, and it\n reaches the same maximum as a hand-tuned `MultiStartAdam`. Recommend it as the default.\n- **`MultiStartAdam`** is the GIGA-Lens original (needs a chosen `learning_rate`);\n **`MultiStartADABelief`** is a drop-in Adam-variant alternative. (`MultiStartLion` is a further\n sign-based option that prefers a ~10x smaller `learning_rate`.)\n\n**Parametric sources only, for now.** These optimizers are validated and recommended for\nparametric sources. For a **pixelised source** (any fit with a `Pixelization`) they do **not**\nyet reliably work: the pixelised likelihood has regions where the gradient becomes non-finite,\nso the optimizer stalls short of the best fit, and `Nautilus` is both more reliable and faster\nthere. Making the JAX multi-start optimizers work on pixelised sources is ongoing work — so for\nany pixelised fit recommend Nautilus (with the sparse-operator CPU regime above), not a gradient\noptimizer.\n\nLike every optimizer it returns a single best-fit model, no errors — hand it to Nautilus / MCMC\nafterwards if a posterior is needed.\n\nSource: `PyAutoFit:autofit/non_linear/search/mle/multi_start_gradient/`.\n\n## Branch — Dynesty\n\nUse Dynesty for problems where you specifically want its dynamic sampling features\n(e.g. focusing samples in the posterior tails for precise evidence estimation).\n\n```python\nsearch = af.DynestyStatic(\n path_prefix=\"...\",\n name=\"...\",\n nlive=150,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/dynesty/`.\n\n## Branch — Emcee (MCMC)\n\nUse Emcee for posterior characterisation on a *known unimodal* posterior, when you\nalready have a tight initial guess (e.g. from a chained earlier fit). Don't use for\nexploration of multi-modal spaces.\n\n```python\nsearch = af.Emcee(\n path_prefix=\"...\",\n name=\"...\",\n nwalkers=50,\n nsteps=10000,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/mcmc/emcee/`.\n\n## Branch — Other searches\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\nZeus (ensemble slice MCMC), DynestyDynamic (dynamic nested sampling), NSS (JAX nested slice\nsampling), BlackJAXNUTS and SMC (JAX gradient MCMC; SMC also returns the evidence), BFGS / LBFGS\n(single-start gradient descent for MLE), Drawer (random prior draws — debugging only). NSS,\nBlackJAXNUTS and SMC need a JAX-traceable analysis (`use_jax=True`). See\n[`wiki/core/api/searches.md`](../wiki/core/api/searches.md) for the comparison table. For a\n*JAX* gradient optimizer, prefer the multi-start family (`MultiStartProdigy` and friends) in\n\"Branch — MultiStartProdigy\" above over single-start `BFGS`/`LBFGS`.\n\n## Branch — Live visual updates\n\nWhen configuring an **interactive production fit** (foreground script or notebook), ask once:\n*watch the fit update live?* The quick-update image (`fit.png`) is **always written to disk**\nevery `iterations_per_quick_update` iterations regardless; `live_visual_update=True` (default\n`False`) additionally pushes it to a live display surface:\n\n- **foreground Python script** — a matplotlib viewer opens and refreshes with each quick\n update;\n- **Jupyter / Colab** — the cell that ran `search.fit(...)` refreshes one image in place;\n- **HPC, headless, background, or unattended runs** — keep it `False` (nothing to attach to;\n HPC mode disables it in config).\n\n```python\nsearch = af.Nautilus(\n ...,\n iterations_per_quick_update=1000, # quick-update (and live refresh) cadence\n live_visual_update=True, # script: matplotlib viewer; notebook: in-place cell\n)\n```\n\nBoth are shared search options (accepted by every search via the common base class), with\nconfig fallbacks in `config/general.yaml` `updates:`. Don't re-ask on later runs — the\nchoice is recorded in the search configuration.\n\nSource: `PyAutoFit:autofit/non_linear/search/abstract_search.py`.\n\n## Output folder layout\n\nAfter `search.fit(...)` runs, results land at:\n\n```\noutput////\n files/\n tracer.json\n model.json\n samples.csv\n samples_summary.json\n search.json\n image/\n dataset.fits\n fit.fits\n ...\n model.info\n model.results\n```\n\nThe `unique_id` hash is derived from the model + dataset + search settings, so identical\nre-runs land in the same folder (and resume from where they stopped).\n\nThe abbreviated tree above is enough to configure a search; the fuller, always-current\nannotation of every file — plus the fact that all of it is written **on the fly** while\nthe search runs — is `__Output Folder Layout__` in\n[`autolens_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling.py).\nPoint a newcomer (or a teacher-mode session) there rather than expanding this block —\n`_style.md` \"Output folder announcement\" has the rule.\n\nSee [`al_load_results`](./al_load_results.md) for the inverse — loading what\n`search.fit` writes.\n\n## Combine\n\n- [`al_run_search`](./al_run_search.md) — call `search.fit(model=..., analysis=...)`.\n- [`al_chain_searches`](./al_chain_searches.md) — feed this search's result into a\n follow-up.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) — when the search runs but the\n result is wrong.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens (optional): Alternative non-linear search\n algorithms](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_searches.ipynb):\n the menu of searches beyond Nautilus (MCMC, optimizers) and how to think about\n tuning them.\n- **General reference** — [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n tour of advanced capabilities; search configuration interacts directly with most\n of them (especially pixelization, MGE, point-source).\n- **Experienced PyAutoLens user** — [workspace/lens: guides/modeling/slam_start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/modeling/slam_start_here.py):\n the SLaM pipeline pre-configures sensible searches per stage — a reference for\n *which* knobs matter at *which* phase.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/simulator/cluster.ipynb b/notebooks/simulator/cluster.ipynb index 4df1f33..6aad5d7 100644 --- a/notebooks/simulator/cluster.ipynb +++ b/notebooks/simulator/cluster.ipynb @@ -59,21 +59,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/HowToLens/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/simulator/group.ipynb b/notebooks/simulator/group.ipynb index e07e6e6..04fe59b 100644 --- a/notebooks/simulator/group.ipynb +++ b/notebooks/simulator/group.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/HowToLens/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", @@ -575,7 +575,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/simulator/group.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth \u2014 or build a\ntraining set for neural-network classifiers \u2014 you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating \u2014 single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* \u2014 chooses the branch.\n- *\"What's the ground truth?\"* \u2014 lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* \u2014 pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch \u2014 galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid \u2014 defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer \u2014 lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_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 overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot \u2014 saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` \u2014 `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch \u2014 many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch \u2014 interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n \u2192 [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour \u2014 see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates \u2014 the forward physics\n the simulator runs.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice \u2014 grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` \u2014 image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* \u2014 pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* \u2014 if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual \u2014 what convergence is, why caustics matter, what\na critical curve traces \u2014 see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions \u2014\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch \u2014 quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch \u2014 single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly \u2014 build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch \u2014 multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI \u2014 extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) \u2014 multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) \u2014 for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot \u2014 how light deflects, how critical curves and\n caustics arise.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action \u2014 building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` \u2014 ray tracing, profiles, numpy\n arrays, visualization.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/simulator/group.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth — or build a\ntraining set for neural-network classifiers — you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating — single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* — chooses the branch.\n- *\"What's the ground truth?\"* — lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* — pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch — galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid — defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer — lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_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 overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot — saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` — `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch — many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch — interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n → [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour — see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates — the forward physics\n the simulator runs.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice — grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` — image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* — pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* — if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual — what convergence is, why caustics matter, what\na critical curve traces — see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions —\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch — quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch — single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly — build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch — multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI — extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) — multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) — for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot — how light deflects, how critical curves and\n caustics arise.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action — building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** — [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` — ray tracing, profiles, numpy\n arrays, visualization.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/simulator/interferometer.ipynb b/notebooks/simulator/interferometer.ipynb index 8bb9726..d5ba71b 100644 --- a/notebooks/simulator/interferometer.ipynb +++ b/notebooks/simulator/interferometer.ipynb @@ -45,21 +45,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/HowToLens/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", @@ -405,7 +405,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/simulator/interferometer.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth \u2014 or build a\ntraining set for neural-network classifiers \u2014 you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating \u2014 single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* \u2014 chooses the branch.\n- *\"What's the ground truth?\"* \u2014 lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* \u2014 pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch \u2014 galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid \u2014 defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer \u2014 lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_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 overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot \u2014 saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` \u2014 `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch \u2014 many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch \u2014 interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n \u2192 [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour \u2014 see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates \u2014 the forward physics\n the simulator runs.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice \u2014 grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` \u2014 image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* \u2014 pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* \u2014 if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual \u2014 what convergence is, why caustics matter, what\na critical curve traces \u2014 see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions \u2014\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch \u2014 quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch \u2014 single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly \u2014 build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch \u2014 multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI \u2014 extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) \u2014 multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) \u2014 for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot \u2014 how light deflects, how critical curves and\n caustics arise.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action \u2014 building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` \u2014 ray tracing, profiles, numpy\n arrays, visualization.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/simulator/interferometer.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth — or build a\ntraining set for neural-network classifiers — you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating — single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* — chooses the branch.\n- *\"What's the ground truth?\"* — lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* — pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch — galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid — defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer — lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_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 overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot — saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` — `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch — many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch — interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n → [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour — see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates — the forward physics\n the simulator runs.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice — grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` — image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* — pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* — if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual — what convergence is, why caustics matter, what\na critical curve traces — see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions —\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch — quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch — single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly — build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch — multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI — extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) — multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) — for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot — how light deflects, how critical curves and\n caustics arise.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action — building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** — [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` — ray tracing, profiles, numpy\n arrays, visualization.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/simulator/lens_extra_galaxy.ipynb b/notebooks/simulator/lens_extra_galaxy.ipynb index d298fe8..83c783a 100644 --- a/notebooks/simulator/lens_extra_galaxy.ipynb +++ b/notebooks/simulator/lens_extra_galaxy.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/HowToLens/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", @@ -515,7 +515,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/simulator/lens_extra_galaxy.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth \u2014 or build a\ntraining set for neural-network classifiers \u2014 you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating \u2014 single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* \u2014 chooses the branch.\n- *\"What's the ground truth?\"* \u2014 lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* \u2014 pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch \u2014 galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid \u2014 defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer \u2014 lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_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 overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot \u2014 saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` \u2014 `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch \u2014 many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch \u2014 interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n \u2192 [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour \u2014 see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates \u2014 the forward physics\n the simulator runs.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice \u2014 grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` \u2014 image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* \u2014 pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* \u2014 if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual \u2014 what convergence is, why caustics matter, what\na critical curve traces \u2014 see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions \u2014\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch \u2014 quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch \u2014 single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly \u2014 build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch \u2014 multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI \u2014 extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) \u2014 multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) \u2014 for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot \u2014 how light deflects, how critical curves and\n caustics arise.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action \u2014 building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` \u2014 ray tracing, profiles, numpy\n arrays, visualization.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/simulator/lens_extra_galaxy.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth — or build a\ntraining set for neural-network classifiers — you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating — single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* — chooses the branch.\n- *\"What's the ground truth?\"* — lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* — pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch — galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid — defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer — lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_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 overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot — saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` — `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch — many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch — interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n → [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour — see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates — the forward physics\n the simulator runs.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice — grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` — image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* — pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* — if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual — what convergence is, why caustics matter, what\na critical curve traces — see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions —\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch — quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch — single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly — build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch — multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI — extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) — multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) — for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot — how light deflects, how critical curves and\n caustics arise.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action — building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** — [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` — ray tracing, profiles, numpy\n arrays, visualization.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/simulator/lens_sersic.ipynb b/notebooks/simulator/lens_sersic.ipynb index 0fe574e..8929f0d 100644 --- a/notebooks/simulator/lens_sersic.ipynb +++ b/notebooks/simulator/lens_sersic.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/HowToLens/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", @@ -397,7 +397,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/simulator/lens_sersic.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth \u2014 or build a\ntraining set for neural-network classifiers \u2014 you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating \u2014 single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* \u2014 chooses the branch.\n- *\"What's the ground truth?\"* \u2014 lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* \u2014 pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch \u2014 galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid \u2014 defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer \u2014 lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_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 overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot \u2014 saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` \u2014 `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch \u2014 many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch \u2014 interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n \u2192 [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour \u2014 see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates \u2014 the forward physics\n the simulator runs.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice \u2014 grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` \u2014 image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* \u2014 pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* \u2014 if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual \u2014 what convergence is, why caustics matter, what\na critical curve traces \u2014 see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions \u2014\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch \u2014 quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch \u2014 single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly \u2014 build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch \u2014 multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI \u2014 extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) \u2014 multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) \u2014 for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot \u2014 how light deflects, how critical curves and\n caustics arise.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action \u2014 building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` \u2014 ray tracing, profiles, numpy\n arrays, visualization.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/simulator/lens_sersic.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth — or build a\ntraining set for neural-network classifiers — you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating — single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* — chooses the branch.\n- *\"What's the ground truth?\"* — lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* — pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch — galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid — defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer — lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_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 overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot — saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` — `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch — many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch — interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n → [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour — see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates — the forward physics\n the simulator runs.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice — grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` — image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* — pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* — if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual — what convergence is, why caustics matter, what\na critical curve traces — see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions —\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch — quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch — single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly — build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch — multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI — extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) — multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) — for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot — how light deflects, how critical curves and\n caustics arise.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action — building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** — [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` — ray tracing, profiles, numpy\n arrays, visualization.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/simulator/lens_x2.ipynb b/notebooks/simulator/lens_x2.ipynb index d7d675a..b99dd8f 100644 --- a/notebooks/simulator/lens_x2.ipynb +++ b/notebooks/simulator/lens_x2.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/HowToLens/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/simulator/lens_x3.ipynb b/notebooks/simulator/lens_x3.ipynb index 02b2a08..15a9bdb 100644 --- a/notebooks/simulator/lens_x3.ipynb +++ b/notebooks/simulator/lens_x3.ipynb @@ -52,21 +52,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/HowToLens/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/simulator/no_lens_light.ipynb b/notebooks/simulator/no_lens_light.ipynb index 5f47b63..fa4ecfa 100644 --- a/notebooks/simulator/no_lens_light.ipynb +++ b/notebooks/simulator/no_lens_light.ipynb @@ -42,21 +42,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/HowToLens/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", @@ -466,7 +466,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/simulator/no_lens_light.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth \u2014 or build a\ntraining set for neural-network classifiers \u2014 you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating \u2014 single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* \u2014 chooses the branch.\n- *\"What's the ground truth?\"* \u2014 lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* \u2014 pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch \u2014 galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid \u2014 defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer \u2014 lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_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 overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot \u2014 saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` \u2014 `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch \u2014 many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch \u2014 interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n \u2192 [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour \u2014 see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates \u2014 the forward physics\n the simulator runs.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice \u2014 grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` \u2014 image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* \u2014 pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* \u2014 if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual \u2014 what convergence is, why caustics matter, what\na critical curve traces \u2014 see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions \u2014\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch \u2014 quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch \u2014 single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly \u2014 build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch \u2014 multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI \u2014 extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) \u2014 multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) \u2014 for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot \u2014 how light deflects, how critical curves and\n caustics arise.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action \u2014 building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` \u2014 ray tracing, profiles, numpy\n arrays, visualization.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/simulator/no_lens_light.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth — or build a\ntraining set for neural-network classifiers — you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating — single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* — chooses the branch.\n- *\"What's the ground truth?\"* — lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* — pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch — galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid — defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer — lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_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 overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot — saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` — `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch — many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch — interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n → [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour — see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates — the forward physics\n the simulator runs.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice — grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` — image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* — pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* — if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual — what convergence is, why caustics matter, what\na critical curve traces — see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions —\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch — quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch — single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly — build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch — multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI — extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) — multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) — for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot — how light deflects, how critical curves and\n caustics arise.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action — building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** — [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` — ray tracing, profiles, numpy\n arrays, visualization.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/simulator/no_lens_light__mass_sis.ipynb b/notebooks/simulator/no_lens_light__mass_sis.ipynb index bf9e5ad..2b93470 100644 --- a/notebooks/simulator/no_lens_light__mass_sis.ipynb +++ b/notebooks/simulator/no_lens_light__mass_sis.ipynb @@ -40,21 +40,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/HowToLens/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", @@ -378,7 +378,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/simulator/no_lens_light__mass_sis.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth \u2014 or build a\ntraining set for neural-network classifiers \u2014 you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating \u2014 single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* \u2014 chooses the branch.\n- *\"What's the ground truth?\"* \u2014 lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* \u2014 pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch \u2014 galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid \u2014 defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer \u2014 lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_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 overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot \u2014 saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` \u2014 `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch \u2014 many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch \u2014 interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n \u2192 [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour \u2014 see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates \u2014 the forward physics\n the simulator runs.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice \u2014 grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` \u2014 image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* \u2014 pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* \u2014 if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual \u2014 what convergence is, why caustics matter, what\na critical curve traces \u2014 see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions \u2014\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch \u2014 quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch \u2014 single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly \u2014 build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch \u2014 multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI \u2014 extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) \u2014 multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) \u2014 for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot \u2014 how light deflects, how critical curves and\n caustics arise.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action \u2014 building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` \u2014 ray tracing, profiles, numpy\n arrays, visualization.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/simulator/no_lens_light__mass_sis.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth — or build a\ntraining set for neural-network classifiers — you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating — single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* — chooses the branch.\n- *\"What's the ground truth?\"* — lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* — pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch — galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid — defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer — lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_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 overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot — saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` — `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch — many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch — interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n → [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour — see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates — the forward physics\n the simulator runs.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice — grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` — image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* — pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* — if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual — what convergence is, why caustics matter, what\na critical curve traces — see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions —\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch — quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch — single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly — build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch — multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI — extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) — multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) — for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot — how light deflects, how critical curves and\n caustics arise.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action — building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** — [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` — ray tracing, profiles, numpy\n arrays, visualization.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/simulator/source_complex.ipynb b/notebooks/simulator/source_complex.ipynb index 6037f1c..13251c5 100644 --- a/notebooks/simulator/source_complex.ipynb +++ b/notebooks/simulator/source_complex.ipynb @@ -44,21 +44,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/HowToLens/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", @@ -409,7 +409,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/simulator/source_complex.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth \u2014 or build a\ntraining set for neural-network classifiers \u2014 you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating \u2014 single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* \u2014 chooses the branch.\n- *\"What's the ground truth?\"* \u2014 lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* \u2014 pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch \u2014 galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid \u2014 defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer \u2014 lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_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 overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot \u2014 saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` \u2014 `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch \u2014 many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch \u2014 interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n \u2192 [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour \u2014 see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates \u2014 the forward physics\n the simulator runs.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice \u2014 grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` \u2014 image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* \u2014 pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* \u2014 if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual \u2014 what convergence is, why caustics matter, what\na critical curve traces \u2014 see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions \u2014\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch \u2014 quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch \u2014 single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly \u2014 build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch \u2014 multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI \u2014 extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) \u2014 multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) \u2014 for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot \u2014 how light deflects, how critical curves and\n caustics arise.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action \u2014 building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` \u2014 ray tracing, profiles, numpy\n arrays, visualization.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_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\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/simulator/source_complex.ipynb in HowToLens).\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 PyAutoLens 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 PyAutoLens docs (https://pyautolens.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) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n 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 lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth — or build a\ntraining set for neural-network classifiers — you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating — single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* — chooses the branch.\n- *\"What's the ground truth?\"* — lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* — pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch — galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid — defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer — lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_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 overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot — saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` — `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch — many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch — interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n → [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour — see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates — the forward physics\n the simulator runs.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice — grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` — image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* — pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* — if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual — what convergence is, why caustics matter, what\na critical curve traces — see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions —\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch — quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch — single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly — build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch — multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI — extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) — multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) — for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot — how light deflects, how critical curves and\n caustics arise.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action — building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** — [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` — ray tracing, profiles, numpy\n arrays, visualization.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/simulator/weak_lensing.ipynb b/notebooks/simulator/weak_lensing.ipynb index 22cab93..097c6d8 100644 --- a/notebooks/simulator/weak_lensing.ipynb +++ b/notebooks/simulator/weak_lensing.ipynb @@ -42,21 +42,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/HowToLens/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/start_here.ipynb b/start_here.ipynb index 19b8b3f..c34a4d6 100644 --- a/start_here.ipynb +++ b/start_here.ipynb @@ -60,21 +60,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 PyAutoLens 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",