diff --git a/README.md b/README.md index 27fb6b3..97ade1d 100644 --- a/README.md +++ b/README.md @@ -90,17 +90,14 @@ for the chapter 1 tutorials listed with a `markdown` link below; every other tut - Tutorial 5: Data — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_5_data.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_5_data.md)) - Tutorial 6: Fitting — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_6_fitting.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_6_fitting.md)) - Tutorial 7: Summary — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_7_summary.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_7_summary.md)) -- **[Chapter 2: Lens Modeling](scripts/chapter_2_lens_modeling/README.md)** — Bayesian inference, non-linear searches, lens modeling, search chaining, prior passing, and SLaM pipelines. - - Tutorial 1: Non-linear Search — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb)) - - Tutorial 2: Practicalities — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb)) - - Tutorial 3: Why Modeling Is Hard — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.ipynb)) - - Tutorial 4: Linear Profiles — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_4_linear_profiles.ipynb)) - - Tutorial 6: Masking and Positions — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_2_lens_modeling/tutorial_6_masking_and_positions.ipynb)) - - Tutorial 7: Results — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_2_lens_modeling/tutorial_7_results.ipynb)) - - Tutorial 8: Need for Speed — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_2_lens_modeling/tutorial_8_need_for_speed.ipynb)) - - Tutorial 9: Search Chaining — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_2_lens_modeling/tutorial_9_search_chaining.ipynb)) - - Tutorial 10: Prior Passing — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_2_lens_modeling/tutorial_10_prior_passing.ipynb)) - - Tutorial 11: SLaM — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_2_lens_modeling/tutorial_11_slam.ipynb)) +- **[Chapter 2: Lens Modeling](scripts/chapter_2_lens_modeling/README.md)** — Non-linear searches, linear profiles, datasets and likelihoods, and search chaining. + - [Tutorial 1: Non-linear Search](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb) — Parameter space, priors and fitting a lens model. + - [Tutorial 2: Practicalities](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb) — Running fits and inspecting their results. + - [Tutorial 3: Why Modeling Is Hard](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.ipynb) — Local maxima, degeneracies and investigating difficult fits. + - [Tutorial 4: Linear Profiles](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_4_linear_profiles.ipynb) — Solving light-profile intensities and using multi-Gaussian expansions. + - [Tutorial 5: Data and Likelihoods](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_5_data_and_likelihoods.ipynb) — Separating datasets, models and likelihoods, including positions penalties. + - [Tutorial 6: Search Chaining](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_6_search_chaining.ipynb) — Combining searches and introducing the SLaM pipelines. + - [Tutorial 7: Summary](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_7_summary.ipynb) — Bringing the chapter together and continuing to pixelized sources. - **[Chapter 3: Pixelizations](scripts/chapter_3_pixelizations/README.md)** — From MGE to pixelized sources: mappings, inversions, Bayesian regularization, borders and chained lens fits. - Tutorial 1 Pixelizations — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb)) - Tutorial 2 Bayesian Regularization — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_3_pixelizations/tutorial_2_bayesian_regularization.ipynb)) @@ -116,8 +113,10 @@ for the chapter 1 tutorials listed with a `markdown` link below; every other tut - Tutorial 4: Group Scale — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_4_scaling_up_lensing/tutorial_4_group_scale.ipynb)) - Tutorial 5: Cluster Scale — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.ipynb)) - Tutorial 6: Weak Lensing — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_4_scaling_up_lensing/tutorial_6_weak_lensing.ipynb)) -- **[Optional Tutorials](scripts/chapter_optional/)** — Alternative non-linear searches and advanced topics. - - Tutorial Optional: Searches — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_optional/tutorial_searches.ipynb)) +- **[Optional Tutorials](scripts/chapter_optional/README.md)** — Search methods, runtime and historical workflows. + - [Need for Speed](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_need_for_speed.ipynb) — Computation, batching and estimating runtime. + - [Historical Prior Passing](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_prior_passing.ipynb) — An optional runnable example of prior passing using model_centred, a technique central to older workflows. + - [Searches](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_searches.ipynb) — Alternative non-linear search methods. Model-fits can run faster on a GPU. In Colab, enable one via *Runtime* → *Change runtime type* → *Hardware accelerator* before running a notebook. diff --git a/images/chapter_2/circular_vs_annular.png b/images/chapter_2/circular_vs_annular.png new file mode 100755 index 0000000..a8e18af Binary files /dev/null and b/images/chapter_2/circular_vs_annular.png differ diff --git a/llms-full.txt b/llms-full.txt index c76d28a..d0234f3 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -28,26 +28,19 @@ AUTO-GENERATED by PyAutoHands — do not edit by hand; regenerate with generate. ## chapter_2_lens_modeling -- [Tutorial 10: Prior Passing](scripts/chapter_2_lens_modeling/tutorial_10_prior_passing.py): In the previous tutorial, we used non-linear search chaining to break the model-fitting procedure down into two non-linear searches. This used an initial search to fit a simple lens model, whose results were used to tune and initialize the priors of a more complex lens model that was fitted by the second search. - - Contents: Initial Setup, Dataset Auto-Simulation, Model, Search, Result (Search 1), Prior Passing, Result, Wrap Up, Detailed Explanation Of Prior Passing, EXAMPLE -- [Tutorial 11: SLaM](scripts/chapter_2_lens_modeling/tutorial_11_slam.py): In the previous two tutorials, we learnt how search chaining breaks a lens model-fit into a sequence of simpler non-linear searches, and how prior passing carries the results of each search into the next. Together, they give us the flexibility to juggle the dimensionality, priors and settings of each search — the three drivers of run-time we met in tutorial 8 — whilst still fitting a complex and realistic lens model at the end. - - Contents: Search Chaining In The Workspace, SLaM (Source, Light and Mass), Wrap Up - [Tutorial 1: Non-linear Search](scripts/chapter_2_lens_modeling/tutorial_1_non_linear_search.py): In Chapter 1, we predicted what a strong lens would look like for a given set of model parameters and compared that prediction with an observed image. - - Contents: Overview, Parameter Space, Automated Exploration, Deeper Background, PyAutoFit, Initial Setup, Dataset Auto-Simulation, Mask, Model, Priors, Analysis, Non-linear Search, Search Settings, Model Fit, Result, Inspecting the Fit, Other Searches, Wrap Up + - Contents: Overview, Parameter Space, More Dimensions, Automated Exploration, Deeper Background, PyAutoFit, Initial Setup, Dataset Auto-Simulation, Mask, Model, Priors, Analysis, Non-linear Search, Search Settings, Model Fit, Result, Inspecting the Fit, Other Searches, Wrap Up - [Tutorial 2: Practicalities](scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py): In the previous tutorial, we fitted a simple lens model using Nautilus. We now move to a more realistic image, containing both the foreground lens galaxy’s light and the lensed source. - Contents: Dataset, Mask, Model, Analysis, Search, Search Settings, Output Updates, VRAM Use, Run Times, Notebooks and Scripts, Model Fit, Result Info, Output Folder, Unique Identifier, Resuming and Loading, Output Folder Contents, Parameter Uncertainties, Plot Labels, Configuration, Further Results, Wrap Up - [Tutorial 3: Why Modeling Is Hard](scripts/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.py): We now have the tools to build a lens model, run a search and inspect its results. However, a search finishing does not necessarily mean that it has found a satisfactory fit. - Contents: Overview, Dataset and Mask, Model and Analysis, A Less Thorough Search, Inspecting the Result, Comparing Searches, Why Modeling Is Hard, Three Ways Forward, Prior Tuning, Profile Centres, Lens-Light Shape, Mass Shape, Lens-Light Size, Light Concentration, Einstein Radius, Source and Shear Priors, Inspecting the Tuned Model, Prior-Tuned Fit, Assessing the Improvement, Prior Tuning: Benefits and Limitations, Reducing Complexity, Linking Parameters, Inspecting the Simpler Model, Fitting the Simpler Model, Reducing Complexity: Benefits and Limitations, Search More Thoroughly, Original Model, More Thorough Search, Comparing the Approaches, Benefits and Weaknesses, Run Times, Model Mismatch, Wrap Up - [Tutorial 4: Linear Profiles](scripts/chapter_2_lens_modeling/tutorial_4_linear_profiles.py): In the previous tutorial, we made a lens model easier to fit by tuning priors, linking parameters or searching more thoroughly. Each approach involved a trade-off between flexibility, assumptions and computation. - Contents: Overview, Dataset and Mask, Linear Light Profiles, Why This Helps, Model, Search and Run Time, Result, Intensities, Visualisation, Basis, A First Gaussian Basis, Evaluating the Basis, Inspecting the Basis Fit, Lens MGE, Source MGE, Combined Model, Inspecting the Model, Model Fit, Result, Multi-Gaussian Expansion Benefits, Benefits Have Costs, Positive Intensities, Other Basis Functions, Wrap Up -- [Tutorial 6: Masking and Positions](scripts/chapter_2_lens_modeling/tutorial_6_masking_and_positions.py): We have learnt everything we need to know about non-linear searches to model a strong lens and infer a good lens model solution. Now, lets consider masking in more detail, something we have not given much consideration previously. We'll also learn a neat trick to improve the speed and accuracy of a non-linear search. - - Contents: Initial Setup, Dataset Auto-Simulation, Mask, Model + Analysis, Run Time, Search, Discussion, Positions Thresholding, Wrap Up -- [Tutorial 7: Results](scripts/chapter_2_lens_modeling/tutorial_7_results.py): In the previous tutorials, each search returned a `Result` object, which we used to plot the maximum log likelihood fit each model-fit. In this tutorial, we'll take a look at the result object in a little more detail. - - Contents: Initial Setup, Dataset Auto-Simulation, Tracer & Fit, Samples, Workspace, Database, Wrap Up -- [Tutorial 8: Need For Speed](scripts/chapter_2_lens_modeling/tutorial_8_need_for_speed.py): In this chapter, we have learnt how to model strong lenses and how to balance complexity and realism to ensure that we infer a good lens model. - - Contents: Searching Non-linear Parameter Space, Cost Per Evaluation, JAX, Run Time Estimation, Data Quantity, Wrap Up -- [Tutorial 9: Search Chaining](scripts/chapter_2_lens_modeling/tutorial_9_search_chaining.py): Throughout this chapter, we have fitted the data using just one non-linear search. The previous tutorial discussed the run-time cost of doing this: with a single search, the dimensionality of the model, the priors on its parameters and the search settings must all be juggled at once, leaving us little flexibility to trade them off against one another. - - Contents: Initial Setup, Dataset Auto-Simulation, Model, Search + Analysis, Result, Prior Passing, Run Time, Model Fit, Wrap Up +- [Tutorial 5: Data and Likelihoods](scripts/chapter_2_lens_modeling/tutorial_5_data_and_likelihoods.py): Throughout this chapter, we have fitted imaging data using light and mass profiles. However, the modeling tools we have learnt are not tied to this particular type of observation. We can use the same approach to fit interferometer measurements, the positions of multiply imaged point sources, or the shapes of weakly lensed galaxies. + - Contents: Dataset, Circular Masks, Beyond the Bright Arcs, Mask, Positions Constraints, Choosing Positions, The Positions Penalty, Model and Analysis, Search and Result, Contaminating Light, Extra Galaxy Dataset, Extra Galaxy Region, Noise Scaling, Interpreting the Scaled Dataset, Interferometer Data, Point-Source Data, Weak-Lensing Data, Multiple Datasets, Wrap Up +- [Tutorial 6: Search Chaining](scripts/chapter_2_lens_modeling/tutorial_6_search_chaining.py): Look again at our lens image. The foreground galaxy's light, its gravitational deflection and the background source all contribute to what we observe. Fitting them together requires the search to explore several connected parts of the model. + - Contents: The Search Chain, Dataset and Mask, Multi-Gaussian Expansions, Model 1, Search 1, Inspecting Search 1, Fixing the Lens-Light Geometry, The Power-Law Mass Model, Model 2, Automatically Estimated Positions, Search 2, Result 2, Conditional Uncertainties, Search Chaining and SLaM, Wrap Up +- [Tutorial 7: Summary](scripts/chapter_2_lens_modeling/tutorial_7_summary.py): (no summary in script docstring) ## chapter_3_pixelizations @@ -83,6 +76,10 @@ AUTO-GENERATED by PyAutoHands — do not edit by hand; regenerate with generate. ## chapter_optional +- [Optional Tutorial: Need for Speed](scripts/chapter_optional/tutorial_need_for_speed.py): Two fits to the same image can take very different amounts of time. Finding a good fit with a simple model may be quick, whereas exploring the uncertainties of a more flexible model can take much longer. Both the calculation performed for each model and the search through parameter space contribute to this difference. + - Contents: Searching Parameter Space, Cost Per Evaluation, JAX, Batches and GPU Memory, Run Time Estimation, Data Quantity, Wrap Up +- [Optional Tutorial: Historical Prior Passing](scripts/chapter_optional/tutorial_prior_passing.py): This optional tutorial preserves a technique used in earlier **PyAutoLens** modelling workflows, up to around 2025: passing parameter constraints from one search into the priors of a later search. + - Contents: Initial Setup, Dataset Auto-Simulation, Model, Search, Result (Search 1), Prior Passing, Result, Wrap Up, Detailed Explanation Of Prior Passing, EXAMPLE - [Tutorial: Alternative Searches](scripts/chapter_optional/tutorial_searches.py): Chapter 2 introduces lens modeling using Nautilus. This optional tutorial explores alternative search settings, optimisation and Markov chain Monte Carlo (MCMC) after you have completed HowToLens. - Contents: Nested Sampling, Optimisation, MCMC diff --git a/llms.txt b/llms.txt index 306e34d..f6970d4 100644 --- a/llms.txt +++ b/llms.txt @@ -37,7 +37,7 @@ analysis?" below). - **How does a non-linear search find a model?** → [scripts/chapter_2_lens_modeling/tutorial_1_non_linear_search.py](scripts/chapter_2_lens_modeling/tutorial_1_non_linear_search.py): Parameter space, priors, nested sampling with Nautilus. - **My fit found a wrong (local-maxima) solution — what do I do?** → [scripts/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.py](scripts/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.py): Prior tuning, simplifying the model, and other escapes from local maxima. - **What are linear light profiles / MGE?** → [scripts/chapter_2_lens_modeling/tutorial_4_linear_profiles.py](scripts/chapter_2_lens_modeling/tutorial_4_linear_profiles.py): Solving intensities linearly; the Multi-Gaussian Expansion basis. -- **How do I chain searches / what is SLaM?** → [scripts/chapter_2_lens_modeling/tutorial_9_search_chaining.py](scripts/chapter_2_lens_modeling/tutorial_9_search_chaining.py) then [scripts/chapter_2_lens_modeling/tutorial_11_slam.py](scripts/chapter_2_lens_modeling/tutorial_11_slam.py). +- **How do I chain searches / what is SLaM?** → [scripts/chapter_2_lens_modeling/tutorial_6_search_chaining.py](scripts/chapter_2_lens_modeling/tutorial_6_search_chaining.py), including its SLaM introduction. - **How do I reconstruct a complex source on a pixel grid?** → [scripts/chapter_3_pixelizations/tutorial_1_pixelizations.py](scripts/chapter_3_pixelizations/tutorial_1_pixelizations.py) through [tutorial_2_bayesian_regularization.py](scripts/chapter_3_pixelizations/tutorial_2_bayesian_regularization.py). - **How do I model lenses with many galaxies, groups, clusters or weak lensing?** → [scripts/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.py](scripts/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.py) through [tutorial_6_weak_lensing.py](scripts/chapter_4_scaling_up_lensing/tutorial_6_weak_lensing.py). diff --git a/notebooks/chapter_2_lens_modeling/README.md b/notebooks/chapter_2_lens_modeling/README.md index f2d037b..419ff49 100644 --- a/notebooks/chapter_2_lens_modeling/README.md +++ b/notebooks/chapter_2_lens_modeling/README.md @@ -1,27 +1,26 @@ -In chapter 2, we'll take you through how to model strong lenses using a non-linear search, ending with how -searches are chained together into automated lens modeling pipelines. +In chapter 2, we fit strong lenses with non-linear searches, investigate difficult solutions and build a search chain. +The six main lessons are followed by a summary. Results are covered in Tutorial 2 and SLaM in Tutorial 6. -**Colab** links to every tutorial are included. +## Tutorials -# Files +- [Tutorial 1: Non-linear Search](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb) — Parameter space, priors and fitting a lens model. -- [Tutorial 1: Non-linear Search](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb) — How a non-linear search is used to fit a lens model and the concepts of a parameter space and priors. +- [Tutorial 2: Practicalities](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb) — Running fits and inspecting their results. -- [Tutorial 2: Practicalities](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb) — Practicalities of performing model-fitting, like how to inspect the results on your hard-disk. +- [Tutorial 3: Why Modeling Is Hard](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.ipynb) — Local maxima, degeneracies and investigating difficult fits. +- [Tutorial 4: Linear Profiles](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_4_linear_profiles.ipynb) — Solving light-profile intensities and using multi-Gaussian expansions. -- [Tutorial 3: Why Modeling Is Hard](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.ipynb) — What to do when PyAutoLens finds an inaccurate lens model. +- [Tutorial 5: Data and Likelihoods](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_5_data_and_likelihoods.ipynb) — Separating datasets, models and likelihoods, including positions penalties. -- [Tutorial 4: Linear Profiles](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_4_linear_profiles.ipynb) — Light profiles which capture complex morphologies in a reduced number of non-linear parameters. +- [Tutorial 6: Search Chaining](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_6_search_chaining.ipynb) — Combining searches and introducing the SLaM pipelines. -- [Tutorial 6: Masking and Positions](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_2_lens_modeling/tutorial_6_masking_and_positions.ipynb) — How to mask and mark positions on your data to improve the lens model. +- [Tutorial 7: Summary](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_7_summary.ipynb) — Bringing the chapter together and continuing to pixelized sources. -- [Tutorial 7: Results](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_2_lens_modeling/tutorial_7_results.ipynb) — Overview of the results available after successfully fitting a lens model. +## Optional reading -- [Tutorial 8: Need for Speed](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_2_lens_modeling/tutorial_8_need_for_speed.ipynb) — How to fit complex models whilst balancing efficiency and run-time. +- [Need for Speed](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_need_for_speed.ipynb) — Computation, batching and estimating runtime. -- [Tutorial 9: Search Chaining](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_2_lens_modeling/tutorial_9_search_chaining.ipynb) — Breaking the lens modeling procedure into a chained sequence of model-fits. +- [Historical Prior Passing](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_prior_passing.ipynb) — An optional runnable example of prior passing using model_centred, a technique central to older workflows. -- [Tutorial 10: Prior Passing](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_2_lens_modeling/tutorial_10_prior_passing.ipynb) — How the results of earlier searches are passed to later searches. - -- [Tutorial 11: SLaM](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_2_lens_modeling/tutorial_11_slam.ipynb) — Template pipelines for fitting lens models in standardized ways. +- [Searches](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_searches.ipynb) — Alternative non-linear search methods. diff --git a/notebooks/chapter_2_lens_modeling/tutorial_10_prior_passing.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_10_prior_passing.ipynb deleted file mode 100644 index 3d5dc13..0000000 --- a/notebooks/chapter_2_lens_modeling/tutorial_10_prior_passing.ipynb +++ /dev/null @@ -1,633 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 10: Prior Passing\n", - "==========================\n", - "\n", - "In the previous tutorial, we used non-linear search chaining to break the model-fitting procedure down into two\n", - "non-linear searches. This used an initial search to fit a simple lens model, whose results were used to tune and\n", - "initialize the priors of a more complex lens model that was fitted by the second search.\n", - "\n", - "However, the results were passed between searches were passed manually. I explicitly wrote out every result as a prior\n", - "containing the values inferred in the first search. **PyAutoLens** has an API for passing priors in a more generalized\n", - "way, which is the topic of this tutorial.\n", - "\n", - "__Contents__\n", - "\n", - "- **Initial Setup:** Load the same strong lensing data as the previous tutorial.\n", - "- **Dataset Auto-Simulation:** Simulate the dataset via its simulator script if it is not on your hard-disk.\n", - "- **Model:** Compose the lens model fitted to the data.\n", - "- **Search:** Configure the non-linear search used to fit the model.\n", - "- **Result (Search 1):** The results of search 1, which are used for prior passing.\n", - "- **Prior Passing:** Use the prior passing API to pass the results of search 1 without writing out values manually.\n", - "- **Result:** Overview of the results of the model-fit.\n", - "- **Wrap Up:** Summary of the script and next steps.\n", - "- **Detailed Explanation Of Prior Passing:** A detailed overview of how prior passing works and tools to customize it.\n", - "- **EXAMPLE:** Lets go through an example using a real parameter." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Google Colab Setup__\n", - "\n", - "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": { - "cellView": "form", - "jupyter": { - "source_hidden": true - } - }, - "outputs": [], - "source": [ - "# @title Set up Google Colab { display-mode: \"form\" }\n", - "try:\n", - " import google.colab\n", - "except ImportError:\n", - " from autolens import setup_colab as _setup_colab\n", - "else:\n", - " import importlib\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.check_call(\n", - " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", - " )\n", - " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", - "\n", - "_setup_colab.setup(\"howtolens\")" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autolens import jax_wrapper # Sets JAX environment before other imports\n", - "\n", - "from autolens import setup_notebook; setup_notebook()\n", - "\n", - "import numpy as np\n", - "from pathlib import Path\n", - "import autolens as al\n", - "import autolens.plot as aplt\n", - "import autofit as af" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Initial Setup__\n", - "\n", - "we'll use the same strong lensing data as the previous tutorial, where:\n", - "\n", - " - The lens galaxy's light is an `Sersic`.\n", - " - The lens system uses an `Isothermal` galaxy mass profile and a separate `ExternalShear` field.\n", - " - The source galaxy's light is an `Exponential`.\n", - " \n", - "All the usual steps for setting up a model fit (masking, analysis, etc.) are included below." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "dataset_name = \"lens_sersic\"\n", - "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Dataset Auto-Simulation__\n", - "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "al.util.dataset.simulate_if_needed(\n", - " dataset_path, simulator=\"scripts/simulator/lens_sersic.py\"\n", - ")\n", - "\n", - "dataset = 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.1,\n", - ")\n", - "\n", - "mask_radius = 2.6\n", - "\n", - "mask = al.Mask2D.circular(\n", - " shape_native=dataset.shape_native,\n", - " pixel_scales=dataset.pixel_scales,\n", - " radius=mask_radius,\n", - ")\n", - "\n", - "dataset = dataset.apply_mask(mask=mask)\n", - "\n", - "aplt.subplot_imaging_dataset(dataset=dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Model__\n", - "\n", - "We are going to use the same result of search 1 from the previous tutorial. Thus, we set up an identical model such \n", - "that we instantly load the result from hard-disk." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge = af.Model(al.lp_linear.Sersic)\n", - "mass = af.Model(al.mp.Isothermal)\n", - "\n", - "bulge.centre_0 = 0.0\n", - "bulge.centre_1 = 0.0\n", - "mass.centre_0 = 0.0\n", - "mass.centre_1 = 0.0\n", - "\n", - "mass.ell_comps = bulge.ell_comps\n", - "\n", - "bulge.sersic_index = 4.0\n", - "\n", - "lens = af.Model(al.Galaxy, redshift=0.5, bulge=bulge, mass=mass)\n", - "field = af.Model(al.MassField, redshift=0.5, shear=al.mp.ExternalShear)\n", - "\n", - "source = af.Model(al.Galaxy, redshift=1.0, bulge=al.lp_linear.ExponentialCore)\n", - "\n", - "model_1 = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `info` attribute shows the model in a readable format." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(model_1.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The same model can also be visualized as a figure, making its structure easier to understand at a glance.\n", - "\n", - "The figure shows how the model is organized: which parameters belong to each component, and whether they are free,\n", - "fixed, shared, linked by an expression, solved during the fit, or not configured. `model.info` provides the\n", - "corresponding numerical details, including the prior assigned to each free parameter and the value of each fixed\n", - "parameter.\n", - "\n", - "This is the same model as the first search of the previous tutorial. Keep it in mind as you read the second\n", - "model below: this tutorial is about what prior passing changes between the two and, more importantly, about what\n", - "it does not." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "af.ModelPlotter(model_1).figure()" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Search__\n", - "\n", - "We also create the same search as the previous tutorial, using the same name to ensure we use the same results, and \n", - "run it." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search_1 = af.Nautilus(\n", - " path_prefix=Path(\"howtolens\", \"chapter_2\"),\n", - " name=\"tutorial_9_search_chaining_1\",\n", - " unique_tag=dataset_name,\n", - " n_live=100,\n", - " iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations\n", - ")\n", - "\n", - "analysis_1 = al.AnalysisImaging(dataset=dataset)\n", - "\n", - "result_1 = search_1.fit(model=model_1, analysis=analysis_1)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Result (Search 1)__\n", - "\n", - "The results which are used for prior passing are summarised in the `info` attribute." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result_1.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Prior Passing__\n", - "\n", - "We are now going to use the prior passing API to pass these results, in a way which does not require us to manually \n", - "write out the inferred parameter values of each component. The details of how prior passing is performed will be \n", - "expanded upon at the end of the tutorial.\n", - "\n", - "We start with the lens's bulge, which in the previous search was an `Sersic` with its centre fixed to (0.0, 0.0) \n", - "and its `sersic_index` fixed to 4.0. The API for passing priors is shown below and there are two things worth noting:\n", - "\n", - " 1) We pass the priors using the `model` attribute of the result. This informs **PyAutoLens** to pass the result as a\n", - " model component that is to be fitted for in the next search, using priors that are initialized from the previous\n", - " search's result. Note, if we pass as a `model` a parameter that was fixed in search 1 (e.g. the `sersic_index`) it \n", - " will be fixed to the same value in search 2.\n", - "\n", - " 2) We do not pass the `centre` or `sersic_index` using `model`, because it would be fixed to the values that it was in \n", - " the first search. By omitting the centre, it uses the default priors on a lens galaxy, whereas we manually tell the \n", - " Sersic index to use a `TruncatedGaussianPrior` centred on 4.0. " - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge = af.Model(al.lp_linear.Sersic)\n", - "\n", - "bulge.ell_comps = result_1.model.galaxies.lens.bulge.ell_comps\n", - "bulge.effective_radius = result_1.model.galaxies.lens.bulge.effective_radius\n", - "bulge.sersic_index = af.TruncatedGaussianPrior(\n", - " mean=4.0, sigma=2.0, lower_limit=0.0, upper_limit=5.0\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For the mass, we again must account for how its centre was fixed to (0.0\", 0.0\") and therefore not pass the centre.\n", - "The external shear belongs to its own field, so we pass that field model separately. Taking it from\n", - "`result_1.model.fields` keeps its parameters free with the priors learned in the first search; taking\n", - "`result_1.instance.fields` would fix them to the fitted values instead." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mass = af.Model(al.mp.Isothermal)\n", - "mass.einstein_radius = result_1.model.galaxies.lens.mass.einstein_radius\n", - "mass.ell_comps = result_1.model.galaxies.lens.mass.ell_comps\n", - "field = result_1.model.fields" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For the source's bulge, we are passing the result of an `Exponential` to an `Sersic`. \n", - "\n", - "We can use a special prior passing method to do this, called `take_attributes`. This scans the `Exponential`\n", - "passed to the `take_attributes` method for all parameters which have the same name as the `Sersic` model,\n", - "and if their names are the same it passes their prior as a `model` (like we did above). Thus, it will locate the\n", - "parameters in common between the two profiles (`centre`, `ell_comps`, `effective_radius`) and pass those,\n", - "leaving the `sersic_index`'s priors as the default values.\n", - "\n", - "The `take_attributes` method is used in many examples of prior passing, when we pass a simpler parameterization of a\n", - "model to a more complex model. Another good example would be passing the result of a `IsothermalSph` to an\n", - "`Isothermal`." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "source_bulge = af.Model(al.lp_linear.Sersic)\n", - "source_bulge.take_attributes(result_1.model.galaxies.source.bulge)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now compose the model with these components that have had their priors customized. " - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "lens = af.Model(al.Galaxy, redshift=0.5, bulge=bulge, mass=mass)\n", - "\n", - "source = af.Model(al.Galaxy, redshift=1.0, bulge=source_bulge)\n", - "\n", - "model_2 = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `info` attribute shows the model, including how all priors are updated via prior passing." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(model_2.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Prior passing replaces almost every number in the `info` above with a narrow prior centred on search 1's result,\n", - "but it changes nothing about the model's structure, because a prior is a number and numbers are not structure.\n", - "\n", - "The two changes we made deliberately, and separately from the passing itself, are structural: `centre` and\n", - "`sersic_index` are free again, because we chose not to pass those, and the source is now a `Sersic` rather than\n", - "an `ExponentialCore` \u2014 the upgrade `take_attributes` exists to make possible." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "af.ModelPlotter(model_2).figure()" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Search__\n", - "\n", - "Lets setup and run the search. I have given it a different name to the previous tutorial so we can compare the priors\n", - "that were passed." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search_2 = af.Nautilus(\n", - " path_prefix=Path(\"howtolens\", \"chapter_2\"),\n", - " name=\"tutorial_10_prior_passing_2\",\n", - " unique_tag=dataset_name,\n", - " n_live=100,\n", - " iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations\n", - ")\n", - "\n", - "analysis_2 = al.AnalysisImaging(dataset=dataset)\n", - "\n", - "print(\n", - " \"The non-linear search has begun running - checkout the output/howtolens/chapter_2\"\n", - " \" folder for live output of the results, images and lens model.\"\n", - " \" This Jupyter notebook cell with progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", - "result_2 = search_2.fit(model=model_2, analysis=analysis_2)\n", - "\n", - "print(\"Search has finished run - you may now continue the notebook.\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Result__\n", - "\n", - "We can again inspect the results via the `info` attribute." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result_2.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And a plot of the image shows we get a good model again!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_fit_imaging(fit=result_2.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Wrap Up__\n", - "\n", - "This tutorial has covered the core of the prior passing API; the chaining examples in the `autolens_workspace`\n", - "(e.g. `autolens_workspace/scripts/guides/modeling/chaining.py`) expand on it further. The main thing to note is that\n", - "we can pass entire profiles or galaxies using prior passing, if their model does not change (which for the bulge,\n", - "mass and source_bulge above, was not true). The API to pass a whole profile or galaxy is as follows:\n", - "\n", - " bulge = result_1.model.galaxies.lens.bulge\n", - " lens = result_1.model.galaxies.lens\n", - " source = result_1.model.galaxies.source\n", - "\n", - "We can also pass priors using an `instance` instead of a `model`. When an `instance` is used, the maximum likelihood\n", - "parameter values are passed as fixed values that are therefore not fitted for by the non-linear search (reducing its\n", - "dimensionality). Chained fits often use this to fix the lens light to the best-fit model of an early search, reducing\n", - "the dimensionality of the searches that follow \u2014 the workspace's chaining examples show this in action.\n", - " \n", - "Lets now think about how priors are passed. Checkout the `model.info` file of the second search of this tutorial. The \n", - "parameters do not use the default priors we saw in search 1 (which are typically broad UniformPriors). Instead, \n", - "they use GaussianPrior`s where:\n", - "\n", - " - The mean values are the median PDF results of every parameter in search 1.\n", - " - The sigma values are specified in the `width_modifier` field of the profile's entry in the `priors.yaml' config \n", - " file (we will discuss why this is used in a moment).\n", - "\n", - "Like the manual `GaussianPrior`'s that were used in the previous tutorial, the prior passing API sets up the prior on each\n", - "parameter with a `GaussianPrior` centred on the high likelihood regions of parameter space!\n", - "\n", - "__Detailed Explanation Of Prior Passing__\n", - "\n", - "To end, I provide a detailed overview of how prior passing works and illustrate tools that can be used to customize\n", - "its behaviour. It is up to you whether you want read this, or go ahead to the next tutorial!\n", - "\n", - "Lets say I chain two parameters as follows:\n", - " \n", - " `mass.einstein_radius = result_1.model.galaxies.lens.mass.einstein_radius`\n", - "\n", - "By invoking the `model` attribute, the prior is passed following 3 rules:\n", - "\n", - " 1) The new parameter, in this case the einstein radius, uses a `GaussianPrior`.This is ideal, as the 1D pdf results \n", - " we compute at the end of a search are easily summarised as a Gaussian.\n", - "\n", - " 2) The mean of the `GaussianPrior` is the median PDF value of the parameter estimated in search 1.\n", - " \n", - " This ensures that the initial sampling of the new search's non-linear starts by searching the region of non-linear \n", - " parameter space that correspond to highest log likelihood solutions in the previous search. Our priors therefore \n", - " correspond to the `correct` regions of parameter space.\n", - "\n", - " 3) The sigma of the Gaussian uses the value specified for the profile in the `config/priors/*.yaml` config file's \n", - " `width_modifer` field (check these files out now).\n", - "\n", - "The idea here is simple. We want a value of sigma that gives a `GaussianPrior` wide enough to search a broad \n", - "region of parameter space, so that the lens model can change if a better solution is nearby. However, we want it \n", - "to be narrow enough that we don't search too much of parameter space, as this will be slow or risk leading us \n", - "into an incorrect solution! \n", - "\n", - "The `width_modifier` values in the priors config file have been chosen based on our experience as being a good\n", - "balance broadly sampling parameter space but not being so narrow important solutions are missed.\n", - " \n", - "There are two ways a value is specified using the priors/width file:\n", - "\n", - " 1) Absolute: In this case, the error assumed on the parameter is the value given in the config file. \n", - " For example, if for the width on centre_0 of a light profile, the width modifier reads \"Absolute\" with a value \n", - " 0.05. This means if the error on the parameter centre_0 was less than 0.05 in the previous search, the sigma of \n", - " its `GaussianPrior` in this search will be 0.05.\n", - " \n", - " 2) Relative: In this case, the error assumed on the parameter is the % of the value of the estimated value given in \n", - " the config file. For example, if the intensity estimated in the previous search was 2.0, and the relative error in \n", - " the config file reads \"Relative\" with a value 0.5, then the sigma of the `GaussianPrior` will be 50% of this \n", - " value, i.e. sigma = 0.5 * 2.0 = 1.0.\n", - "\n", - "We use absolute and relative values for different parameters, depending on their properties. For example, using the \n", - "relative value of a parameter like the `Profile` centre makes no sense. If our lens galaxy is centred at (0.0, 0.0), \n", - "the relative error will always be tiny and thus poorly defined. Therefore, the default configs in **PyAutoLens** use \n", - "absolute errors on the centre.\n", - "\n", - "However, there are parameters where using an absolute value does not make sense. Intensity is a good example of this. \n", - "The intensity of an image depends on its units, S/N, galaxy brightness, etc. There is no single absolute value that \n", - "one can use to generically chain the intensity of any two proflies. Thus, it makes more sense to chain them using \n", - "the relative value from a previous search.\n", - "\n", - "We can customize how priors are passed from the results of a search and non-linear search by editing the\n", - " `prior_passer` settings in the `general.yaml` config file.\n", - "\n", - "__EXAMPLE__\n", - "\n", - "Lets go through an example using a real parameter. Lets say in search 1 we fit the lens galaxy's light with an \n", - "elliptical Sersic profile, and we estimate that its sersic index is equal to 4.0.\n", - " \n", - "To pass this as a prior to search 2 we write:\n", - "\n", - " lens.bulge.sersic_index = result_1.model.lens.bulge.sersic_index\n", - "\n", - "The prior on the lens galaxy's bulge sersic index in search 2 would thus be a `GaussianPrior` with mean=4.0. \n", - "\n", - "The value of the Sersic index `width_modifier` in the priors config file sets sigma. The prior config file specifies \n", - "that we use an \"Absolute\" value of 0.8 to chain this prior. Thus, the `GaussianPrior` in search 2 would have a \n", - "mean=4.0 and sigma=0.8.\n", - "\n", - "If the prior config file had specified that we use an relative value of 0.8, the GaussianPrior in search 2 would have a \n", - "mean=4.0 and sigma = 4.0 * 0.8 = 3.2.\n", - "\n", - "And with that, we're done. Chaining priors is a bit of an art form, but one that works really well. " - ] - } - ], - "metadata": { - "anaconda-cloud": {}, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - }, - "colab": { - "aiContexts": { - "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_10_prior_passing.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" - } - }, - "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file diff --git a/notebooks/chapter_2_lens_modeling/tutorial_11_slam.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_11_slam.ipynb deleted file mode 100644 index cbdba94..0000000 --- a/notebooks/chapter_2_lens_modeling/tutorial_11_slam.ipynb +++ /dev/null @@ -1,155 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 11: SLaM\n", - "=================\n", - "\n", - "In the previous two tutorials, we learnt how search chaining breaks a lens model-fit into a sequence of simpler\n", - "non-linear searches, and how prior passing carries the results of each search into the next. Together, they give us\n", - "the flexibility to juggle the dimensionality, priors and settings of each search \u2014 the three drivers of run-time we\n", - "met in tutorial 8 \u2014 whilst still fitting a complex and realistic lens model at the end.\n", - "\n", - "You could now write your own chained sequences of searches, tailored to whatever lens model is of particular interest\n", - "to your scientific study. However, for most lens models there are standardized approaches one can take to fitting\n", - "them. For example, an effective approach is to first fit a model for the lens's light, then a model for its mass and\n", - "the source. It would be wasteful for all **PyAutoLens** users to have to write their own chained pipelines to perform\n", - "the same tasks.\n", - "\n", - "For this reason, the `autolens_workspace` comes with standardized chained pipelines, which fit common lens models in\n", - "ways we have tested are efficient and robust. This closing tutorial does not run any code; it is a pointer to where\n", - "that material lives, so you know where to go once you want to scale your lens modeling up.\n", - "\n", - "__Contents__\n", - "\n", - "- **Search Chaining In The Workspace:** Where the workspace documents the chaining API introduced in tutorials 9 and 10.\n", - "- **SLaM (Source, Light and Mass):** The standardized pipelines that chain searches for you.\n", - "- **Wrap Up:** Choosing between single searches, your own chained fits and the SLaM pipelines.\n", - "\n", - "__Search Chaining In The Workspace__\n", - "\n", - "The chaining and prior passing API we introduced in tutorials 9 and 10 is documented in full in the workspace guide\n", - "`autolens_workspace/scripts/guides/modeling/chaining.py`. It covers the concise model composition API used in chained\n", - "fits, prior passing and the tools for customizing it, and how chaining is used in practice for automated lens\n", - "modeling.\n", - "\n", - "__SLaM (Source, Light and Mass)__\n", - "\n", - "The workspace's standardized pipelines are called the **SLaM** (Source, Light and Mass) pipelines. They are composed\n", - "of a specific sequence of chained searches:\n", - "\n", - " - `Source`: A pipeline that focuses on producing a robust model for the source's light, using simpler models for the\n", - " lens's light and mass.\n", - "\n", - " - `Light`: A pipeline that fits a complex lens light model (e.g. one with many components), using the initialized\n", - " source model to cleanly deblend the lens and source light.\n", - "\n", - " - `Mass`: A pipeline that fits a complex lens mass model, benefitting from the good models for the lens's light and\n", - " source.\n", - "\n", - "For fitting very complex lens models, for example ones which decompose the mass into its stellar and dark components,\n", - "the **SLaM** pipelines have been carefully crafted to do this in a reliable and automated way that is still efficient.\n", - "They also make fitting many different models to a single dataset efficient, as they reuse the results of earlier\n", - "searches (e.g. in the Source pipeline) to fit different models in the `Light` and `Mass` pipelines for the lens's\n", - "light and mass.\n", - "\n", - "The canonical introduction is `autolens_workspace/scripts/guides/modeling/slam_start_here.py`, which walks through the\n", - "pipeline structure end-to-end. Runnable SLaM examples then live as `slam.py` scripts inside the feature folders of\n", - "each topic, for example `autolens_workspace/scripts/imaging/features/pixelization/slam.py` and\n", - "`autolens_workspace/scripts/imaging/features/multi_gaussian_expansion/slam.py`.\n", - "\n", - "__Wrap Up__\n", - "\n", - "Whether you should use individual searches, your own chained fits, the SLaM pipelines or write your own model-fitting\n", - "script depends on the scope of your scientific analysis. I would advise you begin by trying to adapt the scripts in\n", - "the `autolens_workspace` to fit your data, and also try using the SLaM pipelines once you are a confident\n", - "**PyAutoLens** user.\n", - "\n", - "This tutorial concludes the lens modeling chapter. In the next chapter, we introduce pixelizations, which reconstruct\n", - "the source galaxy on a pixel-grid rather than with light profiles." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Google Colab Setup__\n", - "\n", - "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": { - "cellView": "form", - "jupyter": { - "source_hidden": true - } - }, - "outputs": [], - "source": [ - "# @title Set up Google Colab { display-mode: \"form\" }\n", - "try:\n", - " import google.colab\n", - "except ImportError:\n", - " from autolens import setup_colab as _setup_colab\n", - "else:\n", - " import importlib\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.check_call(\n", - " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", - " )\n", - " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", - "\n", - "_setup_colab.setup(\"howtolens\")" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autolens import setup_notebook; setup_notebook()\n" - ], - "outputs": [], - "execution_count": null - } - ], - "metadata": { - "anaconda-cloud": {}, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - }, - "colab": { - "aiContexts": { - "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_11_slam.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_run_slam_pipeline\n\n---\nname: al_run_slam_pipeline\ndescription: Run a Source-Light-Mass (SLaM) pipeline \u2014 the canonical automated multi-stage lens-modelling workflow. Stages a parametric source fit, a pixelised source fit, a lens-light fit, and a total-mass fit, chaining priors between them. The right starting point for any production-quality lens model, especially with pixelised sources. Prereq: understand `al_chain_searches` and pixelisations.\n---\n\n# Running a SLaM pipeline\n\nSLaM (Source, Light, Mass) is the canonical automated lens-modelling pipeline. It\nchains four or more searches:\n\n1. **SOURCE LP** \u2014 fit a parametric (light-profile) source with a simple lens mass to\n initialise.\n2. **SOURCE PIX** \u2014 switch the source to a pixelised inversion, refining everything.\n The adapt image driving the mesh and regularisation is capped at S/N 3.0, and from\n `source_pix_2` the dataset is re-applied with an adaptive pixelization over-sampling\n map (see \"Branch \u2014 galaxy-scale imaging SLaM\" below).\n3. **LIGHT LP** \u2014 fit a complex lens-light model (e.g. MGE) on top, holding mass + source\n close to the SOURCE PIX result.\n4. **MASS TOTAL** \u2014 fit a more complex mass model (PowerLaw, MGE, multipole) with\n light + source held close.\n\nIt is the most reliable route to a publication-quality lens model. The trade-off is\nruntime \u2014 a SLaM run typically takes 4\u201324 hours on a modern CPU.\n\nCanonical reference: `autolens_workspace:scripts/guides/modeling/slam_start_here.py`.\nTreat this file as the structural template; all other SLaM scripts in the workspace\nare documented relative to it (\"identical to slam_start_here.py except\u2026\").\n\n## Prerequisites\n\nBefore running SLaM, the user should be comfortable with:\n\n- **Pixelisations** \u2014 [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n- **Search chaining** \u2014 [`al_chain_searches`](./al_chain_searches.md) and\n [`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md).\n- **Adapt images** \u2014 adaptive regularisation that uses the lens-light-subtracted image\n to scale source-plane reconstruction smoothness. Covered in the SLaM concept page.\n- **Real-data preprocessing** \u2014 for observational imaging, they should already have\n made explicit decisions about mask radius, contaminating objects, and any manual\n exclusion regions that should not enter the likelihood.\n\nIf they're newer than that, route them through `al_build_imaging_model` +\n`al_run_search` first; SLaM is overkill for a first-fit.\n\nFor the full conceptual treatment of SLaM,\n[`wiki/core/concepts/slam_pipeline.md`](../wiki/core/concepts/slam_pipeline.md).\n\n## Ask\n\n- *\"Imaging or interferometer?\"* \u2014 both supported; the pipelines differ in the analysis\n classes and inversion settings.\n- *\"If this is real imaging data, have you already settled the preprocessing choices:\n mask extent, contaminant masking, and any regions that should be excluded from the\n model?\"* \u2014 if not, route back to [`al_prepare_imaging_data`](./al_prepare_imaging_data.md)\n before starting SLaM.\n- *\"Does the lens galaxy have noticeable lens light to model, or are you doing a\n mass-only fit?\"* \u2014 controls whether LIGHT LP is included.\n- *\"What's the final mass model you want?\"* \u2014 Isothermal+Shear (default), PowerLaw,\n PowerLawMultipole, decomposed Light+Dark, etc. Controls the MASS TOTAL phase.\n- *\"Have you measured image positions for the lensed source?\"* \u2014 recommended for\n pixelised-source fits to avoid unphysical demagnification solutions.\n\n## Branch \u2014 galaxy-scale imaging SLaM\n\nThere is **no importable SLaM module**: each SLaM script defines its stages as plain\nPython functions inline (`source_lp`, `source_pix_1`, `source_pix_2`, `light_lp`,\n`mass_total`, \u2026) and chains them by passing each stage's `af.Result` into the next.\n`slam_start_here.py` is the canonical, fully-documented instance of that pattern \u2014\nso the recipe is *copy and adapt the template*, not write from scratch:\n\n```bash\n# The `init-slam` skill automates this copy; manually it is:\ncp /scripts/guides/modeling/slam_start_here.py scripts/slam_pipeline.py\n```\n\nThen adapt the template's clearly-marked sections to the user's lens \u2014 dataset path\nand pixel scale, mask radius, lens/source redshifts, the LIGHT LP parameterisation,\nand the final MASS TOTAL model. The chaining skeleton you are editing looks like:\n\n```python\n# Inside scripts/slam_pipeline.py (structure of the copied template, abridged):\nsource_lp_result = source_lp(analysis=analysis, ...)\nsource_pix_result_1 = source_pix_1(analysis=analysis, source_lp_result=source_lp_result)\nsource_pix_result_2 = source_pix_2(analysis, source_lp_result, source_pix_result_1)\nlight_result = light_lp(analysis, source_pix_result_1, source_pix_result_2)\nmass_result = mass_total(analysis, source_pix_result_1, source_pix_result_2, light_result)\n```\n\nEach stage function that builds `al.AdaptImages` from\n`al.galaxy_name_image_dict_via_result_from` caps the source entry at S/N 3.0 on an\nexplicit copy first \u2014 the copied template already does this at every stage, so keep the\ncap block when you adapt a stage and add it to any stage you write yourself. The rule,\nthe copy requirement and the interferometer variant are in\n[`al_adaptive_pixelization`](./al_adaptive_pixelization.md) \u2014 \"Adapt image S/N cap\".\n\nFrom `source_pix_2` onwards the dataset is re-applied once with an adaptive\npixelization over-sampling map \u2014 sub-size 4 where the *raw* (pre-cap) source S/N image\nexceeds 3.0, 2 elsewhere \u2014 before the fit is composed, and `light_lp`, `mass_total` and\nevery later stage inherit that dataset. `source_pix_1` does not: its adapt image comes from\nthe parametric SOURCE LP fit, so it keeps the default uniform sub-size. The idiom, and the\n`over_sample_size_via_adapt_from` helper it must never be fed to, are in\n[`al_adaptive_pixelization`](./al_adaptive_pixelization.md) \u2014 \"Adaptive pixelization\nover-sampling\".\n\nImage positions (recommended for pixelised sources, to penalise unphysical\ndemagnified solutions) load from JSON and wire into the stage functions via\n`positions_likelihood_from` / `al.PositionsLH`:\n\n```python\npositions = al.from_json(file_path=dataset_path / \"positions.json\") # Grid2DIrregular\npositions_likelihood = al.PositionsLH(positions=positions, threshold=0.5)\n```\n\nSource citations:\n- `autolens_workspace:scripts/guides/modeling/slam_start_here.py` \u2014 the canonical\n template: stage functions, their chaining, and every per-stage setting.\n- `PyAutoLens:autolens/analysis/positions.py` \u2014 `PositionsLH`.\n\n## Branch \u2014 interferometer SLaM\n\nAnalogous pipelines exist at `autolens_workspace:scripts/interferometer/features/*/slam.py`.\nSubstitute `AnalysisInterferometer` and the visibility-plane SLaM driver.\n\n## Running and monitoring\n\nSLaM writes one output subfolder per phase. Tail the latest phase's search log:\n\n```bash\nls -td output/imaging//slam/*/ | head -1 | xargs -I{} tail -f {}search.log\n```\n\nSmoke test the wiring with `PYAUTO_TEST_MODE=1` before launching the real run \u2014\nall 4+ phases will short-circuit, but you'll catch import / config errors fast.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 load each phase's results separately;\n the MASS TOTAL phase usually holds the final answer.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) \u2014 the\n SOURCE PIX phase produces the pixelised source you'd want to inspect.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) \u2014 SLaM failures usually point to\n one specific phase; the debug skill walks the post-mortem.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Standard Lens Analysis Method\n (SLaM)](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_11_slam.ipynb):\n what SLaM is and why it works \u2014 best-practice multi-stage chaining encoded as a\n ready-made pipeline.\n- **General reference** \u2014 [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n SLaM sits alongside pixelization, MGE, subhalo detection and multi-wavelength on\n the feature tour.\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 canonical SLaM invocation script \u2014 all other SLaM scripts in the workspace are\n documented relative to it.\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" - } - }, - "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file 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 dfef329..f9afb62 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 @@ -23,6 +23,7 @@ "\n", "- **Overview:** Introduce the experiment and the results to inspect.\n", "- **Parameter Space:** Understand how free parameters define the models a search can explore.\n", + "- **More Dimensions:** Understand how model parameters work together.\n", "- **Automated Exploration:** Use a non-linear search to explore possible model parameters.\n", "- **Deeper Background:** Find further explanations of likelihoods and Bayesian inference.\n", "- **PyAutoFit:** Introduce the tools used to define models, priors and searches.\n", @@ -55,23 +56,45 @@ "\n", "__Parameter Space__\n", "\n", - "Imagine varying just two properties of a lens model: the lens\u2019s Einstein radius and the source\u2019s effective radius. Each\n", - "possible pair of values represents a different model and corresponds to a point in a two-dimensional **parameter\n", - "space**.\n", + "Imagine that we fix every property of our lens model except its Einstein radius, $\\theta_{\\rm E}$. We can calculate a predicted image for each value of this parameter, compare that image with our observations, and calculate its log likelihood:\n", "\n", - "Adding another free parameter adds another dimension. Although we cannot easily draw a space with many dimensions, the\n", - "idea remains the same: each point specifies a complete set of values for the model\u2019s free parameters.\n", + "$$\n", + "\\ln \\mathcal{L} = f(\\theta_{\\rm E}).\n", + "$$\n", "\n", - "For each point, we can predict an image and compare it with the data to calculate a log likelihood. Plotting this value\n", - "above each point gives a **log likelihood surface**. High regions correspond to models that explain the data better\n", - "than models in lower regions.\n", + "This is a one-dimensional parameter space. Each position along the horizontal axis represents a different Einstein radius, and the height of the curve tells us how well that model fits the data.\n", "\n", - "The surface can have several peaks, curved ridges and broad regions where different parameter combinations produce\n", - "similar images. These features make it difficult to find the best-fitting model and establish which other models are\n", - "also consistent with the observations.\n", + "Changing the Einstein radius changes the deflection of the source light and therefore the positions and appearance of its lensed images. Values that place the predicted arcs close to the observed arcs can give a higher likelihood; values that put light where the data contain none give a poorer fit.\n", "\n", - "**\ud83e\udd16 Ask AI:** In strong-lens modeling, why might changing the lens mass and the source size together produce similar\n", - "images, and how could this appear on a likelihood surface?\n", + "Now allow the source's effective radius, $R_{\\rm e}$, to vary too:\n", + "\n", + "$$\n", + "\\ln \\mathcal{L} = f(\\theta_{\\rm E}, R_{\\rm e}).\n", + "$$\n", + "\n", + "Every pair of values specifies a different lens model. We can imagine these pairs laid out across a sheet, with Einstein radius along one axis and source size along the other. The log likelihood gives a height above each point, forming a surface.\n", + "\n", + "Changing the source size changes how extended its predicted light is. After lensing, this affects the widths and brightness distribution of the arcs. The best-fitting source size can depend on the mass model: changing one parameter can sometimes be partly compensated by changing another. On our likelihood surface, this can produce an elongated or curved ridge of relatively good fits.\n", + "\n", + "__More Dimensions__\n", + "\n", + "Our actual model has more than two free parameters. The lens has a centre, and the source has its own centre, size and intensity. We can write the same idea more generally as:\n", + "\n", + "$$\n", + "\\ln \\mathcal{L} = f(p_1, p_2, \\ldots, p_N),\n", + "$$\n", + "\n", + "where each $p_i$ is one of the model's free parameters.\n", + "\n", + "Each point in this $N$-dimensional space specifies all the values needed to construct a model and predict an image. A non-linear search explores these points to find models that explain the observations and investigate the range of parameter values consistent with them.\n", + "\n", + "Although we cannot draw the full surface when there are many parameters, its structure still matters. There can be broad regions of poor fits, narrow ridges of good fits, and separate peaks corresponding to different explanations of the image.\n", + "\n", + "For example, moving the source changes the arrangement and relative brightness of its lensed images. Changing the lens mass can also change those images. Several combinations may reproduce some features reasonably well, while only a smaller region reproduces all of them together.\n", + "\n", + "This is why automated modeling involves more than adjusting each parameter independently until the image looks right. The search must explore how the parameters work together.\n", + "\n", + "**\ud83e\udd16 Ask AI:** In strong-lens modeling, why might changing the lens mass and the source size together produce similar images, and how could this appear on a likelihood surface?\n", "\n", "__Automated Exploration__\n", "\n", @@ -308,11 +331,7 @@ "source": [ "We describe the source with an `ExponentialCoreSph` light profile at a fixed redshift of 1.0.\n", "\n", - "Here, we use the profile from `al.lp_linear`. Its centre and effective radius are explored by the non-linear search,\n", - "while its intensity is calculated by a linear solve for each proposed model.\n", - "\n", - "The intensity is therefore still fitted to the data, but it does not add a dimension to the non-linear search. Tutorial\n", - "4, *Linear Profiles*, explains this distinction and how it helps us fit more flexible light distributions." + "Its free parameters include its centre, effective radius and intensity. The search varies these quantities together with the lens mass parameters. Changing the source intensity changes the brightness of the predicted lensed emission, allowing the model to match the observed flux as well as the shape and location of the arcs." ] }, { @@ -320,7 +339,7 @@ "metadata": {}, "source": [ "\n", - "bulge = af.Model(al.lp_linear.ExponentialCoreSph)\n", + "bulge = af.Model(al.lp.ExponentialCoreSph)\n", "source = af.Model(al.Galaxy, redshift=1.0, bulge=bulge)" ], "outputs": [], @@ -355,11 +374,9 @@ "source": [ "The `model.info` attribute summarises the model before we fit it.\n", "\n", - "Look for the lens mass and source light components, the priors assigned to their free parameters and the fixed galaxy\n", - "redshifts. Notice that the source intensity is treated as a linear parameter rather than assigned a prior for the\n", - "non-linear search.\n", + "Look for the lens mass and source light components and the priors assigned to their free parameters. The source intensity is one of the quantities the search will fit; the galaxy redshifts are fixed.\n", "\n", - "This describes what we intend to fit. It contains no inferred parameter values yet, because the search has not run." + "Compare these same components in the model diagram. Together, the summary and diagram describe what we intend to fit. They do not contain inferred parameter values yet, because the search has not run." ] }, { @@ -379,8 +396,7 @@ "The model diagram shows the same structure visually. Follow the branches from `galaxies` to the lens and source, then\n", "to their mass and light profiles.\n", "\n", - "Compare the free profile parameters with the fixed redshifts and the linearly solved source intensity. These\n", - "distinctions determine which quantities the non-linear search must explore.\n", + "Compare the free profile parameters, including the source intensity, with the fixed redshifts. These distinctions determine which quantities the non-linear search must explore.\n", "\n", "The lens redshift of 0.5 places it in front of the source at redshift 1.0. PyAutoLens uses these redshifts to establish\n", "the ordering and distances needed for ray tracing.\n", @@ -504,7 +520,6 @@ "including ray tracing and PSF convolution. It compares that prediction with the masked imaging data, using the noise\n", "map to evaluate the log likelihood.\n", "\n", - "For our linear source profile, this evaluation also solves for the intensity before calculating the likelihood.\n", "\n", "You performed the same essential comparison in Chapter 1 when you created a `FitImaging` object and inspected its\n", "`log_likelihood`. The Analysis object makes that calculation available to the search so it can be repeated for many\n", diff --git a/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb index c98e1aa..e7e1236 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb @@ -191,9 +191,7 @@ "The lens galaxy contains both a light profile and a mass profile. The external shear is a separate field at the lens\n", "redshift, and the source galaxy contains its own light profile.\n", "\n", - "Here, we use ordinary light profiles from `al.lp`, so their intensities are also free parameters explored by Nautilus.\n", - "Tutorial 1 used a linear source-light profile, whose intensity was solved separately. In *Linear Profiles*, we will\n", - "return to that approach and see how it simplifies more complex models." + "As in Tutorial 1, the light-profile intensities are free parameters explored by Nautilus. Here, the search must determine the brightness of both the foreground lens galaxy and the background source, alongside their other properties." ] }, { diff --git a/notebooks/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.ipynb index fa716bc..6fe2fd8 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.ipynb @@ -327,22 +327,19 @@ "source": [ "__Why Modeling Is Hard__\n", "\n", - "A lens image can sometimes be reproduced approximately by several different combinations of lens light, mass and source\n", - "light. These combinations occupy different regions of parameter space.\n", + "Our example deliberately makes the search less thorough by reducing the number of live points from 200 to 21. This is a somewhat contrived way to expose a difficulty within a short tutorial: your particular run may still find a good solution.\n", "\n", - "A **local maximum** is a point whose likelihood is higher than that of nearby points, even though a better solution\n", - "exists elsewhere. The **global maximum** is the highest likelihood available within the chosen model and parameter\n", - "ranges.\n", + "The underlying problem, however, is common in modeling real lenses. Different combinations of lens light, mass and source light can reproduce parts of an image, creating several promising regions of parameter space. A search may explore one region thoroughly while missing a better solution elsewhere.\n", "\n", - "A search can spend its effort exploring one promising region and miss another. With only 21 live points, there is\n", - "little opportunity to represent all the important regions of this model\u2019s parameter space.\n", + "A **local maximum** has a likelihood at least as high as nearby parameter values. There may still be another peak with a higher likelihood elsewhere. The **global maximum** is the highest likelihood available within the chosen model and parameter ranges.\n", "\n", - "More free parameters can make exploration harder, but the parameter count is only part of the problem. Strong\n", - "relationships between parameters, narrow regions of good solutions and separated peaks also matter.\n", + "In a real analysis, it can be difficult to establish whether the best solution we have found is a local or global maximum. We do not know the true parameters, and a plausible-looking fit does not prove that every important region has been explored.\n", "\n", - "A poor fit can therefore result from incomplete exploration. However, residuals alone do not establish that the search\n", - "has reached a local maximum: the physical model or the assumptions about the data may also be inadequate. We return to\n", - "this distinction under *Model Mismatch*.\n", + "Finding a higher-likelihood solution demonstrates that an earlier result was not the global maximum. Repeatedly recovering a similar solution increases our confidence, but does not prove that no better solution exists.\n", + "\n", + "The approaches in this tutorial are therefore tools for investigation. By changing justified priors, simplifying selected parts of the model and exploring more thoroughly, we can investigate suspicious fits and understand what makes the modeling difficult.\n", + "\n", + "Residuals also require interpretation: they can arise because the search missed a good solution, or because the model cannot describe the data adequately. We will return to this distinction under *Model Mismatch*.\n", "\n", "__Three Ways Forward__\n", "\n", @@ -897,17 +894,15 @@ "\n", "__Search More Thoroughly__\n", "\n", - "Our first two approaches changed the priors or reduced the freedom of the model. We now return to the original model\n", - "and ask Nautilus to explore it more thoroughly.\n", + "Our first two approaches changed the priors or reduced the freedom of the model. We now return to the original model and ask Nautilus to explore it more thoroughly.\n", + "\n", + "We increase the number of live points to 300. A larger population gives the search more opportunity to represent different promising regions of parameter space, although this generally requires more computation and does not guarantee that every important region will be found.\n", "\n", - "This retains separate centres and shapes for the lens light and mass, allowing the image to constrain them without the\n", - "links introduced above.\n", + "Increasing the number of live points is only one option. There are many different non-linear search methods, and they explore parameter space in different ways. Trying another method can make a substantial difference when a particular search struggles with a model.\n", "\n", - "We increase the number of live points to 300. A larger population gives the search more opportunity to represent\n", - "different promising regions of parameter space.\n", + "The optional tutorial, `chapter_optional/tutorial_searches.py`, introduces alternative searches, including optimisation and MCMC. Their outputs serve different purposes: finding a high-likelihood solution and characterising parameter uncertainty are related but distinct tasks.\n", "\n", - "This approach requires no estimates of the lens shape or size by eye beyond the original modeling choices. Its main\n", - "cost is computation: exploring more thoroughly generally takes longer.\n", + "When investigating a difficult fit, compare repeated runs and, where appropriate, different search methods using the same model, priors and likelihood. Examine the fitted images and residuals alongside the likelihood values. Agreement provides useful evidence; disagreement tells us that further investigation is needed.\n", "\n", "__Original Model__\n", "\n", @@ -1142,9 +1137,7 @@ "\n", "Later in this chapter, we will see how search chaining brings these ideas together for more complex lens models.\n", "\n", - "First, *Linear Profiles* introduces another way to make fitting easier: solving light-profile intensities separately\n", - "from the non-linear search. This will let us describe more detailed light distributions without adding a separate\n", - "non-linear parameter for every intensity." + "The next tutorial introduces another way to simplify the search while describing more detailed light distributions." ] } ], diff --git a/notebooks/chapter_2_lens_modeling/tutorial_5_data_and_likelihoods.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_5_data_and_likelihoods.ipynb new file mode 100644 index 0000000..6f2e5ac --- /dev/null +++ b/notebooks/chapter_2_lens_modeling/tutorial_5_data_and_likelihoods.ipynb @@ -0,0 +1,722 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Tutorial 5: Data and Likelihoods\n", + "================================\n", + "\n", + "Throughout this chapter, we have fitted imaging data using light and mass profiles. However, the modeling tools we have\n", + "learnt are not tied to this particular type of observation. We can use the same approach to fit interferometer\n", + "measurements, the positions of multiply imaged point sources, or the shapes of weakly lensed galaxies.\n", + "\n", + "This flexibility comes from separating the different parts of a model fit. The **dataset** contains the measurements\n", + "and their uncertainties. The **model** describes the physical system and its free parameters. The **Analysis** object\n", + "uses that model to predict the measurements and evaluates a **likelihood**, which tells us how well those predictions\n", + "agree with the data. The **search** explores the model's parameters using the likelihood and priors.\n", + "\n", + "The search does not need to know whether it is fitting image pixels, interferometer visibilities or image positions. It\n", + "supplies parameter values and receives a likelihood. By changing the dataset and the Analysis object, we can adapt the\n", + "tools we already know to a different observation, while retaining the model components appropriate to that system.\n", + "\n", + "We will build up this idea through familiar imaging examples. First, we explain why our circular masks retain the lens\n", + "galaxy, the arcs and their faint surroundings. We then consider how positions constraints provide additional\n", + "information about the mass model, and how noise scaling changes the contribution of contaminating light to the fit.\n", + "\n", + "These examples show how we can change the information entering an analysis without rebuilding the entire modeling\n", + "procedure. By the end of the tutorial, we will connect this separation to other types of lensing data and to analyses\n", + "that combine several datasets, each with its own likelihood, to constrain a shared physical model.\n", + "\n", + "__Contents__\n", + "\n", + "- **Dataset:** Return to the imaging example containing lens and source light.\n", + "- **Circular Masks:** Understand why we retain the central lens and surrounding arcs.\n", + "- **Beyond the Bright Arcs:** Recognise the information in faint emission and apparently empty regions.\n", + "- **Mask:** Define the 2D mask applied to the dataset for the model-fit.\n", + "- **Positions Constraints:** Use corresponding image features to constrain the mass model.\n", + "- **Choosing Positions:** Identify and plot features with a common source origin.\n", + "- **The Positions Penalty:** Understand the source-plane threshold and fast consistency check.\n", + "- **Model and Analysis:** Add the positions constraint to the imaging analysis.\n", + "- **Search and Result:** Fit the image with the positions constraint.\n", + "- **Contaminating Light:** Recognise light not described by the main lens and source.\n", + "- **Extra Galaxy Dataset:** Inspect an image containing a neighbouring galaxy.\n", + "- **Extra Galaxy Region:** Load the region selected for noise scaling.\n", + "- **Noise Scaling:** Reduce the weight of contaminated pixels.\n", + "- **Interpreting the Scaled Dataset:** Distinguish lost light information from gravitational deflection.\n", + "- **Interferometer Data:** Adapt the shared model composition API to visibilities.\n", + "- **Point-Source Data:** Fit measured positions and their uncertainties.\n", + "- **Weak-Lensing Data:** Constrain mass using background galaxy shapes.\n", + "- **Multiple Datasets:** Combine suitable likelihoods to constrain shared parameters.\n", + "- **Wrap Up:** Connect datasets, models, analyses and searches." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Google Colab Setup__\n", + "\n", + "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": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, + "outputs": [], + "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", + "try:\n", + " import google.colab\n", + "except ImportError:\n", + " from autolens import setup_colab as _setup_colab\n", + "else:\n", + " import importlib\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.check_call(\n", + " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", + " )\n", + " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", + "\n", + "_setup_colab.setup(\"howtolens\")" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from autolens import jax_wrapper # Sets JAX environment before other imports\n", + "\n", + "from autolens import setup_notebook; setup_notebook()\n", + "\n", + "from pathlib import Path\n", + "import autolens as al\n", + "import autolens.plot as aplt\n", + "import autofit as af" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Dataset__\n", + "\n", + "Return to the image from *Practicalities*, containing both the foreground lens galaxy and the lensed source.\n", + "\n", + "Look first at the bright central galaxy, then follow its light outwards. Its brightness decreases gradually; it does\n", + "not end at a sharp boundary. Around it, the source forms bright arcs with fainter emission extending beyond their most\n", + "obvious features.\n", + "\n", + "Our model describes both galaxies. We therefore want the fitted region to contain their useful light, including the" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "dataset_name = \"lens_sersic\"\n", + "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name\n", + "\n", + "al.util.dataset.simulate_if_needed(\n", + " dataset_path, simulator=\"scripts/simulator/lens_sersic.py\"\n", + ")\n", + "\n", + "dataset = 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.1,\n", + ")\n", + "\n", + "aplt.subplot_imaging_dataset(dataset=dataset)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Circular Masks__\n", + "\n", + "A circular mask gives us one continuous region containing the central lens galaxy, the arcs and their surroundings. We\n", + "fit the lens and source light together within this region.\n", + "\n", + "The figure below compares this with an annular mask, which excludes the centre. Although the annulus retains the bright\n", + "arcs, it discards the central lens light that helps constrain the foreground galaxy's profile.\n", + "\n", + "Removing the centre does not remove the lens galaxy's contribution to the arcs. Its extended light still overlaps the\n", + "source emission farther out, so we still need to describe it in our model.\n", + "\n", + "Throughout these PyAutoLens analyses, we therefore use circular masks. The annulus is shown here to explain the\n", + "information it would discard, rather than as another masking procedure to follow.\n", + "\n", + "![Circular and annular masks compared on the same simulated lens image; grey shading marks excluded pixels](../../images/chapter_2/circular_vs_annular.png)\n", + "\n", + "__Beyond the Bright Arcs__\n", + "\n", + "The circle should extend beyond the brightest features. Faint source emission can help constrain the source's extent,\n", + "while the outskirts of the lens galaxy help constrain how its brightness falls with radius.\n", + "\n", + "Individual pixels in these regions may contain only a weak signal. Taken together, they can still distinguish between\n", + "models that look similar around the bright centre and arcs.\n", + "\n", + "Regions without detectable emission are useful too. A mass model might reproduce the observed arcs but predict an\n", + "additional image elsewhere. If that location lies inside our circle, the extra predicted light disagrees with the data\n", + "and reduces the likelihood.\n", + "\n", + "If we exclude that location, the likelihood cannot see the disagreement. A mask drawn tightly around the observed arcs\n", + "could therefore hide evidence that the lens model is wrong.\n", + "\n", + "This is why we retain a generous circular region around the system, including the space between and around its bright\n", + "features.\n", + "\n", + "__Mask__\n", + "\n", + "We use a circular mask with a radius of 3.0 arcseconds for this example. It contains the central galaxy, the lensed\n", + "arcs and surrounding pixels that constrain their fainter emission.\n", + "\n", + "The aim is to include the system as a whole, rather than trace the outlines of individual bright features. Galaxy\n", + "profiles have extended faint wings, so this does not mean capturing every last photon.\n", + "\n", + "Including more pixels generally adds computation, but making the fitted region unnecessarily small can discard\n", + "information that helps distinguish competing lens models.\n", + "\n", + "In real observations, the surrounding region may also contain neighbouring galaxies. We will address their light later" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "mask = al.Mask2D.circular(\n", + " shape_native=dataset.shape_native,\n", + " pixel_scales=dataset.pixel_scales,\n", + " radius=3.0,\n", + ")\n", + "\n", + "dataset = dataset.apply_mask(mask=mask)\n", + "\n", + "aplt.subplot_imaging_dataset(dataset=dataset)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Positions Constraints__\n", + "\n", + "Look again at the lensed source. Its multiple images are different views of the same background galaxy. If we identify\n", + "the same feature in two or more images, a suitable mass model should trace those positions back to approximately the\n", + "same location in the source plane.\n", + "\n", + "An unsuitable mass model may instead trace them to widely separated locations. It could reproduce some of the observed\n", + "light while failing this requirement of the lensing geometry.\n", + "\n", + "We can supply these image positions to the analysis and check their source-plane separation for every proposed mass\n", + "model. When that separation exceeds a chosen threshold, a likelihood penalty discourages the search from exploring the\n", + "model.\n", + "\n", + "This gives the search a useful constraint: the marked features must be explainable as multiple images of the same\n", + "source feature. It does not tell the search the correct mass parameters in advance.\n", + "\n", + "__Choosing Positions__\n", + "\n", + "Positions must refer to the same source feature seen in different lensed images. For example, a compact bright knot may\n", + "appear in several arcs. Marking its location in each image gives us positions that should trace back together.\n", + "\n", + "Simply choosing the brightest pixel in each arc is not always reliable. An extended source may contain several bright\n", + "knots, and different knots may dominate different images. Foreground lens light can also make a feature's position\n", + "difficult to identify.\n", + "\n", + "For an individual lens, we can choose positions by inspecting the image or using the workspace's data-preparation GUI.\n", + "Always plot the selected positions over the image and check which features they mark.\n", + "\n", + "In *Search Chaining*, we will introduce a more automated approach: using an initial fitted model to estimate positions\n", + "for a subsequent analysis.\n", + "\n", + "For this example, we supply four positions corresponding to the centre of the simulated source, seen in different parts\n", + "of the arcs. These coordinates were checked against the simulation's mass model and rounded to three decimal places." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "positions = al.Grid2DIrregular(\n", + " values=[(0.271, 1.673), (-1.499, 0.195), (1.499, -0.195), (-0.271, -1.673)]\n", + ")\n", + "\n", + "aplt.subplot_imaging_dataset(dataset=dataset, positions=positions)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__The Positions Penalty__\n", + "\n", + "For each proposed mass model, PyAutoLens ray-traces the marked image positions to the source plane and calculates the\n", + "largest separation between them.\n", + "\n", + "The threshold specifies how far apart we allow those source-plane positions to be, in arcseconds. If their maximum\n", + "separation exceeds it, the analysis applies a large likelihood penalty. If they fall within it, no positions penalty is\n", + "applied.\n", + "\n", + "This check is extremely fast compared with evaluating the full imaging likelihood. It only requires ray-tracing a\n", + "handful of positions and calculating their separations, rather than predicting and comparing the light across thousands\n", + "of image pixels. It therefore adds very little computational cost while providing useful guidance to the search.\n", + "\n", + "We use this as a broad consistency check. The marked positions have uncertainties, and features in extended arcs may\n", + "not identify exactly the same source location. A threshold that is too restrictive can therefore penalise otherwise\n", + "suitable mass models.\n", + "\n", + "A threshold that is too generous has the opposite weakness: substantially different source locations may pass the\n", + "check, providing little guidance to the search.\n", + "\n", + "Here we use a broad threshold of 1.0 arcsecond. For comparison, our rounded coordinates trace within 0.001 arcseconds\n", + "of one another under the simulation's true model. The much larger threshold deliberately allows approximate agreement\n", + "while discouraging widely separated solutions; it is not a measurement of positional uncertainty or a universal setting\n", + "for other lenses.\n", + "\n", + "The positions come from the image we already fit. Here, the penalty is a practical constraint for guiding exploration,\n", + "rather than an additional independent measurement with its own positional-error likelihood.\n", + "\n", + "Passing this check does not mean that a model fits the image. It must still reproduce the observed light through the" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "positions_threshold = 1.0" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Model and Analysis__\n", + "\n", + "We reuse the model from *Linear Profiles*: S\u00e9rsic lens light, an elliptical isothermal mass profile, external shear and\n", + "exponential source light. The two light-profile intensities are solved during each likelihood evaluation.\n", + "\n", + "The new ingredient belongs to the analysis. We create a `PositionsLH` object containing our marked positions and their\n", + "allowed source-plane separation, then pass it alongside the imaging dataset to `AnalysisImaging`.\n", + "\n", + "This illustrates the separation introduced at the start of the tutorial. We have added a constraint to the analysis" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "lens = af.Model(\n", + " al.Galaxy,\n", + " redshift=0.5,\n", + " bulge=al.lp_linear.Sersic,\n", + " mass=al.mp.Isothermal,\n", + ")\n", + "\n", + "source = af.Model(\n", + " al.Galaxy,\n", + " redshift=1.0,\n", + " bulge=al.lp_linear.ExponentialCore,\n", + ")\n", + "\n", + "field = af.Model(\n", + " al.MassField,\n", + " redshift=0.5,\n", + " shear=al.mp.ExternalShear,\n", + ")\n", + "\n", + "model = af.Collection(\n", + " galaxies=af.Collection(lens=lens, source=source),\n", + " fields=field,\n", + ")\n", + "\n", + "positions_likelihood = al.PositionsLH(\n", + " positions=positions,\n", + " threshold=positions_threshold,\n", + ")\n", + "\n", + "analysis = al.AnalysisImaging(\n", + " dataset=dataset,\n", + " positions_likelihood_list=[positions_likelihood],\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Search and Result__\n", + "\n", + "Run Nautilus using this model and analysis. The search explores the same physical parameters as before, but the\n", + "analysis now discourages mass models that trace our marked features to widely separated source locations.\n", + "\n", + "This can help the search avoid unsuitable regions of parameter space. It does not guarantee that the search finds the\n", + "global maximum, and incorrectly chosen positions or an overly restrictive threshold can steer it away from a good\n", + "solution.\n", + "\n", + "Inspect the fitted image and normalised residuals after the search finishes. Check the central lens galaxy and the\n", + "surrounding arcs, including their fainter emission. Satisfying the positions constraint is only one requirement; the" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "search = af.Nautilus(\n", + " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", + " name=\"tutorial_5_with_positions\",\n", + " unique_tag=dataset_name,\n", + " n_live=200,\n", + " n_batch=50,\n", + " iterations_per_quick_update=2500,\n", + ")\n", + "\n", + "result = search.fit(model=model, analysis=analysis)\n", + "\n", + "print(result.info)\n", + "\n", + "aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Contaminating Light__\n", + "\n", + "A large circular mask can contain light from objects other than the lens galaxy and its source. A neighbouring galaxy\n", + "may appear beside an arc, with its fainter outskirts overlapping the emission we want to fit.\n", + "\n", + "Our current light model contains only the main lens and source. If we ask it to explain the neighbouring galaxy too,\n", + "the search may distort those components to reproduce light that belongs to a different object.\n", + "\n", + "One approach is to include the neighbour explicitly in the model. We will explore this in Chapter 4. Here, we introduce\n", + "**noise scaling**, which reduces the influence of selected pixels on the fit while retaining our circular mask.\n", + "\n", + "This is useful when we want to prevent contaminating light from driving the fit, without introducing another light\n", + "profile and its free parameters.\n", + "\n", + "__Extra Galaxy Dataset__\n", + "\n", + "Load a second simulated image containing a neighbouring galaxy. Look towards the upper-right of the main lens, where\n", + "the extra galaxy's bright centre and extended light are visible.\n", + "\n", + "Follow its light towards the lensed arcs. The contamination is not confined to the galaxy's brightest pixels, and some\n", + "pixels contain light from more than one object.\n", + "\n", + "This example will show how we change the contribution of those pixels to the likelihood. We begin with the full image," + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "dataset_name_extra = \"lens_extra_galaxy\"\n", + "dataset_path_extra = Path(\"dataset\") / \"imaging\" / dataset_name_extra\n", + "\n", + "al.util.dataset.simulate_if_needed(\n", + " dataset_path_extra,\n", + " simulator=\"scripts/simulator/lens_extra_galaxy.py\",\n", + ")\n", + "\n", + "dataset_extra = al.Imaging.from_fits(\n", + " data_path=dataset_path_extra / \"data.fits\",\n", + " noise_map_path=dataset_path_extra / \"noise_map.fits\",\n", + " psf_path=dataset_path_extra / \"psf.fits\",\n", + " pixel_scales=0.1,\n", + ")\n", + "\n", + "aplt.subplot_imaging_dataset(dataset=dataset_extra)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Extra Galaxy Region__\n", + "\n", + "The simulator supplies a file identifying a region around the extra galaxy. For real observations, we would define this\n", + "region ourselves after inspecting the image, for example using the workspace's data-preparation GUI.\n", + "\n", + "This selection has a different purpose from our main circular mask. The circular mask defines the overall region we\n", + "fit. The extra-galaxy selection identifies pixels within that region whose influence we want to reduce.\n", + "\n", + "The supplied region surrounds the neighbour's centre and extends into its fainter light. It is an approximation to the\n", + "contaminated area, rather than a boundary at which the galaxy's light suddenly ends.\n", + "\n", + "We load the file with `invert=True` so that its selected pixels follow the convention expected by the noise-scaling" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "mask_extra_galaxies = al.Mask2D.from_fits(\n", + " file_path=dataset_path_extra / \"mask_extra_galaxies.fits\",\n", + " pixel_scales=dataset_extra.pixel_scales,\n", + " invert=True,\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Noise Scaling__\n", + "\n", + "Recall that the imaging likelihood compares the difference between the data and model with the uncertainty in each\n", + "pixel. A difference has less influence when the assigned uncertainty is larger.\n", + "\n", + "Noise scaling uses this relationship to give contaminated pixels almost no weight. By default, the method below sets\n", + "their noise values to a very large number and their data values to zero.\n", + "\n", + "This is a deliberate modification of the data used by the analysis. It does not mean that the original measurement had\n", + "such a large uncertainty, and it does not subtract a physical model of the neighbouring galaxy.\n", + "\n", + "Apply the noise scaling first, then apply the same 3.0-arcsecond circular mask. The selected pixels remain inside the" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "dataset_scaled = dataset_extra.apply_noise_scaling(\n", + " mask=mask_extra_galaxies,\n", + ")\n", + "\n", + "mask = al.Mask2D.circular(\n", + " shape_native=dataset_scaled.shape_native,\n", + " pixel_scales=dataset_scaled.pixel_scales,\n", + " radius=3.0,\n", + ")\n", + "\n", + "dataset_scaled = dataset_scaled.apply_mask(mask=mask)\n", + "\n", + "aplt.subplot_imaging_dataset(dataset=dataset_scaled)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Interpreting the Scaled Dataset__\n", + "\n", + "Compare the data, noise-map and signal-to-noise panels. In the selected region, the data have been set to zero and the\n", + "noise has been increased. The galaxy has not physically disappeared; we have told the analysis to obtain almost no\n", + "information from those pixels.\n", + "\n", + "This also means losing information about any lens or source light in the same pixels. Noise scaling cannot distinguish\n", + "which galaxy emitted a photon. Where the neighbour overlaps important parts of an arc, explicitly modeling its light\n", + "may preserve more useful information.\n", + "\n", + "Light outside the selected region can still affect the fit, including faint wings spread by the PSF. Inspect the\n", + "surrounding pixels rather than assuming the selection removes every contribution from the neighbour.\n", + "\n", + "There is a further distinction for lensing: reducing the weight of a galaxy's light does not remove its gravitational\n", + "deflection. The extra galaxy in this simulation also has mass. Whether that mass must be included in the lens model is\n", + "a separate question, which we develop in Chapter 4.\n", + "\n", + "To use this prepared dataset, we would pass it to `AnalysisImaging`. The analysis then uses the modified data and noise" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "analysis_scaled = al.AnalysisImaging(dataset=dataset_scaled)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Changing the noise map changes the likelihood itself. We should therefore not interpret a change in the absolute likelihood before and after scaling as evidence that we have found a better physical model.\n", + "\n", + "__Interferometer Data__\n", + "\n", + "In Chapter 1, we saw that an interferometer measures **visibilities**, rather than the image pixels used throughout\n", + "this chapter.\n", + "\n", + "We can still describe the lens using mass profiles and the source using light profiles. The model predicts a lensed\n", + "image, but that image must be transformed into predicted visibilities before we compare it with the observations.\n", + "\n", + "`AnalysisInterferometer` performs this comparison using the measured visibilities and their uncertainties. We replace\n", + "the imaging dataset and analysis with their interferometer equivalents, while retaining the familiar process of\n", + "defining a model and running a search.\n", + "\n", + "The model is built using the same composition API for every dataset type: `af.Model` defines profiles and galaxies, and\n", + "`af.Collection` groups them into the complete model. We use the same syntax to assign priors, fix parameters and link\n", + "parameters between components. The appropriate physical components may change, but we do not need to learn a different\n", + "way of constructing models.\n", + "\n", + "The mask has a different role here. It defines the real-space grid on which we predict the lensed emission; it does not\n", + "select observed image pixels for the likelihood. The measurements being fitted are the visibilities.\n", + "\n", + "The workspace's `scripts/interferometer/modeling.py` demonstrates the complete procedure. The light and mass profiles,\n", + "priors and search tools should already feel familiar\u2014the main change is how the model predicts the measured quantities.\n", + "\n", + "__Point-Source Data__\n", + "\n", + "For a multiply imaged compact source, such as a quasar, we may measure the positions of its separate images and their\n", + "positional uncertainties. These measurements can constrain the lens mass without requiring us to fit an extended arc\n", + "pixel by pixel.\n", + "\n", + "A `PointDataset` stores the measurements, and `AnalysisPoint` connects them to the lens model. The analysis evaluates\n", + "how consistently the model explains the observed image positions, using the chosen positional likelihood.\n", + "\n", + "This differs from the positions penalty introduced earlier. That penalty provides a broad consistency constraint\n", + "alongside an imaging fit. A point-source analysis treats the measured positions and their uncertainties as the\n", + "observations to be fitted.\n", + "\n", + "The physical model also changes where appropriate: a point source replaces the extended source-light profile. However,\n", + "we still define mass profiles, assign priors and use a search to explore their parameters.\n", + "\n", + "See `autolens_workspace/scripts/point_source/modeling.py` for a complete example.\n", + "\n", + "__Weak-Lensing Data__\n", + "\n", + "Weak lensing uses the small distortions of many background galaxies to constrain a foreground mass distribution. Rather\n", + "than fitting bright arcs from one strongly lensed source, we work with a catalogue of galaxy positions and shape\n", + "measurements.\n", + "\n", + "Each galaxy has an unknown intrinsic shape as well as measurement uncertainty. A single elongated galaxy therefore does\n", + "not tell us the lensing distortion directly. The information emerges from the pattern across many galaxies.\n", + "\n", + "A `WeakDataset` contains the measurements used for this comparison. `AnalysisWeak` evaluates the lens model's predicted\n", + "distortion at the galaxy positions and compares it with the measured shapes, accounting for the adopted uncertainties.\n", + "\n", + "Once again, the search does not need a new interface. It explores the mass-model parameters using the likelihood\n", + "returned by the analysis.\n", + "\n", + "Chapter 4 develops weak-lensing modeling further. The workspace's `scripts/weak/modeling.py` also shows how these\n", + "components fit together.\n", + "\n", + "__Multiple Datasets__\n", + "\n", + "Separating datasets from models also allows several observations to constrain the same physical system.\n", + "\n", + "Imagine observing one lens in two wavebands. Both images are produced by the same foreground mass distribution, but the\n", + "lens and source brightness can differ between wavebands. Each observation also has its own PSF and noise map.\n", + "\n", + "We can give each dataset its own Analysis object and connect both to a model that shares the mass parameters while\n", + "allowing appropriate light-profile parameters to differ.\n", + "\n", + "For datasets that are independent given the model, their likelihoods multiply. Equivalently, their log likelihoods add:\n", + "\n", + "$$\n", + "\\ln \\mathcal{L}_{\\mathrm{total}} = \\ln \\mathcal{L}_1 + \\ln \\mathcal{L}_2.\n", + "$$\n", + "\n", + "The search then explores parameter values using this combined likelihood. A proposed mass model must explain both\n", + "observations, rather than fitting either one in isolation.\n", + "\n", + "This can also combine different kinds of measurements, such as imaging and point-source positions. We must take care\n", + "with information shared between datasets: treating the same measurement twice as independent would count its\n", + "information twice.\n", + "\n", + "Joint modeling is an advanced topic. The workspace's `scripts/multi_dataset/` examples explain how to construct these\n", + "analyses and decide which parameters to share. For now, the important idea is that each dataset can have its own\n", + "prediction and likelihood calculation while contributing to a common model fit.\n", + "\n", + "__Wrap Up__\n", + "\n", + "We began with familiar imaging data and examined how different information enters the fit. The circular mask retains\n", + "the lens, arcs and their surroundings. Positions constraints help identify suitable mass models. Noise scaling reduces\n", + "the influence of selected contaminated pixels.\n", + "\n", + "These changes belong to different parts of the analysis, but they all fit into the same structure:\n", + "\n", + "- The **dataset** contains the measurements and their uncertainties.\n", + "- The **model** describes the physical system and its free parameters.\n", + "- The **Analysis** object connects the model to the observations and calculates their likelihood.\n", + "- The **search** explores the parameters using that likelihood and the priors.\n", + "\n", + "This separation is why the tools learnt in this chapter extend beyond fitting one image. Whether we fit imaging,\n", + "visibilities, point-source positions or weak-lensing shapes, we compose the model using the same `af.Model` and\n", + "`af.Collection` API. We adapt its physical components to the problem, select the appropriate dataset and Analysis\n", + "objects, and pass them to the search through the familiar `search.fit(model=model, analysis=analysis)` interface.\n", + "\n", + "In the next tutorial, we will use this flexibility to connect several fits in a sequence. An initial, simpler analysis\n", + "will provide information that helps us construct and fit a more complex model.\n", + "\n", + "**\ud83e\udd16 Ask AI:** I have two images of the same gravitational lens taken in different wavebands. Which parts of the physical model might be shared, which might differ, and what must each Analysis object know about its own observation?" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.1" + }, + "colab": { + "aiContexts": { + "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_5_data_and_likelihoods.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" + } + }, + "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file 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 deleted file mode 100644 index 71c9ec1..0000000 --- a/notebooks/chapter_2_lens_modeling/tutorial_6_masking_and_positions.ipynb +++ /dev/null @@ -1,481 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 6: Masking and Positions\n", - "=================================\n", - "\n", - "We have learnt everything we need to know about non-linear searches to model a strong lens and infer a good lens\n", - "model solution. Now, lets consider masking in more detail, something we have not given much consideration previously.\n", - "We'll also learn a neat trick to improve the speed and accuracy of a non-linear search.\n", - "\n", - "__Contents__\n", - "\n", - "- **Initial Setup:** we'll use the same strong lensing data as tutorial 1, where.\n", - "- **Dataset Auto-Simulation:** Simulate the dataset via its simulator script if it is not on your hard-disk.\n", - "- **Mask:** Define the 2D mask applied to the dataset for the model-fit.\n", - "- **Model + Analysis:** Compose the lens model and create the analysis that fits it using the chosen mask.\n", - "- **Run Time:** Profiling the expected run time of the model-fit.\n", - "- **Search:** Configure the non-linear search used to fit the model.\n", - "- **Discussion:** So, we can choose the mask we use in a model-fit.\n", - "- **Positions Thresholding:** We can manually specify a set of image-plane (y,x) coordinates corresponding to the multiple images.\n", - "- **Wrap Up:** Summary of the script and next steps." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Google Colab Setup__\n", - "\n", - "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "jupyter": { - "source_hidden": true - } - }, - "outputs": [], - "source": [ - "# @title Set up Google Colab { display-mode: \"form\" }\n", - "try:\n", - " import google.colab\n", - "except ImportError:\n", - " from autolens import setup_colab as _setup_colab\n", - "else:\n", - " import importlib\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.check_call(\n", - " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", - " )\n", - " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", - "\n", - "_setup_colab.setup(\"howtolens\")" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autolens import jax_wrapper # Sets JAX environment before other imports\n", - "\n", - "from autolens import setup_notebook; setup_notebook()\n", - "\n", - "from pathlib import Path\n", - "import autolens as al\n", - "import autolens.plot as aplt\n", - "import autofit as af" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Initial Setup__\n", - "\n", - "we'll use the same strong lensing data as tutorial 1, where:\n", - "\n", - " - The lens galaxy's total mass distribution is a `IsothermalSph`.\n", - " - The source galaxy's light is a `ExponentialCoreSph`." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "dataset_name = \"simple__no_lens_light__mass_sis\"\n", - "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Dataset Auto-Simulation__\n", - "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "al.util.dataset.simulate_if_needed(\n", - " dataset_path, simulator=\"scripts/simulator/no_lens_light__mass_sis.py\"\n", - ")\n", - "\n", - "dataset = 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.1,\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Mask__\n", - "\n", - "In this tutorial, our data only contained the light from the lensed source. We therefore want our mask to include all \n", - "of the source's light. There are different shaped masks that we can use to achieve this, and we can compare them by\n", - "plotting masks on the imaging data.\n", - "\n", - "Below, we use a 'circular_annular' mask, which unlike the 'circular' masks we have used previous includes an additional\n", - "input parameter 'inner_radius' that removes the central regions of the image. Below, we use too large of a value of\n", - "`inner_radius=0.8`, which cuts into the lensed source galaxy's light, clearly this isn't a good mask." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mask = al.Mask2D.circular_annular(\n", - " shape_native=dataset.shape_native,\n", - " pixel_scales=dataset.pixel_scales,\n", - " inner_radius=0.8,\n", - " outer_radius=2.7,\n", - ")\n", - "\n", - "dataset = dataset.apply_mask(mask=mask)\n", - "\n", - "aplt.subplot_imaging_dataset(dataset=dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can decrease the `inner_radius` to correct for this." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "dataset = 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.1,\n", - ")\n", - "\n", - "mask = al.Mask2D.circular_annular(\n", - " shape_native=dataset.shape_native,\n", - " pixel_scales=dataset.pixel_scales,\n", - " inner_radius=0.4,\n", - " outer_radius=2.7,\n", - ")\n", - "\n", - "dataset = dataset.apply_mask(mask=mask)\n", - "\n", - "aplt.subplot_imaging_dataset(dataset=dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Model + Analysis__\n", - "\n", - "Lets fit the data using this mask, by creating the search as per usual. \n", - "\n", - "Note that the `imaging` data with this mask applied is passed into the `AnalysisImaging` object, ensuring that this \n", - "is the mask the model-fit uses. \n", - "\n", - "we also use a linear light profile, simplifying the model as discussed in the previous tutorial." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "model = af.Collection(\n", - " galaxies=af.Collection(\n", - " lens=af.Model(al.Galaxy, redshift=0.5, mass=al.mp.IsothermalSph),\n", - " source=af.Model(al.Galaxy, redshift=1.0, bulge=al.lp_linear.ExponentialCoreSph),\n", - " ),\n", - ")\n", - "\n", - "search = af.Nautilus(\n", - " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", - " name=\"tutorial_6_with_custom_mask\",\n", - " unique_tag=dataset_name,\n", - " n_live=80,\n", - " n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2.\n", - " iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations\n", - ")\n", - "\n", - "analysis = al.AnalysisImaging(dataset=dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Run Time__\n", - "\n", - "Smaller masks speed up the log likelihood evaluation time, because fewer image pixels mean fewer calculations are\n", - "required to evaluate the model image's fit to the data. \n", - "\n", - "This includes computing fewer deflection angles from the mass profiles and performing fewer 2D convolutions of the PSF\n", - "to account for blurring.\n", - "\n", - "__Search__\n", - "\n", - "Run the non-linear search." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search.fit(model=model, analysis=analysis)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Discussion__\n", - "\n", - "So, we can choose the mask we use in a model-fit. We know that we want the mask to not remove any of the lensed source \n", - "galaxy's light, but is this the 'right' mask? What is the 'right' mask? Maybe we want a bigger mask? a smaller mask?\n", - "\n", - "When it comes to choosing a mask, we are essentially balancing two things: computational run-time and accuracy. When we\n", - "use a bigger mask the model-fit will take longer to perform. Why? Because a bigger mask includes more image-pixels \n", - "in the analysis, and for every additional image-pixel we have to compute its deflection angles, trace it to the source\n", - "plane, fit its light, etc.\n", - " \n", - "If run-time was not a consideration we would always choose a bigger mask, for two reasons:\n", - "\n", - " 1) The lensed source galaxy may have very faint emission that when you choose the mask you simply do not notice. \n", - " Overly aggressive masking runs the risk of us inadvertantly masking out some of the source's light, which would \n", - " otherwise better constrain the lens model!\n", - " \n", - " 2) When the data is fitted with a model image, the fit is performed only within the masked region. For certain lens\n", - " models it is possible that it may produce extraneous source emission outside of the masked region that is not actually\n", - " observed in the lens data itself. If this region had not been masked-out, the model would create residuals in these\n", - " locations and reduce the value of likelihood appropriately, whereas if it is masked out this reduction in likelihood is \n", - " not fed through to the analysis. \n", - "\n", - "As you use **PyAutoLens** more you will get a feel for how fast a model-fit will run given the quality of data, lens \n", - "model complexity, non-linear search settings, etc. As you develop this intuition, I recommend that you always aim to \n", - "use as large of a mask as possible (whilst still achieving reasonable run-times). Aggressive masking will make \n", - "**PyAutoLens** run very fast, but could lead you to infer an incorrect lens model! \n", - "\n", - "If your data includes the light of the foreground lens galaxy you pretty much have no choice but to use a large \n", - "circular mask, because it is important to capture the lens galaxy's extended emission. This will probably extend well \n", - "beyond the light of the source. Nevertheless, the size of this circular mask will still play an important role in the\n", - "overall run time!\n", - "\n", - "__Positions Thresholding__\n", - "\n", - "We can manually specify a set of image-plane (y,x) coordinates corresponding to the multiple images of a strong lens's \n", - "source-galaxy. If we supply these positions, every time a lens model is fitted **PyAutoLens** will first check that \n", - "these pixels trace within a specified arc-second threshold of one another in the source-plane (which is controlled \n", - "by an input `position_threshold`). If they do not trace within this threshold of one another, a large penalty term\n", - "is added to the likelihood.\n", - "\n", - "This provides two benefits:\n", - "\n", - " 1) The model-fit is faster as the non-linear search as when searching regions of parameter space where the mass-model \n", - " is clearly not accurate, a computationally fast ray-tracing of 2 or 4 image-pixels is performed.\n", - " \n", - " 2) By removing these solutions, a global-maximum solution may be reached instead of a local-maxima. This is \n", - " because removing the incorrect mass models makes the non-linear parameter space less complex.\n", - "\n", - "Once we begin to sample accurate lens models, the position threshold will be met and no penalty term will be included\n", - "in the likelihood function.\n", - "\n", - "We can create the image-plane positions using the `Grid2DIrregular` object, which defines a grid of $(y,x)$ coordinates\n", - "which are on an irregular grid (in contrast to the `Grid2D` object which assumes the $(y,x)$ coordinates are on a \n", - "regular uniform grid). T" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "positions = al.Grid2DIrregular(\n", - " values=[(1.6, 0.0), (0.0, 1.6), (-1.6, 0.0), (0.0, -1.6)]\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To check that the image positions are accurate, we plot them as marked points on the image using `positions=`." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "aplt.subplot_imaging_dataset(dataset=dataset, positions=positions)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For the positions to be used in a model-fit, we create a `PositionsLH` object which we pass to \n", - "the `AnalysisImaging` class. \n", - "\n", - "This object includes the `threshold` that the positions must trace within during model-fit for a lens model to not\n", - "receive a likelihood penalty.\n", - "\n", - "The threshold of 1.0\" is large. For an accurate lens model we would anticipate the positions trace within < 0.01\" of\n", - "one another. However, we only want the threshold to aid the non-linear with the choice of mass model in the intiial \n", - "fit.\n", - "\n", - "We choose an excessively large threshold for two reasons:\n", - "\n", - " 1) Even with such a large value, we still apply a likelihood penalty to the *vast majority* of unphysical lens models \n", - " which trace the pixels even further away in the source plane.\n", - " \n", - " 2) If we set the threshold too low, there is a risk we may apply the penalty to physically plausible solutions. \n", - " A conservative value of 1.0\" therefore a wise choice." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "positions_likelihood = al.PositionsLH(positions=positions, threshold=1.0)\n", - "\n", - "analysis = al.AnalysisImaging(\n", - " dataset=dataset, positions_likelihood_list=[positions_likelihood]\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Run Time__\n", - "\n", - "Checking a few positions is cheaper than evaluating the full image likelihood. Rejecting unsuitable mass models early\n", - "can therefore speed up the initial exploration of parameter space; the benefit depends on the model and dataset.\n", - "\n", - "__Search__\n", - "\n", - "Run the non-linear search." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search = af.Nautilus(\n", - " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", - " name=\"tutorial_6_with_positions\",\n", - " unique_tag=dataset_name,\n", - " n_live=80,\n", - " n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2.\n", - " iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations\n", - ")\n", - "\n", - "print(\n", - " \"The non-linear search has begun running - checkout the output/howtolens/chapter_2/tutorial_6_with_positions\"\n", - " \" folder for live output of the results, images and lens model.\"\n", - " \" This Jupyter notebook cell with progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", - "search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"Search has finished run - you may now continue the notebook.\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Wrap Up__\n", - "\n", - "You may now wish to checkout the `autolens_workspace/*/imaging/data_preparation` package. This includes tools for \n", - "creating custom masks and marking the positions on a strong lens (via a GUI) so you can use them in a model-fit.\n", - "\n", - "There are two things you should bare in mind in terms of masking and positions:\n", - "\n", - " 1) Customizing the mask and positions for the analysis of one strong lens gets the analysis running fast and can \n", - " provide accurate non-linear sampling. However, for a large sample of lenses, this high level of customization may take \n", - " a lot of time. \n", - " \n", - " 2) When using positions, we must be *extremely* careful. It is often unclear whether a lensed source consists of one \n", - " or more galaxies, and each galaxy may have multiple distinct sources of light. When you mark the positions, they may \n", - " not truly originate from the same location in the source-plane. This is why the conservative positions threshold of\n", - " 1.0\" is wise, as it is sufficiently large that even if the detailed structure of the source means we mark the positions\n", - " incorrectly it will not mean that we remove physically plausible mass models. " - ] - } - ], - "metadata": { - "anaconda-cloud": {}, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - }, - "colab": { - "aiContexts": { - "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 — 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" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file diff --git a/notebooks/chapter_2_lens_modeling/tutorial_6_search_chaining.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_6_search_chaining.ipynb new file mode 100644 index 0000000..80cf3ba --- /dev/null +++ b/notebooks/chapter_2_lens_modeling/tutorial_6_search_chaining.ipynb @@ -0,0 +1,668 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Tutorial 6: Search Chaining\n", + "===========================\n", + "\n", + "Look again at our lens image. The foreground galaxy's light, its gravitational deflection and the background source all\n", + "contribute to what we observe. Fitting them together requires the search to explore several connected parts of the\n", + "model.\n", + "\n", + "Yet we do not always need to keep every part free throughout an analysis. Once we have obtained a satisfactory\n", + "description of the foreground light, we can hold aspects of that description fixed while investigating the mass\n", + "distribution in greater detail.\n", + "\n", + "**Search chaining** connects a sequence of fits in this way. Each search has a particular purpose, and its result\n", + "supplies information used to construct a later analysis.\n", + "\n", + "In this tutorial, an initial fit will describe the lens and source light using multi-Gaussian expansions, alongside an\n", + "isothermal mass profile and external shear. We will then fix the fitted lens-light geometry and replace the isothermal\n", + "mass profile with a power-law profile whose slope is free.\n", + "\n", + "The second search can therefore investigate a more flexible mass model without simultaneously rediscovering the\n", + "foreground light geometry. We will also use the first result to estimate the positions constraint introduced in the\n", + "previous tutorial.\n", + "\n", + "__Contents__\n", + "\n", + "- **The Search Chain:** Give each search a distinct role.\n", + "- **Dataset and Mask:** Reuse the imaging dataset and circular mask.\n", + "- **Multi-Gaussian Expansions:** Construct lens and source light models with the MGE helper.\n", + "- **Model 1:** Compose the initial isothermal lens model.\n", + "- **Search 1:** Find a candidate solution with Prodigy.\n", + "- **Inspecting Search 1:** Check the fit before carrying information forward.\n", + "- **Fixing the Lens-Light Geometry:** Use fitted instances while retaining linear intensities.\n", + "- **The Power-Law Mass Model:** Allow the radial mass slope to vary.\n", + "- **Model 2:** Reduce the search to twelve non-linear parameters.\n", + "- **Automatically Estimated Positions:** Derive a positions constraint from the first fit.\n", + "- **Search 2:** Explore the revised model and its uncertainties with Nautilus.\n", + "- **Result 2:** Inspect residuals and posterior distributions.\n", + "- **Conditional Uncertainties:** Understand the consequences of fixed geometry.\n", + "- **Search Chaining and SLaM:** Connect this example to reusable pipelines.\n", + "- **Wrap Up:** Inspecting chained fits and continuing to Chapter 3.\n", + "\n", + "__The Search Chain__\n", + "\n", + "Our first search aims to obtain a useful description of the image relatively quickly. We use `MultiStartProdigy`, which\n", + "runs gradient-based optimisations from multiple starting points.\n", + "\n", + "This gives us a candidate solution to inspect. It does not provide the posterior samples needed to describe parameter\n", + "uncertainties, and we must check its fitted image and residuals before using its result.\n", + "\n", + "Our second search uses Nautilus to explore the revised model more thoroughly. The lens-light centres and shapes will be\n", + "fixed to their fitted values, while the mass and source parameters remain free. The light-profile intensities will\n", + "still be solved during each likelihood evaluation.\n", + "\n", + "This distinction matters: we are fixing the geometry of the foreground light, rather than subtracting a fixed image and\n", + "assuming that its brightness can never change.\n", + "\n", + "Holding fitted quantities fixed is also an assumption. The second result is conditional on that choice and does not\n", + "propagate uncertainty in the fixed lens-light geometry. Later in the tutorial, we will discuss when that approximation" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Google Colab Setup__\n", + "\n", + "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": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, + "outputs": [], + "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", + "try:\n", + " import google.colab\n", + "except ImportError:\n", + " from autolens import setup_colab as _setup_colab\n", + "else:\n", + " import importlib\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.check_call(\n", + " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", + " )\n", + " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", + "\n", + "_setup_colab.setup(\"howtolens\")" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from autolens import jax_wrapper # Sets JAX environment before other imports\n", + "\n", + "from autolens import setup_notebook; setup_notebook()\n", + "\n", + "from pathlib import Path\n", + "import autofit as af\n", + "import autolens as al\n", + "import autolens.plot as aplt\n" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Dataset and Mask__\n", + "\n", + "We use the same `lens_sersic` imaging dataset and 3.0-arcsecond circular mask as the previous tutorial.\n", + "\n", + "Inspect the central lens galaxy and the surrounding arcs. The first fit must describe both: an inaccurate source or" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "dataset_name = \"lens_sersic\"\n", + "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name\n", + "\n", + "al.util.dataset.simulate_if_needed(\n", + " dataset_path,\n", + " simulator=\"scripts/simulator/lens_sersic.py\",\n", + ")\n", + "\n", + "dataset = 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.1,\n", + ")\n", + "\n", + "mask_radius = 3.0\n", + "\n", + "mask = al.Mask2D.circular(\n", + " shape_native=dataset.shape_native,\n", + " pixel_scales=dataset.pixel_scales,\n", + " radius=mask_radius,\n", + ")\n", + "\n", + "dataset = dataset.apply_mask(mask=mask)\n", + "\n", + "aplt.subplot_imaging_dataset(dataset=dataset)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Multi-Gaussian Expansions__\n", + "\n", + "We use the MGE construction introduced in *Linear Profiles*. Within each galaxy's Gaussian group, the profiles share a\n", + "centre and elliptical shape. Their widths are fixed, and their intensities are solved together during the fit.\n", + "\n", + "The lens and source have separate groups, so their centres and shapes remain independent.\n", + "\n", + "To avoid repeating the construction loops from Tutorial 4, we use `al.model_util.mge_model_from`. This helper builds an\n", + "ordinary model from linear Gaussian profiles; it does not fit the data or introduce a different model-composition API.\n", + "\n", + "The lens uses 30 Gaussians, with widths spanning 0.01 to 3.0 arcseconds. The source uses 15 Gaussians spanning 0.0001\n", + "to 1.0 arcseconds in the source plane. These ranges provide components on different scales; they do not imply that the\n", + "smallest components are individually resolved by the observations.\n", + "\n", + "In this helper, `mask_radius` sets the largest Gaussian width. The source's value of 1.0 therefore controls its" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "lens_bulge = al.model_util.mge_model_from(\n", + " mask_radius=mask_radius,\n", + " total_gaussians=30,\n", + " centre_prior_is_uniform=True,\n", + " sigma_min=dataset.pixel_scales[0] / 10.0,\n", + ")\n", + "\n", + "source_bulge = al.model_util.mge_model_from(\n", + " mask_radius=1.0,\n", + " total_gaussians=15,\n", + " centre_prior_is_uniform=False,\n", + " sigma_min=1.0e-4,\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Model 1__\n", + "\n", + "Combine these light profiles with an elliptical isothermal mass profile and external shear.\n", + "\n", + "The isothermal profile gives the first search a mass model with a fixed radial slope. In the second search, we will\n", + "relax this restriction using a power-law profile.\n", + "\n", + "We do not force the mass to share the lens light's centre or elliptical shape. The first fit must determine those\n", + "properties independently from the image.\n", + "\n", + "Despite containing 45 Gaussian light profiles, this model has only 15 non-linear parameters: four describe each\n", + "galaxy's shared light geometry, five describe the isothermal mass profile, and two describe external shear. The\n", + "Gaussian widths are fixed and their intensities are solved linearly.\n", + "\n", + "Inspect `model_1.info` and its diagram to identify those independent parameters before fitting." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "lens = af.Model(\n", + " al.Galaxy,\n", + " redshift=0.5,\n", + " bulge=lens_bulge,\n", + " mass=al.mp.Isothermal,\n", + ")\n", + "\n", + "source = af.Model(al.Galaxy, redshift=1.0, bulge=source_bulge)\n", + "\n", + "field = af.Model(al.MassField, redshift=0.5, shear=al.mp.ExternalShear)\n", + "\n", + "model_1 = af.Collection(\n", + " galaxies=af.Collection(lens=lens, source=source),\n", + " fields=field,\n", + ")\n", + "\n", + "print(model_1.info)\n", + "\n", + "af.ModelPlotter(model_1).figure()" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Search 1__\n", + "\n", + "We begin with `MultiStartProdigy`, using the settings introduced in the optional searches tutorial: 48 starting points\n", + "and up to 300 gradient steps per start.\n", + "\n", + "Multiple starting points give the optimiser opportunities to find different solutions. They do not guarantee that it\n", + "finds the best one, so we will inspect the result before carrying any information forward.\n", + "\n", + "`batch_size=4` limits how many starts are processed together, reducing memory use. It does not reduce the total number\n", + "of starts.\n", + "\n", + "The analysis fits the imaging data without a positions constraint. After this search, we will use the fitted model to\n", + "estimate positions for the next analysis.\n", + "\n", + "Prodigy's job here is to find a good-fitting set of parameter values. It does not attempt to map out the full range of\n", + "plausible solutions or calculate posterior uncertainty intervals\u2014the parameter \"errors\".\n", + "\n", + "This narrower task is one reason we expect it to finish sooner than a thorough Nautilus run, alongside its use of\n", + "gradients. It is therefore useful for our first stage, where we need a satisfactory model to build on rather than a" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "search_1 = af.MultiStartProdigy(\n", + " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", + " name=\"tutorial_6_search_1\",\n", + " unique_tag=dataset_name,\n", + " n_starts=48,\n", + " n_steps=300,\n", + " batch_size=4,\n", + ")\n", + "\n", + "analysis_1 = al.AnalysisImaging(dataset=dataset, use_jax=True)\n", + "\n", + "result_1 = search_1.fit(model=model_1, analysis=analysis_1)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "JAX supplies the gradients used by Prodigy. Its initial compilation adds a setup cost; later evaluations reuse the compiled calculation. The total run time depends on the hardware, model and number of optimisation steps required.\n", + "\n", + "__Inspecting Search 1__\n", + "\n", + "Inspect the fitted image and normalised residuals before proceeding.\n", + "\n", + "Look first at the foreground galaxy. Does the MGE reproduce its centre, shape and extended light? Then examine the\n", + "arcs. A poor description of the source can affect how the fit divides overlapping light between the two galaxies.\n", + "\n", + "Search chaining carries information forward, including mistakes. Fixing the foreground geometry from a poor fit can\n", + "prevent the next search from correcting it.\n", + "\n", + "If substantial residual structure remains, investigate the first fit using the approaches from *Why Modeling Is Hard*.\n", + "More optimisation effort may help, but the model may also need additional freedom.\n", + "\n", + "A satisfactory result gives us a candidate lens-light geometry for the next stage. It does not establish its" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "print(result_1.info)\n", + "\n", + "aplt.subplot_fit_imaging(fit=result_1.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Fixing the Lens-Light Geometry__\n", + "\n", + "Until now, we have mainly constructed components using `af.Model`, which leaves selected parameters free for a search\n", + "to fit.\n", + "\n", + "`result_1.instance` instead contains components with numerical parameter values from the highest-likelihood solution\n", + "stored in the first result. We can take its fitted lens-light basis and place that instance into our next model.\n", + "\n", + "Its Gaussian centres and elliptical shapes are then fixed. The widths were already fixed in the first search.\n", + "\n", + "The Gaussian profiles remain **linear light profiles**, however. Their intensities will still be solved during each\n", + "likelihood evaluation of the second fit. We therefore preserve the fitted geometry while allowing the brightness\n", + "assigned to the lens and source to adjust together.\n", + "\n", + "This differs from subtracting the first fit's lens-light image from the data. We continue to fit the original image," + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "lens_bulge_fixed = result_1.instance.galaxies.lens.bulge" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__The Power-Law Mass Model__\n", + "\n", + "The first search used an isothermal mass profile, whose radial density slope is fixed. We now replace it with\n", + "`PowerLaw`, allowing the slope to vary.\n", + "\n", + "The slope controls how quickly the mass density falls with radius. The isothermal case corresponds to `slope=2.0`;\n", + "allowing this parameter to vary lets the second search investigate steeper and shallower profiles.\n", + "\n", + "This extra freedom is scientifically useful, but it also introduces relationships with other parameters, including the\n", + "source size. We should not assume that adding the slope makes it independently or precisely measurable.\n", + "\n", + "We retain free mass-centre coordinates, ellipticity and Einstein radius, alongside external shear. The lens-light" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "lens_2 = af.Model(\n", + " al.Galaxy,\n", + " redshift=0.5,\n", + " bulge=lens_bulge_fixed,\n", + " mass=al.mp.PowerLaw,\n", + ")\n", + "\n", + "field_2 = af.Model(al.MassField, redshift=0.5, shear=al.mp.ExternalShear)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Model 2__\n", + "\n", + "The source MGE remains free to change its centre and shape. This is important because changing the mass profile changes\n", + "how the observed arcs map back to the source plane.\n", + "\n", + "We construct a fresh source model with the same settings as before. Its priors are not replaced with narrow\n", + "distributions derived from the first result.\n", + "\n", + "Combining it with the revised lens gives 12 non-linear parameters: six for the power-law mass profile, two for external\n", + "shear and four for the source geometry.\n", + "\n", + "We have added one mass parameter but removed four lens-light geometry parameters from the search. The second model\n", + "therefore has a more flexible mass profile and fewer non-linear parameters overall.\n", + "\n", + "Twelve non-linear parameters is fewer than we might expect for a model that includes foreground lens light, a flexible\n", + "mass profile, external shear and source light. The lens light is still present, but its fitted geometry no longer\n", + "contributes free parameters to the search, and its intensities are handled by the linear solve.\n", + "\n", + "This is a central benefit of the chain: we can retain a detailed description of the image while asking the second\n", + "search to explore fewer parameters.\n", + "\n", + "Compare the model summary and diagram with those from the first search. The foreground Gaussian geometry should now\n", + "have fixed numerical values, while the source geometry, mass parameters and shear remain free. The lens and source" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "source_bulge_2 = al.model_util.mge_model_from(\n", + " mask_radius=1.0,\n", + " total_gaussians=15,\n", + " centre_prior_is_uniform=False,\n", + " sigma_min=1.0e-4,\n", + ")\n", + "\n", + "source_2 = af.Model(al.Galaxy, redshift=1.0, bulge=source_bulge_2)\n", + "\n", + "model_2 = af.Collection(\n", + " galaxies=af.Collection(lens=lens_2, source=source_2),\n", + " fields=field_2,\n", + ")\n", + "\n", + "print(model_2.info)\n", + "\n", + "af.ModelPlotter(model_2).figure()" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Automatically Estimated Positions__\n", + "\n", + "In the previous tutorial, we supplied image positions explicitly. We can now estimate them from the first fitted model.\n", + "\n", + "The result uses its fitted source location and mass distribution to predict the corresponding multiple-image positions.\n", + "It then constructs a `PositionsLH` constraint for the next analysis.\n", + "\n", + "This carries a second kind of information between searches. Alongside the fitted lens-light geometry, we use the first\n", + "model's lensing geometry to help guide the next search.\n", + "\n", + "These positions are predictions from the first fit, rather than independently measured coordinates. Plot them over the\n", + "image and check that they correspond sensibly to the observed arcs. A poor first model can generate misleading" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "positions_likelihood = result_1.positions_likelihood_from(\n", + " factor=3.0,\n", + " minimum_threshold=0.2,\n", + ")\n", + "\n", + "aplt.subplot_imaging_dataset(\n", + " dataset=dataset,\n", + " positions=positions_likelihood.positions,\n", + ")\n", + "\n", + "print(\"Source-plane threshold:\", positions_likelihood.threshold)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The threshold is three times the source-plane separation calculated from the first model, with a minimum of 0.2 arcseconds. The minimum prevents the numerical precision of the predicted positions from imposing an unnecessarily tight constraint.\n", + "\n", + "As before, this is a broad consistency check rather than a positional-error measurement. Its calculation during the\n", + "search is extremely fast compared with evaluating the full imaging likelihood.\n", + "\n", + "__Search 2__\n", + "\n", + "We now return to Nautilus because we want more than a single good-fitting solution. We want posterior samples that\n", + "describe the range of plausible parameter values and allow us to calculate uncertainty intervals\u2014the parameter\n", + "\"errors\".\n", + "\n", + "Exploring those distributions requires more work than locating one solution, so we generally expect this stage to run\n", + "more slowly than the initial Prodigy optimisation. Fixing the lens-light geometry reduces that burden.\n", + "\n", + "Pass the positions constraint to a new Analysis object and fit `model_2`. We continue to use the original imaging data,\n", + "including the foreground light.\n", + "\n", + "The resulting uncertainties are conditional on the geometry we fixed. Nautilus explores the free parameters of this" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "analysis_2 = al.AnalysisImaging(\n", + " dataset=dataset,\n", + " positions_likelihood_list=[positions_likelihood],\n", + " use_jax=True,\n", + ")\n", + "\n", + "search_2 = af.Nautilus(\n", + " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", + " name=\"tutorial_6_search_2\",\n", + " unique_tag=dataset_name,\n", + " n_live=200,\n", + " n_batch=50,\n", + " iterations_per_quick_update=2500,\n", + ")\n", + "\n", + "result_2 = search_2.fit(model=model_2, analysis=analysis_2)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Result 2__\n", + "\n", + "Inspect the fitted image and normalised residuals again. Check both the arcs and the foreground galaxy: the fixed\n", + "lens-light geometry is still an assumption that the data can reveal to be inadequate.\n", + "\n", + "Compare the result with the first fit. The power-law slope is now free, so the mass model and reconstructed source may\n", + "change together. A change in the inferred source size need not indicate a failure; it can reflect a relationship\n", + "between source structure and the radial mass profile.\n", + "\n", + "This dataset was simulated with an isothermal mass profile, corresponding to a power-law slope of 2.0. Use that known\n", + "value as a check, while recognising that noise, the adopted light models and the fixed lens-light geometry can affect\n", + "the inferred result.\n", + "\n", + "Examine the posterior distributions as well as the highest-likelihood fit. Look for broad intervals and correlations,\n", + "particularly between the mass slope and source parameters. Those distributions contain information that the first" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "print(result_2.info)\n", + "\n", + "aplt.subplot_fit_imaging(fit=result_2.max_log_likelihood_fit)\n", + "\n", + "aplt.corner_anesthetic(samples=result_2.samples)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Conditional Uncertainties__\n", + "\n", + "The second search answers a specific question: which mass and source parameters are consistent with the data **given\n", + "the lens-light geometry we carried forward**?\n", + "\n", + "It allows the Gaussian intensities to adjust, but it does not explore alternative foreground centres or shapes. If\n", + "those geometric quantities are uncertain, their uncertainty can affect how the overlapping light is divided between the\n", + "lens and source.\n", + "\n", + "Fixing them can therefore make the reported mass and source uncertainties narrower than those from an analysis that\n", + "also explores the foreground geometry. It can also shift the inferred parameters if the fixed geometry is inaccurate.\n", + "\n", + "Search chaining makes this trade-off useful by allowing us to investigate the model in stages. It does not make the\n", + "trade-off disappear.\n", + "\n", + "For a final scientific analysis, we can test its importance by allowing the lens-light geometry to vary again,\n", + "repeating the fit with other plausible foreground descriptions, or constructing an analysis that propagates the\n", + "relevant uncertainty.\n", + "\n", + "We should also investigate whether the automatically estimated positions constraint is restrictive enough to influence\n", + "our conclusions. It was derived from an earlier fitted model, not from an independent observation.\n", + "\n", + "**\ud83e\udd16 Ask AI:** My chained fit gives a narrow uncertainty interval on the mass slope. How could fixing the foreground light geometry affect that interval, and what comparisons would help me assess it?\n", + "\n", + "__Search Chaining and SLaM__\n", + "\n", + "Our two searches had different jobs. The first used a relatively fast optimisation to obtain a description of the\n", + "foreground light and an initial lens model. The second fixed the foreground geometry, introduced a more flexible mass\n", + "profile and used Nautilus to explore the remaining parameter uncertainties.\n", + "\n", + "The second model contained fewer non-linear parameters even though its mass profile was more flexible. This is one of\n", + "the main benefits of fitting different parts of the system in stages.\n", + "\n", + "More elaborate chains follow the same principle. An initial source model can help configure a later source\n", + "reconstruction, a foreground-light fit can support a more detailed mass analysis, and an earlier lens model can supply\n", + "positions constraints for subsequent searches.\n", + "\n", + "PyAutoLens provides **SLaM**, short for **Source, Light and Mass**, to organise these stages into reusable modeling\n", + "pipelines. The workspace's `scripts/imaging/features/multi_gaussian_expansion/slam.py` provides a concrete example.\n", + "\n", + "__Wrap Up__\n", + "\n", + "A pipeline automates the sequence, but each stage still needs a suitable model and a result worth carrying forward.\n", + "Inspecting the intermediate fits remains essential.\n", + "\n", + "In Chapter 3, we will introduce pixelized source reconstructions, which describe source structure beyond the smooth\n", + "profiles used here. Search chaining will provide a way to connect those more detailed reconstructions to the tools we" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.1" + }, + "colab": { + "aiContexts": { + "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_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_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" + } + }, + "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file diff --git a/notebooks/chapter_2_lens_modeling/tutorial_7_results.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_7_results.ipynb deleted file mode 100644 index 1710ea0..0000000 --- a/notebooks/chapter_2_lens_modeling/tutorial_7_results.ipynb +++ /dev/null @@ -1,294 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 7: Results\n", - "===================\n", - "\n", - "In the previous tutorials, each search returned a `Result` object, which we used to plot the maximum log likelihood\n", - "fit each model-fit. In this tutorial, we'll take a look at the result object in a little more detail.\n", - "\n", - "__Contents__\n", - "\n", - "- **Initial Setup:** Run a separate fit to the Tutorial 1 dataset to obtain a `Result` object.\n", - "- **Dataset Auto-Simulation:** Simulate the dataset via its simulator script if it is not on your hard-disk.\n", - "- **Tracer & Fit:** In the previous tutorials, we saw that this result contains the maximum log likelihood fit, which.\n", - "- **Samples:** The result contains a lot more information about the model-fit.\n", - "- **Workspace:** We are not going into any more detail on the result variable in this tutorial, or in the.\n", - "- **Database:** Once a search has completed running, we have a set of results on our hard disk which we can.\n", - "- **Wrap Up:** Summary of the script and next steps." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Google Colab Setup__\n", - "\n", - "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "jupyter": { - "source_hidden": true - } - }, - "outputs": [], - "source": [ - "# @title Set up Google Colab { display-mode: \"form\" }\n", - "try:\n", - " import google.colab\n", - "except ImportError:\n", - " from autolens import setup_colab as _setup_colab\n", - "else:\n", - " import importlib\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.check_call(\n", - " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", - " )\n", - " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", - "\n", - "_setup_colab.setup(\"howtolens\")" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autolens import jax_wrapper # Sets JAX environment before other imports\n", - "\n", - "from autolens import setup_notebook; setup_notebook()\n", - "\n", - "from pathlib import Path\n", - "import autolens as al\n", - "import autolens.plot as aplt\n", - "import autofit as af" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Initial Setup__\n", - "\n", - "We use the same dataset as Tutorial 1 and run a separate fit to obtain a `Result` object. Here, the source uses an\n", - "ordinary light profile, so its intensity is explored by the non-linear search. This setup does not reload the\n", - "Tutorial 1 result." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "dataset_name = \"simple__no_lens_light__mass_sis\"\n", - "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Dataset Auto-Simulation__\n", - "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "al.util.dataset.simulate_if_needed(\n", - " dataset_path, simulator=\"scripts/simulator/no_lens_light__mass_sis.py\"\n", - ")\n", - "\n", - "dataset = 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.1,\n", - ")\n", - "\n", - "mask_radius = 3.0\n", - "\n", - "mask = al.Mask2D.circular(\n", - " shape_native=dataset.shape_native,\n", - " pixel_scales=dataset.pixel_scales,\n", - " radius=mask_radius,\n", - ")\n", - "\n", - "dataset = dataset.apply_mask(mask=mask)\n", - "\n", - "model = af.Collection(\n", - " galaxies=af.Collection(\n", - " lens=af.Model(al.Galaxy, redshift=0.5, mass=al.mp.IsothermalSph),\n", - " source=af.Model(al.Galaxy, redshift=1.0, bulge=al.lp.ExponentialCoreSph),\n", - " ),\n", - ")\n", - "\n", - "search = af.Nautilus(\n", - " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", - " name=\"tutorial_1_non_linear_search\",\n", - " unique_tag=dataset_name,\n", - " n_live=80,\n", - " n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2.\n", - " iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations\n", - ")\n", - "\n", - "analysis = al.AnalysisImaging(dataset=dataset)\n", - "\n", - "result = search.fit(model=model, analysis=analysis)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Tracer & Fit__\n", - "\n", - "In the previous tutorials, we saw that this result contains the maximum log likelihood fit, which provide\n", - "a fast way to visualize the result.\n", - "\n", - "It also contains the maximum log likelihood tracer." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_tracer(\n", - " tracer=result.max_log_likelihood_tracer, grid=mask.derive_grid.all_false\n", - ")\n", - "\n", - "aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Samples__\n", - "\n", - "The result contains a lot more information about the model-fit. \n", - "\n", - "For example, the `Samples` object contains all of the non-linear search samples, including the parameters \n", - "of every successful lens model evaluation and their log likelihood values. These are used for computing information \n", - "about the model-fit, such as the most probably parameter estimates and the error inferred for every parameter." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result.samples)\n", - "print(\"Parameters of 1st Sample:\")\n", - "print(result.samples.parameter_lists[0][:])\n", - "print(\"Log Likelihood of 1st Sample:\")\n", - "print(result.samples.log_likelihood_list[0])" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Workspace__\n", - "\n", - "We are not going into any more detail on the result variable in this tutorial, or in the **HowToLens** lectures.\n", - "\n", - "A comprehensive description of the results can be found at the following package:\n", - "\n", - " `autolens_workspace/*/guides/results`\n", - " \n", - "The results API for CCD imaging data is the same as for other data types (e.g. interferometer, point-soures). This\n", - "package can therefore be used to learn the API and then translate to other data types.\n", - "\n", - "\n", - "__Database__\n", - "\n", - "Once a search has completed running, we have a set of results on our hard disk which we can manually inspect and \n", - "analyse. Alternatively, we can return the results from the search.fit() method and manipulate them in a Python script\n", - "or notebook. \n", - "\n", - "However, imagine you have a large dataset consisting of many images of strong lenses. You analyse each image \n", - "individually using a search, producing a large library of results on your hard disk. There will be lots of paths and \n", - "directories to navigate, and at some point there will simply be too many results for it to be an efficient use of your \n", - "time to analyse the results by sifting through the outputs on your hard disk one-by-one.\n", - "\n", - "**PyAutoLens**'s database tools solve this problem, by making it possible for us to write the results to a .sqlite \n", - "database file and load the results from hard-disk to a Python script or Jupyter notebook. This database supports\n", - "advanced queries, so specific results can be loaded and inspected.\n", - "\n", - "We won't go into any more detail on the database in this tutorial. If you think the database will be useful, checkout \n", - "the full set of database tutorials which can be found in the folder `autolens_workspace/*/guides/results/database`. \n", - "\n", - "Here, you'll learn how to:\n", - "\n", - " - Use the database to query for results which fit a certain lens model or give a certain result. \n", - " \n", - " - Use the `Samples` to produce many different results from the fit, including error estimates on parameters and \n", - " plots of the probability density function of parameters in 1D and 2D.\n", - " \n", - " - Visualize results, for example the fit to a lens dataset.\n", - "\n", - "__Wrap Up__\n", - "\n", - "Even if you are only modeling a small sample of lenses, if you anticipate using **PyAutoLens** for the long-term I \n", - "strongly recommend you begin using the database to inspect and analyse your result. \n", - "\n", - "This is because it makes it simple to perform all analyse in a Jupyter notebook, which is the most flexible and \n", - "versatile way to check results and make figures." - ] - } - ], - "metadata": { - "anaconda-cloud": {}, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - }, - "colab": { - "aiContexts": { - "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 — 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" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file diff --git a/notebooks/chapter_2_lens_modeling/tutorial_7_summary.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_7_summary.ipynb new file mode 100644 index 0000000..9d6759e --- /dev/null +++ b/notebooks/chapter_2_lens_modeling/tutorial_7_summary.ipynb @@ -0,0 +1,71 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Tutorial 7: Summary\n", + "===================\n", + "\n", + "__Summary__\n", + "\n", + "You have now fitted a lens model by searching through its possible parameter values, rather than choosing those\n", + "values by hand.\n", + "\n", + "We began by connecting a point in parameter space to a predicted image and its likelihood. We then explored why\n", + "finding a convincing fit can be difficult: parameters can compensate for one another, different solutions can\n", + "produce similar images, and a search can settle at a local maximum. Inspecting the fit, changing search settings\n", + "and trying other search methods help us investigate these possibilities.\n", + "\n", + "Linear light profiles simplified part of this problem by solving for intensities within each likelihood evaluation.\n", + "Search chaining then showed how an initial fit can support a more detailed analysis, while making clear which\n", + "quantities remain free and which assumptions are carried forward.\n", + "\n", + "We also separated the ingredients of a modelling calculation. The dataset supplies the observations; the model\n", + "describes the objects and parameters; the analysis defines how their predictions are compared with those\n", + "observations; and the search explores the resulting parameter space. The same `af.Model` and `af.Collection`\n", + "composition API is used across datasets. Different observations require different predictions and likelihoods,\n", + "but much of the modelling framework remains familiar.\n", + "\n", + "You can now adapt the examples in `autolens_workspace` to your own data, or use the simulators to investigate a\n", + "lens whose input properties you know. Start by inspecting the image and the fitted residuals, and treat the first\n", + "plausible solution as something to investigate rather than proof that the search has found the global maximum.\n", + "\n", + "Chapter 3 develops a more flexible description of the background source: reconstructing its light on a pixelization\n", + "instead of representing it with analytic light profiles." + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.1" + }, + "colab": { + "aiContexts": { + "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_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_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" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file 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 deleted file mode 100644 index f1afdf5..0000000 --- a/notebooks/chapter_2_lens_modeling/tutorial_8_need_for_speed.ipynb +++ /dev/null @@ -1,250 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 8: Need For Speed\n", - "==========================\n", - "\n", - "In this chapter, we have learnt how to model strong lenses and how to balance complexity and realism to ensure that we\n", - "infer a good lens model.\n", - "\n", - "For fitting more complex lens models, the final challenge that we face is keeping the run-time low. One can easily end\n", - "up in a situation where a model-fit takes days, or longer, to fit just one image. For fitting complex models and high\n", - "resolution datasets this is somewhat unavoidable. However, it is worth us discussing what drives the long run-times of\n", - "the lens modeling process and how we might speed it up.\n", - "\n", - "The preceding tutorials discussed the costs contributing to a fit's elapsed time. Lets remind ourselves of the main\n", - "factors that drive the run-time and how we might reduce it.\n", - "\n", - "For sequential likelihood evaluations, the search's evaluation cost is approximately the product of two numbers:\n", - "\n", - " - The number of log likelihood evaluations the non-linear search performs before it converges.\n", - "\n", - " - The time each individual log likelihood evaluation takes.\n", - "\n", - "Batching evaluates several models together, so this product does not directly predict GPU elapsed time. Compilation\n", - "and saving output also add time. The approaches below address these costs or reduce the exploration needed.\n", - "\n", - "__Contents__\n", - "\n", - "- **Searching Non-linear Parameter Space:** What drives the number of likelihood evaluations a search performs.\n", - "- **Cost Per Evaluation:** What drives the time a single log likelihood evaluation takes.\n", - "- **JAX:** How **PyAutoLens** compiles the likelihood function with JAX and runs it on CPUs and GPUs.\n", - "- **Run Time Estimation:** How to estimate the overall run-time of a fit before committing to it.\n", - "- **Data Quantity:** How the amount of data fitted, and the mask applied to it, drives run-times.\n", - "- **Wrap Up:** Summary of the script and next steps.\n", - "\n", - "__Searching Non-linear Parameter Space__\n", - "\n", - "The time it takes for the non-linear search to sample parameter space and find the high likelihood models is driven by:\n", - "\n", - " - Dimensionality: A more complex parameter space (e.g. more parameters) takes longer to search.\n", - " - Priors: The broader the priors on each parameter the longer the search.\n", - " - Settings: Non-linear search settings which sample parameter space more thoroughly (e.g. a higher `n_live`) lead to\n", - " longer run-times.\n", - "\n", - "When we use only one search to fit a lens model, we are somewhat restricted in how we can try to achieve faster run\n", - "times by changing these 3 aspects of the search. We have already seen one powerful exception: the linear light\n", - "profiles of tutorial 4 remove every `intensity` parameter from the non-linear parameter space, reducing its\n", - "dimensionality and removing some of its most difficult degeneracies at the same time.\n", - "\n", - "The final three tutorials of this chapter (tutorials 9, 10 and 11) introduce 'non-linear search chaining', which fits\n", - "a lens model using multiple searches that are performed back-to-back, passing the results of earlier searches to\n", - "later ones. A key motivation for this is that it gives us a lot more flexibility in juggling the dimensionality,\n", - "priors and settings so as to perform faster and more efficient lens modeling, culminating in the fully automated\n", - "SLaM pipelines of tutorial 11.\n", - "\n", - "In the optional **PyAutoLens** tutorial `chapter_optional/tutorial_searches.py` we discuss other non-linear searches\n", - "supported by **PyAutoLens** which use a different approach to sample parameter space than `Nautilus`. For those\n", - "familiar with statistical inference, this includes maximum likelihood estimators and MCMC algorithms.\n", - "\n", - "For lens modeling, we have not found another non-linear search that provides as robust and efficient results as\n", - "Nautilus. We therefore recommend users stick to `Nautilus`.\n", - "\n", - "__Cost Per Evaluation__\n", - "\n", - "The second number is the time a single log likelihood evaluation takes, which is set by every operation\n", - "**PyAutoLens** performs to fit the strong lens data with a model, for example:\n", - "\n", - " - Computing the deflection angles of the mass model and ray-tracing the image-plane grid to the source-plane.\n", - " - Computing the intensity values of every light profile on those grids.\n", - " - Over-sampling: sub-dividing image pixels into finer sub-pixels where light profiles change rapidly (e.g. the\n", - " centre of the lens galaxy), which multiplies the number of intensity evaluations performed.\n", - " - Convolving the image that comes from the tracer with the telescope's PSF to compare it to the data. The larger\n", - " the PSF, the more expensive this convolution becomes.\n", - " - For linear light profiles, basis functions like the MGE of tutorial 4 and the pixelizations of chapter 3, solving\n", - " the linear algebra of the inversion, which computes the `intensity` values that best fit the data.\n", - "\n", - "More complex fitting techniques therefore cost more per evaluation: a couple of standard light profiles are cheap,\n", - "an MGE costs more (its inversion solves for many Gaussians), and pixelized source reconstructions cost the most.\n", - "As we saw in tutorial 4, this trade often still favours the more advanced technique, because the simpler parameter\n", - "space it produces reduces the number of evaluations the search needs.\n", - "\n", - "__JAX__\n", - "\n", - "How are these operations made fast? **PyAutoLens** uses JAX (https://github.com/jax-ml/jax), Google's numerical\n", - "computing library, which just-in-time (JIT) compiles the entire log likelihood function into optimized machine code.\n", - "\n", - "JIT compilation means the first time the likelihood function is called, JAX traces through every operation it\n", - "performs (ray-tracing, light profile evaluation, PSF convolution, the linear algebra of an inversion) and compiles\n", - "them into a single optimized program. This compilation is a one-off overhead, typically taking seconds to a couple\n", - "of minutes depending on model complexity. Every one of the tens of thousands of likelihood evaluations that follow\n", - "then reuses the compiled program and runs dramatically faster than ordinary Python. When a search begins you will\n", - "see a log message like `JAX jit compiling vectorized (vmap) likelihood function, could take seconds or minutes...`\n", - "-- that is the compilation happening.\n", - "\n", - "JAX's second superpower is that the same compiled code runs on either a CPU or a GPU. On a GPU, likelihood\n", - "evaluations are not only faster individually but can be batched, with many evaluated simultaneously (the\n", - "`n_batch` search input and its VRAM implications were discussed in tutorial 2). GPU speed-ups over CPU\n", - "of an order of magnitude or more are common, and they grow with the size of the dataset and model. If you have\n", - "access to a GPU (even a modest laptop GPU), it is the single biggest speed-up available to you.\n", - "\n", - "You do not need to do anything to switch this on. JAX installs with `autolens` by default, and every\n", - "`AnalysisImaging` object we have created in this chapter defaults to `use_jax=True` and the search compiles and\n", - "batches the likelihood function automatically. You can force the plain NumPy path with\n", - "`al.AnalysisImaging(dataset=dataset, use_jax=False)` (or by setting the environment variable\n", - "`PYAUTO_DISABLE_JAX=1`), which is mainly useful for debugging, as NumPy errors and stack traces are much easier\n", - "to read than JAX ones.\n", - "\n", - "The one trade-off to keep in mind is the compilation overhead itself. For a full model-fit performing tens of\n", - "thousands of likelihood evaluations it is negligible. For a quick one-off calculation (e.g. fitting a single\n", - "tracer to data once, as we did in chapter 1) compilation can take longer than the calculation it speeds up, which\n", - "is why short interactive computations sometimes feel slower than you might expect the first time they run.\n", - "\n", - "Long-time users may remember that **PyAutoLens** previously used `numba`, which recompiles individual Python\n", - "functions into fast machine code. JAX supersedes it: rather than accelerating functions one at a time, it compiles\n", - "and optimizes the likelihood function end-to-end, and adds GPU support and batching on top. The one exception is\n", - "pixelized-source modeling on a CPU, where the `numba` sparse-operator path (see\n", - "`autolens_workspace/scripts/imaging/features/pixelization/cpu_fast_modeling.py`, and chapter 3) remains the faster\n", - "route on many-core machines.\n", - "\n", - "Therefore, **PyAutoLens** is pretty well optimized and there are no 'low hanging fruit' speed ups available by\n", - "writing the code in a different language.\n", - "\n", - "__Run Time Estimation__\n", - "\n", - "Tutorial 2 explains how likelihood cost, the number of evaluations, compilation and output contribute to elapsed time.\n", - "It does not measure a likelihood evaluation time or predict a fixed duration for the fit.\n", - "\n", - "An estimate needs measurements from the actual likelihood calculation, using the intended model, dataset, hardware\n", - "and batch size. A standalone `FitImaging` calculation need not follow the same compiled and batched path as the search.\n", - "JAX measurements must wait for device calculations to finish, with compilation considered separately from repeated\n", - "evaluations.\n", - "\n", - "The number of evaluations needed also depends on the parameter space and search settings. Compare the saved durations\n", - "of representative completed fits, as in Tutorial 3, before extrapolating to a larger analysis. If those runs suggest\n", - "that a fit will take days or weeks, consider simplifying the model, search chaining or different hardware.\n", - "\n", - "On a GPU, tutorial 2 also showed the other pre-flight check: `analysis.print_vram_use` estimates whether the fit\n", - "will fit within the GPU's memory for your chosen batch size.\n", - "\n", - "__Data Quantity__\n", - "\n", - "The final factor driving run-speed is the quantity of data that is fitted. For every image-pixel that we fit,\n", - "we have to compute the light profile intensities, mass profile deflection angles and convolve it with the telescope's\n", - "PSF. The larger that PSF is, the more convolution operations we have to perform too.\n", - "\n", - "In the previous exercises, we used images with a pixel scale of 0.1\". This value is relatively low resolution: most\n", - "Hubble Space Telescope images have a pixel scale of 0.05\", which is four times the number of pixels! Some telescopes\n", - "observe at scales of 0.03\" or, dare I say it, 0.01\". At these resolutions things can *really* slow down, if we\n", - "do not think carefully about run speed beforehand.\n", - "\n", - "There are ways that we can reduce the number of image-pixels we fit, via masking. If we mask out more of the image,\n", - "we will fit fewer pixels and **PyAutoLens** will run faster. If you want the best, most perfect lens model possible,\n", - "aggressive masking and cutting the data in this way is a bad idea, as discussed in tutorial 6.\n", - "\n", - "__Wrap Up__\n", - "\n", - "This tutorial simply wanted to get you thinking about *why* a lens model takes as long to fit as it does: the number\n", - "of likelihood evaluations the search performs, times the cost of each evaluation, with JAX's compiled likelihood\n", - "function (and a GPU, if you have one) driving the latter down as far as it will go.\n", - "\n", - "The remaining tutorials of this chapter attack the other half of the product: search chaining (tutorial 9) and prior\n", - "passing (tutorial 10) reduce the number of evaluations needed to fit complex models, and the SLaM pipelines\n", - "(tutorial 11) package these ideas into automated pipelines for fitting large samples of lenses." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Google Colab Setup__\n", - "\n", - "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": { - "cellView": "form", - "jupyter": { - "source_hidden": true - } - }, - "outputs": [], - "source": [ - "# @title Set up Google Colab { display-mode: \"form\" }\n", - "try:\n", - " import google.colab\n", - "except ImportError:\n", - " from autolens import setup_colab as _setup_colab\n", - "else:\n", - " import importlib\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.check_call(\n", - " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", - " )\n", - " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", - "\n", - "_setup_colab.setup(\"howtolens\")" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autolens import setup_notebook; setup_notebook()\n" - ], - "outputs": [], - "execution_count": null - } - ], - "metadata": { - "anaconda-cloud": {}, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - }, - "colab": { - "aiContexts": { - "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 — 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" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file diff --git a/notebooks/chapter_2_lens_modeling/tutorial_9_search_chaining.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_9_search_chaining.ipynb deleted file mode 100644 index a860cd3..0000000 --- a/notebooks/chapter_2_lens_modeling/tutorial_9_search_chaining.ipynb +++ /dev/null @@ -1,746 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 9: Search Chaining\n", - "===========================\n", - "\n", - "Throughout this chapter, we have fitted the data using just one non-linear search. The previous tutorial discussed\n", - "the run-time cost of doing this: with a single search, the dimensionality of the model, the priors on its parameters\n", - "and the search settings must all be juggled at once, leaving us little flexibility to trade them off against one\n", - "another.\n", - "\n", - "In this closing part of the chapter, we introduce a technique called 'non-linear search chaining', which fits a lens\n", - "model using a sequence of non-linear searches. The initial searches fit simpler lens models whose parameter spaces can\n", - "be more accurately and efficiently sampled. The results of this search are then passed to later searches which fit\n", - "lens models of gradually increasing complexity.\n", - "\n", - "Lets think back to tutorial 3 of this chapter. We learnt there were three approaches one could take fitting a lens\n", - "model accurately if we found that a model fit failed. These were:\n", - "\n", - " 1) Tuning our priors to the strong lens we're fitting.\n", - " 2) Making our lens model less complex.\n", - " 3) Searching non-linear parameter space for longer.\n", - "\n", - "However, each of the above approaches has disadvantages. The more we tune our priors, the less we can generalize our\n", - "analysis to a different strong lens. The less complex we make our model, the less realistic it is. And if we rely too\n", - "much on searching parameter space for longer, we could end up with search`s that take days, weeks or months to run.\n", - "\n", - "In this tutorial, we are going to show how search chaining combines these 3 approaches such that we can fit\n", - "complex and realistic lens models in a way that that can be generalized to many different strong lenses. To do this,\n", - "we'll run 2 searches, and chain the lens model inferred in the first search to the priors of the second search`s lens\n", - "model.\n", - "\n", - "Our first search will make the same light-traces-mass assumption we made in tutorial 3. We saw that this\n", - "gives a reasonable lens model. However, we'll make a couple of extra simplifying assumptions, to really try and bring\n", - "our lens model complexity down and get the non-linear search running fast.\n", - "\n", - "The model we infer above will therefore be a lot less realistic. But it does not matter, because in the second search\n", - "we are going to relax these assumptions and fit the more realistic lens model. The beauty is that, by running the first\n", - "search, we can use its results to tune the priors of our second search. For example:\n", - "\n", - " 1) The first search should give us a pretty good idea of the lens galaxy's light and mass profiles, for example its\n", - " intensity, effective radius and einstein radius.\n", - "\n", - " 2) It should also give us a pretty good fit to the lensed source galaxy. This means we'll already know where in\n", - " source-plane its is located and what its intensity and effective are.\n", - "\n", - "__Contents__\n", - "\n", - "- **Initial Setup:** Load the same strong lensing data fitted throughout this chapter.\n", - "- **Dataset Auto-Simulation:** Simulate the dataset via its simulator script if it is not on your hard-disk.\n", - "- **Model:** Compose the lens model fitted to the data.\n", - "- **Search + Analysis:** Create the non-linear search and analysis used to fit the first model.\n", - "- **Result:** Overview of the results of the model-fit.\n", - "- **Prior Passing:** Use the results of search 1 to set up the priors of search 2.\n", - "- **Run Time:** Profiling the expected run time of the model-fit.\n", - "- **Model Fit:** Perform the model-fit using the search and analysis.\n", - "- **Wrap Up:** Summary of the script and next steps." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Google Colab Setup__\n", - "\n", - "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "jupyter": { - "source_hidden": true - } - }, - "outputs": [], - "source": [ - "# @title Set up Google Colab { display-mode: \"form\" }\n", - "try:\n", - " import google.colab\n", - "except ImportError:\n", - " from autolens import setup_colab as _setup_colab\n", - "else:\n", - " import importlib\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.check_call(\n", - " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", - " )\n", - " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", - "\n", - "_setup_colab.setup(\"howtolens\")" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autolens import jax_wrapper # Sets JAX environment before other imports\n", - "\n", - "from autolens import setup_notebook; setup_notebook()\n", - "\n", - "import numpy as np\n", - "from pathlib import Path\n", - "import autolens as al\n", - "import autolens.plot as aplt\n", - "import autofit as af" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Initial Setup__\n", - "\n", - "we'll use the same strong lensing data as tutorials 2, 3 and 4 of this chapter, where:\n", - "\n", - " - The lens galaxy's light is an `Sersic`.\n", - " - The lens system uses an `Isothermal` galaxy mass profile and a separate `ExternalShear` field.\n", - " - The source galaxy's light is an `Exponential`." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "dataset_name = \"lens_sersic\"\n", - "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Dataset Auto-Simulation__\n", - "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "al.util.dataset.simulate_if_needed(\n", - " dataset_path, simulator=\"scripts/simulator/lens_sersic.py\"\n", - ")\n", - "\n", - "dataset = 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.1,\n", - ")\n", - "\n", - "mask_radius = 2.6\n", - "\n", - "mask = al.Mask2D.circular(\n", - " shape_native=dataset.shape_native,\n", - " pixel_scales=dataset.pixel_scales,\n", - " radius=mask_radius,\n", - ")\n", - "\n", - "dataset = dataset.apply_mask(mask=mask)\n", - "\n", - "aplt.subplot_imaging_dataset(dataset=dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Model__\n", - "\n", - "As we've eluded to before, one can look at an image and immediately identify the centre of the lens galaxy. It's \n", - "that bright blob of light in the middle! Given that we know we're going to make the lens model more complex in the \n", - "next search, lets take a more liberal approach than before and fix the lens centre to $(y,x)$ = (0.0\", 0.0\").\n", - "\n", - "Now, you might be thinking, doesn`t this prevent our search from generalizing to other strong lenses? What if the \n", - "centre of their lens galaxy isn't at (0.0\", 0.0\")?\n", - "\n", - "Well, this is true if our dataset reduction centres the lens galaxy somewhere else. But we get to choose where we \n", - "centre it when we make the image. Therefore, I`d recommend you always centre the lens galaxy at the same location, \n", - "and (0.0\", 0.0\") seems the best choice!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge = af.Model(al.lp_linear.Sersic)\n", - "mass = af.Model(al.mp.Isothermal)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You haven't actually seen a line like this one before. By setting a parameter to a number (and not a prior) it is be \n", - "removed from non-linear parameter space and always fixed to that value. Pretty neat, huh?" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge.centre_0 = 0.0\n", - "bulge.centre_1 = 0.0\n", - "mass.centre_0 = 0.0\n", - "mass.centre_1 = 0.0" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Lets use the same approach of making the ellipticity of the mass trace that of the bulge." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mass.ell_comps = bulge.ell_comps" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We also discussed that the Sersic index of most lens galaxies is around 4. Lets fix it to 4 this time." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge.sersic_index = 4.0" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now compose the model with these components that have had their priors customized. \n", - "\n", - "We have not done anything to the source model, but use an `Exponential` which will become the more complex\n", - "`Sersic` in the second search." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "lens = af.Model(al.Galaxy, redshift=0.5, bulge=bulge, mass=mass)\n", - "field = af.Model(al.MassField, redshift=0.5, shear=al.mp.ExternalShear)\n", - "\n", - "source = af.Model(al.Galaxy, redshift=1.0, bulge=al.lp_linear.ExponentialCore)\n", - "\n", - "model_1 = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `info` attribute shows the model in a readable format." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(model_1.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The same model can also be visualized as a figure, making its structure easier to understand at a glance.\n", - "\n", - "The figure shows how the model is organized: which parameters belong to each component, and whether they are free,\n", - "fixed, shared, linked by an expression, solved during the fit, or not configured. `model.info` provides the\n", - "corresponding numerical details, including the prior assigned to each free parameter and the value of each fixed\n", - "parameter.\n", - "\n", - "Eleven dimensions is a deliberately crude model, and that is exactly what the first search in a chain wants: it\n", - "needs only to be good enough to locate the lens roughly, and to do so quickly." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "af.ModelPlotter(model_1).figure()" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Search + Analysis__\n", - "\n", - "Now lets create the search and analysis." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search_1 = af.Nautilus(\n", - " path_prefix=Path(\"howtolens\", \"chapter_2\"),\n", - " name=\"tutorial_9_search_chaining_1\",\n", - " unique_tag=dataset_name,\n", - " n_live=100,\n", - " iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations\n", - ")\n", - "\n", - "analysis_1 = al.AnalysisImaging(dataset=dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Lets run the search, noting that our liberal approach to reducing the lens model complexity has reduced it to just \n", - "11 parameters." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(\n", - " \"The non-linear search has begun running - checkout the output/howtolens/chapter_2\"\n", - " \" folder for live output of the results, images and lens model.\"\n", - " \" This Jupyter notebook cell with progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", - "result_1 = search_1.fit(model=model_1, analysis=analysis_1)\n", - "\n", - "print(\"Search has finished run - you may now continue the notebook.\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Result__\n", - "\n", - "The results are summarised in the `info` attribute." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result_1.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And indeed, we get a reasonably good model and fit to the data, in a much shorter space of time!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_fit_imaging(fit=result_1.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Prior Passing__\n", - "\n", - "Now all we need to do is look at the results of search 1 and pass the results as priors for search 2. Lets setup \n", - "a custom search that does exactly that.\n", - "\n", - "`GaussianPrior`'s are a nice way to pass priors. They tell the non-linear search where to look, but leave open the \n", - "possibility that there might be a better solution nearby. In contrast, `UniformPrior`'s put hard limits on what values a \n", - "parameter can or can`t take. It makes it more likely we will accidentally cut-out the global maxima solution." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge = af.Model(al.lp_linear.Sersic)\n", - "mass = af.Model(al.mp.Isothermal)\n", - "field = af.Model(al.MassField, redshift=0.5, shear=al.mp.ExternalShear)\n", - "source_bulge = af.Model(al.lp_linear.Sersic)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "What I've done below is looked at the results of search 1 and manually specified a prior for every parameter. If a \n", - "parameter was fixed in the previous search, its prior is based around the previous value. Don't worry about the sigma \n", - "values for now, I've chosen values that I know will ensure reasonable sampling, but we'll cover this later.\n", - "\n", - "__LENS LIGHT PRIORS:__" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge.centre.centre_0 = af.GaussianPrior(\n", - " mean=0.0,\n", - " sigma=0.1,\n", - ")\n", - "bulge.centre.centre_1 = af.GaussianPrior(\n", - " mean=0.0,\n", - " sigma=0.1,\n", - ")\n", - "bulge.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior(\n", - " mean=0.05, sigma=0.15, lower_limit=-1.0, upper_limit=1.0\n", - ")\n", - "bulge.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior(\n", - " mean=0.0, sigma=0.2, lower_limit=-1.0, upper_limit=1.0\n", - ")\n", - "bulge.effective_radius = af.TruncatedGaussianPrior(\n", - " mean=0.72, sigma=0.2, lower_limit=0.0, upper_limit=np.inf\n", - ")\n", - "bulge.sersic_index = af.TruncatedGaussianPrior(\n", - " mean=4.0, sigma=2.0, lower_limit=0.0, upper_limit=np.inf\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__LENS MASS PRIORS:__" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mass.centre.centre_0 = af.GaussianPrior(\n", - " mean=0.0,\n", - " sigma=0.1,\n", - ")\n", - "mass.centre.centre_1 = af.GaussianPrior(\n", - " mean=0.0,\n", - " sigma=0.1,\n", - ")\n", - "mass.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior(\n", - " mean=0.05, sigma=0.15, lower_limit=-1.0, upper_limit=1.0\n", - ")\n", - "mass.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior(\n", - " mean=0.0, sigma=0.2, lower_limit=-1.0, upper_limit=1.0\n", - ")\n", - "mass.einstein_radius = af.TruncatedGaussianPrior(\n", - " mean=1.6, sigma=0.1, lower_limit=0.0, upper_limit=np.inf\n", - ")\n", - "field.shear.gamma_1 = af.GaussianPrior(mean=0.05, sigma=0.05)\n", - "field.shear.gamma_2 = af.GaussianPrior(mean=0.05, sigma=0.05)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__SOURCE LIGHT PRIORS:__" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "source_bulge.centre.centre_0 = af.GaussianPrior(\n", - " mean=0.0,\n", - " sigma=0.1,\n", - ")\n", - "source_bulge.centre.centre_1 = af.GaussianPrior(\n", - " mean=0.0,\n", - " sigma=0.1,\n", - ")\n", - "source_bulge.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior(\n", - " mean=0.08, sigma=0.15, lower_limit=-1.0, upper_limit=1.0\n", - ")\n", - "source_bulge.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior(\n", - " mean=-0.06, sigma=0.2, lower_limit=-1.0, upper_limit=1.0\n", - ")\n", - "source_bulge.effective_radius = af.TruncatedGaussianPrior(\n", - " mean=0.1, sigma=0.2, lower_limit=0.0, upper_limit=np.inf\n", - ")\n", - "source_bulge.sersic_index = af.TruncatedGaussianPrior(\n", - " mean=1.0, sigma=1.0, lower_limit=0.0, upper_limit=np.inf\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now compose the model with these components that have had their priors customized. " - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "lens = af.Model(al.Galaxy, redshift=0.5, bulge=bulge, mass=mass)\n", - "\n", - "source = af.Model(al.Galaxy, redshift=1.0, bulge=source_bulge)\n", - "\n", - "model_2 = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `info` attribute shows the model, including the priors specified above." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(model_2.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The second model is the comparison worth making. The centres and the `sersic_index` are free again, the pairing\n", - "between `bulge` and `mass` has gone with them, and the source is now a `Sersic` with a `sersic_index` of its\n", - "own: nineteen free parameters against the eleven of `model_1`.\n", - "\n", - "That is search chaining: search 1 fits the small model, and what it learns buys us the priors that make the\n", - "large model affordable." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "af.ModelPlotter(model_2).figure()" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Lets setup and run the search. As expected, it gives us the correct lens model. However, it does so significantly \n", - "faster than we are used to!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search_2 = af.Nautilus(\n", - " path_prefix=Path(\"howtolens\", \"chapter_2\"),\n", - " name=\"tutorial_9_search_chaining_2\",\n", - " unique_tag=dataset_name,\n", - " n_live=150,\n", - " iterations_per_quick_update=25000, # Outputs Notebook visualization of max likelihood model every N iterations\n", - ")\n", - "\n", - "analysis_2 = al.AnalysisImaging(dataset=dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Run Time__\n", - "\n", - "Whilst the run-time of the log likelihood function is pretty much unchanged from the first search, the overall run-time\n", - "of the search should decrease.\n", - "\n", - "This is because via prior passing we have informed the search of where to look in parameter space, meaning it \n", - "should spend far fewer than ~10000 iterations per free parameter.\n", - "\n", - "__Model Fit__\n", - "\n", - "Run the search." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(\n", - " \"The non-linear search has begun running - checkout the output/howtolens/chapter_2\"\n", - " \" folder for live output of the results, images and lens model.\"\n", - " \" This Jupyter notebook cell with progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", - "result_2 = search_2.fit(model=model_2, analysis=analysis_2)\n", - "\n", - "print(\"Search has finished run - you may now continue the notebook.\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Result__\n", - "\n", - "We can again inspect the results via the `info` attribute." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result_2.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And a plot of the image shows we get a good model again!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_fit_imaging(fit=result_2.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Wrap Up__\n", - "\n", - "Chaining two searches together was a huge success. We managed to fit a complex and realistic model, but were able to \n", - "begin by making simplifying assumptions that eased our search of non-linear parameter space. We could apply search 1 to \n", - "pretty much any strong lens and therefore get ourselves a decent lens model with which to tune search 2`s priors.\n", - "\n", - "You are probably thinking though that there is one huge, giant, glaring flaw in all of this that I've not mentioned. \n", - "Search 2 can`t be generalized to another lens, because its priors are tuned to the image we fitted. If we had a lot \n", - "of lenses, we`d have to write a new search for every single one. This isn't ideal, is it?\n", - "\n", - "Fortunately, we can pass priors in **PyAutoLens** without specifying the specific values. The API for this technique,\n", - "called prior passing, is the topic of the next tutorial." - ] - } - ], - "metadata": { - "anaconda-cloud": {}, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - }, - "colab": { - "aiContexts": { - "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?\"* — 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" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file diff --git a/notebooks/chapter_optional/README.md b/notebooks/chapter_optional/README.md new file mode 100644 index 0000000..2ff62b7 --- /dev/null +++ b/notebooks/chapter_optional/README.md @@ -0,0 +1,9 @@ +# Optional tutorials + +These lessons supplement the main chapters. Historical prior passing is retained for understanding older analyses. + +- [Need for Speed](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_need_for_speed.ipynb) — Computation, batching and estimating runtime. + +- [Historical Prior Passing](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_prior_passing.ipynb) — An optional runnable example of prior passing using model_centred, a technique central to older workflows. + +- [Searches](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_searches.ipynb) — Alternative non-linear search methods. diff --git a/notebooks/chapter_optional/tutorial_need_for_speed.ipynb b/notebooks/chapter_optional/tutorial_need_for_speed.ipynb new file mode 100644 index 0000000..2a585c2 --- /dev/null +++ b/notebooks/chapter_optional/tutorial_need_for_speed.ipynb @@ -0,0 +1,244 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Optional Tutorial: Need for Speed\n", + "================================\n", + "\n", + "Two fits to the same image can take very different amounts of time. Finding a good fit with a simple model may be\n", + "quick, whereas exploring the uncertainties of a more flexible model can take much longer. Both the calculation\n", + "performed for each model and the search through parameter space contribute to this difference.\n", + "\n", + "This optional tutorial looks at these costs, including JAX compilation, batching and hardware. It builds on the fits\n", + "we have performed in chapter 2, but is not a prerequisite for the pixelized source reconstructions of chapter 3.\n", + "Return to it when planning a larger analysis, or when a fit takes longer than you expected.\n", + "\n", + "__Contents__\n", + "\n", + "- **Searching Parameter Space:** What determines how much exploration a search needs.\n", + "- **Cost Per Evaluation:** The calculations required to compare one model with the data.\n", + "- **JAX:** Compilation and the cost of the first evaluation.\n", + "- **Batches and GPU Memory:** Evaluating models together and choosing a batch size.\n", + "- **Run Time Estimation:** Measuring the costs relevant to your analysis.\n", + "- **Data Quantity:** How image resolution and the fitted region affect computation.\n", + "- **Wrap Up:** Putting these considerations together.\n", + "\n", + "__Searching Parameter Space__\n", + "\n", + "A non-linear search evaluates models until its stopping criteria are met. The number of evaluations depends on more\n", + "than the number of free parameters. A narrow, curved region of high likelihood can be difficult to explore, as can\n", + "several separated peaks. Two models with the same number of parameters need not take similar amounts of time to fit.\n", + "\n", + "Broad priors can require the search to explore large regions that fit the data poorly. However, narrowing a prior\n", + "just to make a fit faster risks excluding plausible solutions. The prior should express a justified assumption\n", + "about the parameter, rather than the region we hope will give the quickest result.\n", + "\n", + "Search settings also determine how much work is performed. More live points in Nautilus, or more starting points\n", + "and optimisation steps in Prodigy, cost computation but may improve exploration. Tutorial 3 showed why reducing\n", + "this effort too far can leave us with a local maximum.\n", + "\n", + "The searches also answer different questions. Prodigy seeks a good-fitting model without exploring the posterior\n", + "to measure parameter uncertainties. Nautilus performs that additional exploration, so we should expect uncertainty\n", + "estimation to take longer. The search chain in Tutorial 6 uses these different strengths at different stages.\n", + "\n", + "The optional tutorial `chapter_optional/tutorial_searches.py` introduces other search methods. Trying a different\n", + "method can help with a difficult fit; the appropriate choice depends on both the parameter space and whether we\n", + "need a best-fitting model or a description of its uncertainties.\n", + "\n", + "__Cost Per Evaluation__\n", + "\n", + "For every model proposed by the search, we must predict the observed image and compare it with the data. This\n", + "includes calculating deflection angles, ray-tracing the image-plane grid, evaluating light profiles and convolving\n", + "the predicted image with the telescope's PSF.\n", + "\n", + "Over-sampling adds calculations within image pixels, so that rapidly changing light profiles are represented\n", + "accurately. Linear light profiles also require a linear solve for their intensities. An MGE includes many such\n", + "profiles, while the pixelized source reconstructions introduced in chapter 3 require their own reconstruction.\n", + "\n", + "The cost of these operations depends on the number of pixels, profiles and source elements, as well as the numerical\n", + "methods and their implementation. There is no universal ordering in which every MGE is slower than a few light\n", + "profiles, or every pixelized reconstruction is slower than an MGE.\n", + "\n", + "Adding more Gaussian components to an MGE increases the work in the linear calculation. However, solving their\n", + "intensities linearly can make the non-linear parameter space easier to explore, as we saw in Tutorial 4. A model\n", + "that costs more per evaluation can therefore finish sooner if the search needs substantially fewer evaluations.\n", + "Timing one evaluation alone does not tell us how long the whole fit will take.\n", + "\n", + "__JAX__\n", + "\n", + "**PyAutoLens** uses JAX (https://github.com/jax-ml/jax) to compile supported likelihood calculations and to calculate\n", + "the derivatives used by gradient-based searches such as Prodigy.\n", + "\n", + "The first evaluation includes tracing the calculation and compiling it into a program that can be reused. Later\n", + "evaluations with new parameter values can then use that compiled program. This is why the beginning of a fit may\n", + "feel slow even when subsequent evaluations are fast.\n", + "\n", + "Reuse depends on the calculation retaining a compatible structure. Changing array shapes, data types or settings\n", + "treated as fixed during compilation can require a new compilation. We should therefore distinguish the initial\n", + "setup cost from the cost of repeated evaluations, rather than assuming compilation happens only once across an\n", + "entire sequence of fits.\n", + "\n", + "The imaging analyses in this chapter use JAX by default. Setting `use_jax=False` in `al.AnalysisImaging` selects the\n", + "NumPy path, which can be useful when diagnosing a calculation or comparing implementations. This does not make a\n", + "gradient-based search independent of derivatives: such a search still needs a supported differentiable calculation.\n", + "\n", + "__Batches and GPU Memory__\n", + "\n", + "Instead of evaluating one model at a time, a search can evaluate a batch of models together. This can increase the\n", + "number of evaluations completed per second, particularly on a GPU, but it also requires memory for several\n", + "calculations at once.\n", + "\n", + "For Nautilus, `n_batch` controls the batch of likelihood evaluations. For MultiStartProdigy, `batch_size` controls\n", + "how many optimisation starts are processed together. These settings play different roles in the searches, but\n", + "both affect the amount of work held in memory.\n", + "\n", + "A larger batch may improve throughput, but eventually the improvement can diminish or the calculation can exceed\n", + "the available GPU memory. The largest possible batch is not automatically the best setting.\n", + "\n", + "A GPU is also not guaranteed to outperform a CPU for every fit. The outcome depends on the model, dataset, batch\n", + "size, numerical precision and hardware. Compilation and moving data to the device contribute to elapsed time too.\n", + "Compare the same analysis on the hardware available to you, including the costs relevant to your use: a short\n", + "interactive calculation and a long modelling campaign can favour different choices.\n", + "\n", + "__Run Time Estimation__\n", + "\n", + "To estimate how long a fit will take, start with a representative analysis: the model, dataset, search settings and\n", + "hardware should resemble those you intend to use. A timing measured with a simpler model or a smaller image may\n", + "give a misleading impression of the work ahead.\n", + "\n", + "Separate the time spent preparing and compiling the calculation from the time spent evaluating models afterwards.\n", + "JAX can dispatch calculations before they have finished, so a measurement must wait for the calculation to complete.\n", + "Otherwise, we may time only the act of submitting the work.\n", + "\n", + "For a batched search, the useful quantity is how many likelihood evaluations are completed per second. Timing a\n", + "standalone `FitImaging` calculation does not necessarily measure the compiled, batched calculation used by the search.\n", + "\n", + "Even with this measurement, we do not yet know how many evaluations the search will need. A short run can reveal\n", + "expensive calculations or memory problems, but it cannot reliably predict how long exploration of a difficult\n", + "parameter space will take. Completed fits to similar datasets provide a more useful starting point.\n", + "\n", + "When comparing approaches, inspect their results alongside their durations. A fit that finishes quickly at a poor\n", + "local maximum has not achieved the same outcome as one that finds a convincing solution. Likewise, finding one\n", + "good model and measuring its uncertainties are different amounts of work.\n", + "\n", + "__Data Quantity__\n", + "\n", + "Consider two images covering the same region of sky. One has pixels that are 0.1 arcseconds across, while the other\n", + "has pixels that are 0.05 arcseconds across. Halving the pixel scale doubles the number of pixels along each axis,\n", + "giving approximately four times as many pixels in the fitted region.\n", + "\n", + "The finer image therefore requires calculations at more positions. The precise increase in runtime also depends\n", + "on over-sampling, the PSF, the model and how the calculation is implemented; four times as many pixels does not\n", + "necessarily mean a fit takes exactly four times as long.\n", + "\n", + "The circular mask determines how much of the image enters the fit. However, as we discussed in Tutorial 5, faint\n", + "lens and source emission still contains information, including where a proposed model predicts light that the\n", + "image does not contain. Shrinking the circle until only the brightest features remain can change the inferred model.\n", + "\n", + "We therefore choose a circle large enough to contain the relevant emission, including the lens galaxy's light.\n", + "If that calculation is expensive, we investigate the model, search and computational settings while retaining\n", + "the region needed for the scientific analysis.\n", + "\n", + "__Wrap Up__\n", + "\n", + "A lens fit takes time both because each proposed model requires a calculation and because the search must explore\n", + "many possible models. These costs interact: solving light-profile intensities linearly adds work to each evaluation\n", + "but can substantially simplify the search through parameter space.\n", + "\n", + "JAX, batching and suitable hardware can accelerate the calculations. Search chaining can organise the exploration\n", + "into stages, using an initial fit to inform a more detailed analysis. Neither removes the need to inspect the\n", + "result and investigate alternative solutions.\n", + "\n", + "When a fit is slow, identify where the time is being spent before changing settings. Compilation, expensive\n", + "evaluations and prolonged exploration call for different responses. Compare changes using both elapsed time and\n", + "the quality of the inference you obtain.\n", + "\n", + "**\ud83e\udd16 Ask AI:** Two searches fit the same lens image. One quickly finds a good-looking model, while the other takes\n", + "much longer and returns parameter uncertainties. What should I compare before deciding whether the faster search\n", + "is sufficient for my scientific question?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Google Colab Setup__\n", + "\n", + "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": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, + "outputs": [], + "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", + "try:\n", + " import google.colab\n", + "except ImportError:\n", + " from autolens import setup_colab as _setup_colab\n", + "else:\n", + " import importlib\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.check_call(\n", + " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", + " )\n", + " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", + "\n", + "_setup_colab.setup(\"howtolens\")" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from autolens import setup_notebook; setup_notebook()\n" + ], + "outputs": [], + "execution_count": null + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.1" + }, + "colab": { + "aiContexts": { + "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_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_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" + } + }, + "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file diff --git a/notebooks/chapter_optional/tutorial_prior_passing.ipynb b/notebooks/chapter_optional/tutorial_prior_passing.ipynb new file mode 100644 index 0000000..31e67af --- /dev/null +++ b/notebooks/chapter_optional/tutorial_prior_passing.ipynb @@ -0,0 +1,606 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Optional Tutorial: Historical Prior Passing\n", + "===========================================\n", + "\n", + "This optional tutorial preserves a technique used in earlier **PyAutoLens** modelling workflows, up to around 2025:\n", + "passing parameter constraints from one search into the priors of a later search.\n", + "\n", + "For example, an initial search might constrain the Einstein radius. A subsequent search could use a narrower prior\n", + "centred on that inferred value, reducing the region it needs to explore. The prior-passing API automated this\n", + "construction using the results of the earlier fit.\n", + "\n", + "This approach is no longer part of the recommended workflow taught in this chapter. Tutorial 6 instead demonstrates\n", + "a chain that fixes selected lens-light geometry, retains fresh priors for the parameters being explored and uses\n", + "the first result to construct a positions penalty. Search chaining does not require passing narrowed priors\n", + "between searches.\n", + "\n", + "The distinction matters because an earlier fit can be incomplete or trapped at a local maximum. Restricting a later\n", + "search around that result can prevent it from finding alternatives. Using the same data again with priors derived\n", + "from its earlier fit also requires care when interpreting the resulting uncertainties.\n", + "\n", + "New readers can skip this tutorial and continue to chapter 3. It is retained to help readers understand older\n", + "scripts and analyses, rather than as an additional technique they need to learn before modelling their own lenses.\n", + "\n", + "Prior passing is still supported through `result.model_centred`. This tutorial runs two searches to demonstrate\n", + "that API. The historical distinction is its role in our workflows: it used to be central to search chaining,\n", + "whereas the main chapter now uses fresh priors and fixes selected components instead.\n", + "\n", + "`result.model` preserves the input priors. `result.model_centred` creates new priors centred on the inferred\n", + "parameter values. `result.instance` supplies fitted values that are held fixed. We will inspect the second model\n", + "to see which parameters receive centred priors and which receive fresh priors.\n", + "\n", + "__Contents__\n", + "\n", + "- **Initial Setup:** Load the lens_sersic imaging dataset.\n", + "- **Dataset Auto-Simulation:** Simulate the dataset via its simulator script if it is not on your hard-disk.\n", + "- **Model:** Compose the lens model fitted to the data.\n", + "- **Search:** Configure the non-linear search used to fit the model.\n", + "- **Result (Search 1):** The results of search 1, which are used for prior passing.\n", + "- **Prior Passing:** Use the prior passing API to pass the results of search 1 without writing out values manually.\n", + "- **Result:** Overview of the results of the model-fit.\n", + "- **Wrap Up:** Summary of the script and next steps.\n", + "- **Detailed Explanation Of Prior Passing:** A detailed overview of how prior passing works and tools to customize it.\n", + "- **EXAMPLE:** Compare absolute and relative widths for a Sersic index." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Google Colab Setup__\n", + "\n", + "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": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, + "outputs": [], + "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", + "try:\n", + " import google.colab\n", + "except ImportError:\n", + " from autolens import setup_colab as _setup_colab\n", + "else:\n", + " import importlib\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.check_call(\n", + " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", + " )\n", + " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", + "\n", + "_setup_colab.setup(\"howtolens\")" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from autolens import jax_wrapper # Sets JAX environment before other imports\n", + "\n", + "from autolens import setup_notebook; setup_notebook()\n", + "\n", + "import numpy as np\n", + "from pathlib import Path\n", + "import autolens as al\n", + "import autolens.plot as aplt\n", + "import autofit as af" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Initial Setup__\n", + "\n", + "We use the lens_sersic simulated imaging dataset, where:\n", + "\n", + " - The lens galaxy's light is an `Sersic`.\n", + " - The lens system uses an `Isothermal` galaxy mass profile and a separate `ExternalShear` field.\n", + " - The source galaxy's light is an `ExponentialCore`.\n", + "\n", + "All the usual steps for setting up a model fit (masking, analysis, etc.) are included below." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "dataset_name = \"lens_sersic\"\n", + "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Dataset Auto-Simulation__\n", + "\n", + "If the dataset does not already exist on your system, it will be created by running the corresponding\n", + "simulator script. This ensures that all example scripts can be run without manually simulating data first." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "al.util.dataset.simulate_if_needed(\n", + " dataset_path, simulator=\"scripts/simulator/lens_sersic.py\"\n", + ")\n", + "\n", + "dataset = 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.1,\n", + ")\n", + "\n", + "mask_radius = 3.0\n", + "\n", + "mask = al.Mask2D.circular(\n", + " shape_native=dataset.shape_native,\n", + " pixel_scales=dataset.pixel_scales,\n", + " radius=mask_radius,\n", + ")\n", + "\n", + "dataset = dataset.apply_mask(mask=mask)\n", + "\n", + "aplt.subplot_imaging_dataset(dataset=dataset)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Model__\n", + "\n", + "The first search fits a simpler model: the lens-light centre and Sersic index are fixed, the mass centre is fixed,\n", + "and the mass and light share their ellipticity. The second search will free some of these choices and use a more\n", + "flexible source profile. This tutorial performs its own fits; it does not require saved results from Tutorial 6." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "bulge = af.Model(al.lp_linear.Sersic)\n", + "mass = af.Model(al.mp.Isothermal)\n", + "\n", + "bulge.centre_0 = 0.0\n", + "bulge.centre_1 = 0.0\n", + "mass.centre_0 = 0.0\n", + "mass.centre_1 = 0.0\n", + "\n", + "mass.ell_comps = bulge.ell_comps\n", + "\n", + "bulge.sersic_index = 4.0\n", + "\n", + "lens = af.Model(al.Galaxy, redshift=0.5, bulge=bulge, mass=mass)\n", + "field = af.Model(al.MassField, redshift=0.5, shear=al.mp.ExternalShear)\n", + "\n", + "source = af.Model(al.Galaxy, redshift=1.0, bulge=al.lp_linear.ExponentialCore)\n", + "\n", + "model_1 = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The `info` attribute shows the model in a readable format." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(model_1.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The same model can also be visualized as a figure, making its structure easier to understand at a glance.\n", + "\n", + "The figure shows how the model is organized: which parameters belong to each component, and whether they are free,\n", + "fixed, shared, linked by an expression, solved during the fit, or not configured. `model.info` provides the\n", + "corresponding numerical details, including the prior assigned to each free parameter and the value of each fixed\n", + "parameter.\n", + "\n", + "Keep this model in mind when inspecting the second model below: changing priors and changing the physical\n", + "components are separate choices." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model_1).figure()" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Search__\n", + "\n", + "We run Nautilus to obtain a fit and posterior samples for the first model. Inspect its inferred parameters before\n", + "using them to construct priors for the second search. As with the earlier tutorials, a completed search does not\n", + "by itself establish that the solution is the global maximum." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "search_1 = af.Nautilus(\n", + " path_prefix=Path(\"howtolens\", \"chapter_optional\"),\n", + " name=\"tutorial_prior_passing_1\",\n", + " unique_tag=dataset_name,\n", + " n_live=100,\n", + " iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations\n", + ")\n", + "\n", + "analysis_1 = al.AnalysisImaging(dataset=dataset)\n", + "\n", + "result_1 = search_1.fit(model=model_1, analysis=analysis_1)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Result (Search 1)__\n", + "\n", + "The results which are used for prior passing are summarised in the `info` attribute." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(result_1.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Prior Passing__\n", + "\n", + "We are now going to use the prior passing API to pass these results, in a way which does not require us to manually\n", + "write out the inferred parameter values of each component. The details of how prior passing is performed will be\n", + "expanded upon at the end of the tutorial.\n", + "\n", + "We start with the lens's bulge, which in the previous search was an `Sersic` with its centre fixed to (0.0, 0.0)\n", + "and its `sersic_index` fixed to 4.0. The API for passing priors is shown below and there are two things worth noting:\n", + "\n", + " 1) We pass the priors using the `model_centred` attribute of the result. This informs **PyAutoLens** to pass the result as a\n", + " model component that is to be fitted for in the next search, using priors that are initialized from the previous\n", + " search's result. Note, if we pass through `model_centred` a parameter that was fixed in search 1 (e.g. the `sersic_index`) it\n", + " will be fixed to the same value in search 2.\n", + "\n", + " 2) We do not pass the `centre` or `sersic_index` using `model_centred`, because it would be fixed to the values that it was in\n", + " the first search. By omitting the centre, it uses the default priors on a lens galaxy, whereas we manually tell the\n", + " Sersic index to use a `TruncatedGaussianPrior` centred on 4.0." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "bulge = af.Model(al.lp_linear.Sersic)\n", + "\n", + "bulge.ell_comps = result_1.model_centred.galaxies.lens.bulge.ell_comps\n", + "bulge.effective_radius = result_1.model_centred.galaxies.lens.bulge.effective_radius\n", + "bulge.sersic_index = af.TruncatedGaussianPrior(\n", + " mean=4.0, sigma=2.0, lower_limit=0.0, upper_limit=5.0\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For the mass, we again must account for how its centre was fixed to (0.0\", 0.0\") and therefore not pass the centre.\n", + "The external shear belongs to its own field, so we pass that field model separately. Taking it from\n", + "`result_1.model_centred.fields` keeps its parameters free with the priors learned in the first search; taking\n", + "`result_1.instance.fields` would fix them to the fitted values instead." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "mass = af.Model(al.mp.Isothermal)\n", + "mass.einstein_radius = result_1.model_centred.galaxies.lens.mass.einstein_radius\n", + "mass.ell_comps = result_1.model_centred.galaxies.lens.mass.ell_comps\n", + "field = result_1.model_centred.fields" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For the source's bulge, we are passing the result of an `ExponentialCore` to an `Sersic`.\n", + "\n", + "We can use a special prior passing method to do this, called `take_attributes`. This scans the `ExponentialCore`\n", + "passed to the `take_attributes` method for all parameters which have the same name as the `Sersic` model,\n", + "and if their names are the same it copies their prior from the centred model. Thus, it will locate the\n", + "parameters in common between the two profiles (`centre`, `ell_comps`, `effective_radius`) and pass those,\n", + "leaving the `sersic_index`'s priors as the default values.\n", + "\n", + "The `take_attributes` method is used in many examples of prior passing, when we pass a simpler parameterization of a\n", + "model to a more complex model. Another good example would be passing the result of a `IsothermalSph` to an\n", + "`Isothermal`." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "source_bulge = af.Model(al.lp_linear.Sersic)\n", + "source_bulge.take_attributes(result_1.model_centred.galaxies.source.bulge)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We now compose the model with these components that have had their priors customized." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "lens = af.Model(al.Galaxy, redshift=0.5, bulge=bulge, mass=mass)\n", + "\n", + "source = af.Model(al.Galaxy, redshift=1.0, bulge=source_bulge)\n", + "\n", + "model_2 = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The `info` attribute shows the model, including how all priors are updated via prior passing." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(model_2.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Compare the priors in `model_2.info` with those in `model_1.info`. Transferred free parameters now have truncated\n", + "Gaussian priors centred on the first result. Newly freed parameters retain the priors we assigned separately.\n", + "The widths come from configuration; they need not all be narrower than the original priors.\n", + "\n", + "The two changes we made deliberately, and separately from the passing itself, are structural: `centre` and\n", + "`sersic_index` are free again, because we chose not to pass those, and the source is now a `Sersic` rather than\n", + "an `ExponentialCore` \u2014 the upgrade `take_attributes` exists to make possible." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model_2).figure()" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Search__\n", + "\n", + "We now fit the second model, using a separate output name so we can inspect both searches and their priors." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "search_2 = af.Nautilus(\n", + " path_prefix=Path(\"howtolens\", \"chapter_optional\"),\n", + " name=\"tutorial_prior_passing_2\",\n", + " unique_tag=dataset_name,\n", + " n_live=100,\n", + " iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations\n", + ")\n", + "\n", + "analysis_2 = al.AnalysisImaging(dataset=dataset)\n", + "\n", + "print(\n", + " \"The non-linear search has begun running - checkout the output/howtolens/chapter_optional\"\n", + " \" folder for live output of the results, images and lens model.\"\n", + " \" This Jupyter notebook cell with progress once search has completed - this could take some time!\"\n", + ")\n", + "\n", + "result_2 = search_2.fit(model=model_2, analysis=analysis_2)\n", + "\n", + "print(\"Search has finished run - you may now continue the notebook.\")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Result__\n", + "\n", + "We can again inspect the results via the `info` attribute." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(result_2.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Inspect the fitted image and residuals to assess how well the second model explains the data." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "aplt.subplot_fit_imaging(fit=result_2.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Wrap Up__\n", + "\n", + "We have fitted a simpler model, used `result_1.model_centred` to transfer priors for selected components, and fitted\n", + "a second model with additional freedom. Entire profiles or galaxies can also be transferred when appropriate:\n", + "\n", + "```python\n", + "bulge = result_1.model_centred.galaxies.lens.bulge\n", + "lens = result_1.model_centred.galaxies.lens\n", + "source = result_1.model_centred.galaxies.source\n", + "```\n", + "\n", + "Passing `result_1.instance` instead supplies fixed fitted values. Tutorial 6 uses this to fix lens-light geometry\n", + "while continuing to solve linear intensities. The later uncertainties are conditional on the quantities held fixed.\n", + "\n", + "This optional technique remains available, but it is not required for the search-chaining workflow in the main\n", + "chapter. Inspect the first fit carefully: centring priors on a local maximum can make other solutions harder to find.\n", + "Using constraints inferred from the same data as new priors also requires care when interpreting later uncertainties.\n", + "\n", + "__Detailed Explanation Of Prior Passing__\n", + "\n", + "For each transferred free parameter, `model_centred` creates a `TruncatedGaussianPrior`. Its mean is the posterior\n", + "median when available, falling back to the maximum-likelihood value for results without a posterior median.\n", + "Parameter limits are taken from configuration, falling back to the original prior's limits.\n", + "\n", + "The width is determined by the parameter's configured width modifier. In this implementation it is not taken\n", + "from the posterior error bars. The new priors therefore concentrate exploration near inferred values without\n", + "reproducing the complete posterior distribution or its correlations.\n", + "\n", + "An absolute width modifier specifies sigma in the parameter's units. A relative width modifier scales with the\n", + "inferred value, with any configured floor providing a minimum width. A parameter near zero can otherwise produce\n", + "a vanishingly small relative width, so centres and other parameters that can cross zero require particular care.\n", + "The linear intensities used here are solved inside the likelihood and do not receive non-linear priors.\n", + "\n", + "Explicit alternatives are `result_1.model_centred_absolute(a=...)` and `result_1.model_centred_relative(r=...)`.\n", + "The absolute variant sets sigma to `a`; the relative variant sets sigma to `r` times the inferred value. Choose\n", + "positive, meaningful widths for the components being transferred: a single relative factor is unsuitable for\n", + "parameters that can be zero or negative, and a single absolute width need not suit parameters with different units.\n", + "\n", + "These centred priors need not match a strongly asymmetric or multimodal posterior. Even a broad width does not\n", + "guarantee that the second search can recover solutions missed by the first.\n", + "\n", + "__EXAMPLE__\n", + "\n", + "Suppose a first search gives a posterior median Sersic index of 4.0. With an absolute width modifier of 0.8,\n", + "`model_centred` constructs a truncated Gaussian prior with mean 4.0 and sigma 0.8, subject to the parameter limits.\n", + "With a relative width modifier of 0.8 and no active floor, sigma would instead be 4.0 * 0.8 = 3.2.\n", + "\n", + "These values illustrate the distinction; they are not recommended settings or a statement of the current defaults.\n", + "The centre of a new prior comes from the result, while its width expresses how much freedom we give the next search.\n", + "\n", + "**\ud83e\udd16 Ask AI:** In this two-search lens fit, some parameters receive priors from `model_centred`, others receive fresh\n", + "priors, and some remain fixed. How could each choice affect the solutions found and the uncertainties reported?\n", + "\n", + "Return to Tutorial 6 for the main chapter's search-chaining approach, or continue to chapter 3 for pixelized source\n", + "reconstructions." + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.1" + }, + "colab": { + "aiContexts": { + "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_prior_passing.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" + } + }, + "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file diff --git a/scripts/chapter_2_lens_modeling/README.md b/scripts/chapter_2_lens_modeling/README.md index f2d037b..419ff49 100644 --- a/scripts/chapter_2_lens_modeling/README.md +++ b/scripts/chapter_2_lens_modeling/README.md @@ -1,27 +1,26 @@ -In chapter 2, we'll take you through how to model strong lenses using a non-linear search, ending with how -searches are chained together into automated lens modeling pipelines. +In chapter 2, we fit strong lenses with non-linear searches, investigate difficult solutions and build a search chain. +The six main lessons are followed by a summary. Results are covered in Tutorial 2 and SLaM in Tutorial 6. -**Colab** links to every tutorial are included. +## Tutorials -# Files +- [Tutorial 1: Non-linear Search](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb) — Parameter space, priors and fitting a lens model. -- [Tutorial 1: Non-linear Search](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb) — How a non-linear search is used to fit a lens model and the concepts of a parameter space and priors. +- [Tutorial 2: Practicalities](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb) — Running fits and inspecting their results. -- [Tutorial 2: Practicalities](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb) — Practicalities of performing model-fitting, like how to inspect the results on your hard-disk. +- [Tutorial 3: Why Modeling Is Hard](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.ipynb) — Local maxima, degeneracies and investigating difficult fits. +- [Tutorial 4: Linear Profiles](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_4_linear_profiles.ipynb) — Solving light-profile intensities and using multi-Gaussian expansions. -- [Tutorial 3: Why Modeling Is Hard](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.ipynb) — What to do when PyAutoLens finds an inaccurate lens model. +- [Tutorial 5: Data and Likelihoods](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_5_data_and_likelihoods.ipynb) — Separating datasets, models and likelihoods, including positions penalties. -- [Tutorial 4: Linear Profiles](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_4_linear_profiles.ipynb) — Light profiles which capture complex morphologies in a reduced number of non-linear parameters. +- [Tutorial 6: Search Chaining](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_6_search_chaining.ipynb) — Combining searches and introducing the SLaM pipelines. -- [Tutorial 6: Masking and Positions](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_2_lens_modeling/tutorial_6_masking_and_positions.ipynb) — How to mask and mark positions on your data to improve the lens model. +- [Tutorial 7: Summary](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_7_summary.ipynb) — Bringing the chapter together and continuing to pixelized sources. -- [Tutorial 7: Results](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_2_lens_modeling/tutorial_7_results.ipynb) — Overview of the results available after successfully fitting a lens model. +## Optional reading -- [Tutorial 8: Need for Speed](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_2_lens_modeling/tutorial_8_need_for_speed.ipynb) — How to fit complex models whilst balancing efficiency and run-time. +- [Need for Speed](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_need_for_speed.ipynb) — Computation, batching and estimating runtime. -- [Tutorial 9: Search Chaining](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_2_lens_modeling/tutorial_9_search_chaining.ipynb) — Breaking the lens modeling procedure into a chained sequence of model-fits. +- [Historical Prior Passing](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_prior_passing.ipynb) — An optional runnable example of prior passing using model_centred, a technique central to older workflows. -- [Tutorial 10: Prior Passing](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_2_lens_modeling/tutorial_10_prior_passing.ipynb) — How the results of earlier searches are passed to later searches. - -- [Tutorial 11: SLaM](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.11.1.1/notebooks/chapter_2_lens_modeling/tutorial_11_slam.ipynb) — Template pipelines for fitting lens models in standardized ways. +- [Searches](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_searches.ipynb) — Alternative non-linear search methods. diff --git a/scripts/chapter_2_lens_modeling/introduction b/scripts/chapter_2_lens_modeling/introduction index 4d6881c..2621521 100755 --- a/scripts/chapter_2_lens_modeling/introduction +++ b/scripts/chapter_2_lens_modeling/introduction @@ -1,14 +1,14 @@ -At the end of the introduction tutorials, we could fit strong lensing `Imaging` with a `Tracer`. However, we simulated the -image ourselves, which meant we knew the combination of `LightProfile`'. and `MassProfile`'. provided a good fit. - -In this set of tutorials, we'll deal the situation that we face in the real world and assume we have no knowledge of -which solutions actually provide a good fit. This process of finding the good solutions is called 'lens modeling', -and its what we wrote **PyAutoLens** to do. - -At the end of tutorials you will understand: - -1) The concept of a `NonLinearSearch` and non-linear parameter space. -2) How to perform a `NonLinearSearch` to fit a lens model. -3) The trade-off between realism and complexity when choosing a lens model. -4) Why an incorrect lens model may be inferred and how to prevent this from happening. -5) The challenges that are involved in inferred a robust lens model in a computationally reasonable run-time. +At the end of the introduction tutorials, we could fit strong lensing `Imaging` with a `Tracer`. However, we simulated the +image ourselves, which meant we knew the combination of light and mass profiles that provided a good fit. + +In this set of tutorials, we'll deal with the situation that we face in the real world and assume we have no knowledge of +which solutions actually provide a good fit. This process of finding the good solutions is called 'lens modeling', +and it's what we wrote **PyAutoLens** to do. + +At the end of these tutorials you will understand: + +1) The concept of a `NonLinearSearch` and non-linear parameter space. +2) How to perform a `NonLinearSearch` to fit a lens model. +3) The trade-off between realism and complexity when choosing a lens model. +4) Why an incorrect lens model may be inferred and how to investigate alternative solutions. +5) The challenges that are involved in inferring a robust lens model in a computationally reasonable run-time. diff --git a/scripts/chapter_2_lens_modeling/tutorial_10_prior_passing.py b/scripts/chapter_2_lens_modeling/tutorial_10_prior_passing.py deleted file mode 100644 index 43f4b74..0000000 --- a/scripts/chapter_2_lens_modeling/tutorial_10_prior_passing.py +++ /dev/null @@ -1,369 +0,0 @@ -""" -Tutorial 10: Prior Passing -========================== - -In the previous tutorial, we used non-linear search chaining to break the model-fitting procedure down into two -non-linear searches. This used an initial search to fit a simple lens model, whose results were used to tune and -initialize the priors of a more complex lens model that was fitted by the second search. - -However, the results were passed between searches were passed manually. I explicitly wrote out every result as a prior -containing the values inferred in the first search. **PyAutoLens** has an API for passing priors in a more generalized -way, which is the topic of this tutorial. - -__Contents__ - -- **Initial Setup:** Load the same strong lensing data as the previous tutorial. -- **Dataset Auto-Simulation:** Simulate the dataset via its simulator script if it is not on your hard-disk. -- **Model:** Compose the lens model fitted to the data. -- **Search:** Configure the non-linear search used to fit the model. -- **Result (Search 1):** The results of search 1, which are used for prior passing. -- **Prior Passing:** Use the prior passing API to pass the results of search 1 without writing out values manually. -- **Result:** Overview of the results of the model-fit. -- **Wrap Up:** Summary of the script and next steps. -- **Detailed Explanation Of Prior Passing:** A detailed overview of how prior passing works and tools to customize it. -- **EXAMPLE:** Lets go through an example using a real parameter. - -""" - -from autolens import jax_wrapper # Sets JAX environment before other imports - -# from autolens import setup_notebook; setup_notebook() - -import numpy as np -from pathlib import Path -import autolens as al -import autolens.plot as aplt -import autofit as af - -""" -__Initial Setup__ - -we'll use the same strong lensing data as the previous tutorial, where: - - - The lens galaxy's light is an `Sersic`. - - The lens system uses an `Isothermal` galaxy mass profile and a separate `ExternalShear` field. - - The source galaxy's light is an `Exponential`. - -All the usual steps for setting up a model fit (masking, analysis, etc.) are included below. -""" -dataset_name = "lens_sersic" -dataset_path = Path("dataset") / "imaging" / dataset_name - -""" -__Dataset Auto-Simulation__ - -If the dataset does not already exist on your system, it will be created by running the corresponding -simulator script. This ensures that all example scripts can be run without manually simulating data first. -""" -al.util.dataset.simulate_if_needed( - dataset_path, simulator="scripts/simulator/lens_sersic.py" -) - -dataset = al.Imaging.from_fits( - data_path=dataset_path / "data.fits", - noise_map_path=dataset_path / "noise_map.fits", - psf_path=dataset_path / "psf.fits", - pixel_scales=0.1, -) - -mask_radius = 2.6 - -mask = al.Mask2D.circular( - shape_native=dataset.shape_native, - pixel_scales=dataset.pixel_scales, - radius=mask_radius, -) - -dataset = dataset.apply_mask(mask=mask) - -aplt.subplot_imaging_dataset(dataset=dataset) - -""" -__Model__ - -We are going to use the same result of search 1 from the previous tutorial. Thus, we set up an identical model such -that we instantly load the result from hard-disk. -""" -bulge = af.Model(al.lp_linear.Sersic) -mass = af.Model(al.mp.Isothermal) - -bulge.centre_0 = 0.0 -bulge.centre_1 = 0.0 -mass.centre_0 = 0.0 -mass.centre_1 = 0.0 - -mass.ell_comps = bulge.ell_comps - -bulge.sersic_index = 4.0 - -lens = af.Model(al.Galaxy, redshift=0.5, bulge=bulge, mass=mass) -field = af.Model(al.MassField, redshift=0.5, shear=al.mp.ExternalShear) - -source = af.Model(al.Galaxy, redshift=1.0, bulge=al.lp_linear.ExponentialCore) - -model_1 = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field) - -""" -The `info` attribute shows the model in a readable format. -""" -print(model_1.info) - -""" -The same model can also be visualized as a figure, making its structure easier to understand at a glance. - -The figure shows how the model is organized: which parameters belong to each component, and whether they are free, -fixed, shared, linked by an expression, solved during the fit, or not configured. `model.info` provides the -corresponding numerical details, including the prior assigned to each free parameter and the value of each fixed -parameter. - -This is the same model as the first search of the previous tutorial. Keep it in mind as you read the second -model below: this tutorial is about what prior passing changes between the two and, more importantly, about what -it does not. -""" -af.ModelPlotter(model_1).figure() - -""" -__Search__ - -We also create the same search as the previous tutorial, using the same name to ensure we use the same results, and -run it. -""" -search_1 = af.Nautilus( - path_prefix=Path("howtolens", "chapter_2"), - name="tutorial_9_search_chaining_1", - unique_tag=dataset_name, - n_live=100, - iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations -) - -analysis_1 = al.AnalysisImaging(dataset=dataset) - -result_1 = search_1.fit(model=model_1, analysis=analysis_1) - -""" -__Result (Search 1)__ - -The results which are used for prior passing are summarised in the `info` attribute. -""" -print(result_1.info) - -""" -__Prior Passing__ - -We are now going to use the prior passing API to pass these results, in a way which does not require us to manually -write out the inferred parameter values of each component. The details of how prior passing is performed will be -expanded upon at the end of the tutorial. - -We start with the lens's bulge, which in the previous search was an `Sersic` with its centre fixed to (0.0, 0.0) -and its `sersic_index` fixed to 4.0. The API for passing priors is shown below and there are two things worth noting: - - 1) We pass the priors using the `model` attribute of the result. This informs **PyAutoLens** to pass the result as a - model component that is to be fitted for in the next search, using priors that are initialized from the previous - search's result. Note, if we pass as a `model` a parameter that was fixed in search 1 (e.g. the `sersic_index`) it - will be fixed to the same value in search 2. - - 2) We do not pass the `centre` or `sersic_index` using `model`, because it would be fixed to the values that it was in - the first search. By omitting the centre, it uses the default priors on a lens galaxy, whereas we manually tell the - Sersic index to use a `TruncatedGaussianPrior` centred on 4.0. -""" -bulge = af.Model(al.lp_linear.Sersic) - -bulge.ell_comps = result_1.model.galaxies.lens.bulge.ell_comps -bulge.effective_radius = result_1.model.galaxies.lens.bulge.effective_radius -bulge.sersic_index = af.TruncatedGaussianPrior( - mean=4.0, sigma=2.0, lower_limit=0.0, upper_limit=5.0 -) - -""" -For the mass, we again must account for how its centre was fixed to (0.0", 0.0") and therefore not pass the centre. -The external shear belongs to its own field, so we pass that field model separately. Taking it from -`result_1.model.fields` keeps its parameters free with the priors learned in the first search; taking -`result_1.instance.fields` would fix them to the fitted values instead. -""" -mass = af.Model(al.mp.Isothermal) -mass.einstein_radius = result_1.model.galaxies.lens.mass.einstein_radius -mass.ell_comps = result_1.model.galaxies.lens.mass.ell_comps -field = result_1.model.fields - -""" -For the source's bulge, we are passing the result of an `Exponential` to an `Sersic`. - -We can use a special prior passing method to do this, called `take_attributes`. This scans the `Exponential` -passed to the `take_attributes` method for all parameters which have the same name as the `Sersic` model, -and if their names are the same it passes their prior as a `model` (like we did above). Thus, it will locate the -parameters in common between the two profiles (`centre`, `ell_comps`, `effective_radius`) and pass those, -leaving the `sersic_index`'s priors as the default values. - -The `take_attributes` method is used in many examples of prior passing, when we pass a simpler parameterization of a -model to a more complex model. Another good example would be passing the result of a `IsothermalSph` to an -`Isothermal`. -""" -source_bulge = af.Model(al.lp_linear.Sersic) -source_bulge.take_attributes(result_1.model.galaxies.source.bulge) - -""" -We now compose the model with these components that have had their priors customized. -""" -lens = af.Model(al.Galaxy, redshift=0.5, bulge=bulge, mass=mass) - -source = af.Model(al.Galaxy, redshift=1.0, bulge=source_bulge) - -model_2 = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field) - -""" -The `info` attribute shows the model, including how all priors are updated via prior passing. -""" -print(model_2.info) - -""" -Prior passing replaces almost every number in the `info` above with a narrow prior centred on search 1's result, -but it changes nothing about the model's structure, because a prior is a number and numbers are not structure. - -The two changes we made deliberately, and separately from the passing itself, are structural: `centre` and -`sersic_index` are free again, because we chose not to pass those, and the source is now a `Sersic` rather than -an `ExponentialCore` — the upgrade `take_attributes` exists to make possible. -""" -af.ModelPlotter(model_2).figure() - -""" -__Search__ - -Lets setup and run the search. I have given it a different name to the previous tutorial so we can compare the priors -that were passed. -""" -search_2 = af.Nautilus( - path_prefix=Path("howtolens", "chapter_2"), - name="tutorial_10_prior_passing_2", - unique_tag=dataset_name, - n_live=100, - iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations -) - -analysis_2 = al.AnalysisImaging(dataset=dataset) - -print( - "The non-linear search has begun running - checkout the output/howtolens/chapter_2" - " folder for live output of the results, images and lens model." - " This Jupyter notebook cell with progress once search has completed - this could take some time!" -) - -result_2 = search_2.fit(model=model_2, analysis=analysis_2) - -print("Search has finished run - you may now continue the notebook.") - -""" -__Result__ - -We can again inspect the results via the `info` attribute. -""" -print(result_2.info) - -""" -And a plot of the image shows we get a good model again! -""" -aplt.subplot_fit_imaging(fit=result_2.max_log_likelihood_fit) - -""" -__Wrap Up__ - -This tutorial has covered the core of the prior passing API; the chaining examples in the `autolens_workspace` -(e.g. `autolens_workspace/scripts/guides/modeling/chaining.py`) expand on it further. The main thing to note is that -we can pass entire profiles or galaxies using prior passing, if their model does not change (which for the bulge, -mass and source_bulge above, was not true). The API to pass a whole profile or galaxy is as follows: - - bulge = result_1.model.galaxies.lens.bulge - lens = result_1.model.galaxies.lens - source = result_1.model.galaxies.source - -We can also pass priors using an `instance` instead of a `model`. When an `instance` is used, the maximum likelihood -parameter values are passed as fixed values that are therefore not fitted for by the non-linear search (reducing its -dimensionality). Chained fits often use this to fix the lens light to the best-fit model of an early search, reducing -the dimensionality of the searches that follow — the workspace's chaining examples show this in action. - -Lets now think about how priors are passed. Checkout the `model.info` file of the second search of this tutorial. The -parameters do not use the default priors we saw in search 1 (which are typically broad UniformPriors). Instead, -they use GaussianPrior`s where: - - - The mean values are the median PDF results of every parameter in search 1. - - The sigma values are specified in the `width_modifier` field of the profile's entry in the `priors.yaml' config - file (we will discuss why this is used in a moment). - -Like the manual `GaussianPrior`'s that were used in the previous tutorial, the prior passing API sets up the prior on each -parameter with a `GaussianPrior` centred on the high likelihood regions of parameter space! - -__Detailed Explanation Of Prior Passing__ - -To end, I provide a detailed overview of how prior passing works and illustrate tools that can be used to customize -its behaviour. It is up to you whether you want read this, or go ahead to the next tutorial! - -Lets say I chain two parameters as follows: - - `mass.einstein_radius = result_1.model.galaxies.lens.mass.einstein_radius` - -By invoking the `model` attribute, the prior is passed following 3 rules: - - 1) The new parameter, in this case the einstein radius, uses a `GaussianPrior`.This is ideal, as the 1D pdf results - we compute at the end of a search are easily summarised as a Gaussian. - - 2) The mean of the `GaussianPrior` is the median PDF value of the parameter estimated in search 1. - - This ensures that the initial sampling of the new search's non-linear starts by searching the region of non-linear - parameter space that correspond to highest log likelihood solutions in the previous search. Our priors therefore - correspond to the `correct` regions of parameter space. - - 3) The sigma of the Gaussian uses the value specified for the profile in the `config/priors/*.yaml` config file's - `width_modifer` field (check these files out now). - -The idea here is simple. We want a value of sigma that gives a `GaussianPrior` wide enough to search a broad -region of parameter space, so that the lens model can change if a better solution is nearby. However, we want it -to be narrow enough that we don't search too much of parameter space, as this will be slow or risk leading us -into an incorrect solution! - -The `width_modifier` values in the priors config file have been chosen based on our experience as being a good -balance broadly sampling parameter space but not being so narrow important solutions are missed. - -There are two ways a value is specified using the priors/width file: - - 1) Absolute: In this case, the error assumed on the parameter is the value given in the config file. - For example, if for the width on centre_0 of a light profile, the width modifier reads "Absolute" with a value - 0.05. This means if the error on the parameter centre_0 was less than 0.05 in the previous search, the sigma of - its `GaussianPrior` in this search will be 0.05. - - 2) Relative: In this case, the error assumed on the parameter is the % of the value of the estimated value given in - the config file. For example, if the intensity estimated in the previous search was 2.0, and the relative error in - the config file reads "Relative" with a value 0.5, then the sigma of the `GaussianPrior` will be 50% of this - value, i.e. sigma = 0.5 * 2.0 = 1.0. - -We use absolute and relative values for different parameters, depending on their properties. For example, using the -relative value of a parameter like the `Profile` centre makes no sense. If our lens galaxy is centred at (0.0, 0.0), -the relative error will always be tiny and thus poorly defined. Therefore, the default configs in **PyAutoLens** use -absolute errors on the centre. - -However, there are parameters where using an absolute value does not make sense. Intensity is a good example of this. -The intensity of an image depends on its units, S/N, galaxy brightness, etc. There is no single absolute value that -one can use to generically chain the intensity of any two proflies. Thus, it makes more sense to chain them using -the relative value from a previous search. - -We can customize how priors are passed from the results of a search and non-linear search by editing the - `prior_passer` settings in the `general.yaml` config file. - -__EXAMPLE__ - -Lets go through an example using a real parameter. Lets say in search 1 we fit the lens galaxy's light with an -elliptical Sersic profile, and we estimate that its sersic index is equal to 4.0. - -To pass this as a prior to search 2 we write: - - lens.bulge.sersic_index = result_1.model.lens.bulge.sersic_index - -The prior on the lens galaxy's bulge sersic index in search 2 would thus be a `GaussianPrior` with mean=4.0. - -The value of the Sersic index `width_modifier` in the priors config file sets sigma. The prior config file specifies -that we use an "Absolute" value of 0.8 to chain this prior. Thus, the `GaussianPrior` in search 2 would have a -mean=4.0 and sigma=0.8. - -If the prior config file had specified that we use an relative value of 0.8, the GaussianPrior in search 2 would have a -mean=4.0 and sigma = 4.0 * 0.8 = 3.2. - -And with that, we're done. Chaining priors is a bit of an art form, but one that works really well. -""" diff --git a/scripts/chapter_2_lens_modeling/tutorial_11_slam.py b/scripts/chapter_2_lens_modeling/tutorial_11_slam.py deleted file mode 100755 index bb22d0d..0000000 --- a/scripts/chapter_2_lens_modeling/tutorial_11_slam.py +++ /dev/null @@ -1,69 +0,0 @@ -""" -Tutorial 11: SLaM -================= - -In the previous two tutorials, we learnt how search chaining breaks a lens model-fit into a sequence of simpler -non-linear searches, and how prior passing carries the results of each search into the next. Together, they give us -the flexibility to juggle the dimensionality, priors and settings of each search — the three drivers of run-time we -met in tutorial 8 — whilst still fitting a complex and realistic lens model at the end. - -You could now write your own chained sequences of searches, tailored to whatever lens model is of particular interest -to your scientific study. However, for most lens models there are standardized approaches one can take to fitting -them. For example, an effective approach is to first fit a model for the lens's light, then a model for its mass and -the source. It would be wasteful for all **PyAutoLens** users to have to write their own chained pipelines to perform -the same tasks. - -For this reason, the `autolens_workspace` comes with standardized chained pipelines, which fit common lens models in -ways we have tested are efficient and robust. This closing tutorial does not run any code; it is a pointer to where -that material lives, so you know where to go once you want to scale your lens modeling up. - -__Contents__ - -- **Search Chaining In The Workspace:** Where the workspace documents the chaining API introduced in tutorials 9 and 10. -- **SLaM (Source, Light and Mass):** The standardized pipelines that chain searches for you. -- **Wrap Up:** Choosing between single searches, your own chained fits and the SLaM pipelines. - -__Search Chaining In The Workspace__ - -The chaining and prior passing API we introduced in tutorials 9 and 10 is documented in full in the workspace guide -`autolens_workspace/scripts/guides/modeling/chaining.py`. It covers the concise model composition API used in chained -fits, prior passing and the tools for customizing it, and how chaining is used in practice for automated lens -modeling. - -__SLaM (Source, Light and Mass)__ - -The workspace's standardized pipelines are called the **SLaM** (Source, Light and Mass) pipelines. They are composed -of a specific sequence of chained searches: - - - `Source`: A pipeline that focuses on producing a robust model for the source's light, using simpler models for the - lens's light and mass. - - - `Light`: A pipeline that fits a complex lens light model (e.g. one with many components), using the initialized - source model to cleanly deblend the lens and source light. - - - `Mass`: A pipeline that fits a complex lens mass model, benefitting from the good models for the lens's light and - source. - -For fitting very complex lens models, for example ones which decompose the mass into its stellar and dark components, -the **SLaM** pipelines have been carefully crafted to do this in a reliable and automated way that is still efficient. -They also make fitting many different models to a single dataset efficient, as they reuse the results of earlier -searches (e.g. in the Source pipeline) to fit different models in the `Light` and `Mass` pipelines for the lens's -light and mass. - -The canonical introduction is `autolens_workspace/scripts/guides/modeling/slam_start_here.py`, which walks through the -pipeline structure end-to-end. Runnable SLaM examples then live as `slam.py` scripts inside the feature folders of -each topic, for example `autolens_workspace/scripts/imaging/features/pixelization/slam.py` and -`autolens_workspace/scripts/imaging/features/multi_gaussian_expansion/slam.py`. - -__Wrap Up__ - -Whether you should use individual searches, your own chained fits, the SLaM pipelines or write your own model-fitting -script depends on the scope of your scientific analysis. I would advise you begin by trying to adapt the scripts in -the `autolens_workspace` to fit your data, and also try using the SLaM pipelines once you are a confident -**PyAutoLens** user. - -This tutorial concludes the lens modeling chapter. In the next chapter, we introduce pixelizations, which reconstruct -the source galaxy on a pixel-grid rather than with light profiles. -""" - -# from autolens import setup_notebook; setup_notebook() diff --git a/scripts/chapter_2_lens_modeling/tutorial_12_summary b/scripts/chapter_2_lens_modeling/tutorial_12_summary deleted file mode 100755 index 7ba51a1..0000000 --- a/scripts/chapter_2_lens_modeling/tutorial_12_summary +++ /dev/null @@ -1,20 +0,0 @@ -Congratulations, you've completed the second chapter of the **PyAutoLens** tutorials! - -In this chapter, you learnt: - -1) What a non-linear search is. -2) How to use a non-linear search to sample the parameter space of a model. -3) How the priors we give parameters specify our search of this parameter space. -4) How one must carefully balance complexity and realism when fitting a model to a data-set. -5) The importance of factoring in run-speed when modeling a lens, and tricks to speed up the analysis. -6) About masking data and using positions in the analysis. -7) How to chain searches together into automated lens modeling pipelines, passing priors from one search - to the next, and how the SLaM pipelines standardize this. - -At this point, you are ready to begin modeling lenses. The 'modeling' folders in the -autolens_workspace contains a number of scripts that can be easily adopted to model lens using a variety of different -approaches, lens models and non-linear searches. If you have your own lens data, I'd recommend you adapt these -scripts to your data. If you don't have your own data, checkout the 'simulators' folder to simulate your own dataset! - -Alternatively, you may wish to continue on to chapter 3 on pixelized source reconstructions. - diff --git a/scripts/chapter_2_lens_modeling/tutorial_1_non_linear_search.py b/scripts/chapter_2_lens_modeling/tutorial_1_non_linear_search.py index fa3f54b..5689ba2 100644 --- a/scripts/chapter_2_lens_modeling/tutorial_1_non_linear_search.py +++ b/scripts/chapter_2_lens_modeling/tutorial_1_non_linear_search.py @@ -1,4 +1,4 @@ -""" +r""" Tutorial 1: Non-linear Search ============================= @@ -18,6 +18,7 @@ - **Overview:** Introduce the experiment and the results to inspect. - **Parameter Space:** Understand how free parameters define the models a search can explore. +- **More Dimensions:** Understand how model parameters work together. - **Automated Exploration:** Use a non-linear search to explore possible model parameters. - **Deeper Background:** Find further explanations of likelihoods and Bayesian inference. - **PyAutoFit:** Introduce the tools used to define models, priors and searches. @@ -50,23 +51,45 @@ __Parameter Space__ -Imagine varying just two properties of a lens model: the lens’s Einstein radius and the source’s effective radius. Each -possible pair of values represents a different model and corresponds to a point in a two-dimensional **parameter -space**. +Imagine that we fix every property of our lens model except its Einstein radius, $\theta_{\rm E}$. We can calculate a predicted image for each value of this parameter, compare that image with our observations, and calculate its log likelihood: + +$$ +\ln \mathcal{L} = f(\theta_{\rm E}). +$$ + +This is a one-dimensional parameter space. Each position along the horizontal axis represents a different Einstein radius, and the height of the curve tells us how well that model fits the data. + +Changing the Einstein radius changes the deflection of the source light and therefore the positions and appearance of its lensed images. Values that place the predicted arcs close to the observed arcs can give a higher likelihood; values that put light where the data contain none give a poorer fit. + +Now allow the source's effective radius, $R_{\rm e}$, to vary too: + +$$ +\ln \mathcal{L} = f(\theta_{\rm E}, R_{\rm e}). +$$ + +Every pair of values specifies a different lens model. We can imagine these pairs laid out across a sheet, with Einstein radius along one axis and source size along the other. The log likelihood gives a height above each point, forming a surface. -Adding another free parameter adds another dimension. Although we cannot easily draw a space with many dimensions, the -idea remains the same: each point specifies a complete set of values for the model’s free parameters. +Changing the source size changes how extended its predicted light is. After lensing, this affects the widths and brightness distribution of the arcs. The best-fitting source size can depend on the mass model: changing one parameter can sometimes be partly compensated by changing another. On our likelihood surface, this can produce an elongated or curved ridge of relatively good fits. -For each point, we can predict an image and compare it with the data to calculate a log likelihood. Plotting this value -above each point gives a **log likelihood surface**. High regions correspond to models that explain the data better -than models in lower regions. +__More Dimensions__ -The surface can have several peaks, curved ridges and broad regions where different parameter combinations produce -similar images. These features make it difficult to find the best-fitting model and establish which other models are -also consistent with the observations. +Our actual model has more than two free parameters. The lens has a centre, and the source has its own centre, size and intensity. We can write the same idea more generally as: -**🤖 Ask AI:** In strong-lens modeling, why might changing the lens mass and the source size together produce similar -images, and how could this appear on a likelihood surface? +$$ +\ln \mathcal{L} = f(p_1, p_2, \ldots, p_N), +$$ + +where each $p_i$ is one of the model's free parameters. + +Each point in this $N$-dimensional space specifies all the values needed to construct a model and predict an image. A non-linear search explores these points to find models that explain the observations and investigate the range of parameter values consistent with them. + +Although we cannot draw the full surface when there are many parameters, its structure still matters. There can be broad regions of poor fits, narrow ridges of good fits, and separate peaks corresponding to different explanations of the image. + +For example, moving the source changes the arrangement and relative brightness of its lensed images. Changing the lens mass can also change those images. Several combinations may reproduce some features reasonably well, while only a smaller region reproduces all of them together. + +This is why automated modeling involves more than adjusting each parameter independently until the image looks right. The search must explore how the parameters work together. + +**🤖 Ask AI:** In strong-lens modeling, why might changing the lens mass and the source size together produce similar images, and how could this appear on a likelihood surface? __Automated Exploration__ @@ -199,14 +222,10 @@ """ We describe the source with an `ExponentialCoreSph` light profile at a fixed redshift of 1.0. -Here, we use the profile from `al.lp_linear`. Its centre and effective radius are explored by the non-linear search, -while its intensity is calculated by a linear solve for each proposed model. - -The intensity is therefore still fitted to the data, but it does not add a dimension to the non-linear search. Tutorial -4, *Linear Profiles*, explains this distinction and how it helps us fit more flexible light distributions. +Its free parameters include its centre, effective radius and intensity. The search varies these quantities together with the lens mass parameters. Changing the source intensity changes the brightness of the predicted lensed emission, allowing the model to match the observed flux as well as the shape and location of the arcs. """ -bulge = af.Model(al.lp_linear.ExponentialCoreSph) +bulge = af.Model(al.lp.ExponentialCoreSph) source = af.Model(al.Galaxy, redshift=1.0, bulge=bulge) """ @@ -224,11 +243,9 @@ """ The `model.info` attribute summarises the model before we fit it. -Look for the lens mass and source light components, the priors assigned to their free parameters and the fixed galaxy -redshifts. Notice that the source intensity is treated as a linear parameter rather than assigned a prior for the -non-linear search. +Look for the lens mass and source light components and the priors assigned to their free parameters. The source intensity is one of the quantities the search will fit; the galaxy redshifts are fixed. -This describes what we intend to fit. It contains no inferred parameter values yet, because the search has not run. +Compare these same components in the model diagram. Together, the summary and diagram describe what we intend to fit. They do not contain inferred parameter values yet, because the search has not run. """ print(model.info) @@ -237,8 +254,7 @@ The model diagram shows the same structure visually. Follow the branches from `galaxies` to the lens and source, then to their mass and light profiles. -Compare the free profile parameters with the fixed redshifts and the linearly solved source intensity. These -distinctions determine which quantities the non-linear search must explore. +Compare the free profile parameters, including the source intensity, with the fixed redshifts. These distinctions determine which quantities the non-linear search must explore. The lens redshift of 0.5 places it in front of the source at redshift 1.0. PyAutoLens uses these redshifts to establish the ordering and distances needed for ray tracing. @@ -318,7 +334,6 @@ including ray tracing and PSF convolution. It compares that prediction with the masked imaging data, using the noise map to evaluate the log likelihood. -For our linear source profile, this evaluation also solves for the intensity before calculating the likelihood. You performed the same essential comparison in Chapter 1 when you created a `FitImaging` object and inspected its `log_likelihood`. The Analysis object makes that calculation available to the search so it can be repeated for many diff --git a/scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py b/scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py index 0a86407..c14c7aa 100755 --- a/scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py +++ b/scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py @@ -126,9 +126,7 @@ The lens galaxy contains both a light profile and a mass profile. The external shear is a separate field at the lens redshift, and the source galaxy contains its own light profile. -Here, we use ordinary light profiles from `al.lp`, so their intensities are also free parameters explored by Nautilus. -Tutorial 1 used a linear source-light profile, whose intensity was solved separately. In *Linear Profiles*, we will -return to that approach and see how it simplifies more complex models. +As in Tutorial 1, the light-profile intensities are free parameters explored by Nautilus. Here, the search must determine the brightness of both the foreground lens galaxy and the background source, alongside their other properties. """ field = af.Model( diff --git a/scripts/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.py b/scripts/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.py index 63bafad..ade29e5 100644 --- a/scripts/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.py +++ b/scripts/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.py @@ -229,22 +229,19 @@ """ __Why Modeling Is Hard__ -A lens image can sometimes be reproduced approximately by several different combinations of lens light, mass and source -light. These combinations occupy different regions of parameter space. +Our example deliberately makes the search less thorough by reducing the number of live points from 200 to 21. This is a somewhat contrived way to expose a difficulty within a short tutorial: your particular run may still find a good solution. -A **local maximum** is a point whose likelihood is higher than that of nearby points, even though a better solution -exists elsewhere. The **global maximum** is the highest likelihood available within the chosen model and parameter -ranges. +The underlying problem, however, is common in modeling real lenses. Different combinations of lens light, mass and source light can reproduce parts of an image, creating several promising regions of parameter space. A search may explore one region thoroughly while missing a better solution elsewhere. -A search can spend its effort exploring one promising region and miss another. With only 21 live points, there is -little opportunity to represent all the important regions of this model’s parameter space. +A **local maximum** has a likelihood at least as high as nearby parameter values. There may still be another peak with a higher likelihood elsewhere. The **global maximum** is the highest likelihood available within the chosen model and parameter ranges. -More free parameters can make exploration harder, but the parameter count is only part of the problem. Strong -relationships between parameters, narrow regions of good solutions and separated peaks also matter. +In a real analysis, it can be difficult to establish whether the best solution we have found is a local or global maximum. We do not know the true parameters, and a plausible-looking fit does not prove that every important region has been explored. -A poor fit can therefore result from incomplete exploration. However, residuals alone do not establish that the search -has reached a local maximum: the physical model or the assumptions about the data may also be inadequate. We return to -this distinction under *Model Mismatch*. +Finding a higher-likelihood solution demonstrates that an earlier result was not the global maximum. Repeatedly recovering a similar solution increases our confidence, but does not prove that no better solution exists. + +The approaches in this tutorial are therefore tools for investigation. By changing justified priors, simplifying selected parts of the model and exploring more thoroughly, we can investigate suspicious fits and understand what makes the modeling difficult. + +Residuals also require interpretation: they can arise because the search missed a good solution, or because the model cannot describe the data adequately. We will return to this distinction under *Model Mismatch*. __Three Ways Forward__ @@ -656,17 +653,15 @@ __Search More Thoroughly__ -Our first two approaches changed the priors or reduced the freedom of the model. We now return to the original model -and ask Nautilus to explore it more thoroughly. +Our first two approaches changed the priors or reduced the freedom of the model. We now return to the original model and ask Nautilus to explore it more thoroughly. + +We increase the number of live points to 300. A larger population gives the search more opportunity to represent different promising regions of parameter space, although this generally requires more computation and does not guarantee that every important region will be found. -This retains separate centres and shapes for the lens light and mass, allowing the image to constrain them without the -links introduced above. +Increasing the number of live points is only one option. There are many different non-linear search methods, and they explore parameter space in different ways. Trying another method can make a substantial difference when a particular search struggles with a model. -We increase the number of live points to 300. A larger population gives the search more opportunity to represent -different promising regions of parameter space. +The optional tutorial, `chapter_optional/tutorial_searches.py`, introduces alternative searches, including optimisation and MCMC. Their outputs serve different purposes: finding a high-likelihood solution and characterising parameter uncertainty are related but distinct tasks. -This approach requires no estimates of the lens shape or size by eye beyond the original modeling choices. Its main -cost is computation: exploring more thoroughly generally takes longer. +When investigating a difficult fit, compare repeated runs and, where appropriate, different search methods using the same model, priors and likelihood. Examine the fitted images and residuals alongside the likelihood values. Agreement provides useful evidence; disagreement tells us that further investigation is needed. __Original Model__ @@ -857,7 +852,5 @@ Later in this chapter, we will see how search chaining brings these ideas together for more complex lens models. -First, *Linear Profiles* introduces another way to make fitting easier: solving light-profile intensities separately -from the non-linear search. This will let us describe more detailed light distributions without adding a separate -non-linear parameter for every intensity. +The next tutorial introduces another way to simplify the search while describing more detailed light distributions. """ diff --git a/scripts/chapter_2_lens_modeling/tutorial_5_data_and_likelihoods.py b/scripts/chapter_2_lens_modeling/tutorial_5_data_and_likelihoods.py new file mode 100644 index 0000000..16e77af --- /dev/null +++ b/scripts/chapter_2_lens_modeling/tutorial_5_data_and_likelihoods.py @@ -0,0 +1,524 @@ +""" +Tutorial 5: Data and Likelihoods +================================ + +Throughout this chapter, we have fitted imaging data using light and mass profiles. However, the modeling tools we have +learnt are not tied to this particular type of observation. We can use the same approach to fit interferometer +measurements, the positions of multiply imaged point sources, or the shapes of weakly lensed galaxies. + +This flexibility comes from separating the different parts of a model fit. The **dataset** contains the measurements +and their uncertainties. The **model** describes the physical system and its free parameters. The **Analysis** object +uses that model to predict the measurements and evaluates a **likelihood**, which tells us how well those predictions +agree with the data. The **search** explores the model's parameters using the likelihood and priors. + +The search does not need to know whether it is fitting image pixels, interferometer visibilities or image positions. It +supplies parameter values and receives a likelihood. By changing the dataset and the Analysis object, we can adapt the +tools we already know to a different observation, while retaining the model components appropriate to that system. + +We will build up this idea through familiar imaging examples. First, we explain why our circular masks retain the lens +galaxy, the arcs and their faint surroundings. We then consider how positions constraints provide additional +information about the mass model, and how noise scaling changes the contribution of contaminating light to the fit. + +These examples show how we can change the information entering an analysis without rebuilding the entire modeling +procedure. By the end of the tutorial, we will connect this separation to other types of lensing data and to analyses +that combine several datasets, each with its own likelihood, to constrain a shared physical model. + +__Contents__ + +- **Dataset:** Return to the imaging example containing lens and source light. +- **Circular Masks:** Understand why we retain the central lens and surrounding arcs. +- **Beyond the Bright Arcs:** Recognise the information in faint emission and apparently empty regions. +- **Mask:** Define the 2D mask applied to the dataset for the model-fit. +- **Positions Constraints:** Use corresponding image features to constrain the mass model. +- **Choosing Positions:** Identify and plot features with a common source origin. +- **The Positions Penalty:** Understand the source-plane threshold and fast consistency check. +- **Model and Analysis:** Add the positions constraint to the imaging analysis. +- **Search and Result:** Fit the image with the positions constraint. +- **Contaminating Light:** Recognise light not described by the main lens and source. +- **Extra Galaxy Dataset:** Inspect an image containing a neighbouring galaxy. +- **Extra Galaxy Region:** Load the region selected for noise scaling. +- **Noise Scaling:** Reduce the weight of contaminated pixels. +- **Interpreting the Scaled Dataset:** Distinguish lost light information from gravitational deflection. +- **Interferometer Data:** Adapt the shared model composition API to visibilities. +- **Point-Source Data:** Fit measured positions and their uncertainties. +- **Weak-Lensing Data:** Constrain mass using background galaxy shapes. +- **Multiple Datasets:** Combine suitable likelihoods to constrain shared parameters. +- **Wrap Up:** Connect datasets, models, analyses and searches. + +""" + +from autolens import jax_wrapper # Sets JAX environment before other imports + +# from autolens import setup_notebook; setup_notebook() + +from pathlib import Path +import autolens as al +import autolens.plot as aplt +import autofit as af + +""" +__Dataset__ + +Return to the image from *Practicalities*, containing both the foreground lens galaxy and the lensed source. + +Look first at the bright central galaxy, then follow its light outwards. Its brightness decreases gradually; it does +not end at a sharp boundary. Around it, the source forms bright arcs with fainter emission extending beyond their most +obvious features. + +Our model describes both galaxies. We therefore want the fitted region to contain their useful light, including the +faint outskirts that are less immediately apparent in the image.""" + +dataset_name = "lens_sersic" +dataset_path = Path("dataset") / "imaging" / dataset_name + +al.util.dataset.simulate_if_needed( + dataset_path, simulator="scripts/simulator/lens_sersic.py" +) + +dataset = al.Imaging.from_fits( + data_path=dataset_path / "data.fits", + noise_map_path=dataset_path / "noise_map.fits", + psf_path=dataset_path / "psf.fits", + pixel_scales=0.1, +) + +aplt.subplot_imaging_dataset(dataset=dataset) + +""" +__Circular Masks__ + +A circular mask gives us one continuous region containing the central lens galaxy, the arcs and their surroundings. We +fit the lens and source light together within this region. + +The figure below compares this with an annular mask, which excludes the centre. Although the annulus retains the bright +arcs, it discards the central lens light that helps constrain the foreground galaxy's profile. + +Removing the centre does not remove the lens galaxy's contribution to the arcs. Its extended light still overlaps the +source emission farther out, so we still need to describe it in our model. + +Throughout these PyAutoLens analyses, we therefore use circular masks. The annulus is shown here to explain the +information it would discard, rather than as another masking procedure to follow. + +![Circular and annular masks compared on the same simulated lens image; grey shading marks excluded pixels](../../images/chapter_2/circular_vs_annular.png) + +__Beyond the Bright Arcs__ + +The circle should extend beyond the brightest features. Faint source emission can help constrain the source's extent, +while the outskirts of the lens galaxy help constrain how its brightness falls with radius. + +Individual pixels in these regions may contain only a weak signal. Taken together, they can still distinguish between +models that look similar around the bright centre and arcs. + +Regions without detectable emission are useful too. A mass model might reproduce the observed arcs but predict an +additional image elsewhere. If that location lies inside our circle, the extra predicted light disagrees with the data +and reduces the likelihood. + +If we exclude that location, the likelihood cannot see the disagreement. A mask drawn tightly around the observed arcs +could therefore hide evidence that the lens model is wrong. + +This is why we retain a generous circular region around the system, including the space between and around its bright +features. + +__Mask__ + +We use a circular mask with a radius of 3.0 arcseconds for this example. It contains the central galaxy, the lensed +arcs and surrounding pixels that constrain their fainter emission. + +The aim is to include the system as a whole, rather than trace the outlines of individual bright features. Galaxy +profiles have extended faint wings, so this does not mean capturing every last photon. + +Including more pixels generally adds computation, but making the fitted region unnecessarily small can discard +information that helps distinguish competing lens models. + +In real observations, the surrounding region may also contain neighbouring galaxies. We will address their light later +in this tutorial, while retaining the large circular region used to fit the lens.""" + +mask = al.Mask2D.circular( + shape_native=dataset.shape_native, + pixel_scales=dataset.pixel_scales, + radius=3.0, +) + +dataset = dataset.apply_mask(mask=mask) + +aplt.subplot_imaging_dataset(dataset=dataset) + +""" +__Positions Constraints__ + +Look again at the lensed source. Its multiple images are different views of the same background galaxy. If we identify +the same feature in two or more images, a suitable mass model should trace those positions back to approximately the +same location in the source plane. + +An unsuitable mass model may instead trace them to widely separated locations. It could reproduce some of the observed +light while failing this requirement of the lensing geometry. + +We can supply these image positions to the analysis and check their source-plane separation for every proposed mass +model. When that separation exceeds a chosen threshold, a likelihood penalty discourages the search from exploring the +model. + +This gives the search a useful constraint: the marked features must be explainable as multiple images of the same +source feature. It does not tell the search the correct mass parameters in advance. + +__Choosing Positions__ + +Positions must refer to the same source feature seen in different lensed images. For example, a compact bright knot may +appear in several arcs. Marking its location in each image gives us positions that should trace back together. + +Simply choosing the brightest pixel in each arc is not always reliable. An extended source may contain several bright +knots, and different knots may dominate different images. Foreground lens light can also make a feature's position +difficult to identify. + +For an individual lens, we can choose positions by inspecting the image or using the workspace's data-preparation GUI. +Always plot the selected positions over the image and check which features they mark. + +In *Search Chaining*, we will introduce a more automated approach: using an initial fitted model to estimate positions +for a subsequent analysis. + +For this example, we supply four positions corresponding to the centre of the simulated source, seen in different parts +of the arcs. These coordinates were checked against the simulation's mass model and rounded to three decimal places. +They are in `(y, x)` order, measured in arcseconds. Plot them over the image before fitting.""" + +positions = al.Grid2DIrregular( + values=[(0.271, 1.673), (-1.499, 0.195), (1.499, -0.195), (-0.271, -1.673)] +) + +aplt.subplot_imaging_dataset(dataset=dataset, positions=positions) + +""" +__The Positions Penalty__ + +For each proposed mass model, PyAutoLens ray-traces the marked image positions to the source plane and calculates the +largest separation between them. + +The threshold specifies how far apart we allow those source-plane positions to be, in arcseconds. If their maximum +separation exceeds it, the analysis applies a large likelihood penalty. If they fall within it, no positions penalty is +applied. + +This check is extremely fast compared with evaluating the full imaging likelihood. It only requires ray-tracing a +handful of positions and calculating their separations, rather than predicting and comparing the light across thousands +of image pixels. It therefore adds very little computational cost while providing useful guidance to the search. + +We use this as a broad consistency check. The marked positions have uncertainties, and features in extended arcs may +not identify exactly the same source location. A threshold that is too restrictive can therefore penalise otherwise +suitable mass models. + +A threshold that is too generous has the opposite weakness: substantially different source locations may pass the +check, providing little guidance to the search. + +Here we use a broad threshold of 1.0 arcsecond. For comparison, our rounded coordinates trace within 0.001 arcseconds +of one another under the simulation's true model. The much larger threshold deliberately allows approximate agreement +while discouraging widely separated solutions; it is not a measurement of positional uncertainty or a universal setting +for other lenses. + +The positions come from the image we already fit. Here, the penalty is a practical constraint for guiding exploration, +rather than an additional independent measurement with its own positional-error likelihood. + +Passing this check does not mean that a model fits the image. It must still reproduce the observed light through the +imaging likelihood.""" + +positions_threshold = 1.0 + +""" +__Model and Analysis__ + +We reuse the model from *Linear Profiles*: Sérsic lens light, an elliptical isothermal mass profile, external shear and +exponential source light. The two light-profile intensities are solved during each likelihood evaluation. + +The new ingredient belongs to the analysis. We create a `PositionsLH` object containing our marked positions and their +allowed source-plane separation, then pass it alongside the imaging dataset to `AnalysisImaging`. + +This illustrates the separation introduced at the start of the tutorial. We have added a constraint to the analysis +without changing the physical components of the model or the interface used by the search.""" + +lens = af.Model( + al.Galaxy, + redshift=0.5, + bulge=al.lp_linear.Sersic, + mass=al.mp.Isothermal, +) + +source = af.Model( + al.Galaxy, + redshift=1.0, + bulge=al.lp_linear.ExponentialCore, +) + +field = af.Model( + al.MassField, + redshift=0.5, + shear=al.mp.ExternalShear, +) + +model = af.Collection( + galaxies=af.Collection(lens=lens, source=source), + fields=field, +) + +positions_likelihood = al.PositionsLH( + positions=positions, + threshold=positions_threshold, +) + +analysis = al.AnalysisImaging( + dataset=dataset, + positions_likelihood_list=[positions_likelihood], +) + +""" +__Search and Result__ + +Run Nautilus using this model and analysis. The search explores the same physical parameters as before, but the +analysis now discourages mass models that trace our marked features to widely separated source locations. + +This can help the search avoid unsuitable regions of parameter space. It does not guarantee that the search finds the +global maximum, and incorrectly chosen positions or an overly restrictive threshold can steer it away from a good +solution. + +Inspect the fitted image and normalised residuals after the search finishes. Check the central lens galaxy and the +surrounding arcs, including their fainter emission. Satisfying the positions constraint is only one requirement; the +model must also explain the light throughout the circular mask.""" + +search = af.Nautilus( + path_prefix=Path("howtolens") / "chapter_2", + name="tutorial_5_with_positions", + unique_tag=dataset_name, + n_live=200, + n_batch=50, + iterations_per_quick_update=2500, +) + +result = search.fit(model=model, analysis=analysis) + +print(result.info) + +aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) + +""" +__Contaminating Light__ + +A large circular mask can contain light from objects other than the lens galaxy and its source. A neighbouring galaxy +may appear beside an arc, with its fainter outskirts overlapping the emission we want to fit. + +Our current light model contains only the main lens and source. If we ask it to explain the neighbouring galaxy too, +the search may distort those components to reproduce light that belongs to a different object. + +One approach is to include the neighbour explicitly in the model. We will explore this in Chapter 4. Here, we introduce +**noise scaling**, which reduces the influence of selected pixels on the fit while retaining our circular mask. + +This is useful when we want to prevent contaminating light from driving the fit, without introducing another light +profile and its free parameters. + +__Extra Galaxy Dataset__ + +Load a second simulated image containing a neighbouring galaxy. Look towards the upper-right of the main lens, where +the extra galaxy's bright centre and extended light are visible. + +Follow its light towards the lensed arcs. The contamination is not confined to the galaxy's brightest pixels, and some +pixels contain light from more than one object. + +This example will show how we change the contribution of those pixels to the likelihood. We begin with the full image, +before applying either noise scaling or the circular mask.""" + +dataset_name_extra = "lens_extra_galaxy" +dataset_path_extra = Path("dataset") / "imaging" / dataset_name_extra + +al.util.dataset.simulate_if_needed( + dataset_path_extra, + simulator="scripts/simulator/lens_extra_galaxy.py", +) + +dataset_extra = al.Imaging.from_fits( + data_path=dataset_path_extra / "data.fits", + noise_map_path=dataset_path_extra / "noise_map.fits", + psf_path=dataset_path_extra / "psf.fits", + pixel_scales=0.1, +) + +aplt.subplot_imaging_dataset(dataset=dataset_extra) + +""" +__Extra Galaxy Region__ + +The simulator supplies a file identifying a region around the extra galaxy. For real observations, we would define this +region ourselves after inspecting the image, for example using the workspace's data-preparation GUI. + +This selection has a different purpose from our main circular mask. The circular mask defines the overall region we +fit. The extra-galaxy selection identifies pixels within that region whose influence we want to reduce. + +The supplied region surrounds the neighbour's centre and extends into its fainter light. It is an approximation to the +contaminated area, rather than a boundary at which the galaxy's light suddenly ends. + +We load the file with `invert=True` so that its selected pixels follow the convention expected by the noise-scaling +method.""" + +mask_extra_galaxies = al.Mask2D.from_fits( + file_path=dataset_path_extra / "mask_extra_galaxies.fits", + pixel_scales=dataset_extra.pixel_scales, + invert=True, +) + +""" +__Noise Scaling__ + +Recall that the imaging likelihood compares the difference between the data and model with the uncertainty in each +pixel. A difference has less influence when the assigned uncertainty is larger. + +Noise scaling uses this relationship to give contaminated pixels almost no weight. By default, the method below sets +their noise values to a very large number and their data values to zero. + +This is a deliberate modification of the data used by the analysis. It does not mean that the original measurement had +such a large uncertainty, and it does not subtract a physical model of the neighbouring galaxy. + +Apply the noise scaling first, then apply the same 3.0-arcsecond circular mask. The selected pixels remain inside the +fitted region, but differences between their data and predicted light contribute negligibly to the fit.""" + +dataset_scaled = dataset_extra.apply_noise_scaling( + mask=mask_extra_galaxies, +) + +mask = al.Mask2D.circular( + shape_native=dataset_scaled.shape_native, + pixel_scales=dataset_scaled.pixel_scales, + radius=3.0, +) + +dataset_scaled = dataset_scaled.apply_mask(mask=mask) + +aplt.subplot_imaging_dataset(dataset=dataset_scaled) + +""" +__Interpreting the Scaled Dataset__ + +Compare the data, noise-map and signal-to-noise panels. In the selected region, the data have been set to zero and the +noise has been increased. The galaxy has not physically disappeared; we have told the analysis to obtain almost no +information from those pixels. + +This also means losing information about any lens or source light in the same pixels. Noise scaling cannot distinguish +which galaxy emitted a photon. Where the neighbour overlaps important parts of an arc, explicitly modeling its light +may preserve more useful information. + +Light outside the selected region can still affect the fit, including faint wings spread by the PSF. Inspect the +surrounding pixels rather than assuming the selection removes every contribution from the neighbour. + +There is a further distinction for lensing: reducing the weight of a galaxy's light does not remove its gravitational +deflection. The extra galaxy in this simulation also has mass. Whether that mass must be included in the lens model is +a separate question, which we develop in Chapter 4. + +To use this prepared dataset, we would pass it to `AnalysisImaging`. The analysis then uses the modified data and noise +map when calculating the likelihood. The search interface remains unchanged.""" + +analysis_scaled = al.AnalysisImaging(dataset=dataset_scaled) + +r""" +Changing the noise map changes the likelihood itself. We should therefore not interpret a change in the absolute likelihood before and after scaling as evidence that we have found a better physical model. + +__Interferometer Data__ + +In Chapter 1, we saw that an interferometer measures **visibilities**, rather than the image pixels used throughout +this chapter. + +We can still describe the lens using mass profiles and the source using light profiles. The model predicts a lensed +image, but that image must be transformed into predicted visibilities before we compare it with the observations. + +`AnalysisInterferometer` performs this comparison using the measured visibilities and their uncertainties. We replace +the imaging dataset and analysis with their interferometer equivalents, while retaining the familiar process of +defining a model and running a search. + +The model is built using the same composition API for every dataset type: `af.Model` defines profiles and galaxies, and +`af.Collection` groups them into the complete model. We use the same syntax to assign priors, fix parameters and link +parameters between components. The appropriate physical components may change, but we do not need to learn a different +way of constructing models. + +The mask has a different role here. It defines the real-space grid on which we predict the lensed emission; it does not +select observed image pixels for the likelihood. The measurements being fitted are the visibilities. + +The workspace's `scripts/interferometer/modeling.py` demonstrates the complete procedure. The light and mass profiles, +priors and search tools should already feel familiar—the main change is how the model predicts the measured quantities. + +__Point-Source Data__ + +For a multiply imaged compact source, such as a quasar, we may measure the positions of its separate images and their +positional uncertainties. These measurements can constrain the lens mass without requiring us to fit an extended arc +pixel by pixel. + +A `PointDataset` stores the measurements, and `AnalysisPoint` connects them to the lens model. The analysis evaluates +how consistently the model explains the observed image positions, using the chosen positional likelihood. + +This differs from the positions penalty introduced earlier. That penalty provides a broad consistency constraint +alongside an imaging fit. A point-source analysis treats the measured positions and their uncertainties as the +observations to be fitted. + +The physical model also changes where appropriate: a point source replaces the extended source-light profile. However, +we still define mass profiles, assign priors and use a search to explore their parameters. + +See `autolens_workspace/scripts/point_source/modeling.py` for a complete example. + +__Weak-Lensing Data__ + +Weak lensing uses the small distortions of many background galaxies to constrain a foreground mass distribution. Rather +than fitting bright arcs from one strongly lensed source, we work with a catalogue of galaxy positions and shape +measurements. + +Each galaxy has an unknown intrinsic shape as well as measurement uncertainty. A single elongated galaxy therefore does +not tell us the lensing distortion directly. The information emerges from the pattern across many galaxies. + +A `WeakDataset` contains the measurements used for this comparison. `AnalysisWeak` evaluates the lens model's predicted +distortion at the galaxy positions and compares it with the measured shapes, accounting for the adopted uncertainties. + +Once again, the search does not need a new interface. It explores the mass-model parameters using the likelihood +returned by the analysis. + +Chapter 4 develops weak-lensing modeling further. The workspace's `scripts/weak/modeling.py` also shows how these +components fit together. + +__Multiple Datasets__ + +Separating datasets from models also allows several observations to constrain the same physical system. + +Imagine observing one lens in two wavebands. Both images are produced by the same foreground mass distribution, but the +lens and source brightness can differ between wavebands. Each observation also has its own PSF and noise map. + +We can give each dataset its own Analysis object and connect both to a model that shares the mass parameters while +allowing appropriate light-profile parameters to differ. + +For datasets that are independent given the model, their likelihoods multiply. Equivalently, their log likelihoods add: + +$$ +\ln \mathcal{L}_{\mathrm{total}} = \ln \mathcal{L}_1 + \ln \mathcal{L}_2. +$$ + +The search then explores parameter values using this combined likelihood. A proposed mass model must explain both +observations, rather than fitting either one in isolation. + +This can also combine different kinds of measurements, such as imaging and point-source positions. We must take care +with information shared between datasets: treating the same measurement twice as independent would count its +information twice. + +Joint modeling is an advanced topic. The workspace's `scripts/multi_dataset/` examples explain how to construct these +analyses and decide which parameters to share. For now, the important idea is that each dataset can have its own +prediction and likelihood calculation while contributing to a common model fit. + +__Wrap Up__ + +We began with familiar imaging data and examined how different information enters the fit. The circular mask retains +the lens, arcs and their surroundings. Positions constraints help identify suitable mass models. Noise scaling reduces +the influence of selected contaminated pixels. + +These changes belong to different parts of the analysis, but they all fit into the same structure: + +- The **dataset** contains the measurements and their uncertainties. +- The **model** describes the physical system and its free parameters. +- The **Analysis** object connects the model to the observations and calculates their likelihood. +- The **search** explores the parameters using that likelihood and the priors. + +This separation is why the tools learnt in this chapter extend beyond fitting one image. Whether we fit imaging, +visibilities, point-source positions or weak-lensing shapes, we compose the model using the same `af.Model` and +`af.Collection` API. We adapt its physical components to the problem, select the appropriate dataset and Analysis +objects, and pass them to the search through the familiar `search.fit(model=model, analysis=analysis)` interface. + +In the next tutorial, we will use this flexibility to connect several fits in a sequence. An initial, simpler analysis +will provide information that helps us construct and fit a more complex model. + +**🤖 Ask AI:** I have two images of the same gravitational lens taken in different wavebands. Which parts of the physical model might be shared, which might differ, and what must each Analysis object know about its own observation? +""" diff --git a/scripts/chapter_2_lens_modeling/tutorial_6_masking_and_positions.py b/scripts/chapter_2_lens_modeling/tutorial_6_masking_and_positions.py deleted file mode 100644 index fa55750..0000000 --- a/scripts/chapter_2_lens_modeling/tutorial_6_masking_and_positions.py +++ /dev/null @@ -1,283 +0,0 @@ -""" -Tutorial 6: Masking and Positions -================================= - -We have learnt everything we need to know about non-linear searches to model a strong lens and infer a good lens -model solution. Now, lets consider masking in more detail, something we have not given much consideration previously. -We'll also learn a neat trick to improve the speed and accuracy of a non-linear search. - -__Contents__ - -- **Initial Setup:** we'll use the same strong lensing data as tutorial 1, where. -- **Dataset Auto-Simulation:** Simulate the dataset via its simulator script if it is not on your hard-disk. -- **Mask:** Define the 2D mask applied to the dataset for the model-fit. -- **Model + Analysis:** Compose the lens model and create the analysis that fits it using the chosen mask. -- **Run Time:** Profiling the expected run time of the model-fit. -- **Search:** Configure the non-linear search used to fit the model. -- **Discussion:** So, we can choose the mask we use in a model-fit. -- **Positions Thresholding:** We can manually specify a set of image-plane (y,x) coordinates corresponding to the multiple images. -- **Wrap Up:** Summary of the script and next steps. - -""" - -from autolens import jax_wrapper # Sets JAX environment before other imports - -# from autolens import setup_notebook; setup_notebook() - -from pathlib import Path -import autolens as al -import autolens.plot as aplt -import autofit as af - -""" -__Initial Setup__ - -we'll use the same strong lensing data as tutorial 1, where: - - - The lens galaxy's total mass distribution is a `IsothermalSph`. - - The source galaxy's light is a `ExponentialCoreSph`. -""" -dataset_name = "simple__no_lens_light__mass_sis" -dataset_path = Path("dataset") / "imaging" / dataset_name - -""" -__Dataset Auto-Simulation__ - -If the dataset does not already exist on your system, it will be created by running the corresponding -simulator script. This ensures that all example scripts can be run without manually simulating data first. -""" -al.util.dataset.simulate_if_needed( - dataset_path, simulator="scripts/simulator/no_lens_light__mass_sis.py" -) - -dataset = al.Imaging.from_fits( - data_path=dataset_path / "data.fits", - noise_map_path=dataset_path / "noise_map.fits", - psf_path=dataset_path / "psf.fits", - pixel_scales=0.1, -) - -""" -__Mask__ - -In this tutorial, our data only contained the light from the lensed source. We therefore want our mask to include all -of the source's light. There are different shaped masks that we can use to achieve this, and we can compare them by -plotting masks on the imaging data. - -Below, we use a 'circular_annular' mask, which unlike the 'circular' masks we have used previous includes an additional -input parameter 'inner_radius' that removes the central regions of the image. Below, we use too large of a value of -`inner_radius=0.8`, which cuts into the lensed source galaxy's light, clearly this isn't a good mask. -""" -mask = al.Mask2D.circular_annular( - shape_native=dataset.shape_native, - pixel_scales=dataset.pixel_scales, - inner_radius=0.8, - outer_radius=2.7, -) - -dataset = dataset.apply_mask(mask=mask) - -aplt.subplot_imaging_dataset(dataset=dataset) - -""" -We can decrease the `inner_radius` to correct for this. -""" -dataset = al.Imaging.from_fits( - data_path=dataset_path / "data.fits", - noise_map_path=dataset_path / "noise_map.fits", - psf_path=dataset_path / "psf.fits", - pixel_scales=0.1, -) - -mask = al.Mask2D.circular_annular( - shape_native=dataset.shape_native, - pixel_scales=dataset.pixel_scales, - inner_radius=0.4, - outer_radius=2.7, -) - -dataset = dataset.apply_mask(mask=mask) - -aplt.subplot_imaging_dataset(dataset=dataset) - -""" -__Model + Analysis__ - -Lets fit the data using this mask, by creating the search as per usual. - -Note that the `imaging` data with this mask applied is passed into the `AnalysisImaging` object, ensuring that this -is the mask the model-fit uses. - -we also use a linear light profile, simplifying the model as discussed in the previous tutorial. -""" -model = af.Collection( - galaxies=af.Collection( - lens=af.Model(al.Galaxy, redshift=0.5, mass=al.mp.IsothermalSph), - source=af.Model(al.Galaxy, redshift=1.0, bulge=al.lp_linear.ExponentialCoreSph), - ), -) - -search = af.Nautilus( - path_prefix=Path("howtolens") / "chapter_2", - name="tutorial_6_with_custom_mask", - unique_tag=dataset_name, - n_live=80, - n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2. - iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations -) - -analysis = al.AnalysisImaging(dataset=dataset) - -""" -__Run Time__ - -Smaller masks speed up the log likelihood evaluation time, because fewer image pixels mean fewer calculations are -required to evaluate the model image's fit to the data. - -This includes computing fewer deflection angles from the mass profiles and performing fewer 2D convolutions of the PSF -to account for blurring. - -__Search__ - -Run the non-linear search. -""" -search.fit(model=model, analysis=analysis) - -""" -__Discussion__ - -So, we can choose the mask we use in a model-fit. We know that we want the mask to not remove any of the lensed source -galaxy's light, but is this the 'right' mask? What is the 'right' mask? Maybe we want a bigger mask? a smaller mask? - -When it comes to choosing a mask, we are essentially balancing two things: computational run-time and accuracy. When we -use a bigger mask the model-fit will take longer to perform. Why? Because a bigger mask includes more image-pixels -in the analysis, and for every additional image-pixel we have to compute its deflection angles, trace it to the source -plane, fit its light, etc. - -If run-time was not a consideration we would always choose a bigger mask, for two reasons: - - 1) The lensed source galaxy may have very faint emission that when you choose the mask you simply do not notice. - Overly aggressive masking runs the risk of us inadvertantly masking out some of the source's light, which would - otherwise better constrain the lens model! - - 2) When the data is fitted with a model image, the fit is performed only within the masked region. For certain lens - models it is possible that it may produce extraneous source emission outside of the masked region that is not actually - observed in the lens data itself. If this region had not been masked-out, the model would create residuals in these - locations and reduce the value of likelihood appropriately, whereas if it is masked out this reduction in likelihood is - not fed through to the analysis. - -As you use **PyAutoLens** more you will get a feel for how fast a model-fit will run given the quality of data, lens -model complexity, non-linear search settings, etc. As you develop this intuition, I recommend that you always aim to -use as large of a mask as possible (whilst still achieving reasonable run-times). Aggressive masking will make -**PyAutoLens** run very fast, but could lead you to infer an incorrect lens model! - -If your data includes the light of the foreground lens galaxy you pretty much have no choice but to use a large -circular mask, because it is important to capture the lens galaxy's extended emission. This will probably extend well -beyond the light of the source. Nevertheless, the size of this circular mask will still play an important role in the -overall run time! - -__Positions Thresholding__ - -We can manually specify a set of image-plane (y,x) coordinates corresponding to the multiple images of a strong lens's -source-galaxy. If we supply these positions, every time a lens model is fitted **PyAutoLens** will first check that -these pixels trace within a specified arc-second threshold of one another in the source-plane (which is controlled -by an input `position_threshold`). If they do not trace within this threshold of one another, a large penalty term -is added to the likelihood. - -This provides two benefits: - - 1) The model-fit is faster as the non-linear search as when searching regions of parameter space where the mass-model - is clearly not accurate, a computationally fast ray-tracing of 2 or 4 image-pixels is performed. - - 2) By removing these solutions, a global-maximum solution may be reached instead of a local-maxima. This is - because removing the incorrect mass models makes the non-linear parameter space less complex. - -Once we begin to sample accurate lens models, the position threshold will be met and no penalty term will be included -in the likelihood function. - -We can create the image-plane positions using the `Grid2DIrregular` object, which defines a grid of $(y,x)$ coordinates -which are on an irregular grid (in contrast to the `Grid2D` object which assumes the $(y,x)$ coordinates are on a -regular uniform grid). T -""" -positions = al.Grid2DIrregular( - values=[(1.6, 0.0), (0.0, 1.6), (-1.6, 0.0), (0.0, -1.6)] -) - -""" -To check that the image positions are accurate, we plot them as marked points on the image using `positions=`. -""" - -aplt.subplot_imaging_dataset(dataset=dataset, positions=positions) - -""" -For the positions to be used in a model-fit, we create a `PositionsLH` object which we pass to -the `AnalysisImaging` class. - -This object includes the `threshold` that the positions must trace within during model-fit for a lens model to not -receive a likelihood penalty. - -The threshold of 1.0" is large. For an accurate lens model we would anticipate the positions trace within < 0.01" of -one another. However, we only want the threshold to aid the non-linear with the choice of mass model in the intiial -fit. - -We choose an excessively large threshold for two reasons: - - 1) Even with such a large value, we still apply a likelihood penalty to the *vast majority* of unphysical lens models - which trace the pixels even further away in the source plane. - - 2) If we set the threshold too low, there is a risk we may apply the penalty to physically plausible solutions. - A conservative value of 1.0" therefore a wise choice. -""" -positions_likelihood = al.PositionsLH(positions=positions, threshold=1.0) - -analysis = al.AnalysisImaging( - dataset=dataset, positions_likelihood_list=[positions_likelihood] -) - -""" -__Run Time__ - -Checking a few positions is cheaper than evaluating the full image likelihood. Rejecting unsuitable mass models early -can therefore speed up the initial exploration of parameter space; the benefit depends on the model and dataset. - -__Search__ - -Run the non-linear search. -""" -search = af.Nautilus( - path_prefix=Path("howtolens") / "chapter_2", - name="tutorial_6_with_positions", - unique_tag=dataset_name, - n_live=80, - n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2. - iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations -) - -print( - "The non-linear search has begun running - checkout the output/howtolens/chapter_2/tutorial_6_with_positions" - " folder for live output of the results, images and lens model." - " This Jupyter notebook cell with progress once search has completed - this could take some time!" -) - -search.fit(model=model, analysis=analysis) - -print("Search has finished run - you may now continue the notebook.") - -""" -__Wrap Up__ - -You may now wish to checkout the `autolens_workspace/*/imaging/data_preparation` package. This includes tools for -creating custom masks and marking the positions on a strong lens (via a GUI) so you can use them in a model-fit. - -There are two things you should bare in mind in terms of masking and positions: - - 1) Customizing the mask and positions for the analysis of one strong lens gets the analysis running fast and can - provide accurate non-linear sampling. However, for a large sample of lenses, this high level of customization may take - a lot of time. - - 2) When using positions, we must be *extremely* careful. It is often unclear whether a lensed source consists of one - or more galaxies, and each galaxy may have multiple distinct sources of light. When you mark the positions, they may - not truly originate from the same location in the source-plane. This is why the conservative positions threshold of - 1.0" is wise, as it is sufficiently large that even if the detailed structure of the source means we mark the positions - incorrectly it will not mean that we remove physically plausible mass models. -""" diff --git a/scripts/chapter_2_lens_modeling/tutorial_6_search_chaining.py b/scripts/chapter_2_lens_modeling/tutorial_6_search_chaining.py new file mode 100644 index 0000000..2637da3 --- /dev/null +++ b/scripts/chapter_2_lens_modeling/tutorial_6_search_chaining.py @@ -0,0 +1,459 @@ +""" +Tutorial 6: Search Chaining +=========================== + +Look again at our lens image. The foreground galaxy's light, its gravitational deflection and the background source all +contribute to what we observe. Fitting them together requires the search to explore several connected parts of the +model. + +Yet we do not always need to keep every part free throughout an analysis. Once we have obtained a satisfactory +description of the foreground light, we can hold aspects of that description fixed while investigating the mass +distribution in greater detail. + +**Search chaining** connects a sequence of fits in this way. Each search has a particular purpose, and its result +supplies information used to construct a later analysis. + +In this tutorial, an initial fit will describe the lens and source light using multi-Gaussian expansions, alongside an +isothermal mass profile and external shear. We will then fix the fitted lens-light geometry and replace the isothermal +mass profile with a power-law profile whose slope is free. + +The second search can therefore investigate a more flexible mass model without simultaneously rediscovering the +foreground light geometry. We will also use the first result to estimate the positions constraint introduced in the +previous tutorial. + +__Contents__ + +- **The Search Chain:** Give each search a distinct role. +- **Dataset and Mask:** Reuse the imaging dataset and circular mask. +- **Multi-Gaussian Expansions:** Construct lens and source light models with the MGE helper. +- **Model 1:** Compose the initial isothermal lens model. +- **Search 1:** Find a candidate solution with Prodigy. +- **Inspecting Search 1:** Check the fit before carrying information forward. +- **Fixing the Lens-Light Geometry:** Use fitted instances while retaining linear intensities. +- **The Power-Law Mass Model:** Allow the radial mass slope to vary. +- **Model 2:** Reduce the search to twelve non-linear parameters. +- **Automatically Estimated Positions:** Derive a positions constraint from the first fit. +- **Search 2:** Explore the revised model and its uncertainties with Nautilus. +- **Result 2:** Inspect residuals and posterior distributions. +- **Conditional Uncertainties:** Understand the consequences of fixed geometry. +- **Search Chaining and SLaM:** Connect this example to reusable pipelines. +- **Wrap Up:** Inspecting chained fits and continuing to Chapter 3. + +__The Search Chain__ + +Our first search aims to obtain a useful description of the image relatively quickly. We use `MultiStartProdigy`, which +runs gradient-based optimisations from multiple starting points. + +This gives us a candidate solution to inspect. It does not provide the posterior samples needed to describe parameter +uncertainties, and we must check its fitted image and residuals before using its result. + +Our second search uses Nautilus to explore the revised model more thoroughly. The lens-light centres and shapes will be +fixed to their fitted values, while the mass and source parameters remain free. The light-profile intensities will +still be solved during each likelihood evaluation. + +This distinction matters: we are fixing the geometry of the foreground light, rather than subtracting a fixed image and +assuming that its brightness can never change. + +Holding fitted quantities fixed is also an assumption. The second result is conditional on that choice and does not +propagate uncertainty in the fixed lens-light geometry. Later in the tutorial, we will discuss when that approximation +is useful and when those parameters should be allowed to vary again.""" + +from autolens import jax_wrapper # Sets JAX environment before other imports + +# from autolens import setup_notebook; setup_notebook() + +from pathlib import Path +import autofit as af +import autolens as al +import autolens.plot as aplt + + +""" +__Dataset and Mask__ + +We use the same `lens_sersic` imaging dataset and 3.0-arcsecond circular mask as the previous tutorial. + +Inspect the central lens galaxy and the surrounding arcs. The first fit must describe both: an inaccurate source or +mass model can affect how the overlapping light is assigned to the foreground galaxy.""" + +dataset_name = "lens_sersic" +dataset_path = Path("dataset") / "imaging" / dataset_name + +al.util.dataset.simulate_if_needed( + dataset_path, + simulator="scripts/simulator/lens_sersic.py", +) + +dataset = al.Imaging.from_fits( + data_path=dataset_path / "data.fits", + noise_map_path=dataset_path / "noise_map.fits", + psf_path=dataset_path / "psf.fits", + pixel_scales=0.1, +) + +mask_radius = 3.0 + +mask = al.Mask2D.circular( + shape_native=dataset.shape_native, + pixel_scales=dataset.pixel_scales, + radius=mask_radius, +) + +dataset = dataset.apply_mask(mask=mask) + +aplt.subplot_imaging_dataset(dataset=dataset) + +""" +__Multi-Gaussian Expansions__ + +We use the MGE construction introduced in *Linear Profiles*. Within each galaxy's Gaussian group, the profiles share a +centre and elliptical shape. Their widths are fixed, and their intensities are solved together during the fit. + +The lens and source have separate groups, so their centres and shapes remain independent. + +To avoid repeating the construction loops from Tutorial 4, we use `al.model_util.mge_model_from`. This helper builds an +ordinary model from linear Gaussian profiles; it does not fit the data or introduce a different model-composition API. + +The lens uses 30 Gaussians, with widths spanning 0.01 to 3.0 arcseconds. The source uses 15 Gaussians spanning 0.0001 +to 1.0 arcseconds in the source plane. These ranges provide components on different scales; they do not imply that the +smallest components are individually resolved by the observations. + +In this helper, `mask_radius` sets the largest Gaussian width. The source's value of 1.0 therefore controls its +Gaussian widths—it does not apply another mask to the image.""" + +lens_bulge = al.model_util.mge_model_from( + mask_radius=mask_radius, + total_gaussians=30, + centre_prior_is_uniform=True, + sigma_min=dataset.pixel_scales[0] / 10.0, +) + +source_bulge = al.model_util.mge_model_from( + mask_radius=1.0, + total_gaussians=15, + centre_prior_is_uniform=False, + sigma_min=1.0e-4, +) + +""" +__Model 1__ + +Combine these light profiles with an elliptical isothermal mass profile and external shear. + +The isothermal profile gives the first search a mass model with a fixed radial slope. In the second search, we will +relax this restriction using a power-law profile. + +We do not force the mass to share the lens light's centre or elliptical shape. The first fit must determine those +properties independently from the image. + +Despite containing 45 Gaussian light profiles, this model has only 15 non-linear parameters: four describe each +galaxy's shared light geometry, five describe the isothermal mass profile, and two describe external shear. The +Gaussian widths are fixed and their intensities are solved linearly. + +Inspect `model_1.info` and its diagram to identify those independent parameters before fitting. +""" + +lens = af.Model( + al.Galaxy, + redshift=0.5, + bulge=lens_bulge, + mass=al.mp.Isothermal, +) + +source = af.Model(al.Galaxy, redshift=1.0, bulge=source_bulge) + +field = af.Model(al.MassField, redshift=0.5, shear=al.mp.ExternalShear) + +model_1 = af.Collection( + galaxies=af.Collection(lens=lens, source=source), + fields=field, +) + +print(model_1.info) + +af.ModelPlotter(model_1).figure() + +""" +__Search 1__ + +We begin with `MultiStartProdigy`, using the settings introduced in the optional searches tutorial: 48 starting points +and up to 300 gradient steps per start. + +Multiple starting points give the optimiser opportunities to find different solutions. They do not guarantee that it +finds the best one, so we will inspect the result before carrying any information forward. + +`batch_size=4` limits how many starts are processed together, reducing memory use. It does not reduce the total number +of starts. + +The analysis fits the imaging data without a positions constraint. After this search, we will use the fitted model to +estimate positions for the next analysis. + +Prodigy's job here is to find a good-fitting set of parameter values. It does not attempt to map out the full range of +plausible solutions or calculate posterior uncertainty intervals—the parameter "errors". + +This narrower task is one reason we expect it to finish sooner than a thorough Nautilus run, alongside its use of +gradients. It is therefore useful for our first stage, where we need a satisfactory model to build on rather than a +final measurement of every parameter's uncertainty. The speed advantage still depends on the problem and settings.""" + +search_1 = af.MultiStartProdigy( + path_prefix=Path("howtolens") / "chapter_2", + name="tutorial_6_search_1", + unique_tag=dataset_name, + n_starts=48, + n_steps=300, + batch_size=4, +) + +analysis_1 = al.AnalysisImaging(dataset=dataset, use_jax=True) + +result_1 = search_1.fit(model=model_1, analysis=analysis_1) + +""" +JAX supplies the gradients used by Prodigy. Its initial compilation adds a setup cost; later evaluations reuse the compiled calculation. The total run time depends on the hardware, model and number of optimisation steps required. + +__Inspecting Search 1__ + +Inspect the fitted image and normalised residuals before proceeding. + +Look first at the foreground galaxy. Does the MGE reproduce its centre, shape and extended light? Then examine the +arcs. A poor description of the source can affect how the fit divides overlapping light between the two galaxies. + +Search chaining carries information forward, including mistakes. Fixing the foreground geometry from a poor fit can +prevent the next search from correcting it. + +If substantial residual structure remains, investigate the first fit using the approaches from *Why Modeling Is Hard*. +More optimisation effort may help, but the model may also need additional freedom. + +A satisfactory result gives us a candidate lens-light geometry for the next stage. It does not establish its +uncertainty or prove that the solution is unique.""" + +print(result_1.info) + +aplt.subplot_fit_imaging(fit=result_1.max_log_likelihood_fit) + +""" +__Fixing the Lens-Light Geometry__ + +Until now, we have mainly constructed components using `af.Model`, which leaves selected parameters free for a search +to fit. + +`result_1.instance` instead contains components with numerical parameter values from the highest-likelihood solution +stored in the first result. We can take its fitted lens-light basis and place that instance into our next model. + +Its Gaussian centres and elliptical shapes are then fixed. The widths were already fixed in the first search. + +The Gaussian profiles remain **linear light profiles**, however. Their intensities will still be solved during each +likelihood evaluation of the second fit. We therefore preserve the fitted geometry while allowing the brightness +assigned to the lens and source to adjust together. + +This differs from subtracting the first fit's lens-light image from the data. We continue to fit the original image, +with foreground and background light included in the prediction.""" + +lens_bulge_fixed = result_1.instance.galaxies.lens.bulge + +""" +__The Power-Law Mass Model__ + +The first search used an isothermal mass profile, whose radial density slope is fixed. We now replace it with +`PowerLaw`, allowing the slope to vary. + +The slope controls how quickly the mass density falls with radius. The isothermal case corresponds to `slope=2.0`; +allowing this parameter to vary lets the second search investigate steeper and shallower profiles. + +This extra freedom is scientifically useful, but it also introduces relationships with other parameters, including the +source size. We should not assume that adding the slope makes it independently or precisely measurable. + +We retain free mass-centre coordinates, ellipticity and Einstein radius, alongside external shear. The lens-light +geometry is fixed separately: we are not forcing the mass distribution to follow the light.""" + +lens_2 = af.Model( + al.Galaxy, + redshift=0.5, + bulge=lens_bulge_fixed, + mass=al.mp.PowerLaw, +) + +field_2 = af.Model(al.MassField, redshift=0.5, shear=al.mp.ExternalShear) + +""" +__Model 2__ + +The source MGE remains free to change its centre and shape. This is important because changing the mass profile changes +how the observed arcs map back to the source plane. + +We construct a fresh source model with the same settings as before. Its priors are not replaced with narrow +distributions derived from the first result. + +Combining it with the revised lens gives 12 non-linear parameters: six for the power-law mass profile, two for external +shear and four for the source geometry. + +We have added one mass parameter but removed four lens-light geometry parameters from the search. The second model +therefore has a more flexible mass profile and fewer non-linear parameters overall. + +Twelve non-linear parameters is fewer than we might expect for a model that includes foreground lens light, a flexible +mass profile, external shear and source light. The lens light is still present, but its fitted geometry no longer +contributes free parameters to the search, and its intensities are handled by the linear solve. + +This is a central benefit of the chain: we can retain a detailed description of the image while asking the second +search to explore fewer parameters. + +Compare the model summary and diagram with those from the first search. The foreground Gaussian geometry should now +have fixed numerical values, while the source geometry, mass parameters and shear remain free. The lens and source +intensities are still solved linearly.""" + +source_bulge_2 = al.model_util.mge_model_from( + mask_radius=1.0, + total_gaussians=15, + centre_prior_is_uniform=False, + sigma_min=1.0e-4, +) + +source_2 = af.Model(al.Galaxy, redshift=1.0, bulge=source_bulge_2) + +model_2 = af.Collection( + galaxies=af.Collection(lens=lens_2, source=source_2), + fields=field_2, +) + +print(model_2.info) + +af.ModelPlotter(model_2).figure() + +""" +__Automatically Estimated Positions__ + +In the previous tutorial, we supplied image positions explicitly. We can now estimate them from the first fitted model. + +The result uses its fitted source location and mass distribution to predict the corresponding multiple-image positions. +It then constructs a `PositionsLH` constraint for the next analysis. + +This carries a second kind of information between searches. Alongside the fitted lens-light geometry, we use the first +model's lensing geometry to help guide the next search. + +These positions are predictions from the first fit, rather than independently measured coordinates. Plot them over the +image and check that they correspond sensibly to the observed arcs. A poor first model can generate misleading +positions as well as an inaccurate light distribution.""" + +positions_likelihood = result_1.positions_likelihood_from( + factor=3.0, + minimum_threshold=0.2, +) + +aplt.subplot_imaging_dataset( + dataset=dataset, + positions=positions_likelihood.positions, +) + +print("Source-plane threshold:", positions_likelihood.threshold) + +""" +The threshold is three times the source-plane separation calculated from the first model, with a minimum of 0.2 arcseconds. The minimum prevents the numerical precision of the predicted positions from imposing an unnecessarily tight constraint. + +As before, this is a broad consistency check rather than a positional-error measurement. Its calculation during the +search is extremely fast compared with evaluating the full imaging likelihood. + +__Search 2__ + +We now return to Nautilus because we want more than a single good-fitting solution. We want posterior samples that +describe the range of plausible parameter values and allow us to calculate uncertainty intervals—the parameter +"errors". + +Exploring those distributions requires more work than locating one solution, so we generally expect this stage to run +more slowly than the initial Prodigy optimisation. Fixing the lens-light geometry reduces that burden. + +Pass the positions constraint to a new Analysis object and fit `model_2`. We continue to use the original imaging data, +including the foreground light. + +The resulting uncertainties are conditional on the geometry we fixed. Nautilus explores the free parameters of this +second model; it cannot recover uncertainty in parameters we have removed from the search.""" + +analysis_2 = al.AnalysisImaging( + dataset=dataset, + positions_likelihood_list=[positions_likelihood], + use_jax=True, +) + +search_2 = af.Nautilus( + path_prefix=Path("howtolens") / "chapter_2", + name="tutorial_6_search_2", + unique_tag=dataset_name, + n_live=200, + n_batch=50, + iterations_per_quick_update=2500, +) + +result_2 = search_2.fit(model=model_2, analysis=analysis_2) + +""" +__Result 2__ + +Inspect the fitted image and normalised residuals again. Check both the arcs and the foreground galaxy: the fixed +lens-light geometry is still an assumption that the data can reveal to be inadequate. + +Compare the result with the first fit. The power-law slope is now free, so the mass model and reconstructed source may +change together. A change in the inferred source size need not indicate a failure; it can reflect a relationship +between source structure and the radial mass profile. + +This dataset was simulated with an isothermal mass profile, corresponding to a power-law slope of 2.0. Use that known +value as a check, while recognising that noise, the adopted light models and the fixed lens-light geometry can affect +the inferred result. + +Examine the posterior distributions as well as the highest-likelihood fit. Look for broad intervals and correlations, +particularly between the mass slope and source parameters. Those distributions contain information that the first +optimisation did not provide.""" + +print(result_2.info) + +aplt.subplot_fit_imaging(fit=result_2.max_log_likelihood_fit) + +aplt.corner_anesthetic(samples=result_2.samples) + +""" +__Conditional Uncertainties__ + +The second search answers a specific question: which mass and source parameters are consistent with the data **given +the lens-light geometry we carried forward**? + +It allows the Gaussian intensities to adjust, but it does not explore alternative foreground centres or shapes. If +those geometric quantities are uncertain, their uncertainty can affect how the overlapping light is divided between the +lens and source. + +Fixing them can therefore make the reported mass and source uncertainties narrower than those from an analysis that +also explores the foreground geometry. It can also shift the inferred parameters if the fixed geometry is inaccurate. + +Search chaining makes this trade-off useful by allowing us to investigate the model in stages. It does not make the +trade-off disappear. + +For a final scientific analysis, we can test its importance by allowing the lens-light geometry to vary again, +repeating the fit with other plausible foreground descriptions, or constructing an analysis that propagates the +relevant uncertainty. + +We should also investigate whether the automatically estimated positions constraint is restrictive enough to influence +our conclusions. It was derived from an earlier fitted model, not from an independent observation. + +**🤖 Ask AI:** My chained fit gives a narrow uncertainty interval on the mass slope. How could fixing the foreground light geometry affect that interval, and what comparisons would help me assess it? + +__Search Chaining and SLaM__ + +Our two searches had different jobs. The first used a relatively fast optimisation to obtain a description of the +foreground light and an initial lens model. The second fixed the foreground geometry, introduced a more flexible mass +profile and used Nautilus to explore the remaining parameter uncertainties. + +The second model contained fewer non-linear parameters even though its mass profile was more flexible. This is one of +the main benefits of fitting different parts of the system in stages. + +More elaborate chains follow the same principle. An initial source model can help configure a later source +reconstruction, a foreground-light fit can support a more detailed mass analysis, and an earlier lens model can supply +positions constraints for subsequent searches. + +PyAutoLens provides **SLaM**, short for **Source, Light and Mass**, to organise these stages into reusable modeling +pipelines. The workspace's `scripts/imaging/features/multi_gaussian_expansion/slam.py` provides a concrete example. + +__Wrap Up__ + +A pipeline automates the sequence, but each stage still needs a suitable model and a result worth carrying forward. +Inspecting the intermediate fits remains essential. + +In Chapter 3, we will introduce pixelized source reconstructions, which describe source structure beyond the smooth +profiles used here. Search chaining will provide a way to connect those more detailed reconstructions to the tools we +have already learnt.""" diff --git a/scripts/chapter_2_lens_modeling/tutorial_7_results.py b/scripts/chapter_2_lens_modeling/tutorial_7_results.py deleted file mode 100644 index c9cc7a5..0000000 --- a/scripts/chapter_2_lens_modeling/tutorial_7_results.py +++ /dev/null @@ -1,162 +0,0 @@ -""" -Tutorial 7: Results -=================== - -In the previous tutorials, each search returned a `Result` object, which we used to plot the maximum log likelihood -fit each model-fit. In this tutorial, we'll take a look at the result object in a little more detail. - -__Contents__ - -- **Initial Setup:** Run a separate fit to the Tutorial 1 dataset to obtain a `Result` object. -- **Dataset Auto-Simulation:** Simulate the dataset via its simulator script if it is not on your hard-disk. -- **Tracer & Fit:** In the previous tutorials, we saw that this result contains the maximum log likelihood fit, which. -- **Samples:** The result contains a lot more information about the model-fit. -- **Workspace:** We are not going into any more detail on the result variable in this tutorial, or in the. -- **Database:** Once a search has completed running, we have a set of results on our hard disk which we can. -- **Wrap Up:** Summary of the script and next steps. - -""" - -from autolens import jax_wrapper # Sets JAX environment before other imports - -# from autolens import setup_notebook; setup_notebook() - -from pathlib import Path -import autolens as al -import autolens.plot as aplt -import autofit as af - -""" -__Initial Setup__ - -We use the same dataset as Tutorial 1 and run a separate fit to obtain a `Result` object. Here, the source uses an -ordinary light profile, so its intensity is explored by the non-linear search. This setup does not reload the -Tutorial 1 result. -""" -dataset_name = "simple__no_lens_light__mass_sis" -dataset_path = Path("dataset") / "imaging" / dataset_name - -""" -__Dataset Auto-Simulation__ - -If the dataset does not already exist on your system, it will be created by running the corresponding -simulator script. This ensures that all example scripts can be run without manually simulating data first. -""" -al.util.dataset.simulate_if_needed( - dataset_path, simulator="scripts/simulator/no_lens_light__mass_sis.py" -) - -dataset = al.Imaging.from_fits( - data_path=dataset_path / "data.fits", - noise_map_path=dataset_path / "noise_map.fits", - psf_path=dataset_path / "psf.fits", - pixel_scales=0.1, -) - -mask_radius = 3.0 - -mask = al.Mask2D.circular( - shape_native=dataset.shape_native, - pixel_scales=dataset.pixel_scales, - radius=mask_radius, -) - -dataset = dataset.apply_mask(mask=mask) - -model = af.Collection( - galaxies=af.Collection( - lens=af.Model(al.Galaxy, redshift=0.5, mass=al.mp.IsothermalSph), - source=af.Model(al.Galaxy, redshift=1.0, bulge=al.lp.ExponentialCoreSph), - ), -) - -search = af.Nautilus( - path_prefix=Path("howtolens") / "chapter_2", - name="tutorial_1_non_linear_search", - unique_tag=dataset_name, - n_live=80, - n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2. - iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations -) - -analysis = al.AnalysisImaging(dataset=dataset) - -result = search.fit(model=model, analysis=analysis) - -""" -__Tracer & Fit__ - -In the previous tutorials, we saw that this result contains the maximum log likelihood fit, which provide -a fast way to visualize the result. - -It also contains the maximum log likelihood tracer. -""" -aplt.subplot_tracer( - tracer=result.max_log_likelihood_tracer, grid=mask.derive_grid.all_false -) - -aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) - -""" -__Samples__ - -The result contains a lot more information about the model-fit. - -For example, the `Samples` object contains all of the non-linear search samples, including the parameters -of every successful lens model evaluation and their log likelihood values. These are used for computing information -about the model-fit, such as the most probably parameter estimates and the error inferred for every parameter. -""" -print(result.samples) -print("Parameters of 1st Sample:") -print(result.samples.parameter_lists[0][:]) -print("Log Likelihood of 1st Sample:") -print(result.samples.log_likelihood_list[0]) - -""" -__Workspace__ - -We are not going into any more detail on the result variable in this tutorial, or in the **HowToLens** lectures. - -A comprehensive description of the results can be found at the following package: - - `autolens_workspace/*/guides/results` - -The results API for CCD imaging data is the same as for other data types (e.g. interferometer, point-soures). This -package can therefore be used to learn the API and then translate to other data types. - - -__Database__ - -Once a search has completed running, we have a set of results on our hard disk which we can manually inspect and -analyse. Alternatively, we can return the results from the search.fit() method and manipulate them in a Python script -or notebook. - -However, imagine you have a large dataset consisting of many images of strong lenses. You analyse each image -individually using a search, producing a large library of results on your hard disk. There will be lots of paths and -directories to navigate, and at some point there will simply be too many results for it to be an efficient use of your -time to analyse the results by sifting through the outputs on your hard disk one-by-one. - -**PyAutoLens**'s database tools solve this problem, by making it possible for us to write the results to a .sqlite -database file and load the results from hard-disk to a Python script or Jupyter notebook. This database supports -advanced queries, so specific results can be loaded and inspected. - -We won't go into any more detail on the database in this tutorial. If you think the database will be useful, checkout -the full set of database tutorials which can be found in the folder `autolens_workspace/*/guides/results/database`. - -Here, you'll learn how to: - - - Use the database to query for results which fit a certain lens model or give a certain result. - - - Use the `Samples` to produce many different results from the fit, including error estimates on parameters and - plots of the probability density function of parameters in 1D and 2D. - - - Visualize results, for example the fit to a lens dataset. - -__Wrap Up__ - -Even if you are only modeling a small sample of lenses, if you anticipate using **PyAutoLens** for the long-term I -strongly recommend you begin using the database to inspect and analyse your result. - -This is because it makes it simple to perform all analyse in a Jupyter notebook, which is the most flexible and -versatile way to check results and make figures. -""" diff --git a/scripts/chapter_2_lens_modeling/tutorial_7_summary.py b/scripts/chapter_2_lens_modeling/tutorial_7_summary.py new file mode 100644 index 0000000..ee39574 --- /dev/null +++ b/scripts/chapter_2_lens_modeling/tutorial_7_summary.py @@ -0,0 +1,31 @@ +""" +Tutorial 7: Summary +=================== + +__Summary__ + +You have now fitted a lens model by searching through its possible parameter values, rather than choosing those +values by hand. + +We began by connecting a point in parameter space to a predicted image and its likelihood. We then explored why +finding a convincing fit can be difficult: parameters can compensate for one another, different solutions can +produce similar images, and a search can settle at a local maximum. Inspecting the fit, changing search settings +and trying other search methods help us investigate these possibilities. + +Linear light profiles simplified part of this problem by solving for intensities within each likelihood evaluation. +Search chaining then showed how an initial fit can support a more detailed analysis, while making clear which +quantities remain free and which assumptions are carried forward. + +We also separated the ingredients of a modelling calculation. The dataset supplies the observations; the model +describes the objects and parameters; the analysis defines how their predictions are compared with those +observations; and the search explores the resulting parameter space. The same `af.Model` and `af.Collection` +composition API is used across datasets. Different observations require different predictions and likelihoods, +but much of the modelling framework remains familiar. + +You can now adapt the examples in `autolens_workspace` to your own data, or use the simulators to investigate a +lens whose input properties you know. Start by inspecting the image and the fitted residuals, and treat the first +plausible solution as something to investigate rather than proof that the search has found the global maximum. + +Chapter 3 develops a more flexible description of the background source: reconstructing its light on a pixelization +instead of representing it with analytic light profiles. +""" diff --git a/scripts/chapter_2_lens_modeling/tutorial_8_need_for_speed.py b/scripts/chapter_2_lens_modeling/tutorial_8_need_for_speed.py deleted file mode 100755 index 776d51f..0000000 --- a/scripts/chapter_2_lens_modeling/tutorial_8_need_for_speed.py +++ /dev/null @@ -1,164 +0,0 @@ -""" -Tutorial 8: Need For Speed -========================== - -In this chapter, we have learnt how to model strong lenses and how to balance complexity and realism to ensure that we -infer a good lens model. - -For fitting more complex lens models, the final challenge that we face is keeping the run-time low. One can easily end -up in a situation where a model-fit takes days, or longer, to fit just one image. For fitting complex models and high -resolution datasets this is somewhat unavoidable. However, it is worth us discussing what drives the long run-times of -the lens modeling process and how we might speed it up. - -The preceding tutorials discussed the costs contributing to a fit's elapsed time. Lets remind ourselves of the main -factors that drive the run-time and how we might reduce it. - -For sequential likelihood evaluations, the search's evaluation cost is approximately the product of two numbers: - - - The number of log likelihood evaluations the non-linear search performs before it converges. - - - The time each individual log likelihood evaluation takes. - -Batching evaluates several models together, so this product does not directly predict GPU elapsed time. Compilation -and saving output also add time. The approaches below address these costs or reduce the exploration needed. - -__Contents__ - -- **Searching Non-linear Parameter Space:** What drives the number of likelihood evaluations a search performs. -- **Cost Per Evaluation:** What drives the time a single log likelihood evaluation takes. -- **JAX:** How **PyAutoLens** compiles the likelihood function with JAX and runs it on CPUs and GPUs. -- **Run Time Estimation:** How to estimate the overall run-time of a fit before committing to it. -- **Data Quantity:** How the amount of data fitted, and the mask applied to it, drives run-times. -- **Wrap Up:** Summary of the script and next steps. - -__Searching Non-linear Parameter Space__ - -The time it takes for the non-linear search to sample parameter space and find the high likelihood models is driven by: - - - Dimensionality: A more complex parameter space (e.g. more parameters) takes longer to search. - - Priors: The broader the priors on each parameter the longer the search. - - Settings: Non-linear search settings which sample parameter space more thoroughly (e.g. a higher `n_live`) lead to - longer run-times. - -When we use only one search to fit a lens model, we are somewhat restricted in how we can try to achieve faster run -times by changing these 3 aspects of the search. We have already seen one powerful exception: the linear light -profiles of tutorial 4 remove every `intensity` parameter from the non-linear parameter space, reducing its -dimensionality and removing some of its most difficult degeneracies at the same time. - -The final three tutorials of this chapter (tutorials 9, 10 and 11) introduce 'non-linear search chaining', which fits -a lens model using multiple searches that are performed back-to-back, passing the results of earlier searches to -later ones. A key motivation for this is that it gives us a lot more flexibility in juggling the dimensionality, -priors and settings so as to perform faster and more efficient lens modeling, culminating in the fully automated -SLaM pipelines of tutorial 11. - -In the optional **PyAutoLens** tutorial `chapter_optional/tutorial_searches.py` we discuss other non-linear searches -supported by **PyAutoLens** which use a different approach to sample parameter space than `Nautilus`. For those -familiar with statistical inference, this includes maximum likelihood estimators and MCMC algorithms. - -For lens modeling, we have not found another non-linear search that provides as robust and efficient results as -Nautilus. We therefore recommend users stick to `Nautilus`. - -__Cost Per Evaluation__ - -The second number is the time a single log likelihood evaluation takes, which is set by every operation -**PyAutoLens** performs to fit the strong lens data with a model, for example: - - - Computing the deflection angles of the mass model and ray-tracing the image-plane grid to the source-plane. - - Computing the intensity values of every light profile on those grids. - - Over-sampling: sub-dividing image pixels into finer sub-pixels where light profiles change rapidly (e.g. the - centre of the lens galaxy), which multiplies the number of intensity evaluations performed. - - Convolving the image that comes from the tracer with the telescope's PSF to compare it to the data. The larger - the PSF, the more expensive this convolution becomes. - - For linear light profiles, basis functions like the MGE of tutorial 4 and the pixelizations of chapter 3, solving - the linear algebra of the inversion, which computes the `intensity` values that best fit the data. - -More complex fitting techniques therefore cost more per evaluation: a couple of standard light profiles are cheap, -an MGE costs more (its inversion solves for many Gaussians), and pixelized source reconstructions cost the most. -As we saw in tutorial 4, this trade often still favours the more advanced technique, because the simpler parameter -space it produces reduces the number of evaluations the search needs. - -__JAX__ - -How are these operations made fast? **PyAutoLens** uses JAX (https://github.com/jax-ml/jax), Google's numerical -computing library, which just-in-time (JIT) compiles the entire log likelihood function into optimized machine code. - -JIT compilation means the first time the likelihood function is called, JAX traces through every operation it -performs (ray-tracing, light profile evaluation, PSF convolution, the linear algebra of an inversion) and compiles -them into a single optimized program. This compilation is a one-off overhead, typically taking seconds to a couple -of minutes depending on model complexity. Every one of the tens of thousands of likelihood evaluations that follow -then reuses the compiled program and runs dramatically faster than ordinary Python. When a search begins you will -see a log message like `JAX jit compiling vectorized (vmap) likelihood function, could take seconds or minutes...` --- that is the compilation happening. - -JAX's second superpower is that the same compiled code runs on either a CPU or a GPU. On a GPU, likelihood -evaluations are not only faster individually but can be batched, with many evaluated simultaneously (the -`n_batch` search input and its VRAM implications were discussed in tutorial 2). GPU speed-ups over CPU -of an order of magnitude or more are common, and they grow with the size of the dataset and model. If you have -access to a GPU (even a modest laptop GPU), it is the single biggest speed-up available to you. - -You do not need to do anything to switch this on. JAX installs with `autolens` by default, and every -`AnalysisImaging` object we have created in this chapter defaults to `use_jax=True` and the search compiles and -batches the likelihood function automatically. You can force the plain NumPy path with -`al.AnalysisImaging(dataset=dataset, use_jax=False)` (or by setting the environment variable -`PYAUTO_DISABLE_JAX=1`), which is mainly useful for debugging, as NumPy errors and stack traces are much easier -to read than JAX ones. - -The one trade-off to keep in mind is the compilation overhead itself. For a full model-fit performing tens of -thousands of likelihood evaluations it is negligible. For a quick one-off calculation (e.g. fitting a single -tracer to data once, as we did in chapter 1) compilation can take longer than the calculation it speeds up, which -is why short interactive computations sometimes feel slower than you might expect the first time they run. - -Long-time users may remember that **PyAutoLens** previously used `numba`, which recompiles individual Python -functions into fast machine code. JAX supersedes it: rather than accelerating functions one at a time, it compiles -and optimizes the likelihood function end-to-end, and adds GPU support and batching on top. The one exception is -pixelized-source modeling on a CPU, where the `numba` sparse-operator path (see -`autolens_workspace/scripts/imaging/features/pixelization/cpu_fast_modeling.py`, and chapter 3) remains the faster -route on many-core machines. - -Therefore, **PyAutoLens** is pretty well optimized and there are no 'low hanging fruit' speed ups available by -writing the code in a different language. - -__Run Time Estimation__ - -Tutorial 2 explains how likelihood cost, the number of evaluations, compilation and output contribute to elapsed time. -It does not measure a likelihood evaluation time or predict a fixed duration for the fit. - -An estimate needs measurements from the actual likelihood calculation, using the intended model, dataset, hardware -and batch size. A standalone `FitImaging` calculation need not follow the same compiled and batched path as the search. -JAX measurements must wait for device calculations to finish, with compilation considered separately from repeated -evaluations. - -The number of evaluations needed also depends on the parameter space and search settings. Compare the saved durations -of representative completed fits, as in Tutorial 3, before extrapolating to a larger analysis. If those runs suggest -that a fit will take days or weeks, consider simplifying the model, search chaining or different hardware. - -On a GPU, tutorial 2 also showed the other pre-flight check: `analysis.print_vram_use` estimates whether the fit -will fit within the GPU's memory for your chosen batch size. - -__Data Quantity__ - -The final factor driving run-speed is the quantity of data that is fitted. For every image-pixel that we fit, -we have to compute the light profile intensities, mass profile deflection angles and convolve it with the telescope's -PSF. The larger that PSF is, the more convolution operations we have to perform too. - -In the previous exercises, we used images with a pixel scale of 0.1". This value is relatively low resolution: most -Hubble Space Telescope images have a pixel scale of 0.05", which is four times the number of pixels! Some telescopes -observe at scales of 0.03" or, dare I say it, 0.01". At these resolutions things can *really* slow down, if we -do not think carefully about run speed beforehand. - -There are ways that we can reduce the number of image-pixels we fit, via masking. If we mask out more of the image, -we will fit fewer pixels and **PyAutoLens** will run faster. If you want the best, most perfect lens model possible, -aggressive masking and cutting the data in this way is a bad idea, as discussed in tutorial 6. - -__Wrap Up__ - -This tutorial simply wanted to get you thinking about *why* a lens model takes as long to fit as it does: the number -of likelihood evaluations the search performs, times the cost of each evaluation, with JAX's compiled likelihood -function (and a GPU, if you have one) driving the latter down as far as it will go. - -The remaining tutorials of this chapter attack the other half of the product: search chaining (tutorial 9) and prior -passing (tutorial 10) reduce the number of evaluations needed to fit complex models, and the SLaM pipelines -(tutorial 11) package these ideas into automated pipelines for fitting large samples of lenses. -""" - -# from autolens import setup_notebook; setup_notebook() diff --git a/scripts/chapter_2_lens_modeling/tutorial_9_search_chaining.py b/scripts/chapter_2_lens_modeling/tutorial_9_search_chaining.py deleted file mode 100644 index 7b7187d..0000000 --- a/scripts/chapter_2_lens_modeling/tutorial_9_search_chaining.py +++ /dev/null @@ -1,394 +0,0 @@ -""" -Tutorial 9: Search Chaining -=========================== - -Throughout this chapter, we have fitted the data using just one non-linear search. The previous tutorial discussed -the run-time cost of doing this: with a single search, the dimensionality of the model, the priors on its parameters -and the search settings must all be juggled at once, leaving us little flexibility to trade them off against one -another. - -In this closing part of the chapter, we introduce a technique called 'non-linear search chaining', which fits a lens -model using a sequence of non-linear searches. The initial searches fit simpler lens models whose parameter spaces can -be more accurately and efficiently sampled. The results of this search are then passed to later searches which fit -lens models of gradually increasing complexity. - -Lets think back to tutorial 3 of this chapter. We learnt there were three approaches one could take fitting a lens -model accurately if we found that a model fit failed. These were: - - 1) Tuning our priors to the strong lens we're fitting. - 2) Making our lens model less complex. - 3) Searching non-linear parameter space for longer. - -However, each of the above approaches has disadvantages. The more we tune our priors, the less we can generalize our -analysis to a different strong lens. The less complex we make our model, the less realistic it is. And if we rely too -much on searching parameter space for longer, we could end up with search`s that take days, weeks or months to run. - -In this tutorial, we are going to show how search chaining combines these 3 approaches such that we can fit -complex and realistic lens models in a way that that can be generalized to many different strong lenses. To do this, -we'll run 2 searches, and chain the lens model inferred in the first search to the priors of the second search`s lens -model. - -Our first search will make the same light-traces-mass assumption we made in tutorial 3. We saw that this -gives a reasonable lens model. However, we'll make a couple of extra simplifying assumptions, to really try and bring -our lens model complexity down and get the non-linear search running fast. - -The model we infer above will therefore be a lot less realistic. But it does not matter, because in the second search -we are going to relax these assumptions and fit the more realistic lens model. The beauty is that, by running the first -search, we can use its results to tune the priors of our second search. For example: - - 1) The first search should give us a pretty good idea of the lens galaxy's light and mass profiles, for example its - intensity, effective radius and einstein radius. - - 2) It should also give us a pretty good fit to the lensed source galaxy. This means we'll already know where in - source-plane its is located and what its intensity and effective are. - -__Contents__ - -- **Initial Setup:** Load the same strong lensing data fitted throughout this chapter. -- **Dataset Auto-Simulation:** Simulate the dataset via its simulator script if it is not on your hard-disk. -- **Model:** Compose the lens model fitted to the data. -- **Search + Analysis:** Create the non-linear search and analysis used to fit the first model. -- **Result:** Overview of the results of the model-fit. -- **Prior Passing:** Use the results of search 1 to set up the priors of search 2. -- **Run Time:** Profiling the expected run time of the model-fit. -- **Model Fit:** Perform the model-fit using the search and analysis. -- **Wrap Up:** Summary of the script and next steps. - -""" - -from autolens import jax_wrapper # Sets JAX environment before other imports - -# from autolens import setup_notebook; setup_notebook() - -import numpy as np -from pathlib import Path -import autolens as al -import autolens.plot as aplt -import autofit as af - -""" -__Initial Setup__ - -we'll use the same strong lensing data as tutorials 2, 3 and 4 of this chapter, where: - - - The lens galaxy's light is an `Sersic`. - - The lens system uses an `Isothermal` galaxy mass profile and a separate `ExternalShear` field. - - The source galaxy's light is an `Exponential`. -""" -dataset_name = "lens_sersic" -dataset_path = Path("dataset") / "imaging" / dataset_name - -""" -__Dataset Auto-Simulation__ - -If the dataset does not already exist on your system, it will be created by running the corresponding -simulator script. This ensures that all example scripts can be run without manually simulating data first. -""" -al.util.dataset.simulate_if_needed( - dataset_path, simulator="scripts/simulator/lens_sersic.py" -) - -dataset = al.Imaging.from_fits( - data_path=dataset_path / "data.fits", - noise_map_path=dataset_path / "noise_map.fits", - psf_path=dataset_path / "psf.fits", - pixel_scales=0.1, -) - -mask_radius = 2.6 - -mask = al.Mask2D.circular( - shape_native=dataset.shape_native, - pixel_scales=dataset.pixel_scales, - radius=mask_radius, -) - -dataset = dataset.apply_mask(mask=mask) - -aplt.subplot_imaging_dataset(dataset=dataset) - -""" -__Model__ - -As we've eluded to before, one can look at an image and immediately identify the centre of the lens galaxy. It's -that bright blob of light in the middle! Given that we know we're going to make the lens model more complex in the -next search, lets take a more liberal approach than before and fix the lens centre to $(y,x)$ = (0.0", 0.0"). - -Now, you might be thinking, doesn`t this prevent our search from generalizing to other strong lenses? What if the -centre of their lens galaxy isn't at (0.0", 0.0")? - -Well, this is true if our dataset reduction centres the lens galaxy somewhere else. But we get to choose where we -centre it when we make the image. Therefore, I`d recommend you always centre the lens galaxy at the same location, -and (0.0", 0.0") seems the best choice! -""" -bulge = af.Model(al.lp_linear.Sersic) -mass = af.Model(al.mp.Isothermal) - -""" -You haven't actually seen a line like this one before. By setting a parameter to a number (and not a prior) it is be -removed from non-linear parameter space and always fixed to that value. Pretty neat, huh? -""" -bulge.centre_0 = 0.0 -bulge.centre_1 = 0.0 -mass.centre_0 = 0.0 -mass.centre_1 = 0.0 - -""" -Lets use the same approach of making the ellipticity of the mass trace that of the bulge. -""" -mass.ell_comps = bulge.ell_comps - -""" -We also discussed that the Sersic index of most lens galaxies is around 4. Lets fix it to 4 this time. -""" -bulge.sersic_index = 4.0 - -""" -We now compose the model with these components that have had their priors customized. - -We have not done anything to the source model, but use an `Exponential` which will become the more complex -`Sersic` in the second search. -""" -lens = af.Model(al.Galaxy, redshift=0.5, bulge=bulge, mass=mass) -field = af.Model(al.MassField, redshift=0.5, shear=al.mp.ExternalShear) - -source = af.Model(al.Galaxy, redshift=1.0, bulge=al.lp_linear.ExponentialCore) - -model_1 = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field) - -""" -The `info` attribute shows the model in a readable format. -""" -print(model_1.info) - -""" -The same model can also be visualized as a figure, making its structure easier to understand at a glance. - -The figure shows how the model is organized: which parameters belong to each component, and whether they are free, -fixed, shared, linked by an expression, solved during the fit, or not configured. `model.info` provides the -corresponding numerical details, including the prior assigned to each free parameter and the value of each fixed -parameter. - -Eleven dimensions is a deliberately crude model, and that is exactly what the first search in a chain wants: it -needs only to be good enough to locate the lens roughly, and to do so quickly. -""" -af.ModelPlotter(model_1).figure() - -""" -__Search + Analysis__ - -Now lets create the search and analysis. -""" -search_1 = af.Nautilus( - path_prefix=Path("howtolens", "chapter_2"), - name="tutorial_9_search_chaining_1", - unique_tag=dataset_name, - n_live=100, - iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations -) - -analysis_1 = al.AnalysisImaging(dataset=dataset) - -""" -Lets run the search, noting that our liberal approach to reducing the lens model complexity has reduced it to just -11 parameters. -""" -print( - "The non-linear search has begun running - checkout the output/howtolens/chapter_2" - " folder for live output of the results, images and lens model." - " This Jupyter notebook cell with progress once search has completed - this could take some time!" -) - -result_1 = search_1.fit(model=model_1, analysis=analysis_1) - -print("Search has finished run - you may now continue the notebook.") - -""" -__Result__ - -The results are summarised in the `info` attribute. -""" -print(result_1.info) - -""" -And indeed, we get a reasonably good model and fit to the data, in a much shorter space of time! -""" -aplt.subplot_fit_imaging(fit=result_1.max_log_likelihood_fit) - -""" -__Prior Passing__ - -Now all we need to do is look at the results of search 1 and pass the results as priors for search 2. Lets setup -a custom search that does exactly that. - -`GaussianPrior`'s are a nice way to pass priors. They tell the non-linear search where to look, but leave open the -possibility that there might be a better solution nearby. In contrast, `UniformPrior`'s put hard limits on what values a -parameter can or can`t take. It makes it more likely we will accidentally cut-out the global maxima solution. -""" -bulge = af.Model(al.lp_linear.Sersic) -mass = af.Model(al.mp.Isothermal) -field = af.Model(al.MassField, redshift=0.5, shear=al.mp.ExternalShear) -source_bulge = af.Model(al.lp_linear.Sersic) - -""" -What I've done below is looked at the results of search 1 and manually specified a prior for every parameter. If a -parameter was fixed in the previous search, its prior is based around the previous value. Don't worry about the sigma -values for now, I've chosen values that I know will ensure reasonable sampling, but we'll cover this later. - -__LENS LIGHT PRIORS:__ -""" -bulge.centre.centre_0 = af.GaussianPrior( - mean=0.0, - sigma=0.1, -) -bulge.centre.centre_1 = af.GaussianPrior( - mean=0.0, - sigma=0.1, -) -bulge.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior( - mean=0.05, sigma=0.15, lower_limit=-1.0, upper_limit=1.0 -) -bulge.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior( - mean=0.0, sigma=0.2, lower_limit=-1.0, upper_limit=1.0 -) -bulge.effective_radius = af.TruncatedGaussianPrior( - mean=0.72, sigma=0.2, lower_limit=0.0, upper_limit=np.inf -) -bulge.sersic_index = af.TruncatedGaussianPrior( - mean=4.0, sigma=2.0, lower_limit=0.0, upper_limit=np.inf -) - -""" -__LENS MASS PRIORS:__ -""" -mass.centre.centre_0 = af.GaussianPrior( - mean=0.0, - sigma=0.1, -) -mass.centre.centre_1 = af.GaussianPrior( - mean=0.0, - sigma=0.1, -) -mass.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior( - mean=0.05, sigma=0.15, lower_limit=-1.0, upper_limit=1.0 -) -mass.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior( - mean=0.0, sigma=0.2, lower_limit=-1.0, upper_limit=1.0 -) -mass.einstein_radius = af.TruncatedGaussianPrior( - mean=1.6, sigma=0.1, lower_limit=0.0, upper_limit=np.inf -) -field.shear.gamma_1 = af.GaussianPrior(mean=0.05, sigma=0.05) -field.shear.gamma_2 = af.GaussianPrior(mean=0.05, sigma=0.05) - -""" -__SOURCE LIGHT PRIORS:__ -""" -source_bulge.centre.centre_0 = af.GaussianPrior( - mean=0.0, - sigma=0.1, -) -source_bulge.centre.centre_1 = af.GaussianPrior( - mean=0.0, - sigma=0.1, -) -source_bulge.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior( - mean=0.08, sigma=0.15, lower_limit=-1.0, upper_limit=1.0 -) -source_bulge.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior( - mean=-0.06, sigma=0.2, lower_limit=-1.0, upper_limit=1.0 -) -source_bulge.effective_radius = af.TruncatedGaussianPrior( - mean=0.1, sigma=0.2, lower_limit=0.0, upper_limit=np.inf -) -source_bulge.sersic_index = af.TruncatedGaussianPrior( - mean=1.0, sigma=1.0, lower_limit=0.0, upper_limit=np.inf -) - -""" -We now compose the model with these components that have had their priors customized. -""" -lens = af.Model(al.Galaxy, redshift=0.5, bulge=bulge, mass=mass) - -source = af.Model(al.Galaxy, redshift=1.0, bulge=source_bulge) - -model_2 = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field) - -""" -The `info` attribute shows the model, including the priors specified above. -""" -print(model_2.info) - -""" -The second model is the comparison worth making. The centres and the `sersic_index` are free again, the pairing -between `bulge` and `mass` has gone with them, and the source is now a `Sersic` with a `sersic_index` of its -own: nineteen free parameters against the eleven of `model_1`. - -That is search chaining: search 1 fits the small model, and what it learns buys us the priors that make the -large model affordable. -""" -af.ModelPlotter(model_2).figure() - -""" -Lets setup and run the search. As expected, it gives us the correct lens model. However, it does so significantly -faster than we are used to! -""" -search_2 = af.Nautilus( - path_prefix=Path("howtolens", "chapter_2"), - name="tutorial_9_search_chaining_2", - unique_tag=dataset_name, - n_live=150, - iterations_per_quick_update=25000, # Outputs Notebook visualization of max likelihood model every N iterations -) - -analysis_2 = al.AnalysisImaging(dataset=dataset) - -""" -__Run Time__ - -Whilst the run-time of the log likelihood function is pretty much unchanged from the first search, the overall run-time -of the search should decrease. - -This is because via prior passing we have informed the search of where to look in parameter space, meaning it -should spend far fewer than ~10000 iterations per free parameter. - -__Model Fit__ - -Run the search. -""" -print( - "The non-linear search has begun running - checkout the output/howtolens/chapter_2" - " folder for live output of the results, images and lens model." - " This Jupyter notebook cell with progress once search has completed - this could take some time!" -) - -result_2 = search_2.fit(model=model_2, analysis=analysis_2) - -print("Search has finished run - you may now continue the notebook.") - -""" -__Result__ - -We can again inspect the results via the `info` attribute. -""" -print(result_2.info) - -""" -And a plot of the image shows we get a good model again! -""" -aplt.subplot_fit_imaging(fit=result_2.max_log_likelihood_fit) - -""" -__Wrap Up__ - -Chaining two searches together was a huge success. We managed to fit a complex and realistic model, but were able to -begin by making simplifying assumptions that eased our search of non-linear parameter space. We could apply search 1 to -pretty much any strong lens and therefore get ourselves a decent lens model with which to tune search 2`s priors. - -You are probably thinking though that there is one huge, giant, glaring flaw in all of this that I've not mentioned. -Search 2 can`t be generalized to another lens, because its priors are tuned to the image we fitted. If we had a lot -of lenses, we`d have to write a new search for every single one. This isn't ideal, is it? - -Fortunately, we can pass priors in **PyAutoLens** without specifying the specific values. The API for this technique, -called prior passing, is the topic of the next tutorial. -""" diff --git a/scripts/chapter_optional/README.md b/scripts/chapter_optional/README.md new file mode 100644 index 0000000..2ff62b7 --- /dev/null +++ b/scripts/chapter_optional/README.md @@ -0,0 +1,9 @@ +# Optional tutorials + +These lessons supplement the main chapters. Historical prior passing is retained for understanding older analyses. + +- [Need for Speed](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_need_for_speed.ipynb) — Computation, batching and estimating runtime. + +- [Historical Prior Passing](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_prior_passing.ipynb) — An optional runnable example of prior passing using model_centred, a technique central to older workflows. + +- [Searches](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_searches.ipynb) — Alternative non-linear search methods. diff --git a/scripts/chapter_optional/tutorial_need_for_speed.py b/scripts/chapter_optional/tutorial_need_for_speed.py new file mode 100755 index 0000000..fc40f2c --- /dev/null +++ b/scripts/chapter_optional/tutorial_need_for_speed.py @@ -0,0 +1,159 @@ +""" +Optional Tutorial: Need for Speed +================================ + +Two fits to the same image can take very different amounts of time. Finding a good fit with a simple model may be +quick, whereas exploring the uncertainties of a more flexible model can take much longer. Both the calculation +performed for each model and the search through parameter space contribute to this difference. + +This optional tutorial looks at these costs, including JAX compilation, batching and hardware. It builds on the fits +we have performed in chapter 2, but is not a prerequisite for the pixelized source reconstructions of chapter 3. +Return to it when planning a larger analysis, or when a fit takes longer than you expected. + +__Contents__ + +- **Searching Parameter Space:** What determines how much exploration a search needs. +- **Cost Per Evaluation:** The calculations required to compare one model with the data. +- **JAX:** Compilation and the cost of the first evaluation. +- **Batches and GPU Memory:** Evaluating models together and choosing a batch size. +- **Run Time Estimation:** Measuring the costs relevant to your analysis. +- **Data Quantity:** How image resolution and the fitted region affect computation. +- **Wrap Up:** Putting these considerations together. + +__Searching Parameter Space__ + +A non-linear search evaluates models until its stopping criteria are met. The number of evaluations depends on more +than the number of free parameters. A narrow, curved region of high likelihood can be difficult to explore, as can +several separated peaks. Two models with the same number of parameters need not take similar amounts of time to fit. + +Broad priors can require the search to explore large regions that fit the data poorly. However, narrowing a prior +just to make a fit faster risks excluding plausible solutions. The prior should express a justified assumption +about the parameter, rather than the region we hope will give the quickest result. + +Search settings also determine how much work is performed. More live points in Nautilus, or more starting points +and optimisation steps in Prodigy, cost computation but may improve exploration. Tutorial 3 showed why reducing +this effort too far can leave us with a local maximum. + +The searches also answer different questions. Prodigy seeks a good-fitting model without exploring the posterior +to measure parameter uncertainties. Nautilus performs that additional exploration, so we should expect uncertainty +estimation to take longer. The search chain in Tutorial 6 uses these different strengths at different stages. + +The optional tutorial `chapter_optional/tutorial_searches.py` introduces other search methods. Trying a different +method can help with a difficult fit; the appropriate choice depends on both the parameter space and whether we +need a best-fitting model or a description of its uncertainties. + +__Cost Per Evaluation__ + +For every model proposed by the search, we must predict the observed image and compare it with the data. This +includes calculating deflection angles, ray-tracing the image-plane grid, evaluating light profiles and convolving +the predicted image with the telescope's PSF. + +Over-sampling adds calculations within image pixels, so that rapidly changing light profiles are represented +accurately. Linear light profiles also require a linear solve for their intensities. An MGE includes many such +profiles, while the pixelized source reconstructions introduced in chapter 3 require their own reconstruction. + +The cost of these operations depends on the number of pixels, profiles and source elements, as well as the numerical +methods and their implementation. There is no universal ordering in which every MGE is slower than a few light +profiles, or every pixelized reconstruction is slower than an MGE. + +Adding more Gaussian components to an MGE increases the work in the linear calculation. However, solving their +intensities linearly can make the non-linear parameter space easier to explore, as we saw in Tutorial 4. A model +that costs more per evaluation can therefore finish sooner if the search needs substantially fewer evaluations. +Timing one evaluation alone does not tell us how long the whole fit will take. + +__JAX__ + +**PyAutoLens** uses JAX (https://github.com/jax-ml/jax) to compile supported likelihood calculations and to calculate +the derivatives used by gradient-based searches such as Prodigy. + +The first evaluation includes tracing the calculation and compiling it into a program that can be reused. Later +evaluations with new parameter values can then use that compiled program. This is why the beginning of a fit may +feel slow even when subsequent evaluations are fast. + +Reuse depends on the calculation retaining a compatible structure. Changing array shapes, data types or settings +treated as fixed during compilation can require a new compilation. We should therefore distinguish the initial +setup cost from the cost of repeated evaluations, rather than assuming compilation happens only once across an +entire sequence of fits. + +The imaging analyses in this chapter use JAX by default. Setting `use_jax=False` in `al.AnalysisImaging` selects the +NumPy path, which can be useful when diagnosing a calculation or comparing implementations. This does not make a +gradient-based search independent of derivatives: such a search still needs a supported differentiable calculation. + +__Batches and GPU Memory__ + +Instead of evaluating one model at a time, a search can evaluate a batch of models together. This can increase the +number of evaluations completed per second, particularly on a GPU, but it also requires memory for several +calculations at once. + +For Nautilus, `n_batch` controls the batch of likelihood evaluations. For MultiStartProdigy, `batch_size` controls +how many optimisation starts are processed together. These settings play different roles in the searches, but +both affect the amount of work held in memory. + +A larger batch may improve throughput, but eventually the improvement can diminish or the calculation can exceed +the available GPU memory. The largest possible batch is not automatically the best setting. + +A GPU is also not guaranteed to outperform a CPU for every fit. The outcome depends on the model, dataset, batch +size, numerical precision and hardware. Compilation and moving data to the device contribute to elapsed time too. +Compare the same analysis on the hardware available to you, including the costs relevant to your use: a short +interactive calculation and a long modelling campaign can favour different choices. + +__Run Time Estimation__ + +To estimate how long a fit will take, start with a representative analysis: the model, dataset, search settings and +hardware should resemble those you intend to use. A timing measured with a simpler model or a smaller image may +give a misleading impression of the work ahead. + +Separate the time spent preparing and compiling the calculation from the time spent evaluating models afterwards. +JAX can dispatch calculations before they have finished, so a measurement must wait for the calculation to complete. +Otherwise, we may time only the act of submitting the work. + +For a batched search, the useful quantity is how many likelihood evaluations are completed per second. Timing a +standalone `FitImaging` calculation does not necessarily measure the compiled, batched calculation used by the search. + +Even with this measurement, we do not yet know how many evaluations the search will need. A short run can reveal +expensive calculations or memory problems, but it cannot reliably predict how long exploration of a difficult +parameter space will take. Completed fits to similar datasets provide a more useful starting point. + +When comparing approaches, inspect their results alongside their durations. A fit that finishes quickly at a poor +local maximum has not achieved the same outcome as one that finds a convincing solution. Likewise, finding one +good model and measuring its uncertainties are different amounts of work. + +__Data Quantity__ + +Consider two images covering the same region of sky. One has pixels that are 0.1 arcseconds across, while the other +has pixels that are 0.05 arcseconds across. Halving the pixel scale doubles the number of pixels along each axis, +giving approximately four times as many pixels in the fitted region. + +The finer image therefore requires calculations at more positions. The precise increase in runtime also depends +on over-sampling, the PSF, the model and how the calculation is implemented; four times as many pixels does not +necessarily mean a fit takes exactly four times as long. + +The circular mask determines how much of the image enters the fit. However, as we discussed in Tutorial 5, faint +lens and source emission still contains information, including where a proposed model predicts light that the +image does not contain. Shrinking the circle until only the brightest features remain can change the inferred model. + +We therefore choose a circle large enough to contain the relevant emission, including the lens galaxy's light. +If that calculation is expensive, we investigate the model, search and computational settings while retaining +the region needed for the scientific analysis. + +__Wrap Up__ + +A lens fit takes time both because each proposed model requires a calculation and because the search must explore +many possible models. These costs interact: solving light-profile intensities linearly adds work to each evaluation +but can substantially simplify the search through parameter space. + +JAX, batching and suitable hardware can accelerate the calculations. Search chaining can organise the exploration +into stages, using an initial fit to inform a more detailed analysis. Neither removes the need to inspect the +result and investigate alternative solutions. + +When a fit is slow, identify where the time is being spent before changing settings. Compilation, expensive +evaluations and prolonged exploration call for different responses. Compare changes using both elapsed time and +the quality of the inference you obtain. + +**🤖 Ask AI:** Two searches fit the same lens image. One quickly finds a good-looking model, while the other takes +much longer and returns parameter uncertainties. What should I compare before deciding whether the faster search +is sufficient for my scientific question? + +""" + +# from autolens import setup_notebook; setup_notebook() diff --git a/scripts/chapter_optional/tutorial_prior_passing.py b/scripts/chapter_optional/tutorial_prior_passing.py new file mode 100644 index 0000000..c0691cf --- /dev/null +++ b/scripts/chapter_optional/tutorial_prior_passing.py @@ -0,0 +1,342 @@ +""" +Optional Tutorial: Historical Prior Passing +=========================================== + +This optional tutorial preserves a technique used in earlier **PyAutoLens** modelling workflows, up to around 2025: +passing parameter constraints from one search into the priors of a later search. + +For example, an initial search might constrain the Einstein radius. A subsequent search could use a narrower prior +centred on that inferred value, reducing the region it needs to explore. The prior-passing API automated this +construction using the results of the earlier fit. + +This approach is no longer part of the recommended workflow taught in this chapter. Tutorial 6 instead demonstrates +a chain that fixes selected lens-light geometry, retains fresh priors for the parameters being explored and uses +the first result to construct a positions penalty. Search chaining does not require passing narrowed priors +between searches. + +The distinction matters because an earlier fit can be incomplete or trapped at a local maximum. Restricting a later +search around that result can prevent it from finding alternatives. Using the same data again with priors derived +from its earlier fit also requires care when interpreting the resulting uncertainties. + +New readers can skip this tutorial and continue to chapter 3. It is retained to help readers understand older +scripts and analyses, rather than as an additional technique they need to learn before modelling their own lenses. + +Prior passing is still supported through `result.model_centred`. This tutorial runs two searches to demonstrate +that API. The historical distinction is its role in our workflows: it used to be central to search chaining, +whereas the main chapter now uses fresh priors and fixes selected components instead. + +`result.model` preserves the input priors. `result.model_centred` creates new priors centred on the inferred +parameter values. `result.instance` supplies fitted values that are held fixed. We will inspect the second model +to see which parameters receive centred priors and which receive fresh priors. + +__Contents__ + +- **Initial Setup:** Load the lens_sersic imaging dataset. +- **Dataset Auto-Simulation:** Simulate the dataset via its simulator script if it is not on your hard-disk. +- **Model:** Compose the lens model fitted to the data. +- **Search:** Configure the non-linear search used to fit the model. +- **Result (Search 1):** The results of search 1, which are used for prior passing. +- **Prior Passing:** Use the prior passing API to pass the results of search 1 without writing out values manually. +- **Result:** Overview of the results of the model-fit. +- **Wrap Up:** Summary of the script and next steps. +- **Detailed Explanation Of Prior Passing:** A detailed overview of how prior passing works and tools to customize it. +- **EXAMPLE:** Compare absolute and relative widths for a Sersic index. + +""" + +from autolens import jax_wrapper # Sets JAX environment before other imports + +# from autolens import setup_notebook; setup_notebook() + +import numpy as np +from pathlib import Path +import autolens as al +import autolens.plot as aplt +import autofit as af + +""" +__Initial Setup__ + +We use the lens_sersic simulated imaging dataset, where: + + - The lens galaxy's light is an `Sersic`. + - The lens system uses an `Isothermal` galaxy mass profile and a separate `ExternalShear` field. + - The source galaxy's light is an `ExponentialCore`. + +All the usual steps for setting up a model fit (masking, analysis, etc.) are included below. +""" +dataset_name = "lens_sersic" +dataset_path = Path("dataset") / "imaging" / dataset_name + +""" +__Dataset Auto-Simulation__ + +If the dataset does not already exist on your system, it will be created by running the corresponding +simulator script. This ensures that all example scripts can be run without manually simulating data first. +""" +al.util.dataset.simulate_if_needed( + dataset_path, simulator="scripts/simulator/lens_sersic.py" +) + +dataset = al.Imaging.from_fits( + data_path=dataset_path / "data.fits", + noise_map_path=dataset_path / "noise_map.fits", + psf_path=dataset_path / "psf.fits", + pixel_scales=0.1, +) + +mask_radius = 3.0 + +mask = al.Mask2D.circular( + shape_native=dataset.shape_native, + pixel_scales=dataset.pixel_scales, + radius=mask_radius, +) + +dataset = dataset.apply_mask(mask=mask) + +aplt.subplot_imaging_dataset(dataset=dataset) + +""" +__Model__ + +The first search fits a simpler model: the lens-light centre and Sersic index are fixed, the mass centre is fixed, +and the mass and light share their ellipticity. The second search will free some of these choices and use a more +flexible source profile. This tutorial performs its own fits; it does not require saved results from Tutorial 6. +""" +bulge = af.Model(al.lp_linear.Sersic) +mass = af.Model(al.mp.Isothermal) + +bulge.centre_0 = 0.0 +bulge.centre_1 = 0.0 +mass.centre_0 = 0.0 +mass.centre_1 = 0.0 + +mass.ell_comps = bulge.ell_comps + +bulge.sersic_index = 4.0 + +lens = af.Model(al.Galaxy, redshift=0.5, bulge=bulge, mass=mass) +field = af.Model(al.MassField, redshift=0.5, shear=al.mp.ExternalShear) + +source = af.Model(al.Galaxy, redshift=1.0, bulge=al.lp_linear.ExponentialCore) + +model_1 = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field) + +""" +The `info` attribute shows the model in a readable format. +""" +print(model_1.info) + +""" +The same model can also be visualized as a figure, making its structure easier to understand at a glance. + +The figure shows how the model is organized: which parameters belong to each component, and whether they are free, +fixed, shared, linked by an expression, solved during the fit, or not configured. `model.info` provides the +corresponding numerical details, including the prior assigned to each free parameter and the value of each fixed +parameter. + +Keep this model in mind when inspecting the second model below: changing priors and changing the physical +components are separate choices. +""" +af.ModelPlotter(model_1).figure() + +""" +__Search__ + +We run Nautilus to obtain a fit and posterior samples for the first model. Inspect its inferred parameters before +using them to construct priors for the second search. As with the earlier tutorials, a completed search does not +by itself establish that the solution is the global maximum. +""" +search_1 = af.Nautilus( + path_prefix=Path("howtolens", "chapter_optional"), + name="tutorial_prior_passing_1", + unique_tag=dataset_name, + n_live=100, + iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations +) + +analysis_1 = al.AnalysisImaging(dataset=dataset) + +result_1 = search_1.fit(model=model_1, analysis=analysis_1) + +""" +__Result (Search 1)__ + +The results which are used for prior passing are summarised in the `info` attribute. +""" +print(result_1.info) + +""" +__Prior Passing__ + +We are now going to use the prior passing API to pass these results, in a way which does not require us to manually +write out the inferred parameter values of each component. The details of how prior passing is performed will be +expanded upon at the end of the tutorial. + +We start with the lens's bulge, which in the previous search was an `Sersic` with its centre fixed to (0.0, 0.0) +and its `sersic_index` fixed to 4.0. The API for passing priors is shown below and there are two things worth noting: + + 1) We pass the priors using the `model_centred` attribute of the result. This informs **PyAutoLens** to pass the result as a + model component that is to be fitted for in the next search, using priors that are initialized from the previous + search's result. Note, if we pass through `model_centred` a parameter that was fixed in search 1 (e.g. the `sersic_index`) it + will be fixed to the same value in search 2. + + 2) We do not pass the `centre` or `sersic_index` using `model_centred`, because it would be fixed to the values that it was in + the first search. By omitting the centre, it uses the default priors on a lens galaxy, whereas we manually tell the + Sersic index to use a `TruncatedGaussianPrior` centred on 4.0. +""" +bulge = af.Model(al.lp_linear.Sersic) + +bulge.ell_comps = result_1.model_centred.galaxies.lens.bulge.ell_comps +bulge.effective_radius = result_1.model_centred.galaxies.lens.bulge.effective_radius +bulge.sersic_index = af.TruncatedGaussianPrior( + mean=4.0, sigma=2.0, lower_limit=0.0, upper_limit=5.0 +) + +""" +For the mass, we again must account for how its centre was fixed to (0.0", 0.0") and therefore not pass the centre. +The external shear belongs to its own field, so we pass that field model separately. Taking it from +`result_1.model_centred.fields` keeps its parameters free with the priors learned in the first search; taking +`result_1.instance.fields` would fix them to the fitted values instead. +""" +mass = af.Model(al.mp.Isothermal) +mass.einstein_radius = result_1.model_centred.galaxies.lens.mass.einstein_radius +mass.ell_comps = result_1.model_centred.galaxies.lens.mass.ell_comps +field = result_1.model_centred.fields + +""" +For the source's bulge, we are passing the result of an `ExponentialCore` to an `Sersic`. + +We can use a special prior passing method to do this, called `take_attributes`. This scans the `ExponentialCore` +passed to the `take_attributes` method for all parameters which have the same name as the `Sersic` model, +and if their names are the same it copies their prior from the centred model. Thus, it will locate the +parameters in common between the two profiles (`centre`, `ell_comps`, `effective_radius`) and pass those, +leaving the `sersic_index`'s priors as the default values. + +The `take_attributes` method is used in many examples of prior passing, when we pass a simpler parameterization of a +model to a more complex model. Another good example would be passing the result of a `IsothermalSph` to an +`Isothermal`. +""" +source_bulge = af.Model(al.lp_linear.Sersic) +source_bulge.take_attributes(result_1.model_centred.galaxies.source.bulge) + +""" +We now compose the model with these components that have had their priors customized. +""" +lens = af.Model(al.Galaxy, redshift=0.5, bulge=bulge, mass=mass) + +source = af.Model(al.Galaxy, redshift=1.0, bulge=source_bulge) + +model_2 = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field) + +""" +The `info` attribute shows the model, including how all priors are updated via prior passing. +""" +print(model_2.info) + +""" +Compare the priors in `model_2.info` with those in `model_1.info`. Transferred free parameters now have truncated +Gaussian priors centred on the first result. Newly freed parameters retain the priors we assigned separately. +The widths come from configuration; they need not all be narrower than the original priors. + +The two changes we made deliberately, and separately from the passing itself, are structural: `centre` and +`sersic_index` are free again, because we chose not to pass those, and the source is now a `Sersic` rather than +an `ExponentialCore` — the upgrade `take_attributes` exists to make possible. +""" +af.ModelPlotter(model_2).figure() + +""" +__Search__ + +We now fit the second model, using a separate output name so we can inspect both searches and their priors. +""" +search_2 = af.Nautilus( + path_prefix=Path("howtolens", "chapter_optional"), + name="tutorial_prior_passing_2", + unique_tag=dataset_name, + n_live=100, + iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations +) + +analysis_2 = al.AnalysisImaging(dataset=dataset) + +print( + "The non-linear search has begun running - checkout the output/howtolens/chapter_optional" + " folder for live output of the results, images and lens model." + " This Jupyter notebook cell with progress once search has completed - this could take some time!" +) + +result_2 = search_2.fit(model=model_2, analysis=analysis_2) + +print("Search has finished run - you may now continue the notebook.") + +""" +__Result__ + +We can again inspect the results via the `info` attribute. +""" +print(result_2.info) + +""" +Inspect the fitted image and residuals to assess how well the second model explains the data. +""" +aplt.subplot_fit_imaging(fit=result_2.max_log_likelihood_fit) + +""" +__Wrap Up__ + +We have fitted a simpler model, used `result_1.model_centred` to transfer priors for selected components, and fitted +a second model with additional freedom. Entire profiles or galaxies can also be transferred when appropriate: + +```python +bulge = result_1.model_centred.galaxies.lens.bulge +lens = result_1.model_centred.galaxies.lens +source = result_1.model_centred.galaxies.source +``` + +Passing `result_1.instance` instead supplies fixed fitted values. Tutorial 6 uses this to fix lens-light geometry +while continuing to solve linear intensities. The later uncertainties are conditional on the quantities held fixed. + +This optional technique remains available, but it is not required for the search-chaining workflow in the main +chapter. Inspect the first fit carefully: centring priors on a local maximum can make other solutions harder to find. +Using constraints inferred from the same data as new priors also requires care when interpreting later uncertainties. + +__Detailed Explanation Of Prior Passing__ + +For each transferred free parameter, `model_centred` creates a `TruncatedGaussianPrior`. Its mean is the posterior +median when available, falling back to the maximum-likelihood value for results without a posterior median. +Parameter limits are taken from configuration, falling back to the original prior's limits. + +The width is determined by the parameter's configured width modifier. In this implementation it is not taken +from the posterior error bars. The new priors therefore concentrate exploration near inferred values without +reproducing the complete posterior distribution or its correlations. + +An absolute width modifier specifies sigma in the parameter's units. A relative width modifier scales with the +inferred value, with any configured floor providing a minimum width. A parameter near zero can otherwise produce +a vanishingly small relative width, so centres and other parameters that can cross zero require particular care. +The linear intensities used here are solved inside the likelihood and do not receive non-linear priors. + +Explicit alternatives are `result_1.model_centred_absolute(a=...)` and `result_1.model_centred_relative(r=...)`. +The absolute variant sets sigma to `a`; the relative variant sets sigma to `r` times the inferred value. Choose +positive, meaningful widths for the components being transferred: a single relative factor is unsuitable for +parameters that can be zero or negative, and a single absolute width need not suit parameters with different units. + +These centred priors need not match a strongly asymmetric or multimodal posterior. Even a broad width does not +guarantee that the second search can recover solutions missed by the first. + +__EXAMPLE__ + +Suppose a first search gives a posterior median Sersic index of 4.0. With an absolute width modifier of 0.8, +`model_centred` constructs a truncated Gaussian prior with mean 4.0 and sigma 0.8, subject to the parameter limits. +With a relative width modifier of 0.8 and no active floor, sigma would instead be 4.0 * 0.8 = 3.2. + +These values illustrate the distinction; they are not recommended settings or a statement of the current defaults. +The centre of a new prior comes from the result, while its width expresses how much freedom we give the next search. + +**🤖 Ask AI:** In this two-search lens fit, some parameters receive priors from `model_centred`, others receive fresh +priors, and some remain fixed. How could each choice affect the solutions found and the uncertainties reported? + +Return to Tutorial 6 for the main chapter's search-chaining approach, or continue to chapter 3 for pixelized source +reconstructions. +""" diff --git a/workspace_index.json b/workspace_index.json index c2e229d..42bbd16 100644 --- a/workspace_index.json +++ b/workspace_index.json @@ -165,49 +165,11 @@ "summary": "In this chapter, we have built up the steps needed to describe a gravitational lens and compare its predicted image with an observation:", "title": "Tutorial 7: Summary" }, - { - "contents": [ - "Initial Setup", - "Dataset Auto-Simulation", - "Model", - "Search", - "Result (Search 1)", - "Prior Passing", - "Result", - "Wrap Up", - "Detailed Explanation Of Prior Passing", - "EXAMPLE" - ], - "cross_refs": [ - "autolens_workspace/scripts/guides/modeling/chaining.py" - ], - "notebook": "notebooks/chapter_2_lens_modeling/tutorial_10_prior_passing.ipynb", - "path": "scripts/chapter_2_lens_modeling/tutorial_10_prior_passing.py", - "summary": "In the previous tutorial, we used non-linear search chaining to break the model-fitting procedure down into two non-linear searches. This used an initial search to fit a simple lens model, whose results were used to tune and initialize the priors of a more complex lens model that was fitted by the second search.", - "title": "Tutorial 10: Prior Passing" - }, - { - "contents": [ - "Search Chaining In The Workspace", - "SLaM (Source, Light and Mass)", - "Wrap Up" - ], - "cross_refs": [ - "autolens_workspace/scripts/guides/modeling/chaining.py", - "autolens_workspace/scripts/guides/modeling/slam_start_here.py", - "autolens_workspace/scripts/imaging/features/multi_gaussian_expansion/slam.py", - "autolens_workspace/scripts/imaging/features/pixelization/slam.py", - "slam.py" - ], - "notebook": "notebooks/chapter_2_lens_modeling/tutorial_11_slam.ipynb", - "path": "scripts/chapter_2_lens_modeling/tutorial_11_slam.py", - "summary": "In the previous two tutorials, we learnt how search chaining breaks a lens model-fit into a sequence of simpler non-linear searches, and how prior passing carries the results of each search into the next. Together, they give us the flexibility to juggle the dimensionality, priors and settings of each search \u2014 the three drivers of run-time we met in tutorial 8 \u2014 whilst still fitting a complex and realistic lens model at the end.", - "title": "Tutorial 11: SLaM" - }, { "contents": [ "Overview", "Parameter Space", + "More Dimensions", "Automated Exploration", "Deeper Background", "PyAutoFit", @@ -302,7 +264,9 @@ "Model Mismatch", "Wrap Up" ], - "cross_refs": [], + "cross_refs": [ + "chapter_optional/tutorial_searches.py" + ], "notebook": "notebooks/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.ipynb", "path": "scripts/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.py", "summary": "We now have the tools to build a lens model, run a search and inspect its results. However, a search finishing does not necessarily mean that it has found a satisfactory fit.", @@ -346,73 +310,69 @@ }, { "contents": [ - "Initial Setup", - "Dataset Auto-Simulation", + "Dataset", + "Circular Masks", + "Beyond the Bright Arcs", "Mask", - "Model + Analysis", - "Run Time", - "Search", - "Discussion", - "Positions Thresholding", + "Positions Constraints", + "Choosing Positions", + "The Positions Penalty", + "Model and Analysis", + "Search and Result", + "Contaminating Light", + "Extra Galaxy Dataset", + "Extra Galaxy Region", + "Noise Scaling", + "Interpreting the Scaled Dataset", + "Interferometer Data", + "Point-Source Data", + "Weak-Lensing Data", + "Multiple Datasets", "Wrap Up" ], - "cross_refs": [], - "notebook": "notebooks/chapter_2_lens_modeling/tutorial_6_masking_and_positions.ipynb", - "path": "scripts/chapter_2_lens_modeling/tutorial_6_masking_and_positions.py", - "summary": "We have learnt everything we need to know about non-linear searches to model a strong lens and infer a good lens model solution. Now, lets consider masking in more detail, something we have not given much consideration previously. We'll also learn a neat trick to improve the speed and accuracy of a non-linear search.", - "title": "Tutorial 6: Masking and Positions" - }, - { - "contents": [ - "Initial Setup", - "Dataset Auto-Simulation", - "Tracer & Fit", - "Samples", - "Workspace", - "Database", - "Wrap Up" + "cross_refs": [ + "autolens_workspace/scripts/point_source/modeling.py", + "scripts/interferometer/modeling.py", + "scripts/weak/modeling.py" ], - "cross_refs": [], - "notebook": "notebooks/chapter_2_lens_modeling/tutorial_7_results.ipynb", - "path": "scripts/chapter_2_lens_modeling/tutorial_7_results.py", - "summary": "In the previous tutorials, each search returned a `Result` object, which we used to plot the maximum log likelihood fit each model-fit. In this tutorial, we'll take a look at the result object in a little more detail.", - "title": "Tutorial 7: Results" + "notebook": "notebooks/chapter_2_lens_modeling/tutorial_5_data_and_likelihoods.ipynb", + "path": "scripts/chapter_2_lens_modeling/tutorial_5_data_and_likelihoods.py", + "summary": "Throughout this chapter, we have fitted imaging data using light and mass profiles. However, the modeling tools we have learnt are not tied to this particular type of observation. We can use the same approach to fit interferometer measurements, the positions of multiply imaged point sources, or the shapes of weakly lensed galaxies.", + "title": "Tutorial 5: Data and Likelihoods" }, { "contents": [ - "Searching Non-linear Parameter Space", - "Cost Per Evaluation", - "JAX", - "Run Time Estimation", - "Data Quantity", + "The Search Chain", + "Dataset and Mask", + "Multi-Gaussian Expansions", + "Model 1", + "Search 1", + "Inspecting Search 1", + "Fixing the Lens-Light Geometry", + "The Power-Law Mass Model", + "Model 2", + "Automatically Estimated Positions", + "Search 2", + "Result 2", + "Conditional Uncertainties", + "Search Chaining and SLaM", "Wrap Up" ], "cross_refs": [ - "autolens_workspace/scripts/imaging/features/pixelization/cpu_fast_modeling.py", - "chapter_optional/tutorial_searches.py" + "scripts/imaging/features/multi_gaussian_expansion/slam.py" ], - "notebook": "notebooks/chapter_2_lens_modeling/tutorial_8_need_for_speed.ipynb", - "path": "scripts/chapter_2_lens_modeling/tutorial_8_need_for_speed.py", - "summary": "In this chapter, we have learnt how to model strong lenses and how to balance complexity and realism to ensure that we infer a good lens model.", - "title": "Tutorial 8: Need For Speed" + "notebook": "notebooks/chapter_2_lens_modeling/tutorial_6_search_chaining.ipynb", + "path": "scripts/chapter_2_lens_modeling/tutorial_6_search_chaining.py", + "summary": "Look again at our lens image. The foreground galaxy's light, its gravitational deflection and the background source all contribute to what we observe. Fitting them together requires the search to explore several connected parts of the model.", + "title": "Tutorial 6: Search Chaining" }, { - "contents": [ - "Initial Setup", - "Dataset Auto-Simulation", - "Model", - "Search + Analysis", - "Result", - "Prior Passing", - "Run Time", - "Model Fit", - "Wrap Up" - ], + "contents": [], "cross_refs": [], - "notebook": "notebooks/chapter_2_lens_modeling/tutorial_9_search_chaining.ipynb", - "path": "scripts/chapter_2_lens_modeling/tutorial_9_search_chaining.py", - "summary": "Throughout this chapter, we have fitted the data using just one non-linear search. The previous tutorial discussed the run-time cost of doing this: with a single search, the dimensionality of the model, the priors on its parameters and the search settings must all be juggled at once, leaving us little flexibility to trade them off against one another.", - "title": "Tutorial 9: Search Chaining" + "notebook": "notebooks/chapter_2_lens_modeling/tutorial_7_summary.ipynb", + "path": "scripts/chapter_2_lens_modeling/tutorial_7_summary.py", + "summary": "(no summary in script docstring)", + "title": "Tutorial 7: Summary" }, { "contents": [ @@ -685,6 +645,43 @@ "summary": "Our modeling tutorials have concentrated on **strong lensing**: the multiple images, arcs and Einstein rings produced by galaxy, group and cluster lenses.", "title": "Tutorial 6: Weak Lensing" }, + { + "contents": [ + "Searching Parameter Space", + "Cost Per Evaluation", + "JAX", + "Batches and GPU Memory", + "Run Time Estimation", + "Data Quantity", + "Wrap Up" + ], + "cross_refs": [ + "chapter_optional/tutorial_searches.py" + ], + "notebook": "notebooks/chapter_optional/tutorial_need_for_speed.ipynb", + "path": "scripts/chapter_optional/tutorial_need_for_speed.py", + "summary": "Two fits to the same image can take very different amounts of time. Finding a good fit with a simple model may be quick, whereas exploring the uncertainties of a more flexible model can take much longer. Both the calculation performed for each model and the search through parameter space contribute to this difference.", + "title": "Optional Tutorial: Need for Speed" + }, + { + "contents": [ + "Initial Setup", + "Dataset Auto-Simulation", + "Model", + "Search", + "Result (Search 1)", + "Prior Passing", + "Result", + "Wrap Up", + "Detailed Explanation Of Prior Passing", + "EXAMPLE" + ], + "cross_refs": [], + "notebook": "notebooks/chapter_optional/tutorial_prior_passing.ipynb", + "path": "scripts/chapter_optional/tutorial_prior_passing.py", + "summary": "This optional tutorial preserves a technique used in earlier **PyAutoLens** modelling workflows, up to around 2025: passing parameter constraints from one search into the priors of a later search.", + "title": "Optional Tutorial: Historical Prior Passing" + }, { "contents": [ "Nested Sampling",