From 19b9c5128d76a6a959e079cd7f53b66facbb1bfd Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sun, 1 Nov 2026 15:28:12 +0000 Subject: [PATCH] docs: apply reviewed Chapter 2 modeling lessons --- README.md | 9 +- llms-full.txt | 22 +- llms.txt | 4 +- notebooks/chapter_2_lens_modeling/README.md | 9 +- .../tutorial_1_non_linear_search.ipynb | 914 ++++--------- .../tutorial_2_practicalities.ipynb | 746 +++++----- .../tutorial_3_realism_and_complexity.ipynb | 519 ------- .../tutorial_3_why_modeling_is_hard.ipynb | 1214 +++++++++++++++++ .../tutorial_4_dealing_with_failure.ipynb | 898 ------------ .../tutorial_4_linear_profiles.ipynb | 976 +++++++++++++ .../tutorial_5_linear_profiles.ipynb | 941 ------------- .../tutorial_6_masking_and_positions.ipynb | 4 +- .../tutorial_8_need_for_speed.ipynb | 6 +- .../tutorial_9_search_chaining.ipynb | 6 +- .../chapter_optional/tutorial_searches.ipynb | 104 +- scripts/chapter_2_lens_modeling/README.md | 9 +- .../tutorial_1_non_linear_search.py | 789 ++++------- .../tutorial_2_practicalities.py | 651 +++++---- .../tutorial_3_realism_and_complexity.py | 277 ---- .../tutorial_3_why_modeling_is_hard.py | 869 ++++++++++++ .../tutorial_4_dealing_with_failure.py | 512 ------- .../tutorial_4_linear_profiles.py | 692 ++++++++++ .../tutorial_5_linear_profiles.py | 579 -------- .../tutorial_6_masking_and_positions.py | 4 +- .../tutorial_8_need_for_speed.py | 6 +- .../tutorial_9_search_chaining.py | 6 +- scripts/chapter_optional/tutorial_searches.py | 91 +- workspace_index.json | 156 ++- 28 files changed, 5325 insertions(+), 5688 deletions(-) delete mode 100644 notebooks/chapter_2_lens_modeling/tutorial_3_realism_and_complexity.ipynb create mode 100644 notebooks/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.ipynb delete mode 100644 notebooks/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.ipynb create mode 100644 notebooks/chapter_2_lens_modeling/tutorial_4_linear_profiles.ipynb delete mode 100644 notebooks/chapter_2_lens_modeling/tutorial_5_linear_profiles.ipynb delete mode 100644 scripts/chapter_2_lens_modeling/tutorial_3_realism_and_complexity.py create mode 100644 scripts/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.py delete mode 100644 scripts/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.py create mode 100644 scripts/chapter_2_lens_modeling/tutorial_4_linear_profiles.py delete mode 100644 scripts/chapter_2_lens_modeling/tutorial_5_linear_profiles.py diff --git a/README.md b/README.md index fec1e1f..fb86fa0 100644 --- a/README.md +++ b/README.md @@ -89,11 +89,10 @@ for the chapter 1 tutorials listed with a `markdown` link below; every other tut - 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/2026.10.29.1/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb)) - - Tutorial 2: Practicalities — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb)) - - Tutorial 3: Realism and Complexity — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_2_lens_modeling/tutorial_3_realism_and_complexity.ipynb)) - - Tutorial 4: Dealing with Failure — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.ipynb)) - - Tutorial 5: Linear Profiles — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_2_lens_modeling/tutorial_5_linear_profiles.ipynb)) + - 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.10.29.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.10.29.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.10.29.1/notebooks/chapter_2_lens_modeling/tutorial_8_need_for_speed.ipynb)) diff --git a/llms-full.txt b/llms-full.txt index 29df721..0957321 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -32,16 +32,14 @@ AUTO-GENERATED by PyAutoHands — do not edit by hand; regenerate with generate. - 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): The starting point for most scientific analysis conducted by an Astronomer is that they have observations of a strong lens using a telescope like the Hubble Space Telescope, and seek to learn about the lens galaxy, source galaxy and the Universe from these observations. With **PyAutoLens**, we seek to learn about the lens's mass and ray-tracing, asking questions like how big is the lens galaxy and what does the unlensed source galaxy look like? - - Contents: Overview, Parameter Space, Non-Linear Search, Search Types, Deeper Background, PyAutoFit, Initial Setup, Dataset Auto-Simulation, Mask, Model, Priors, Analysis, Searches, Maximum Likelihood Estimation (MLE), Markov Chain Monte Carlo (MCMC), Nested Sampling, What is The Best Search To Use?, Wrap Up -- [Tutorial 2: Practicalities](scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py): In the last tutorial, we introduced foundational statistical concepts essential for model-fitting, such as parameter spaces, likelihoods, priors, and non-linear searches. Understanding these statistical concepts is crucial for performing model fits effectively. - - Contents: PyAutoFit, Initial Setup, Dataset Auto-Simulation, Mask, Model, Search, Search Settings, Iterations Per Update, Analysis, VRAM Use, Run Times, Model-Fit, Result Info, Output Folder, Unique Identifier, Output Folder Contents, Result, Other Practicalities, Wrap Up -- [Tutorial 3: Realism and Complexity](scripts/chapter_2_lens_modeling/tutorial_3_realism_and_complexity.py): In the previous two tutorials, we fitted a fairly crude and unrealistic model: the lens's mass was spherical, as was the source's light. Given most lens galaxies are literally called 'elliptical galaxies' we should probably model their mass as elliptical! Furthermore, we have completely omitted the lens galaxy's light, which in real observations outshines the source's light and therefore must be included in the lens model. - - Contents: Initial Setup, Dataset Auto-Simulation, Mask, Model, Search + Analysis, Run Time, Result, Global and Local Maxima, Wrap Up -- [Tutorial 4: Dealing With Failure](scripts/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.py): In the previous tutorial we intentionally made our non-linear search infer a local maxima solution and therefore return a physically incorrect lens model. In this tutorial, we will pretend that we have modeled our lens and inferred a local maxima. We introduce three approaches one can take that changes how we fit the model, all of which have the aim of ensuring we infer the global maxima: - - Contents: Initial Setup, Dataset Auto-Simulation, Mask, Prior Tuning, Run Time, Result, Discussion, Approach 2: Reducing Complexity, Approach 3: Look Harder, Wrap Up -- [Tutorial 5: Linear Profiles](scripts/chapter_2_lens_modeling/tutorial_5_linear_profiles.py): In the previous tutorial we learned how to balance model complexity with our non-linear search in order to infer accurate lens model solutions and avoid failure. We saw how in order to fit a model accurately one may have to parameterize and fit a simpler model with fewer non-linear parameters, at the expense of fitting the data less accurately. - - Contents: Initial Setup, Dataset Auto-Simulation, Mask, Linear Light Profiles, Run Time, Result, Intensities, Visualization, Basis, Model Fit, Source MGE, Multi Gaussian Expansion Benefits, Disadvantage of Basis Functions, Positive Only Solver, Other Basis Functions, 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 +- [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, 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. @@ -85,8 +83,8 @@ AUTO-GENERATED by PyAutoHands — do not edit by hand; regenerate with generate. ## chapter_optional -- [Tutorial: Alternative Searches](scripts/chapter_optional/tutorial_searches.py): Up to now, we've always used the non-linear search Nautilus and not considered the input parameters that control its sampling. In this tutorial, we'll consider how we can change these setting to balance finding the global maxima solution with fast run time. - - Contents: Nested Sampling, Optimizers, MCMC +- [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 ## simulator diff --git a/llms.txt b/llms.txt index 2ab4a0f..306e34d 100644 --- a/llms.txt +++ b/llms.txt @@ -35,8 +35,8 @@ analysis?" below). - **How does a telescope image (and noise/PSF) get simulated?** → [scripts/chapter_1_introduction/tutorial_5_data.py](scripts/chapter_1_introduction/tutorial_5_data.py): Optics blurring, Poisson noise, background sky, the simulator API. - **What does "fitting" a lens actually mean?** → [scripts/chapter_1_introduction/tutorial_6_fitting.py](scripts/chapter_1_introduction/tutorial_6_fitting.py): Masking, model images, residuals and the log likelihood. - **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_4_dealing_with_failure.py](scripts/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.py): Prior tuning, simplifying the model, and other escapes from local maxima. -- **What are linear light profiles / MGE?** → [scripts/chapter_2_lens_modeling/tutorial_5_linear_profiles.py](scripts/chapter_2_lens_modeling/tutorial_5_linear_profiles.py): Solving intensities linearly; the Multi-Gaussian Expansion basis. +- **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 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 031e045..d5ab32a 100644 --- a/notebooks/chapter_2_lens_modeling/README.md +++ b/notebooks/chapter_2_lens_modeling/README.md @@ -5,15 +5,14 @@ searches are chained together into automated lens modeling pipelines. # Files -- [Tutorial 1: Non-linear Search](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/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 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/2026.10.29.1/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 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: Realism and Complexity](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_2_lens_modeling/tutorial_3_realism_and_complexity.ipynb) — Finding a balance between realism and complexity when composing and fitting a lens model. -- [Tutorial 4: Dealing with Failure](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.ipynb) — What to do when PyAutoLens finds an inaccurate lens model. +- [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: Linear Profiles](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_2_lens_modeling/tutorial_5_linear_profiles.ipynb) — Light profiles which capture complex morphologies in a reduced number of non-linear parameters. +- [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: Masking and Positions](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.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. 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 2c7ea8d..38df893 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 @@ -7,164 +7,38 @@ "Tutorial 1: Non-linear Search\n", "=============================\n", "\n", - "The starting point for most scientific analysis conducted by an Astronomer is that they have observations of a strong lens\n", - "using a telescope like the Hubble Space Telescope, and seek to learn about the lens galaxy, source galaxy and the\n", - "Universe from these observations. With **PyAutoLens**, we seek to learn about the lens's mass and ray-tracing, asking questions like\n", - "how big is the lens galaxy and what does the unlensed source galaxy look like?\n", + "In Chapter 1, we predicted what a strong lens would look like for a given set of model parameters and compared that\n", + "prediction with an observed image.\n", "\n", - "To answer these questions, we must therefore fit the dataset with a lens model, where the lens model defines the\n", - "light and mass profiles that make up the lens and source galaxies we fit. Our goal is the find the combination of\n", - "light and mass profile parameters that best-fit the data, such that the model represents the strong lens, and therefore\n", - "the Universe, as well as possible.\n", + "By changing the parameters yourself, you could improve the fit and increase its log likelihood. This demonstrated how\n", + "the data constrain a lens model, but manually adjusting parameters becomes difficult as the model grows.\n", "\n", - "This process is called model-fitting, or \"modeling\" for short, and we actually did our first example of this in the\n", - "previous chapter. If you recall, in the fitting tutorial we set up a fit to a simulated dataset where the parameter\n", - "used to simulate the data were unknown, and you guessed the values of the parameters that best fit the data. You\n", - "iteratively improved the model-fit by guessing new parameters, over and over, finding solutions which produced\n", - "higher `log_likelihood` values.\n", + "In this chapter, we use a non-linear search to explore possible parameter values automatically. We will learn how to\n", + "find models that explain the observations, assess their uncertainties and recognise when a fit needs further attention.\n", "\n", - "However, this approach was not optimal: it was manual and slow, we had no certainty that we had found the best\n", - "(e.g. maximum likelihood) solution and for more complex models, with more parameters and profiles, it would\n", - "have been completely unfeasible.\n", - "\n", - "In this chapter, we perform modeling as a scientist would actually do it, and introduce the statistical inference\n", - "techniques that will ultimately allow us to fit complex models made of many light profiles to real strong lens data,\n", - "and begin learning about real galaxies in the Universe.\n", - "\n", - "This first tutorial introduces a number of key statistical concepts that are fundamental to understanding how\n", - "model-fitting works, both for **PyAutoLens** and in general.\n", - "\n", - "__Overview__\n", - "\n", - "In this tutorial, we will use a non-linear search to fit a lens model to simulated imaging of strong lens. We will:\n", - "\n", - "- Introduce concept like a \"parameter space\", \"likelihood surface\" and \"priors\", and relate them to how a non-linear\n", - " search works.\n", - "\n", - "- Introduce the `Analysis` class, which defines the `log_likelihood_function` that quantifies the goodness of fit of a\n", - " model instance to the data.\n", - "\n", - "- Fit datasets with different non-linear searches, including a maximum likelihood estimator (MLE),\n", - " Markov Chain Monte Carlo (MCMC) and nested sampling.\n", + "We begin with simulated imaging, where we know the model used to generate the data. This lets us examine the fitting\n", + "process before tackling the additional challenges of real observations.\n", "\n", "__Contents__\n", "\n", - "- **Overview:** In this tutorial, we will use a non-linear search to fit a lens model to simulated imaging of.\n", - "- **Parameter Space:** In mathematics, a function is defined by its parameters, which map inputs to outputs.\n", - "- **Non-Linear Search:** The method used to fit the model to the data, by sampling the non-linear parameter space.\n", - "- **Search Types:** There are different types of non-linear searches, each of which explores parameter space in a.\n", - "- **Deeper Background:** **The descriptions of how searches work in this example are simplified and phenomenological and do.\n", - "- **PyAutoFit:** Modeling uses the probabilistic programming language.\n", - "- **Initial Setup:** Let's first load the `Imaging` dataset, which we will use to fit a model with a non-linear search.\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:** Compose the lens model fitted to the data.\n", - "- **Priors:** When we examine the `.info` of our model, we notice that each parameter (like `centre`.\n", - "- **Analysis:** Create the Analysis object that defines how the model is fitted to the data.\n", - "- **Searches:** To perform a non-linear search, we create an instance of a `NonLinearSearch` object.\n", - "- **Maximum Likelihood Estimation (MLE):** The simplest search type, which moves \"up\" the likelihood gradient.\n", - "- **Markov Chain Monte Carlo (MCMC):** Walkers explore parameter space, mapping out the likelihood surface.\n", - "- **Nested Sampling:** **Nested Sampling** is an advanced method for model-fitting that excels in handling complex models.\n", - "- **What is The Best Search To Use?:** Choosing between MLE, MCMC and nested sampling for lens modeling.\n", - "- **Wrap Up:** Summary of the script and next steps.\n", - "\n", - "__Parameter Space__\n", - "\n", - "In mathematics, a function is defined by its parameters, which map inputs to outputs. For example, consider the simple function:\n", - "\n", - "\\[\n", - "f(x) = x^2\n", - "\\]\n", - "\n", - "Here, \\(x\\) is the input parameter, and \\(f(x)\\) returns the output \\(x^2\\). This relationship defines\n", - "the \"parameter space\" of the function, which in this case forms a parabola.\n", - "\n", - "Functions can also have multiple parameters, such as:\n", - "\n", - "\\[\n", - "f(x, y, z) = x + y^2 - z^3\n", - "\\]\n", - "\n", - "This defines a parameter space in three dimensions, representing the relationships between \\(x\\), \\(y\\), \\(z\\),\n", - "and the output \\(f(x, y, z)\\).\n", - "\n", - "This concept of parameter space is closely related to how we approach model-fitting. For instance, in chapter 1,\n", - "we created instances of `Galaxy` objects with\n", - "parameters like \\( (\\text{`centre_0`}, \\text{`centre_1`}, \\text{`ell_comps_0`}, \\text{`ell_comps_1`}, \\text{`intensity`}, \\text{`effective_radius`}, \\text{`sersic_index`}) \\).\n", - "These parameters were used to fit data and compute a log likelihood.\n", - "\n", - "We can think of this process as analogous to the function \\(f(\\( (\\text{`centre_0`}, \\text{`centre_1`}, \\text{`ell_comps_0`}, \\text{`ell_comps_1`}, \\text{`intensity`}, \\text{`effective_radius`}, \\text{`sersic_index`}) \\))\\),\n", - "where the output is the log likelihood. This function, which maps parameter values to a log likelihood, is known\n", - "as the \"likelihood function\" in statistical inference. To be explicit, we\u2019ll refer to it as the `log_likelihood_function`\n", - "since it deals with the log of the likelihood function.\n", - "\n", - "By framing the likelihood this way, we can think of our model as having its own parameter space\u2014a multidimensional\n", - "surface defined by all possible values of the\n", - "parameters \\( (\\text{`centre_0`}, \\text{`centre_1`}, \\text{`ell_comps_0`}, \\text{`ell_comps_1`}, \\text{`intensity`}, \\text{`effective_radius`}, \\text{`sersic_index`}) \\).\n", - "This surface, known as the \"likelihood surface,\" represents how the log likelihood changes across different parameter\n", - "values. During model-fitting, our goal is to find the peak of this surface, where the fit to the data is optimal.\n", - "\n", - "This parameter space is \"non-linear,\" meaning the relationship between the model parameters and the log likelihood is\n", - "not a simple linear one. Because of this non-linearity, we cannot predict the log likelihood from a given set of model\n", - "parameters without actually performing a fit to the data, as we did in tutorial 1.\n", - "\n", - "__Non-Linear Search__\n", - "\n", - "Now that we understand our problem in terms of a non-linear parameter space with a likelihood surface, we can\n", - "introduce the method used to fit the model to the data \u2014- the \"non-linear search\".\n", - "\n", - "Previously, our approach involved manually guessing models until finding one with a good fit and high log likelihood.\n", - "Surprisingly, this random guessing forms the basis of how model-fitting using a non-linear search actually works!\n", - "\n", - "A non-linear search involves systematically guessing many models while tracking their log likelihoods. As the\n", - "algorithm progresses, it tends to favor models with parameter combinations that have previously yielded higher\n", - "log likelihoods. This iterative refinement helps to efficiently explore the vast parameter space.\n", - "\n", - "There are two key differences between guessing random models and using a non-linear search:\n", - "\n", - "- **Computational Efficiency**: The non-linear search can evaluate the log likelihood of a model parameter\n", - " combinations in milliseconds and therefore many thousands of models in minutes. This computational speed enables\n", - " it to thoroughly sample potential solutions, which would be impractical for a human.\n", - "\n", - "- **Effective Sampling**: The search algorithm maintains a robust memory of previously guessed models and their log\n", - " likelihoods. This allows it to sample potential solutions more thoroughly and converge on the highest\n", - " likelihood solutions more efficiently, which is again impractical for a human.\n", - "\n", - "Think of the non-linear search as systematically exploring parameter space to pinpoint regions with the highest log\n", - "likelihood values. Its primary goal is to identify and converge on the parameter values that best describe the data.\n", - "\n", - "__Search Types__\n", - "\n", - "There are different types of non-linear searches, each of which explores parameter space in a unique way.\n", - "In this example, we will use three types of searches, which broadly represent the various approaches to non-linear\n", - "searches used in statistical inference.\n", - "\n", - "These are:\n", - "\n", - "- **Maximum Likelihood Estimation (MLE)**: This method aims to find the model that maximizes the likelihood function.\n", - " It does so by testing nearby models and adjusting parameters in the direction that increases the likelihood.\n", - "\n", - "- **Markov Chain Monte Carlo (MCMC)**: This approach uses a group of \"walkers\" that explore parameter space randomly.\n", - " The likelihood at each walker's position influences the probability of the walker moving to a new position.\n", - "\n", - "- **Nested Sampling**: This technique samples points from the parameter space iteratively. Lower likelihood points\n", - " are replaced by higher likelihood ones, gradually concentrating the samples in regions of high likelihood.\n", - "\n", - "We will provide more details on each of these searches below.\n", - "\n", - "__Deeper Background__\n", - "\n", - "**The descriptions of how searches work in this example are simplified and phenomenological and do not give a full\n", - "description of how they work at a deep statistical level. The goal is to provide you with an intuition for how to use\n", - "them and when different searches are appropriate for different problems. Later tutorials will provide a more formal\n", - "description of how these searches work.**\n", - "\n", - "If you're interested in learning more about these principles, you can explore resources such as:\n", - "\n", - "- [Markov Chain Monte Carlo (MCMC)](https://en.wikipedia.org/wiki/Markov_chain_Monte_Carlo)\n", - "- [Introduction to MCMC Sampling](https://twiecki.io/blog/2015/11/10/mcmc-sampling/)\n", - "- [Nested Sampling](https://www.imperial.ac.uk/media/imperial-college/research-centres-and-groups/astrophysics/public/icic/data-analysis-workshop/2016/NestedSampling_JRP.pdf)\n", - "- [A Zero-Math Introduction to MCMC Methods](https://towardsdatascience.com/a-zero-math-introduction-to-markov-chain-monte-carlo-methods-dcba889e0c50)" + "- **Overview**\n", + "- **Parameter Space**\n", + "- **Automated Exploration**\n", + "- **Deeper Background**\n", + "- **PyAutoFit**\n", + "- **Initial Setup**\n", + "- **Dataset Auto-Simulation**\n", + "- **Mask**\n", + "- **Model**\n", + "- **Priors**\n", + "- **Analysis**\n", + "- **Non-linear Search**\n", + "- **Search Settings**\n", + "- **Model Fit**\n", + "- **Result**\n", + "- **Inspecting the Fit**\n", + "- **Other Searches**\n", + "- **Wrap Up**" ] }, { @@ -205,6 +79,82 @@ "_setup_colab.setup(\"howtolens\")" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Overview__\n", + "\n", + "This tutorial introduces the main pieces of an automated model fit:\n", + "\n", + "- The **dataset** contains the measurements and their uncertainties.\n", + "- The **model** describes the physical components and identifies which parameters are free to vary.\n", + "- The **Analysis** object connects the model to the dataset: it predicts the observables for a particular set of parameter values and evaluates their log likelihood.\n", + "- The **search** explores parameter space using this likelihood and the specified priors.\n", + "\n", + "We will explain parameter spaces, likelihood surfaces and priors, then use Nautilus to fit the model and inspect its\n", + "inferred parameters and uncertainties." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__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", + "\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", + "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", + "\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", + "\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?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Automated Exploration__\n", + "\n", + "A non-linear search automates the exploration you performed manually in Chapter 1.\n", + "\n", + "The search proposes parameter values. The Analysis object uses the corresponding model to predict the data and returns\n", + "a log likelihood. The search then uses its algorithm to decide which parameter values to evaluate next.\n", + "\n", + "Automating this process allows us to evaluate many more models than we could inspect by hand. It does not guarantee\n", + "that every search finds the best solution: its starting conditions, settings and the structure of parameter space all\n", + "matter. We will see examples of this later in the chapter." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Deeper Background__\n", + "\n", + "The explanations here introduce what the search does and how to interpret its results. You do not need to understand\n", + "every detail of an algorithm to start using it, but you should understand what it estimates and how it can fail.\n", + "\n", + "For now, work through the example and inspect its fit. After completing HowToLens, the optional searches tutorial and\n", + "the background resources linked below provide further detail on the methods.\n", + "\n", + "- [Nested Sampling](https://www.imperial.ac.uk/media/imperial-college/research-centres-and-groups/astrophysics/public/icic/data-analysis-workshop/2016/NestedSampling_JRP.pdf)\n", + "- [Markov Chain Monte Carlo (MCMC)](https://en.wikipedia.org/wiki/Markov_chain_Monte_Carlo)\n", + "- [Introduction to MCMC Sampling](https://twiecki.io/blog/2015/11/10/mcmc-sampling/)\n", + "- [A Zero-Math Introduction to MCMC Methods](https://towardsdatascience.com/a-zero-math-introduction-to-markov-chain-monte-carlo-methods-dcba889e0c50)" + ] + }, { "cell_type": "code", "metadata": {}, @@ -227,21 +177,19 @@ "source": [ "__PyAutoFit__\n", "\n", - "Modeling uses the probabilistic programming language\n", - "[PyAutoFit](https://github.com/PyAutoLabs/PyAutoFit), an open-source project that allows complex model\n", - "fitting techniques to be straightforwardly integrated into scientific modeling software. \n", + "PyAutoLens uses [PyAutoFit](https://github.com/PyAutoLabs/PyAutoFit) to define free parameters and priors, run non-linear searches and organise their results.\n", "\n", - "**PyAutoFit** is actually a spin-off project of **PyAutoLens**, whereby we found that the statistical techniques and\n", - "methods we applied to model galaxies could be used in a more general setting to many different scientific \n", - "problems. Check it out if you are interested in developing your own software to perform advanced model-fitting!\n", + "We import PyAutoFit as `af`. Its modeling and search tools work alongside the lensing components and Analysis objects\n", + "provided by PyAutoLens, which we import as `al`.\n", "\n", - "We import this library separately from **PyAutoLens**." + "The same PyAutoFit tools can be used for other scientific problems by supplying a suitable model and Analysis object." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "import autofit as af" ], "outputs": [], @@ -253,20 +201,24 @@ "source": [ "__Initial Setup__\n", "\n", - "Let's first load the `Imaging` dataset, which we will use to fit a model with a non-linear search.\n", + "We begin with a simulated image containing a lensed source and no foreground lens light. The simulation uses an\n", + "`IsothermalSph` mass profile for the lens and an `ExponentialCoreSph` light profile for the source.\n", "\n", - "The strong lens in this image was generated using an `IsothermalSph` lens mass profile and `ExponentialCoreSph` source light profile,\n", - "which we'll also use in our model fitting in this tutorial. This means the model we are going to fit is identical to \n", - "the one used to simulate the data, allowing us to assess the fitting process under controlled conditions.\n", + "We will fit the same profile families, allowing their parameters to vary. This gives us a controlled example: the model\n", + "can represent the system that generated the data, so we can focus on how the search explores its parameters.\n", "\n", - "The dataset, as well as all subsequent datasets used in future tutorials, is stored in the HowToLens\n", - "repository's `dataset/imaging` folder (simulated at runtime by the simulator scripts, as shown below)." + "Noise still affects the inferred values. Even a successful search need not recover the simulation\u2019s input parameters\n", + "exactly.\n", + "\n", + "The following code selects the dataset folder. The next cell generates the data if needed and loads the image, noise\n", + "map and point-spread function (PSF)." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "dataset_name = \"simple__no_lens_light__mass_sis\"\n", "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" ], @@ -279,22 +231,26 @@ "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." + "If the dataset is missing, this cell runs the simulator to create it. It then loads the files into an `Imaging` object\n", + "and plots the dataset.\n", + "\n", + "Inspect the lensed emission in the image and its strength relative to the noise map. The PSF describes the telescope\u2019s\n", + "blurring, which must be included when predicting the observed image.\n", + "\n", + "Loading the dataset does not fit a model. It supplies the measurements and observational information that the Analysis\n", + "object will use later." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "if al.util.dataset.should_simulate(str(dataset_path)):\n", " import subprocess\n", " import sys\n", "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulator/no_lens_light__mass_sis.py\"],\n", - " check=True,\n", - " )\n", + " subprocess.run([sys.executable, \"scripts/simulator/no_lens_light__mass_sis.py\"], check=True)\n", "\n", "dataset = al.Imaging.from_fits(\n", " data_path=dataset_path / \"data.fits\",\n", @@ -314,23 +270,27 @@ "source": [ "__Mask__\n", "\n", - "The fit requires a mask, which we define as a 3.0\" circle." + "We apply a circular mask with a radius of 3.0 arcseconds to select the region used for the fit.\n", + "\n", + "Check the plotted mask against the image: the selected region should contain the lensed emission whose structure we\n", + "want to explain.\n", + "\n", + "Masking changes which measurements enter the fit. It does not change the lens model or fix any of its parameters. Later\n", + "in this chapter, *Data and Likelihoods* explores mask choices and the treatment of contaminating objects." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "mask_radius = 3.0\n", "\n", + "mask_radius = 3.0\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": [], @@ -342,23 +302,22 @@ "source": [ "__Model__\n", "\n", - "To compose a lens model, we will set up each `Galaxy` using a `af.Model`. Instead of manually specifying every parameter \n", - "for the galaxy's light and mass profiles (as we did before), we will now define each galaxy using only the class of each \n", - "profile. Using a `Model` object tells **PyAutoLens** that the parameters of the profiles should be fitted for \n", - "during the non-linear search.\n", + "In Chapter 1, we created profile instances by supplying specific parameter values. To fit those parameters, we instead\n", + "wrap the profile class in `af.Model`.\n", "\n", - "In this case, we'll model the lens galaxy with an `IsothermalSph` mass profile and no light component (what it\n", - "was simulated with). " + "For example, `af.Model(al.mp.IsothermalSph)` describes a spherical isothermal mass profile whose centre and Einstein\n", + "radius are free to vary. During the search, specific values are supplied to create an instance of this profile.\n", + "\n", + "We place the mass profile inside a lens galaxy at a fixed redshift of 0.5. We do not include lens light because this\n", + "simulated image contains only the lensed source." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "# Lens:\n", "\n", "mass = af.Model(al.mp.IsothermalSph)\n", - "\n", "lens = af.Model(al.Galaxy, redshift=0.5, mass=mass)" ], "outputs": [], @@ -368,15 +327,21 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We model the source galaxy with a linear `ExponentialCoreSph` light profile (again, what it was simulated with)." + "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." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "bulge = af.Model(al.lp_linear.ExponentialCoreSph)\n", "\n", + "bulge = af.Model(al.lp_linear.ExponentialCoreSph)\n", "source = af.Model(al.Galaxy, redshift=1.0, bulge=bulge)" ], "outputs": [], @@ -386,22 +351,19 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We now have multiple `Model` components, which we bring together into a final lens model via the `Collection` object.\n", + "We combine the lens and source into an `af.Collection`, giving each galaxy a descriptive name.\n", "\n", - "Just like we are used to giving profiles descriptive names, like `bulge`, `disk` and `mass` we also name the galaxies \n", - "that make up our model. Of course, its good practise for us to give them descriptive names and we'll use `lens` and\n", - "`source` to do this throughout the tutorials.\n", + "The resulting structure lets us refer to individual components through paths such as `model.galaxies.lens.mass` and\n", + "`model.galaxies.source.bulge`. We will use these paths shortly to customise their priors.\n", "\n", - "It may seem odd that we define two `Collections`, with the `Collection` in the outer loop only having a `galaxies`\n", - "attribute. In future tutorials, we'll see that we can add additional model-components to a model other than just\n", - "galaxies, and the API below therefore makes it simple to extend the model to include these components." + "The outer collection contains a `galaxies` collection. Keeping galaxies together leaves room for other kinds of\n", + "components, such as external shear fields, alongside them in later models." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "# Overall Lens Model:\n", "\n", "model = af.Collection(galaxies=af.Collection(lens=lens, source=source))" ], @@ -412,21 +374,20 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The `info` attribute shows the model in a readable format.\n", + "The `model.info` attribute summarises the model before we fit it.\n", "\n", - "[The `info` below may not display optimally on your computer screen, for example the whitespace between parameter\n", - "names on the left and parameter priors on the right may lead them to appear across multiple lines. This is a\n", - "common issue in Jupyter notebooks.\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", "\n", - "The`info_whitespace_length` parameter in the file `config/general.yaml` in the [output] section can be changed to \n", - "increase or decrease the amount of whitespace (The Jupyter notebook kernel will need to be reset for this change to \n", - "appear in a notebook).]" + "This describes what we intend to fit. It contains no inferred parameter values yet, because the search has not run." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "print(model.info)" ], "outputs": [], @@ -436,21 +397,23 @@ "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", + "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", - "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", + "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", "\n", - "Each galaxy is labelled with its redshift, `redshift = 0.5` for the lens and `redshift = 1.0` for the source.\n", - "That is how **PyAutoLens** knows which galaxy does the lensing and which one is lensed." + "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", + "\n", + "Like `model.info`, this diagram describes the model\u2019s structure; it does not show whether the model fits the data." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "af.ModelPlotter(model).figure()" ], "outputs": [], @@ -462,43 +425,31 @@ "source": [ "__Priors__\n", "\n", - "When we examine the `.info` of our model, we notice that each parameter (like `centre`, `effective_radius`, \n", - "and `sersic_index` in our `Sersic` model) is associated with priors, such as `UniformPrior`. Priors define the \n", - "range of permissible values that each parameter can assume during the model fitting process, for example a uniform\n", - "prior means that a parameter is equally likely to be any value within the given range, but cannot be outside of it.\n", + "Each free parameter in `model.info` has a **prior**, which describes the probability assigned to its possible values\n", + "before using this dataset\u2019s likelihood.\n", "\n", - "The priors displayed above use default values defined in the `config/priors` directory. These default values have\n", - "been chosen to be broad, and contain the breadth of plausible solutions one should expect when fitting light and mass\n", - "profiles of a real galaxy.\n", + "A `UniformPrior` assigns equal probability density within specified limits and excludes values outside them. A\n", + "`GaussianPrior` places more probability near its mean, with its width controlled by `sigma`.\n", "\n", - "For instance, consider the `centre` parameter of our `IsothermalSph` mass profile. In theory, it could take on any value from\n", - "negative to positive infinity. However, imaging datasets are typically reduced such that the galaxy centre is close\n", - "to (0.0\", 0.0\"). Therefore, a `GaussianPrior` with `mean=0.0` and `sigma=0.1` is a good description of where the\n", - "galaxy `centre` is.\n", + "PyAutoLens supplies default priors, but we should check whether they are appropriate for our dataset. For example, a\n", + "prior centred on zero is suitable for a galaxy\u2019s position only if the image coordinates place it near the origin.\n", "\n", - "If the galaxy had a different centre in the dataset, we would change the mean of the prior to reflect this.\n", - "However, in general, we advise all galaxy images are reduced such that the galaxy is at (0.0\", 0.0\").\n", + "Below, we assign Gaussian priors to the lens and source centres and uniform priors to the Einstein radius and source\n", + "effective radius. Positions and radii are expressed in arcseconds.\n", "\n", - "Priors serve two primary purposes:\n", + "These choices are part of our inference assumptions. A narrow prior can exclude plausible solutions, while a broad\n", + "prior gives the search more parameter space to explore. Priors should therefore reflect justified information about the\n", + "system, rather than simply being adjusted until a preferred answer appears.\n", "\n", - "**Defining Valid Parameter Space:** Priors specify the range of parameter values that constitute valid solutions. \n", - "This ensures that our model explores only those solutions that are consistent with our observed data and physical \n", - "constraints.\n", - "\n", - "**Incorporating Prior Knowledge:** Priors also encapsulate our prior beliefs or expectations about the model \n", - "parameters. For instance, if we have previously fitted a similar model to another dataset and obtained certain \n", - "parameter values, we can incorporate this knowledge into our priors for a new dataset. This approach guides the \n", - "model fitting process towards parameter values that are more probable based on our prior understanding.\n", - "\n", - "Below, we manually specify the priors on all parameter of our lens model. The custom priors below are\n", - "close to the default priors drawn via configfiles, with the main purpose of the code below to show you how to\n", - "customize priors yourself." + "Combining the priors with the likelihood gives the **posterior distribution**: the probability distribution of the\n", + "parameters given the data and our modeling assumptions." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "model.galaxies.lens.mass.centre.centre_0 = af.GaussianPrior(mean=0.0, sigma=0.1)\n", "model.galaxies.lens.mass.centre.centre_1 = af.GaussianPrior(mean=0.0, sigma=0.1)\n", "model.galaxies.lens.mass.einstein_radius = af.UniformPrior(\n", @@ -520,61 +471,21 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "By reprinting the `model.info`, we can see that the priors have been updated to the values we specified." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(model.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Customizing priors changes many numbers in the `info` and nothing at all about the model itself. When you tune\n", - "priors you are changing where the search looks, not what it is looking for." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "af.ModelPlotter(model).figure()" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Analysis__\n", + "Print `model.info` again and find the priors we have changed.\n", "\n", - "The `AnalysisImaging` object defines how an instance of a model, consisting of a set of parameters values for the \n", - "light and mass profiles, is fitted to the `Imaging` dataset.\n", + "The lens-centre coordinates now have Gaussian priors with a mean of 0.0 and a standard deviation of 0.1 arcseconds. The\n", + "source-centre priors are broader, with a standard deviation of 0.3 arcseconds.\n", "\n", - "The fit is performed using the analysis class's `log_likelihood_function`, which in model-fitting is a commonly used \n", - "term to describe a function that given a model and data, fits the model to the data to return a value of log \n", - "likelihood. \n", - "\n", - "In the fitting tutorial in chapter 1 you essentially performed this likelihood function yourself by hand, when you \n", - "entered different models to a `FitImaging` object and used its `log_likelihood` property to quantify how well it \n", - "fitted the data.\n", - "\n", - "A detailed step-by-step visual guide of the likelihood function is provided \n", - "at `autolens_workspace/*/imaging/likelihood_function.ipynb`." + "The Einstein radius has a uniform prior between 0.0 and 8.0 arcseconds, and the source effective radius has a uniform\n", + "prior between 0.0 and 1.0 arcseconds. These are inputs to the fit, not uncertainties measured from the data." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "analysis = al.AnalysisImaging(dataset=dataset)" + "\n", + "print(model.info)" ], "outputs": [], "execution_count": null @@ -583,47 +494,21 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Searches__\n", - "\n", - "To perform a non-linear search, we create an instance of a `NonLinearSearch` object. **PyAutoFit** offers many options \n", - "for this. A detailed description of each search method and guidance on when to use them can be found in \n", - "the [search cookbook](https://pyautofit.readthedocs.io/en/latest/cookbooks/search.html).\n", - "\n", - "In this tutorial, we\u2019ll focus on three searches that represent different approaches to model fitting:\n", - "\n", - "1. **Maximum Likelihood Estimation (MLE)** using the `LBFGS` non-linear search.\n", - "2. **Markov Chain Monte Carlo (MCMC)** using the `Emcee` non-linear search.\n", - "3. **Nested Sampling** using the `Nautilus` non-linear search.\n", + "The model diagram still contains the same galaxies, profiles and free parameters.\n", "\n", - "In this example, non-linear search results are stored in memory rather and not written to hard disk because the fits \n", - "are fast and can therefore be easily regenerated. The next tutorial will perform fits which write results to the\n", - "hard-disk and discuss the outputs that are generated.\n", + "Changing the priors has not changed how those profiles predict an image. It has changed the probability assigned to\n", + "their parameter values, which can affect both the search and the inferred posterior.\n", "\n", - "__Maximum Likelihood Estimation (MLE)__\n", - "\n", - "Maximum likelihood estimation (MLE) is the most straightforward type of non-linear search. Here is a simplified \n", - "overview of how it works:\n", - "\n", - "1. Starts at a point in parameter space with a set of initial values for the model parameters.\n", - "2. Calculates the likelihood of the model at this starting point.\n", - "3. Evaluates the likelihood at nearby points to estimate the gradient, determining the direction in which to move \"up\" in parameter space.\n", - "4. Moves to a new point where, based on the gradient, the likelihood is higher.\n", - "\n", - "This process repeats until the search finds a point where the likelihood can no longer be improved, indicating that \n", - "the maximum likelihood has been reached.\n", - "\n", - "The `LBFGS` search is an example of an MLE algorithm that follows this iterative procedure. Let\u2019s see how it \n", - "performs on our Sersic model.\n", - "\n", - "In the example below, we do not specify a starting point for the MLE, so it begins at the center of the prior \n", - "range for each parameter." + "This is different from changing the model\u2019s physical components\u2014for example, replacing a spherical mass profile with an\n", + "elliptical one." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "search = af.LBFGS()" + "\n", + "af.ModelPlotter(model).figure()" ], "outputs": [], "execution_count": null @@ -632,72 +517,31 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "To begin the model-fit via the non-linear search, we pass it our model and analysis and begin the fit.\n", + "__Analysis__\n", "\n", - "The fit will take a few minutes on GPU to run.\n", + "We have defined the dataset and the model separately. The `AnalysisImaging` object provides the interface between them.\n", "\n", - "**Run Time Error:** On certain operating systems (e.g. Windows, Linux) and Python versions, the code below may produce \n", - "an error. If this occurs, see the `autolens_workspace/guides/modeling/bug_fix` example for a fix." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(\n", - " \"\"\"\n", - " The non-linear search has begun running.\n", - " \n", - " This Jupyter notebook cell with progress once the search has completed - this could take a few minutes!\n", - " \n", - " On-the-fly updates every iterations_per_quick_update are printed to the notebook.\n", - " \"\"\"\n", - ")\n", + "When the search supplies a model instance with specific parameter values, the analysis constructs its predicted image,\n", + "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", - "result = search.fit(model=model, analysis=analysis)\n", + "For our linear source profile, this evaluation also solves for the intensity before calculating the likelihood.\n", "\n", - "print(\"The search has finished run - you may now continue the notebook.\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Upon completion the non-linear search returns a `Result` object, which contains information about the model-fit.\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", + "model instances.\n", "\n", - "The `info` attribute shows the result in a readable format.\n", + "Creating the Analysis object does not start a search. It defines how proposed models will be evaluated.\n", "\n", - "[Above, we discussed that the `info_whitespace_length` parameter in the config files could b changed to make \n", - "the `model.info` attribute display optimally on your computer. This attribute also controls the whitespace of the\n", - "`result.info` attribute.]" + "A detailed step-by-step visual guide is provided at `autolens_workspace/scripts/imaging/likelihood_function.py`." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(result.info)\n" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "One thing the result contains we'll use now is the `FitImaging` object that corresponds to the set of model\n", - "parameters that gave the maximum log likelihood solution. \n", "\n", - "We plot this object to inspect how good our fit was." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit)" + "analysis = al.AnalysisImaging(dataset=dataset)" ], "outputs": [], "execution_count": null @@ -706,69 +550,49 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The fit quality is poor, with significant residuals, meaning that the MLE failed to identify the correct model. \n", + "__Non-linear Search__\n", "\n", - "This happened because the starting point of the search was a poor match to the data, placing it far from the true \n", - "solution in parameter space. As a result, after moving \"up\" the likelihood gradient several times, the search \n", - "settled into a \"local maximum\", a local peak in the likelihood surface that was better than models that surrounded\n", - "it in parameter space, but far from the global maximum solution.\n", + "We are ready to fit the lens model using **Nautilus**, a non-linear search.\n", "\n", - "To achieve a better fit with MLE, the search needs to begin in a region of parameter space where the log likelihood \n", - "is higher. This process is known as \"initialization\" and it involves providing the search with an \n", - "appropriate \"starting point\" in parameter space.\n", + "Nautilus explores combinations of parameter values within the priors. For each combination, the Analysis object\n", + "predicts the image and calculates its log likelihood. This tells the search how well that model explains the data.\n", "\n", - "The code below shows how we can customize the starting point of the search to provide a better initialization,\n", - "with the values input below close to the true values used to simulate the dataset." + "As the search progresses, it concentrates its exploration on regions containing higher-likelihood models. It explores a\n", + "range of possible solutions, allowing us to find a best-fitting model and estimate how uncertain its parameters are.\n", + "\n", + "Nautilus uses a method called **nested sampling**. You do not need to understand its statistical details to work\n", + "through HowToLens. Here, we will focus on configuring a fit and interpreting what it returns." ] }, { - "cell_type": "code", + "cell_type": "markdown", "metadata": {}, "source": [ - "initializer = af.InitializerParamStartPoints(\n", - " {\n", - " model.galaxies.lens.mass.centre.centre_0: 0.0,\n", - " model.galaxies.lens.mass.centre.centre_1: 0.0,\n", - " model.galaxies.lens.mass.einstein_radius: 1.55,\n", - " model.galaxies.source.bulge.centre.centre_0: 0.0,\n", - " model.galaxies.source.bulge.centre.centre_1: 0.0,\n", - " model.galaxies.source.bulge.effective_radius: 0.1,\n", - " }\n", - ")\n", + "__Search Settings__\n", "\n", - "search = af.LBFGS(initializer=initializer)\n", + "One of Nautilus\u2019s main settings is `n_live`, the number of \u201clive points\u201d. Each live point represents a set of model\n", + "parameters being used to explore parameter space.\n", "\n", - "print(\n", - " \"\"\"\n", - " The non-linear search has begun running.\n", - " This Jupyter notebook cell with progress once the search has completed - this could take a few minutes!\n", - " \"\"\"\n", - ")\n", - "\n", - "model = af.Collection(galaxies=af.Collection(lens=lens, source=source))\n", + "Using more live points generally allows a more thorough exploration, but requires more computation. Too few can leave\n", + "important regions unexplored, particularly for complex models.\n", "\n", - "result = search.fit(model=model, analysis=analysis)\n", + "We use 100 live points for this introductory example. This is a starting setting, not a guarantee that every fit will\n", + "succeed. The following tutorials explain how to recognise difficulties and adjust the search.\n", "\n", - "print(\"The search has finished run - you may now continue the notebook.\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "By printing `result.info` and looking at the maximum log likelihood model, we can confirm the search provided a\n", - "good model fit with a much higher likelihood than the incorrect model above." + "The `n_batch` setting controls how many proposed models are evaluated together. It affects computational speed and\n", + "memory use, rather than setting the number of live points." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(result.info)\n", "\n", - "aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit)" + "search = af.Nautilus(\n", + " n_live=100,\n", + " n_batch=50,\n", + " iterations_per_quick_update=2500,\n", + ")" ], "outputs": [], "execution_count": null @@ -777,68 +601,26 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The MLE is a great starting point for model-fitting because it\u2019s fast, conceptually simple, and often yields \n", - "accurate results. It is especially effective if you can provide a good initialization, allowing it to find the \n", - "best-fit solution quickly.\n", - "\n", - "However, MLE has its limitations. As seen above, it can get \"stuck\" in a local maximum, particularly if the \n", - "starting point is poorly chosen. In complex model-fitting problems, providing a suitable starting point can be \n", - "challenging. While MLE performed well in the example with just three parameters, it struggles with models that have \n", - "many parameters, as the complexity of the likelihood surface makes simply moving \"up\" the gradient less effective.\n", - "\n", - "The MLE also does not provide any information on the errors on the parameters, which is a significant limitation.\n", - "The next two types of searches \"map out\" the likelihood surface, such that they not only infer the maximum likelihood\n", - "solution but also quantify the errors on the parameters.\n", - "\n", - "__Markov Chain Monte Carlo (MCMC)__\n", + "__Model Fit__\n", "\n", - "Markov Chain Monte Carlo (MCMC) is a more powerful method for model-fitting, though it is also more computationally \n", - "intensive and conceptually complex. Here\u2019s a simplified overview:\n", + "We start the fit by passing our model and analysis to the search.\n", "\n", - "1. Place a set of \"walkers\" in parameter space, each with random parameter values.\n", - "2. Calculate the likelihood of each walker's position.\n", - "3. Move the walkers to new positions, guided by the likelihood of their current positions. Walkers in high-likelihood \n", - "regions encourage those in lower regions to move closer to them.\n", + "The model supplies the components, free parameters and priors. The analysis defines how each proposed model is compared\n", + "with the data. Nautilus controls which parameter values are explored.\n", "\n", - "This process repeats, with the walkers converging on the highest-likelihood regions of parameter space.\n", + "When using JAX, the numerical computing library used by PyAutoLens, the calculations are first compiled for repeated\n", + "use. You may therefore see an initial pause before the search begins reporting progress.\n", "\n", - "Unlike MLE, MCMC thoroughly explores parameter space. While MLE moves a single point up the likelihood gradient, \n", - "MCMC uses many walkers to explore high-likelihood regions, making it more effective at finding the global maximum, \n", - "though slower. \n", - "\n", - "There is a reduced risk of getting stuck in local maxima, because whilst some walkers may temporarily get stuck in \n", - "one, other walkers will explore other regions of parameter space and encourage the walker in local maxima to move \n", - "away from it and head towards higher likelihood regions.\n", - "\n", - "In the example below, we use the `Emcee` MCMC search to fit the strong lens. The search starts with walkers\n", - "initialized in a \"ball\" around the center of the model\u2019s priors, similar to the MLE search that failed earlier." + "Let the search finish before continuing. Its completion means that it has met its stopping criteria; we must still\n", + "inspect the result to assess whether the fit is satisfactory." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "search = af.Emcee(\n", - " nwalkers=20, # The number of walkers we'll use to sample parameter space.\n", - " nsteps=300, # The number of steps each walker takes, after which 20 * 300 = 6000 steps the non-linear search ends.\n", - ")\n", - "\n", - "print(\n", - " \"\"\"\n", - " The non-linear search has begun running.\n", - " This Jupyter notebook cell with progress once the search has completed - this could take a few minutes!\n", - " \"\"\"\n", - ")\n", - "\n", - "model = af.Collection(galaxies=af.Collection(lens=lens, source=source))\n", - "\n", - "result = search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"The search has finished run - you may now continue the notebook.\")\n", "\n", - "print(result.info)\n", - "\n", - "aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit)" + "result = search.fit(model=model, analysis=analysis)" ], "outputs": [], "execution_count": null @@ -847,57 +629,25 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The MCMC search succeeded, finding the same high-likelihood model that the MLE search with a good starting point \n", - "identified, even without a good initialization. Its use of multiple walkers exploring parameter space allowed it to \n", - "avoid the local maxima that had trapped the MLE search.\n", + "__Result__\n", "\n", - "A major advantage of MCMC is that it provides estimates of parameter uncertainties by \"mapping out\" the likelihood \n", - "surface, unlike MLE, which only finds the maximum likelihood solution. These error estimates are accessible in \n", - "the `result.info` string and through the `result.samples` object, which is explained fully in tutorial 7.\n", + "The search returns a `Result` object. Print its `info` attribute to see the inferred parameter values and their\n", + "estimated uncertainties.\n", "\n", - "While a good starting point wasn't necessary for this simple model, it becomes essential for efficiently mapping the \n", - "likelihood surface in more complex models with many parameters. The code below shows an MCMC fit using a good starting \n", - "point, with two key differences from the MLE initialization:\n", + "Compare this with the earlier `model.info`: that described what we allowed to vary, whereas `result.info` summarises\n", + "what we have inferred from the data.\n", "\n", - "1. Instead of single starting values, we provide bounds for each parameter. MCMC initializes each walker in a \n", - "small \"ball\" in parameter space, requiring a defined range for each parameter from which values are randomly drawn.\n", + "An uncertainty describes the range of parameter values supported by the fit. For example, the data might constrain the\n", + "Einstein radius closely while allowing a wider range of source sizes.\n", "\n", - "2. We do not specify a starting point for the `ell_comps` parameters, allowing its initial values to be drawn from its \n", - "priors. This illustrates that with MCMC, it\u2019s not necessary to know a good starting point for every parameter." + "These estimates depend on our model, priors and noise assumptions, as well as the search having explored the relevant\n", + "solutions. We should inspect the fit before trusting the reported values." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "initializer = af.InitializerParamBounds(\n", - " {\n", - " model.galaxies.lens.mass.centre.centre_0: (-0.01, 0.01),\n", - " model.galaxies.lens.mass.centre.centre_1: (-0.01, 0.01),\n", - " model.galaxies.source.bulge.centre.centre_0: (-0.01, 0.01),\n", - " model.galaxies.source.bulge.centre.centre_1: (-0.01, 0.01),\n", - " model.galaxies.source.bulge.effective_radius: (0.05, 0.15),\n", - " }\n", - ")\n", - "\n", - "search = af.Emcee(\n", - " nwalkers=20, # The number of walkers we'll use to sample parameter space.\n", - " nsteps=300, # The number of steps each walker takes, after which 10 * 200 = 2000 steps the non-linear search ends.\n", - " initializer=initializer,\n", - ")\n", - "\n", - "print(\n", - " \"\"\"\n", - " The non-linear search has begun running.\n", - " This Jupyter notebook cell with progress once the search has completed - this could take a few minutes!\n", - " \"\"\"\n", - ")\n", - "\n", - "model = af.Collection(galaxies=af.Collection(lens=lens, source=source))\n", - "\n", - "result = search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"The search has finished run - you may now continue the notebook.\")\n", "\n", "print(result.info)" ], @@ -908,48 +658,29 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "MCMC is a powerful tool for model-fitting, providing accurate parameter estimates and uncertainties. For simple models\n", - "without a starting point, MCMC can still find the correct solution, and if a good starting point is provided, it can\n", - "efficiently scale to more complex models with more parameters.\n", - "\n", - "The main limitation of MCMC is that one has to supply the number of steps the walkers take (`nsteps`). If this value \n", - "is too low, the walkers may not explore the likelihood surface sufficiently. It can be challenging to know the right \n", - "number of steps, especially if models of different complexity are being fitted or if datasets of varying quality are \n", - "used. One often ends up having to perform \"trial and error\" to verify a sufficient number of steps are used.\n", - "\n", - "MCMC can perform badly in parameter spaces with certain types of complexity, for example when there are\n", - "are many local maxima \"peaks\" that many of the walkers can become stuck walking around them, so many walkers that\n", - "when they communicate with one another they cannot gain enough information to move away from the local peak.\n", - "\n", - "__Nested Sampling__\n", + "__Inspecting the Fit__\n", "\n", - "**Nested Sampling** is an advanced method for model-fitting that excels in handling complex models with intricate \n", - "parameter spaces. Here\u2019s a simplified overview of its process:\n", + "Plot the highest-likelihood model found by the search alongside the data and residuals.\n", "\n", - "1. Start with a set of \"live points\" in parameter space, each initialized with random parameter values drawn from their respective priors.\n", + "Check whether it reproduces the position, shape and brightness of the lensed emission. Then examine the normalised\n", + "residuals for coherent patterns, such as an arc that the model has failed to reproduce.\n", "\n", - "2. Compute the log likelihood for each live point.\n", + "Our simulated data were generated using the same profile families we fitted. A successful fit should therefore leave\n", + "residuals broadly consistent with the noise. We do not expect every pixel to have a residual of zero.\n", "\n", - "3. Draw a new point based on the likelihood of the current live points, favoring regions of higher likelihood.\n", + "Good residuals and sensible parameter estimates provide useful checks, but neither guarantees that every relevant\n", + "solution has been explored. The next tutorials develop the practical skills needed to assess this.\n", "\n", - "4. If the new point has a higher likelihood than any existing live point, it becomes a live point, and the lowest likelihood live point is discarded.\n", - "\n", - "This iterative process continues, gradually focusing the live points around higher likelihood regions of parameter \n", - "space until they converge on the highest likelihood solution.\n", - "\n", - "Like MCMC, Nested Sampling effectively maps out parameter space, providing accurate estimates of parameters and \n", - "their uncertainties." + "**\ud83e\udd16 Ask AI:** My fitted lens model leaves an arc-shaped pattern in the normalised residuals. What could cause this, and\n", + "what should I check before trusting the inferred parameters?" ] }, { "cell_type": "code", "metadata": {}, "source": [ - "search = af.Nautilus(\n", - " n_live=100,\n", - " n_batch=50, # Explained in next tutorial\n", - " iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations\n", - ")" + "\n", + "aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit)" ], "outputs": [], "execution_count": null @@ -958,118 +689,39 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "To begin the model-fit via the non-linear search, we pass it our model and analysis and begin the fit.\n", + "__Other Searches__\n", "\n", - "The fit will take a minute or so to run." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(\n", - " \"\"\"\n", - " The non-linear search has begun running.\n", - " This Jupyter notebook cell with progress once the search has completed - this could take a few minutes!\n", - " \"\"\"\n", - ")\n", - "\n", - "model = af.Collection(galaxies=af.Collection(lens=lens, source=source))\n", - "\n", - "result = search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"The search has finished run - you may now continue the notebook.\")\n", + "Nautilus provides the model fit and parameter uncertainties we need for this introductory example. We will continue\n", + "using it throughout much of HowToLens.\n", "\n", - "print(result.info)\n", + "Other searches can also be useful. Later in this chapter, we will use a fast optimiser for an initial fit before\n", + "running a more thorough Nautilus search.\n", "\n", - "aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null + "You can explore these alternatives in the optional searches tutorial after completing HowToLens. For now, focus on\n", + "building appropriate models and assessing how well they explain the data." + ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "The **Nested Sampling** search was successful, identifying the same high-likelihood model as the MLE and MCMC searches. \n", - "One of the main benefits of Nested Sampling is its ability to provide accurate parameter estimates and uncertainties, \n", - "similar to MCMC. Additionally, it features a built-in stopping criterion, which eliminates the need for users to \n", - "specify the number of steps the search should take. \n", - "\n", - "This method also excels in handling complex parameter spaces, particularly those with multiple local peaks. This is because\n", - "the live points will identify each peak and converge around them, but then begin to be discarded from a peak if higher\n", - "likelihood points are found elsewhere in parameter space. In MCMC, the walkers can get stuck indefinitely in\n", - "peaks, causing the method to stall.\n", - "\n", - "Another significant advantage is that Nested Sampling estimates an important statistical quantity \n", - "known as \"evidence.\" This value quantifies how well the model fits the data while considering the model's complexity,\n", - "making it essential for Bayesian model comparison, which will be covered in later tutorials. \n", - "\n", - "Nested sampling cannot use a starting point, as it always samples parameter space from scratch by drawing live points\n", - "from the priors. This is both good and bad, depending on if you have access to a good starting point or not. If you do\n", - "not, your MCMC / MLE fit will likely struggle with initialization compared to Nested Sampling. Conversely, if you do \n", - "possess a robust starting point, it can significantly enhance the performance of MCMC, allowing it to begin closer to \n", - "the highest likelihood regions of parameter space. This proximity can lead to faster convergence and more reliable results.\n", - "\n", - "However, Nested Sampling does have limitations; it often scales poorly with increased model complexity. For example, \n", - "once a model has around 50 or more parameters, Nested Sampling can become very slow, whereas MCMC remains efficient \n", - "even in such complex parameter spaces.\n", - "\n", - "__What is The Best Search To Use?__\n", - "\n", - "In statistical inference, the choice of the best search method depends on several factors specific to the problem, \n", - "such as model complexity, availability of a starting point, and whether error estimates are required. More subtle \n", - "aspects, like the shape of the likelihood surface and the presence of multiple peaks, also play a role, as you'll \n", - "explore in later tutorials.\n", - "\n", - "When approaching a model-fitting problem, it's usually advisable to try various search methods to find the most \n", - "effective one. \n", - "\n", - "However, after extensive testing within **PyAutoLens**, a clear recommendation has emerged for fitting strong lens models.\n", - "The nested sampling method `Nautilus` consistently proves to be the most effective. It requires fewer iterations than \n", - "MCMC or MLE methods (when no starting point is used), provides robust sampling even for complex models, includes a \n", - "built-in stopping criterion, and delivers reliable error estimates.\n", - "\n", - "All examples in the `autolens_workspace` use the `Nautilus` search, and future tutorials in the **HowToLens**\n", - "series will also use it. We strongly recommend using `Nautilus` from now on.\n", - "\n", - "That said, MLE and MCMC searches can still be effective, and you're encouraged to experiment with them. If you have \n", - "a reliable starting point, MLE and MCMC can outperform `Nautilus` in terms of speed and efficiency. Additionally, \n", - "for very complex models (e.g., with 30+ parameters), `Nautilus` may struggle, while MCMC might handle the complexity \n", - "better\u2014though you're unlikely to encounter that level of complexity soon.\n", - "\n", - "Lastly, MLE, MCMC, and nested sampling are just three categories of non-linear searches, each containing different \n", - "algorithms with their own strengths and weaknesses. Exploring these options could help you find the best approach \n", - "for your model-fitting needs. For more details on each method, see the [search cookbook](https://pyautofit.readthedocs.io/en/latest/cookbooks/search.html).\n", - "\n", "__Wrap Up__\n", "\n", - "This tutorial has laid the foundation with several fundamental concepts in model fitting and statistical inference:\n", - "\n", - "1. **Parameter Space**: This refers to the range of possible values that each parameter in a model can take. It \n", - "defines the dimensions over which the likelihood of different parameter values is evaluated.\n", - "\n", - "2. **Likelihood Function**: This function receives as input a model with specific parameter values and returns a\n", - "log likelihood value that quantifies how well the model describes the data.\n", - "\n", - "3. **Likelihood Surface**: This surface represents how the likelihood of the model varies across the parameter space. \n", - "It helps in identifying the best-fit parameters that maximize the likelihood of the model given the data.\n", + "You have now fitted a lens model automatically, using the same image prediction and likelihood calculation that you\n", + "explored manually in Chapter 1.\n", "\n", - "4. **Non-linear Search**: This is an optimization technique used to explore the parameter space and find the \n", - "combination of parameter values that best describe the data. It iteratively adjusts the parameters to maximize the \n", - "likelihood. Many different search algorithms exist, each with their own strengths and weaknesses, and this tutorial\n", - "used the MLE, MCMC, and nested sampling searches.\n", + "The fit brings together four pieces:\n", "\n", - "5. **Priors**: Priors are probabilities assigned to different values of parameters before considering the data. \n", - "They encapsulate our prior knowledge or assumptions about the parameter values. Priors can constrain the parameter \n", - "space, making the search more efficient and realistic.\n", + "- **Data:** the measurements, uncertainties and observational information.\n", + "- **Model:** the physical components, their free parameters and their priors.\n", + "- **Analysis:** the connection between model and data, predicting the observations and evaluating their likelihood.\n", + "- **Search:** the method that explores parameter values and returns the inferred results.\n", "\n", - "6. **Model Fitting**: The process of adjusting model parameters to minimize the difference between model predictions \n", - "and observed data, quantified by the likelihood function.\n", + "Keeping these pieces separate lets us change the model, dataset or search while retaining the same overall approach.\n", + "Later in the chapter, we will see how this applies to the other types of lensing data introduced in Chapter 1.\n", "\n", - "Understanding these concepts is crucial as they form the backbone of model fitting and parameter estimation in \n", - "scientific research and data analysis. In the next tutorials, these concepts will be further expanded upon to \n", - "deepen your understanding and provide more advanced techniques for model fitting and analysis." + "In the next tutorial, *Practicalities*, we include the foreground lens galaxy\u2019s light and fit a more complex model. We\n", + "will also learn how to follow a search\u2019s progress, navigate its output folder and inspect its saved results." ] } ], diff --git a/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb index e48248e..2249b52 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb @@ -7,78 +7,41 @@ "Tutorial 2: Practicalities\n", "==========================\n", "\n", - "In the last tutorial, we introduced foundational statistical concepts essential for model-fitting, such as parameter\n", - "spaces, likelihoods, priors, and non-linear searches. Understanding these statistical concepts is crucial for\n", - "performing model fits effectively.\n", + "In the previous tutorial, we fitted a simple lens model using Nautilus. We now move to a more realistic image,\n", + "containing both the foreground lens galaxy\u2019s light and the lensed source.\n", "\n", - "However, achieving successful model-fitting also requires practical skills, including how to manage outputs,\n", - "review results, interpret model quality, and ensure run-times are efficient enough for your scientific needs.\n", + "Fitting this image requires additional model components and more free parameters. Alongside building that model, we\n", + "will learn how to configure the search, follow its progress, find its saved output and inspect the resulting fit.\n", "\n", - "This tutorial will focus on these practical aspects of model-fitting, including:\n", + "The overall approach remains the same: the dataset holds the observations, the model describes the physical components,\n", + "and the Analysis object connects them. Nautilus explores the model parameters using the likelihood and priors.\n", "\n", - "- How to save results to your hard disk.\n", - "- How to navigate the output folder and examine model-fit results to assess quality.\n", - "- How to estimate the run-time of a model-fit before initiating it, and change settings to make it faster or run the analysis in parallel.\n", + "By the end, you should be comfortable running a fit and finding the information needed to assess it. The next tutorial\n", + "examines why more complex models can be difficult to fit and what to do when a search struggles.\n", "\n", "__Contents__\n", "\n", - "- **PyAutoFit:** Modeling uses the probabilistic programming language.\n", - "- **Initial Setup:** Lets first load the `Imaging` dataset we'll fit a model with using a non-linear search.\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:** Compose the lens model fitted to the data.\n", - "- **Search:** Configure the non-linear search used to fit the model.\n", - "- **Search Settings:** Nautilus samples parameter space by placing \"live points\" representing different galaxy models.\n", - "- **Iterations Per Update:** Every N iterations, the non-linear search outputs the current results to the folder.\n", - "- **Analysis:** Create the Analysis object that defines how the model is fitted to the data.\n", - "- **VRAM Use:** When running AutoLens with JAX on a GPU, the analysis must fit within the GPU\u2019s available VRAM.\n", - "- **Run Times:** Profiling the expected run time of the model-fit.\n", - "- **Model-Fit:** Begin the model-fit by passing the model and analysis to the search.\n", - "- **Result Info:** A concise readable summary of the results is given by printing its `info` attribute.\n", - "- **Output Folder:** Now checkout the `output` folder.\n", - "- **Unique Identifier:** In the output folder, you will note that results are in a folder which is a collection of random.\n", - "- **Output Folder Contents:** Now this is running you should checkout the `output` folder.\n", - "- **Result:** Overview of the results of the model-fit.\n", - "- **Other Practicalities:** The following are examples of other practicalities which I will document fully in this example.\n", - "- **Wrap Up:** Summary of the script and next steps.\n", - "\n", - "__Search Settings__\n", - "\n", - "Nautilus samples parameter space by placing \"live points\" representing different galaxy models. Each point has an\n", - "associated `log_likelihood` that reflects how well it fits the data. By mapping where high-likelihood solutions are\n", - "located, it can focus on searching those regions.\n", - "\n", - "The main setting to balance is the **number of live points**. More live points allow Nautilus to map parameter space\n", - "more thoroughly, increasing accuracy but also runtime. Fewer live points reduce run-time but may make the search less\n", - "reliable, possibly getting stuck in local maxima.\n", - "\n", - "The ideal number of live points depends on model complexity. More parameters generally require more live points, but\n", - "the default of 200 is sufficient for most lens models. Lower values can still yield reliable results, particularly\n", - "for simpler models. For this example (6 parameters), we reduce the live points to 100 to speed up runtime without\n", - "compromising accuracy.\n", - "\n", - "Tuning non-linear search settings (e.g., the number of live points) to match model complexity is essential. We aim\n", - "for enough live points to ensure accurate results (i.e., finding a global maximum) but not so many that runtime\n", - "is excessive.\n", - "\n", - "In practice, the optimal number of live points is often found through trial and error, guided by summary statistics\n", - "on how well the search is performing, which we\u2019ll cover below. For the simple model fitted here, with a linear light\n", - "profile, 100 live points is sufficient to achieve reliable results.\n", - "\n", - "__Iterations Per Update__\n", - "\n", - "Every N iterations, the non-linear search outputs the current results to the folder `output`,\n", - "which includes producing visualization.\n", - "\n", - "Depending on how long it takes for the model to be fitted to the data (see discussion about run times below),\n", - "this can take up a large fraction of the run-time of the non-linear search.\n", - "\n", - "For this fit, the fit is very fast, thus we set a high value of `iterations_per_quick_update=2500` to ensure these updates\n", - "do not slow down the overall speed of the model-fit.\n", - "\n", - "**If the iteration per update is too low, the model-fit may be significantly slowed down by the time it takes to\n", - "output results and visualization frequently to hard-disk. If your fit is consistent displaying a log saying that it\n", - "is outputting results, try increasing this value to ensure the model-fit runs efficiently.**" + "- **Dataset**\n", + "- **Mask**\n", + "- **Model**\n", + "- **Analysis**\n", + "- **Search**\n", + "- **Search Settings**\n", + "- **Output Updates**\n", + "- **VRAM Use**\n", + "- **Run Times**\n", + "- **Notebooks and Scripts**\n", + "- **Model Fit**\n", + "- **Result Info**\n", + "- **Output Folder**\n", + "- **Unique Identifier**\n", + "- **Resuming and Loading**\n", + "- **Output Folder Contents**\n", + "- **Parameter Uncertainties**\n", + "- **Plot Labels**\n", + "- **Configuration**\n", + "- **Further Results**\n", + "- **Wrap Up**" ] }, { @@ -120,88 +83,45 @@ ] }, { - "cell_type": "code", + "cell_type": "markdown", "metadata": {}, "source": [ + "__Dataset__\n", "\n", - "from autolens import jax_wrapper # Sets JAX environment before other imports\n", - "\n", - "from autolens import setup_notebook; setup_notebook()\n", + "Our new simulated image contains a bright foreground lens galaxy as well as the lensed source.\n", "\n", - "from pathlib import Path\n", - "import autolens as al\n", - "import autolens.plot as aplt" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__PyAutoFit__\n", + "The simulation uses a S\u00e9rsic light profile for the lens galaxy, an elliptical isothermal mass profile, external shear\n", + "and an exponential light profile for the source. We will build a model with these components shortly.\n", "\n", - "Modeling uses the probabilistic programming language\n", - "[PyAutoFit](https://github.com/PyAutoLabs/PyAutoFit), an open-source project that allows complex model\n", - "fitting techniques to be straightforwardly integrated into scientific modeling software.\n", + "As before, the dataset includes the image, its noise map and the telescope\u2019s point-spread function (PSF). If the files\n", + "are missing, the following cell runs the simulator before loading them.\n", "\n", - "The majority of tools that make model-fitting practical are provided by PyAutoFit, for example it handles\n", - "all output of the non-linear search to hard-disk, the visualization of results and the estimation of run-times." + "In the plotted image, look for the central lens galaxy and the extended lensed emission around it. Both contribute to\n", + "the measured light, so our model must account for both." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "import autofit as af" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Initial Setup__\n", "\n", - "Lets first load the `Imaging` dataset we'll fit a model with using a non-linear search.\n", + "from autolens import jax_wrapper # Sets JAX environment before other imports\n", "\n", - "This is the same dataset we fitted in the previous tutorial, and we'll repeat the same fit, as we simply want\n", - "to illustrate the practicalities of model-fitting in this tutorial." - ] - }, - { - "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", + "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", + "\n", + "dataset_name = \"lens_sersic\"\n", + "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name\n", "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ "if al.util.dataset.should_simulate(str(dataset_path)):\n", " import subprocess\n", " import sys\n", "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulator/no_lens_light__mass_sis.py\"],\n", - " check=True,\n", - " )\n", + " subprocess.run([sys.executable, \"scripts/simulator/lens_sersic.py\"], check=True)\n", "\n", "dataset = al.Imaging.from_fits(\n", " data_path=dataset_path / \"data.fits\",\n", @@ -221,23 +141,27 @@ "source": [ "__Mask__\n", "\n", - "The non-linear fit also needs a `Mask2D`, lets use a 3.0\" circle." + "We use a circular mask with a radius of 2.5 arcseconds to select the central region for this fit.\n", + "\n", + "Inspect the masked image: the selected region should contain the lensed emission and enough of the lens galaxy\u2019s light\n", + "to constrain its profile. The mask changes which measurements contribute to the fit; it does not change the physical\n", + "model.\n", + "\n", + "Later in this chapter, *Data and Likelihoods* examines mask choices and how to handle contaminating objects." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "mask_radius = 3.0\n", "\n", + "mask_radius = 2.5\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": [], @@ -249,33 +173,94 @@ "source": [ "__Model__\n", "\n", - "We compose the model using the same API as the previous tutorial.\n", + "The previous model contained a spherical lens mass profile and a spherical source-light profile, with no foreground\n", + "lens light. We now include four components:\n", "\n", - "This model is the same as the previous tutorial, an `IsothermalSph` spherical mass profile representing the lens\n", - "galaxy and a `ExponentialCoreSph` light profile representing the source galaxy." + "- A **S\u00e9rsic light profile** to describe the foreground lens galaxy.\n", + "- An **elliptical isothermal mass profile** to describe its gravitational lensing.\n", + "- An **external shear field** to describe an additional tidal contribution to the lensing.\n", + "- An **exponential light profile** to describe the source galaxy.\n", + "\n", + "The lens galaxy\u2019s light and mass are separate components. Fitting its brightness does not, by itself, determine its\n", + "mass distribution.\n", + "\n", + "These additions let the model describe more structure in the image, but introduce more free parameters for the search\n", + "to explore. This is a recurring balance in modeling: we need enough flexibility to explain the data, while recognising\n", + "that a more complex model can be harder to fit.\n", + "\n", + "We use the model construction from the previous tutorial, adding the lens-light profile and placing external shear in a\n", + "separate `fields` component." ] }, { - "cell_type": "code", + "cell_type": "markdown", "metadata": {}, "source": [ - "# Lens:\n", + "We construct the model using the same approach as Tutorial 1. Passing a profile class into `af.Model` makes its\n", + "parameters available for fitting; supplying a value, such as a galaxy\u2019s redshift, keeps that quantity fixed.\n", + "\n", + "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", - "mass = af.Model(al.mp.IsothermalSph)\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." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ "\n", - "lens = af.Model(al.Galaxy, redshift=0.5, mass=mass)\n", + "field = af.Model(\n", + " al.MassField,\n", + " redshift=0.5,\n", + " shear=al.mp.ExternalShear,\n", + ")\n", "\n", - "# Source:\n", + "model = af.Collection(\n", + " galaxies=af.Collection(\n", + " lens=af.Model(\n", + " al.Galaxy,\n", + " redshift=0.5,\n", + " bulge=al.lp.Sersic,\n", + " mass=al.mp.Isothermal,\n", + " ),\n", + " source=af.Model(\n", + " al.Galaxy,\n", + " redshift=1.0,\n", + " bulge=al.lp.ExponentialCore,\n", + " ),\n", + " ),\n", + " fields=field,\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Print `model.info` and examine the model diagram below.\n", "\n", - "bulge = af.Model(al.lp_linear.ExponentialCoreSph)\n", + "Find the lens-light, lens-mass, source-light and shear components. Notice how each contributes free parameters, while\n", + "the galaxy and field redshifts remain fixed.\n", "\n", - "source = af.Model(al.Galaxy, redshift=1.0, bulge=bulge)\n", + "The parameter count tells us how many quantities the non-linear search must explore. More parameters generally make\n", + "exploration harder, but their relationships matter too: different combinations can produce similar images.\n", "\n", - "# Overall Lens Model:\n", + "These displays describe the model we are about to fit. They do not yet tell us whether it explains the data." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ "\n", - "model = af.Collection(galaxies=af.Collection(lens=lens, source=source))\n", + "print(model.info)\n", "\n", - "print(model.info)" + "af.ModelPlotter(model).figure()" ], "outputs": [], "execution_count": null @@ -284,21 +269,23 @@ "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", + "__Analysis__\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", + "We again use `AnalysisImaging` to connect the model to the dataset.\n", "\n", - "Nothing in this tutorial changes the model \u2014 every setting we discuss below belongs to the search." + "For each proposed model, the analysis predicts the combined lens and lensed-source light, accounts for PSF blurring and\n", + "evaluates the log likelihood using the selected image pixels and their noise values.\n", + "\n", + "Although our model has become more complex, the interface is unchanged: the analysis receives a model instance and\n", + "returns its log likelihood." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "af.ModelPlotter(model).figure()" + "\n", + "analysis = al.AnalysisImaging(dataset=dataset)" ], "outputs": [], "execution_count": null @@ -309,20 +296,28 @@ "source": [ "__Search__\n", "\n", - "We again use the `Nautilus` non-linear search, with settings chosen following the Search Settings discussion above." + "We configure Nautilus with a location for its saved output as well as settings controlling the search.\n", + "\n", + "- `path_prefix` groups the results under `output/howtolens/chapter_2`.\n", + "- `name` identifies this tutorial\u2019s fit.\n", + "- `unique_tag` distinguishes the dataset being fitted.\n", + "\n", + "Together, these organise our results so that fits to different datasets do not become mixed together. PyAutoFit also\n", + "adds an automatically generated identifier, explained in the **Unique Identifier** section below." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "search = af.Nautilus(\n", " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", " name=\"tutorial_2_practicalities\",\n", " unique_tag=dataset_name,\n", - " n_live=100,\n", - " n_batch=50, # GPU batching and VRAM use explained in VRAM section below.\n", - " iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations\n", + " n_live=200,\n", + " n_batch=50,\n", + " iterations_per_quick_update=2500,\n", ")" ], "outputs": [], @@ -332,20 +327,43 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Analysis__\n", + "__Search Settings__\n", + "\n", + "We increase `n_live` from 100 in Tutorial 1 to 200 for this more complex model. More live points generally allow a more\n", + "thorough exploration, at the cost of additional computation. We must still inspect the result rather than assume this\n", + "setting guarantees a successful fit.\n", + "\n", + "`n_batch=50` allows likelihood evaluations to be processed in batches. Evaluating several models together can improve\n", + "performance, particularly on a GPU, but also requires more memory.\n", + "\n", + "These settings serve different purposes: `n_live` controls the live-point population used to explore parameter space,\n", + "whereas `n_batch` controls how evaluations are grouped for computation.\n", "\n", - "We again create the `AnalysisImaging` object which contains the `log_likelihood_function` that the non-linear search\n", - "calls to fit the model to the data." + "Keep these values for the initial run. The following **VRAM Use** section explains how to check memory requirements and\n", + "when to reduce the batch size." ] }, { - "cell_type": "code", + "cell_type": "markdown", "metadata": {}, "source": [ - "analysis = al.AnalysisImaging(dataset=dataset)" - ], - "outputs": [], - "execution_count": null + "__Output Updates__\n", + "\n", + "While the search runs, PyAutoLens can save updated figures showing the best-fitting model found so far. These let you\n", + "follow its progress without waiting for the fit to finish.\n", + "\n", + "We set `iterations_per_quick_update=2500` to request a quick update approximately every 2,500 likelihood evaluations.\n", + "This counts evaluated models, not seconds.\n", + "\n", + "Producing figures takes time. If updates occur almost continuously, increasing this value lets the search spend more\n", + "time exploring models between updates. Decreasing it gives more frequent views of progress.\n", + "\n", + "Quick updates are intended for monitoring. More extensive output is controlled separately by\n", + "`iterations_per_full_update`, and final results are produced when the search finishes.\n", + "\n", + "Keep the current setting for the first run. If you experiment with a different update frequency, restore it to 2,500\n", + "afterwards." + ] }, { "cell_type": "markdown", @@ -353,34 +371,36 @@ "source": [ "__VRAM Use__\n", "\n", - "When running AutoLens with JAX on a GPU, the analysis must fit within the GPU\u2019s\n", - "available VRAM. If insufficient VRAM is available, the analysis will fail with an\n", - "out-of-memory error, typically during JIT compilation or the first likelihood call.\n", + "If you run the fit on a GPU, its calculations must fit within the GPU\u2019s memory, usually called **VRAM**. Insufficient\n", + "memory can cause an out-of-memory error during compilation or evaluation.\n", "\n", - "Two factors dictate the VRAM usage of an analysis:\n", + "Memory requirements depend on the dataset, the model and how many models are evaluated together. Larger images and more\n", + "demanding calculations can require more memory. Increasing Nautilus\u2019s `n_batch` also increases the amount of work held\n", + "in memory at once.\n", "\n", - "- The number of arrays and other data structures JAX must store in VRAM to fit the model\n", - " to the data in the likelihood function. This is dictated by the model complexity and dataset size.\n", + "The following call estimates the memory used by the batched likelihood calculation. `search.batch_size` reports the\n", + "batch size set through Nautilus\u2019s `n_batch` argument.\n", "\n", - "- The `batch_size` sets how many likelihood evaluations are performed simultaneously.\n", - " Increasing the batch size increases VRAM usage but can reduce overall run time,\n", - " while decreasing it lowers VRAM usage at the cost of slower execution.\n", + "Compare the estimate with the GPU memory available, leaving room for other allocations and applications. This is an\n", + "estimate for the likelihood calculation, rather than a guarantee of the total memory used by the process.\n", "\n", - "Before running an analysis, users should check that the estimated VRAM usage for the\n", - "chosen batch size is comfortably below their GPU\u2019s total VRAM.\n", + "If memory is insufficient, try reducing `n_batch` from 50 to 10 and recreate the search before checking again. This\n", + "keeps the same model and live-point setting, but evaluates fewer models together.\n", "\n", - "The method below prints the VRAM usage estimate for the analysis and model with the specified batch size,\n", - "it takes about 20-30 seconds to run so you may want to comment it out once you are familiar with your GPU's VRAM limits.\n", - "\n", - "For the simple model and low resolution dataset fitted in this example VRAM use is relatively low (~0.027GB). For other\n", - "models (e.g. pixelized sources) and higher resolution datasets it can be much higher (> 1GB going beyond 10GB)." + "The estimate itself requires some preparation and may take time. Once you understand the requirements of an unchanged\n", + "setup, you can skip this diagnostic on subsequent runs. On a CPU, the relevant limit is system memory rather than GPU\n", + "VRAM." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "analysis.print_vram_use(model=model, batch_size=search.batch_size)" + "\n", + "analysis.print_vram_use(\n", + " model=model,\n", + " batch_size=search.batch_size,\n", + ")" ], "outputs": [], "execution_count": null @@ -391,69 +411,71 @@ "source": [ "__Run Times__\n", "\n", - "Lens modeling can be a computationally expensive process. When fitting complex models to high resolution datasets \n", - "run times can be of order hours, days, weeks or even months.\n", + "Two main factors determine how much computation a fit requires:\n", "\n", - "Run times are dictated by two factors:\n", + "- How expensive it is to predict the data and calculate the likelihood for a proposed model.\n", + "- How many models the search must evaluate before it finishes.\n", "\n", - " - **The log likelihood evaluation time:** the time it takes for a single `instance` of the model to be fitted to \n", - " the dataset such that a log likelihood is returned.\n", + "Adding lens light and allowing elliptical profiles increases the work involved in each prediction. The additional free\n", + "parameters can also make parameter space harder to explore, requiring more evaluations.\n", "\n", - " - **The number of iterations (e.g. log likelihood evaluations) performed by the non-linear search:** more complex lens\n", - " models require more iterations to converge to a solution (and as discussed above, settings like the number of live\n", - " points also control this).\n", + "With JAX, the initial compilation takes time before repeated evaluations become faster. On a GPU, several evaluations\n", + "can run together, so multiplying a single-model evaluation time by the number of models does not necessarily predict\n", + "the total run time.\n", "\n", - "For this analysis, the log likelihood evaluation time is < 0.01 seconds on CPU, < 0.001 seconds on GPU, which is \n", - "extremely fast for lens modeling. \n", + "Saving figures and results adds further time. The elapsed time therefore includes compilation, searching and output\u2014not\n", + "just the likelihood calculation.\n", "\n", - "The more advanced fitting techniques discussed at the end of chapter 1 (e.g. shapelets, multi Gaussian expansions, \n", - "pixelizations) have longer log likelihood evaluation times. However, on GPU, they can be so fast they may not produce\n", - "significantly longer overall run-time feasible.\n", - "\n", - "To estimate the expected overall run time of the model-fit we multiply the log likelihood evaluation time by an \n", - "estimate of the number of iterations the non-linear search will perform, which is around 50000 to 100000 for this model.\n", + "Watch the progress of your first run to develop an expectation for your computer. The optional *Need for Speed*\n", + "tutorial explains how to investigate performance in more detail." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Notebooks and Scripts__\n", "\n", - "Tests thus far reveal CPU run times are around 30 minutes, and GPU run times around 10 minutes.\n", + "In a notebook, the cell containing `search.fit` remains busy until the search finishes. You can inspect files already\n", + "written to the output folder while it runs, but later cells in the same notebook kernel must wait.\n", "\n", - "__Model-Fit__\n", + "For a longer fit, you may prefer to run the corresponding Python script from the HowToLens repository root:\n", "\n", - "To begin the model-fit, we pass the model and analysis objects to the search, which performs a non-linear search to \n", - "identify models that best fit the data.\n", + "```bash\n", + "python3 scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py\n", + "```\n", "\n", - "Running model fits via non-linear search can take significant time. While the fit in this tutorial should \n", - "complete in a few minutes, more complex models may require longer run times. In Jupyter notebooks, this can be \n", - "limiting, as the notebook cell will only complete once the fit finishes, preventing you from advancing through the \n", - "tutorial or running additional code.\n", + "The notebook and script perform the same analysis, and both save results using the output settings we supplied. Running\n", + "a script does not inherently make the search faster; it lets the fit run separately from your interactive notebook.\n", "\n", - "To work around this, we recommend running tutorial scripts as standalone Python scripts, found\n", - "in the `scripts/` folder of the HowToLens repository. These scripts mirror the notebook tutorials but run independently of\n", - "Jupyter notebooks. For example, you can start a script with:\n", + "Notebooks remain useful for inspecting data, plotting results and exploring their interpretation. Scripts are\n", + "convenient for unattended runs and computing clusters.\n", "\n", - "`python3 scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py`\n", + "Once the fit has completed, rerunning the same setup can load its saved result. We will explain how PyAutoFit\n", + "recognises that setup in **Unique Identifier**." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Model Fit__\n", "\n", - "Using scripts allows results to be saved to the hard drive in the `output` folder, enabling you to inspect results \n", - "immediately once the script completes. When rerun, the script loads results directly from disk, so any Jupyter \n", - "notebook cells will quickly load and display the complete model-fit results if they\u2019re already saved.\n", + "We now pass the model and analysis to Nautilus and begin the fit.\n", "\n", - "This approach not only avoids the slowdowns associated with notebook cells during lengthy runs but is also essential \n", - "for using super-computers for fitting tasks, as they require separate Python scripts.\n", + "Expect an initial compilation stage, followed by search progress and periodic output updates. Use those updates to\n", + "follow how the predicted image improves, but wait for completion before interpreting the final parameter uncertainties.\n", "\n", - "For tasks like loading results, inspecting data, plotting, and interpreting results, Jupyter notebooks remain ideal." + "The output is organised beneath `output/howtolens/chapter_2/lens_sersic/tutorial_2_practicalities`. The dataset tag and\n", + "automatically generated identifier distinguish this particular fit within that folder." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(\n", - " \"The non-linear search has begun running - checkout the output/howtolens/chapter_2/tutorial_2_practicalities\"\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 = search.fit(model=model, analysis=analysis)\n", "\n", - "print(\"Search has finished run - you may now continue the notebook.\")" + "result = search.fit(model=model, analysis=analysis)" ], "outputs": [], "execution_count": null @@ -464,18 +486,23 @@ "source": [ "__Result Info__\n", "\n", - "A concise readable summary of the results is given by printing its `info` attribute.\n", + "Once the search finishes, print `result.info` to inspect the inferred parameter values and their uncertainties.\n", "\n", - "[Above, we discussed that the `info_whitespace_length` parameter in the config files could b changed to make \n", - "the `model.info` attribute display optimally on your computer. This attribute also controls the whitespace of the\n", - "`result.info` attribute.]" + "Compare the lens-light, mass, shear and source-light parameters with the model we defined earlier. Then inspect the fit\n", + "image and residuals, as in Tutorial 1. Sensible-looking parameter values alone do not establish that the model explains\n", + "the data.\n", + "\n", + "The same fit summary is saved as `model.results`, so you can read it without rerunning the notebook." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(result.info)" + "\n", + "print(result.info)\n", + "\n", + "aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit)" ], "outputs": [], "execution_count": null @@ -486,101 +513,144 @@ "source": [ "__Output Folder__\n", "\n", - "Now checkout the `output` folder.\n", + "Open the `output` directory inside your HowToLens repository. Our search settings organise this fit beneath:\n", + "\n", + "```text\n", + "output/howtolens/chapter_2/lens_sersic/tutorial_2_practicalities/\n", + "```\n", + "\n", + "Inside is a folder with a long identifier as its name. This contains the saved model, results, figures and information\n", + "needed to load or resume the fit.\n", + "\n", + "The tree below shows the main output structure. Some products appear only after completion or when enabled in the\n", + "output and plotting configuration.\n", + "\n", + "```text\n", + "output/\n", + "`-- howtolens/\n", + " `-- chapter_2/\n", + " `-- lens_sersic/ # unique_tag: the dataset name\n", + " `-- tutorial_2_practicalities/ # name: this analysis\n", + " `-- /\n", + " |-- model.info # Model components and priors\n", + " |-- model.results # Inferred parameters and uncertainties\n", + " |-- search.summary # Search progress and timing summary\n", + " |-- search.log # Messages written during the run\n", + " |\n", + " |-- image/\n", + " | |-- dataset.fits # Saved imaging data, noise map and PSF\n", + " | |-- dataset.png # Dataset visualisation\n", + " | |-- fit.fits # Model and residual-related arrays\n", + " | |-- fit.png # Visual comparison of model and data\n", + " | `-- ... # Additional configured figures and FITS\n", + " |\n", + " `-- files/\n", + " |-- model.json # Saved model definition\n", + " |-- tracer.json # Highest-likelihood tracer\n", + " |-- search.json # Saved search configuration\n", + " |-- samples.csv # Parameter samples and weights\n", + " |-- samples_info.json # Information about the samples\n", + " |-- samples_summary.json # Summary of inferred parameters\n", + " |-- covariance.csv # Parameter covariance matrix\n", + " |-- dataset_identity.json # Record of the input dataset\n", + " `-- search_internal/ # Search checkpoints, when retained\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Unique Identifier__\n", + "\n", + "The identifier looks like a random string, but it is calculated from the model, the identifying search settings and the\n", + "`unique_tag`.\n", "\n", - "This is where the results of the search are written to hard-disk (in the `tutorial_2_practicalities` folder). \n", + "Rerunning an unchanged setup produces the same identifier and points PyAutoFit to the existing output. Changing the\n", + "model or a search setting that contributes to the identifier produces a different identifier.\n", "\n", - "Once completed images, results and information about the fit appear in this folder, meaning that you don't need \n", - "to keep running Python code to see the result.\n", + "The `unique_tag` lets us distinguish datasets fitted with the same model and search. Here, we set it to `dataset_name`,\n", + "giving the tag `lens_sersic`.\n", "\n", - "__Unique Identifier__\n", + "Do not assume that editing a data file, changing a mask or changing every analysis option automatically creates a new\n", + "identifier. When deliberately fitting a revised dataset or analysis, use a descriptive new tag or search name to keep\n", + "its results separate.\n", + "\n", + "Display settings, such as how often progress figures are produced, need not define a scientifically different fit and\n", + "do not necessarily change the identifier." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Resuming and Loading__\n", "\n", - "In the output folder, you will note that results are in a folder which is a collection of random characters. This acts \n", - "as a `unique_identifier` of the model-fit, where this identifier is generated based on the model, search and dataset \n", - "that are used in the fit.\n", - " \n", - "An identical combination of model, search and dataset generates the same identifier, meaning that rerunning the\n", - "script will use the existing results to resume the model-fit. In contrast, if you change the model, search or dataset,\n", - "a new unique identifier will be generated, ensuring that the model-fit results are output into a separate folder. \n", + "If a Nautilus run is interrupted, rerun the same setup with its output and checkpoint files intact. The search can\n", + "resume from its saved state, rather than starting from scratch. Work performed since the latest checkpoint may need to\n", + "be repeated.\n", "\n", - "We additionally want the unique identifier to be specific to the dataset fitted, so that if we fit different datasets\n", - "with the same model and search results are output to a different folder. We achieved this for the fit above by passing \n", - "the `dataset_name` to the search's `unique_tag`.\n", + "If the fit has already completed, rerunning the same setup loads the saved result instead of repeating the search. This\n", + "is useful when reopening a notebook to inspect or plot a completed analysis.\n", "\n", - "__Output Folder Contents__\n", + "Keep the output files together. The human-readable summaries are useful for inspection, but they do not replace the\n", + "saved samples and other files used to reconstruct results.\n", "\n", - "Now this is running you should checkout the `output` folder. This is where the results of the\n", - "search are written to hard-disk (in the `tutorial_2_practicalities` folder), where all outputs are human readable\n", - "(e.g. as .json, .csv or text files).\n", - "\n", - "As the fit progresses, results are written to the `output` folder on the fly using the highest likelihood model found\n", - "by the non-linear search so far. This means you can inspect the results of the model-fit as it runs, without having to\n", - "wait for the non-linear search to terminate.\n", - " \n", - "The `output` folder includes:\n", - "\n", - " - `model.info`: Summarizes the model, its parameters and their priors discussed in the next tutorial.\n", - " \n", - " - `model.results`: Summarizes the highest likelihood model inferred so far including errors.\n", - " \n", - " - `images`: Visualization of the highest likelihood model-fit to the dataset, (e.g. a fit subplot showing the \n", - " galaxies, model data and residuals).\n", - " \n", - " - `files`: A folder containing .fits files of the dataset, the model as a human-readable .json file, \n", - " a `.csv` table of every non-linear search sample and other files containing information about the model-fit.\n", - " \n", - " - `search.summary`: A file providing summary statistics on the performance of the non-linear search.\n", - " \n", - " - `search_internal`: Internal files of the non-linear search (in this case Nautilus) used for resuming the fit and\n", - " visualizing the search.\n", - "\n", - "__Result__\n", - "\n", - "The `search.fit` method produces a `result` object, packed with useful information about the model fit that we\u2019ll \n", - "explore in detail in a later tutorial.\n", - "\n", - "One component of the `result` object we\u2019ll use now is the `FitImaging` object, which corresponds to the set of model \n", - "parameters that yielded the maximum log-likelihood solution. Plotting this object lets us visually inspect how well \n", - "the model fits the data.\n", - "\n", - "In this example, the fit to the data is excellent, with residuals near zero, as expected since the same model was \n", - "used both to simulate and fit the data." + "The `search_internal` directory contains search-specific state. This tutorial\u2019s output configuration removes it after\n", + "completion to save space; that does not prevent the completed result from being loaded." ] }, { - "cell_type": "code", + "cell_type": "markdown", "metadata": {}, "source": [ - "aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null + "__Output Folder Contents__\n", + "\n", + "Begin with `image/fit.png`. Inspect whether the predicted image reproduces the lens and source light, and whether\n", + "coherent structures remain in the residuals.\n", + "\n", + "Then open `model.results` for the inferred parameters and uncertainties. Use `model.info` alongside it to remind\n", + "yourself which components, fixed values and priors were specified.\n", + "\n", + "`search.summary` and `search.log` help you understand the run\u2019s progress and timing. While the search is still running,\n", + "treat saved fits and summaries as provisional.\n", + "\n", + "The `files` directory supports more detailed analysis in Python. You do not need to manipulate these files to continue\n", + "HowToLens; later we will point you to the workspace examples for loading and analysing completed results.\n", + "\n", + "Output is configurable. `config/output.yaml` controls saved products such as samples and retained search state, while\n", + "files under `config/visualize/` control plotting. Keep the tutorial defaults while learning the workflow." + ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "The Probability Density Functions (PDF's) of the results can be plotted using an in-built visualization \n", - "library, which is wrapped via the `corner_anesthetic` function.\n", + "__Parameter Uncertainties__\n", + "\n", + "A corner plot shows the parameter uncertainties inferred by the search and the relationships between them.\n", "\n", - "The PDF shows the 1D and 2D probabilities estimated for every parameter after the model-fit. The two dimensional \n", - "figures can show the degeneracies between different parameters, for example how increasing the intensity $I$ of the\n", - "source galaxy and decreasing its effective radius $R_{Eff}$ lead to similar likelihoods and probabilities.\n", + "The plots along the diagonal show the distribution of each parameter individually. The other panels show pairs of\n", + "parameters: an elongated or curved distribution indicates that changing one parameter can be compensated by changing\n", + "another.\n", "\n", - "This PDF will be discussed more in the next tutorial.\n", + "For example, a galaxy\u2019s light-profile intensity and effective radius can trade off against one another, producing\n", + "similar images over the fitted region.\n", "\n", - "The plot is labeled with short hand parameter names (e.g. `sersic_index` is mapped to the short hand \n", - "parameter `n`). These mappings ate specified in the `config/notation.yaml` file and can be customized by users.\n", + "Compare these distributions with the uncertainties in `result.info`. A narrow distribution indicates a tightly\n", + "constrained parameter under the assumptions of this fit; it does not account for every possible source of error, such\n", + "as an inappropriate model.\n", "\n", - "The superscripts of labels are the path of names each component was given in the model (e.g. for the `Isothermal`\n", - "mass, `lens.mass`: the galaxy's name `lens` and its name `mass` defined when making the `Model` above)." + "**\ud83e\udd16 Ask AI:** My lens model has small image residuals, but two parameters form a long curved distribution in the corner\n", + "plot. What does this tell me about what the data constrain?" ] }, { "cell_type": "code", "metadata": {}, "source": [ - "aplt.corner_anesthetic(samples=result.samples)\n" + "\n", + "aplt.corner_anesthetic(samples=result.samples)" ], "outputs": [], "execution_count": null @@ -589,24 +659,27 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Components in different named galaxy or profile paths can be distinguished by their superscripts. Profiles within\n", - "the same path, such as Gaussians in a basis, can share a superscript. When the model has more than one top-level\n", - "component, each also gets its own\n", - "corner plot in the output folder (`corner_anesthetic_.png`, switched in `config/visualize/plots_search.yaml`).\n", + "__Plot Labels__\n", "\n", - "The parameters a model is sampled in are not always the ones it is read in: a profile's elliptical components are an\n", - "axis ratio and a position angle, a shear's two components a magnitude and an angle. Passing `latent=True` plots\n", - "these latent parameters instead. The same figure is written to the output folder as `corner_anesthetic_latent.png`\n", - "when `corner_anesthetic_latent` is switched on in `config/visualize/plots_search.yaml` (off by default), once the fit\n", - "is complete. With `latent_model_parameters` enabled, full-sample latent output (`latent_draw_via_pdf: false`)\n", - "writes these columns to `files/latent/samples.csv` with the other latent variables. Periodic angles are recentred\n", - "for the plot; saved values retain the conversion's original range." + "Corner plots use abbreviated parameter names to keep their labels readable. For example, the S\u00e9rsic index may be\n", + "labelled \\(n\\). These labels can be customised in `config/notation.yaml`.\n", + "\n", + "Superscripts distinguish components using their names in the model, such as `lens.mass` and `source.bulge`. Use these\n", + "alongside `model.info` to identify which parameter each panel represents.\n", + "\n", + "The plotting configuration can also produce separate corner plots for individual components, which are easier to\n", + "inspect when the full model contains many parameters.\n", + "\n", + "Some quantities are easier to interpret after conversion. For example, elliptical components can be expressed as an\n", + "axis ratio and position angle. The following plot displays supported derived quantities using `latent=True`; it\n", + "interprets the same fit rather than running another search." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "aplt.corner_anesthetic(samples=result.samples, latent=True)" ], "outputs": [], @@ -616,31 +689,60 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Other Practicalities__\n", + "__Configuration__\n", + "\n", + "The `config` folder controls defaults used throughout HowToLens. You do not need to customise everything before fitting\n", + "your own data, but it helps to know where the main settings live:\n", + "\n", + "- `config/priors/` supplies default priors for model components. Assigning priors explicitly in your script makes those choices visible beside the model.\n", + "- `config/output.yaml` controls saved products, including sample tables and whether internal search files are retained after completion.\n", + "- `config/visualize/` controls which figures are produced. Search plots, including corner plots, are configured in `plots_search.yaml`.\n", + "- `config/notation.yaml` controls parameter labels used in plots.\n", "\n", - "The following are examples of other practicalities which I will document fully in this example script in the future,\n", - "but so far have no found the time:\n", + "Keep the tutorial defaults initially. Saving fewer products can reduce disk usage, but may limit what you can calculate\n", + "later without rerunning the fit.\n", "\n", - "- `config`: The files in the `config` folder which control many aspects of how **PyAutoLens** runs,\n", - " including visualization, the non-linear search settings.\n", + "In particular, a saved summary is not a substitute for the full sample table when you want to perform new calculations\n", + "using the parameter distributions." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Further Results__\n", "\n", - "- `config/priors`: Folder containing the default priors on all model components.\n", + "You now know how to inspect a fit, read its parameter estimates and find its saved output. That is enough to continue\n", + "HowToLens.\n", "\n", - "- `results`: How to load the results of a model-fit from the output folder to a Python script or Jupyter notebook.\n", + "The results also support more detailed work: loading fitted galaxies and tracers, calculating derived quantities,\n", + "making customised figures and comparing many fits.\n", "\n", - "- `output.yaml`: What files are output to control file size.\n", + "Once you are comfortable building models and obtaining satisfactory fits to real data, explore the `autolens_workspace`\n", + "results guide, beginning with `scripts/guides/results/start_here.py` or its notebook counterpart.\n", "\n", + "HowToLens focuses on learning the analysis tools needed to model lenses. The workspace provides the next steps for\n", + "using and manipulating the results of those analyses." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ "__Wrap Up__\n", "\n", - "This tutorial has illustrated how to handle a number of practicalities that are key to performing model-fitting\n", - "effectively. These include:\n", + "We have fitted a model containing lens light, lens mass, external shear and source light, while retaining the same\n", + "data\u2013model\u2013Analysis\u2013search structure introduced in Tutorial 1.\n", "\n", - "- How to save results to your hard disk.\n", + "You have also learned how to configure search and output settings, check GPU memory requirements, run a notebook or\n", + "script, and navigate the saved results. The unique identifier allows an unchanged fit to reuse its output, while\n", + "descriptive names and dataset tags help keep different analyses organised.\n", "\n", - "- How to navigate the output folder and examine model-fit results to assess quality.\n", + "These practical tools make it easier to run and inspect a fit, but they do not guarantee that the search finds a\n", + "satisfactory solution.\n", "\n", - "- How to estimate the run-time of a model-fit before initiating it, and change settings to make it faster or run the\n", - " analysis in parallel." + "In the next tutorial, *Why Modeling Is Hard*, we examine what can go wrong as models become more complex, how to\n", + "recognise the problem and which changes can help." ] } ], diff --git a/notebooks/chapter_2_lens_modeling/tutorial_3_realism_and_complexity.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_3_realism_and_complexity.ipynb deleted file mode 100644 index 46a39e0..0000000 --- a/notebooks/chapter_2_lens_modeling/tutorial_3_realism_and_complexity.ipynb +++ /dev/null @@ -1,519 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 3: Realism and Complexity\n", - "==================================\n", - "\n", - "In the previous two tutorials, we fitted a fairly crude and unrealistic model: the lens's mass was spherical, as was\n", - "the source's light. Given most lens galaxies are literally called 'elliptical galaxies' we should probably model their\n", - "mass as elliptical! Furthermore, we have completely omitted the lens galaxy's light, which in real observations\n", - "outshines the source's light and therefore must be included in the lens model.\n", - "\n", - "In this tutorial, we'll use a more realistic lens model, which consists of the following light and mass profiles:\n", - "\n", - " - An `Sersic` light profile for the lens galaxy's light [7 parameters].\n", - " - A `Isothermal` mass profile for the lens galaxy's mass [5 parameters].\n", - " - An `ExternalShear` which accounts for additional lensing by other galaxies nearby the lens [2 parameters].\n", - " - An `Exponential` light profile for the source-galaxy's light (this is probably still too simple for most\n", - " strong lenses, but we will worry about that later) [6 parameters].\n", - "\n", - "This lens model has 20 free parameters, meaning that the parameter space and likelihood function it defines has a\n", - "dimensionality of N=20. This is over double the number of parameters and dimensions of the models we fitted in the\n", - "previous tutorials and in future exercises, we will fit even more complex models with some 30+ parameters.\n", - "\n", - "Therefore, take note, as we make our lens model more realistic, we also make its parameter space more complex, this is\n", - "an important concept to keep in mind for the remainder of this chapter!\n", - "\n", - "__Contents__\n", - "\n", - "- **Initial Setup:** we'll use new strong lensing data, 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:** Compose the lens model fitted to the data.\n", - "- **Search + Analysis:** Create the non-linear search and analysis used to fit the model.\n", - "- **Run Time:** Profiling the expected run time of the model-fit.\n", - "- **Result:** Overview of the results of the model-fit.\n", - "- **Global and Local Maxima:** Up to now, all our non-linear searches have successfully found lens models that provide visibly.\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 new strong lensing data, 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": [ - "if al.util.dataset.should_simulate(str(dataset_path)):\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulator/lens_sersic.py\"],\n", - " check=True,\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", - "We'll create and use a 2.5\" `Mask2D`, which is slightly smaller than the masks we used in previous tutorials." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mask_radius = 2.5\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)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "When plotted, the lens light`s is clearly visible in the centre of the image." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_imaging_dataset(dataset=dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Model__\n", - "\n", - "Now lets fit the dataset using a search.\n", - "\n", - "Below, we write the `model` using the **PyAutoFit** concise API, which means that we do not have to specify that\n", - "each component of the model is a `Model` object. This is because we are passing the light and mass profiles directly \n", - "to the `Collection` object, which assumes they are `Model` objects.\n", - "\n", - "We will use this consistent API throughout the chapter, so you should get used to it!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "field = af.Model(al.MassField, redshift=0.5, shear=al.mp.ExternalShear)\n", - "model = af.Collection(\n", - " galaxies=af.Collection(\n", - " lens=af.Model(\n", - " al.Galaxy,\n", - " redshift=0.5,\n", - " bulge=al.lp.Sersic,\n", - " mass=al.mp.Isothermal,\n", - " ),\n", - " source=af.Model(al.Galaxy, redshift=1.0, bulge=al.lp.ExponentialCore),\n", - " ),\n", - " fields=field,\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Search + Analysis__\n", - "\n", - "We set up `Nautilus` as we did in the previous tutorial, however given the increase in model complexity we'll use\n", - "a higher `n_live` value of 200 to ensure we sample the complex parameter space efficiently." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search = af.Nautilus(\n", - " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", - " name=\"tutorial_3_realism_and_complexity\",\n", - " unique_tag=dataset_name,\n", - " n_live=200,\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", - "The run time of the `log_likelihood_function` is a little bit more than previous tutorials, because we added more\n", - "light and mass profiles to the model. It is the increased number of parameters that increases the expected run time \n", - "more.\n", - "\n", - "Run the non-linear search." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(\n", - " \"The non-linear search has begun running - checkout the output/howtolens/chapter_2/tutorial_3_realism_and_complexity\"\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 = 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": [ - "__Result__\n", - "\n", - "Inspection of the `info` summary of the result suggests the model has gone to reasonable values." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And lets look at how well the model fits the imaging data, which as we are used to fits the data brilliantly!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Global and Local Maxima__\n", - "\n", - "Up to now, all our non-linear searches have successfully found lens models that provide visibly good fits to the data, \n", - "minimizing residuals and inferring high log likelihood values. These optimal solutions, known as 'global maxima,' \n", - "correspond to the highest likelihood regions across the entire parameter space. In other words, no other lens model \n", - "in the parameter space would yield a higher likelihood. This is the ideal model we always aim to infer.\n", - "\n", - "However, non-linear searches do not always locate these global maxima. They may instead infer 'local maxima' \n", - "solutions, which have high log likelihood values relative to nearby models in the parameter space, but \n", - "significantly lower log likelihoods compared to the true global maxima situated elsewhere. \n", - "\n", - "Why might a non-linear search end up at these local maxima? As previously discussed, the search iterates through \n", - "many models, focusing more on regions of the parameter space where previous guesses yielded higher likelihoods. \n", - "The search gradually 'converges' around any solution with a higher likelihood than surrounding models. If the \n", - "search is not thorough enough, it may settle on a local maxima, appearing to offer a high likelihood \n", - "relative to nearby models but failing to reach the global maxima.\n", - "\n", - "Inferring local maxima is a failure of our non-linear search, and it's something we want to avoid. To illustrate \n", - "this, we can intentionally infer a local maxima by reducing the number of live points (`n_live`) Nautilus uses to \n", - "map out the parameter space. By using very few live points, the initial search over the parameter space has a low \n", - "probability of approaching the global maxima, thus it converges on a local maxima." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search = af.Nautilus(\n", - " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", - " name=\"tutorial_3_realism_and_complexity__local_maxima\",\n", - " unique_tag=dataset_name,\n", - " n_live=75,\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_3_realism_and_complexity__local_maxima\"\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", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Run Time__\n", - "\n", - "Due to the decreased number of live points, the estimate of 10000 iterations per free parameter is now a significant\n", - "overestimate. The actual run time of the model-fit will be much less than this.\n", - "\n", - "Run the non-linear search." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "result_local_maxima = 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": [ - "__Result__\n", - "\n", - "Inspection of the `info` summary of the result suggests certain parameters have gone to different values to the fit\n", - "performed above." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result_local_maxima.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Lats look at the fit to the `Imaging` data, which is clearly worse than our original fit above." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_fit_imaging(fit=result_local_maxima.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Finally, just to be sure we hit a local maxima, lets compare the maximum log likelihood values of the two results \n", - "\n", - "The local maxima value is significantly lower, confirming that our non-linear search simply failed to locate lens \n", - "models which fit the data better when it searched parameter space." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(\"Likelihood of Global Model:\")\n", - "print(result.max_log_likelihood_fit.log_likelihood)\n", - "print(\"Likelihood of Local Model:\")\n", - "print(result_local_maxima.max_log_likelihood_fit.log_likelihood)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Wrap Up__\n", - "\n", - "In this example, we intentionally made our non-linear search fail, by using so few live points it had no hope of \n", - "sampling parameter space thoroughly. For modeling real lenses we wouldn't do this intentionally, but the risk of \n", - "inferring a local maxima is still very real, especially as we make our lens model more complex.\n", - "\n", - "Lets think about *complexity*. As we make our lens model more realistic, we also made it more complex. For this \n", - "tutorial, our non-linear parameter space went from 6 dimensions to 20. This means there was a much larger *volume* of\n", - "parameter space to search. As this volume grows, there becomes a higher chance that our non-linear search gets lost \n", - "and infers a local maxima, especially if we don't set it up with enough live points!\n", - "\n", - "At its core, lens modeling is all about learning how to get a non-linear search to find the global maxima region of \n", - "parameter space, even when the lens model is complex. This will be the main theme throughout the rest of this chapter,\n", - "culminating in the search chaining technique introduced in tutorials 9 and 10.\n", - "\n", - "In the next exercise, we'll learn how to deal with failure and begin thinking about how we can ensure our non-linear \n", - "search finds the global-maximum log likelihood solution. First, think about the following:\n", - "\n", - " 1) When you look at an image of a strong lens, do you get a sense of roughly what values certain lens model \n", - " parameters are?\n", - " \n", - " 2) The non-linear search failed because parameter space was too complex. Could we make it less complex, whilst \n", - " still keeping our lens model fairly realistic?\n", - " \n", - " 3) The source galaxy in this example had only 6 non-linear parameters. Real source galaxies may have multiple\n", - " components (e.g. a disk, bulge, bar, star-forming knot) and there may even be more than 1 source galaxy! Do you \n", - " think there is any hope of us navigating a parameter space if the source contributes 20+ parameters by itself?" - ] - } - ], - "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_3_realism_and_complexity.ipynb in HowToLens).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoLens calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoLens docs (https://pyautolens.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_build_imaging_model\n\n---\nname: al_build_imaging_model\ndescription: Compose a strong-lens model for imaging data — galaxies with light + mass profiles, prior customisation, and an `al.AnalysisImaging` ready to hand to a non-linear search. Writes a runnable Python script in scripts/. Pairs with `al_prepare_imaging_data` (which loads + masks the dataset) and `al_run_search` (which executes the fit). For visibility-plane data see `al_build_interferometer_model`.\n---\n\n# Composing an imaging lens model\n\nThe model is the PyAuto\\* representation of *what kind of lens you think this is* — how\nmany galaxies, at what redshifts, with what light and mass parameterisations, with\nwhich parameters free and which fixed. Building one is the step between \"I have a\nloaded `Imaging` dataset\" and \"I'm running a non-linear search\".\n\nThe canonical example is `autolens_workspace:scripts/imaging/modeling.py`. This skill\ngenerates the equivalent for the user's lens.\n\nThis skill assumes the imaging data is already preprocessing-ready. For real\nobservational data, confirm first that the user has **inspected `dataset.png`** and\nthought through mask extent, contaminating objects, and any regions to exclude — in\nparticular that any **extra galaxies** have been handled (noise-scaled via a\n`mask_extra_galaxies.fits`, or excluded by shrinking the circular mask). If not, route\nthem back to [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) before building the\nmodel — don't compose a model over data with an unaddressed contaminant.\n\n## Ask\n\n- *\"If this is real observational data, have you inspected `dataset.png`, decided the\n mask extent, and handled any extra galaxies (noise-scaled a `mask_extra_galaxies.fits`,\n or shrunk the mask to exclude them)?\"* — if not, stop and do that in\n [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) first.\n- *\"How many galaxies in the model — single galaxy-scale, multi-galaxy (2+ co-dominant, no host halo), group (2–10, optional group halo), cluster?\"* —\n this is the only structural choice. Skill below assumes galaxy-scale; bootstrap a\n variant for groups/clusters via `_bootstrap_skill` if needed.\n- *\"What's the lens light parameterisation — a single Sersic, MGE (multi-Gaussian\n expansion), bulge + disk, or no lens light at all (mass-only)?\"*\n- *\"What's the lens mass — Isothermal (SIE) + ExternalShear is the standard starting\n point; PowerLaw or NFW for total or dark-matter-only models.\"*\n- *\"What's the source — parametric Sersic, MGE, or pixelised inversion?\"* — pixelised\n needs a different `Analysis` wiring; see [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md).\n- *\"What are the lens and source redshifts?\"* — needed for distance ratios; even a\n ballpark value works for relative-comparison runs.\n\n## Branch — galaxy-scale, Sersic light + SIE mass + Sersic source\n\nThe minimum viable model. Save to `scripts/build_model.py`:\n\n```python\n# scripts/build_model.py\nfrom autonerves import jax_wrapper\nimport autofit as af\nimport autolens as al\n\n# Lens light — a Sersic for the bulge.\nlens_bulge = af.Model(al.lp.Sersic)\n\n# Lens mass — SIE plus a separate external field.\nlens_mass = af.Model(al.mp.Isothermal)\nlens_shear = af.Model(al.mp.ExternalShear)\n\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=lens_bulge,\n mass=lens_mass,\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=lens_shear)\n\n# Source light — a single Sersic.\nsource = af.Model(\n al.Galaxy,\n redshift=1.0,\n bulge=af.Model(al.lp.SersicCore),\n)\n\n# Compose into a Collection.\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# Optional: customise priors. E.g. tighten the lens centre.\nlens_mass.centre.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\nlens_mass.centre.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n\n# On real data, bound the Einstein radius from the ring you can see in the image\n# (the default prior is uniform over 0-8\"). A maximum-likelihood optimiser such as\n# MultiStartProdigy otherwise finds degenerate basins where theta_E exceeds the mask,\n# the \"source\" lands on a neighbouring galaxy and the ring is left in the residuals\n# (this is exactly what happened on the bundled COSMOS-Web Ring: theta_E 2.4\" vs 0.8\").\nlens_mass.einstein_radius = af.UniformPrior(lower_limit=0.3, upper_limit=1.5)\n\nprint(model.info)\n```\n\nSource citations:\n- `PyAutoGalaxy:autogalaxy/galaxy/galaxy.py` — `Galaxy`.\n- `PyAutoGalaxy:autogalaxy/galaxy/mass_field.py` — `MassField`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — `Sersic`, `SersicCore`.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — `Isothermal`.\n- `PyAutoFit:autofit/mapper/prior_model/prior_model.py` — `af.Model`.\n- `PyAutoFit:autofit/mapper/prior_model/collection.py` — `af.Collection`.\n\nWiki:\n- [`wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md) — what each\n light profile represents and when to pick which.\n- [`wiki/core/concepts/mass_profiles.md`](../wiki/core/concepts/mass_profiles.md) — same for mass.\n- [`wiki/core/concepts/galaxy_and_plane.md`](../wiki/core/concepts/galaxy_and_plane.md) — how\n galaxies, redshifts, and the `Tracer` fit together.\n\n## Branch — linear (MGE) lens light\n\nFor complex lens galaxy morphologies, replace the single Sersic bulge with a Multi-\nGaussian Expansion of *linear* light profiles. Linear profiles have their\n*intensities* solved analytically inside the fit, so the search only varies\nshape parameters — far fewer dimensions, much better convergence.\n\n```python\nn_gaussians = 30\ngaussian_per_basis = [\n af.Model(al.lp_linear.Gaussian) for _ in range(n_gaussians)\n]\n# Tie centres + ellipticities across the basis; let only sigma + intensity vary.\nfor g in gaussian_per_basis[1:]:\n g.centre = gaussian_per_basis[0].centre\n g.ell_comps = gaussian_per_basis[0].ell_comps\n\nlens_bulge = af.Model(al.lp_basis.Basis, profile_list=gaussian_per_basis)\n```\n\nSee `PyAutoGalaxy:autogalaxy/profiles/light/linear/` for the linear-profile classes.\n\n## Branch — pixelised source\n\nFor sources with complex morphology (lensed arcs, multiple components), reconstruct\nthe source on a pixel grid rather than as a parametric Sersic. The model wiring is\ndifferent: the source `Galaxy` carries a `Pixelization`, and the `Analysis` needs a\npositions likelihood penalty to keep the inversion well-posed.\n\nSee [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) for\nthe full pattern.\n\n## Wrap with an analysis\n\nOnce the model is built, wrap your loaded `dataset` (from `al_prepare_imaging_data`)\nin an analysis object:\n\n```python\nanalysis = al.AnalysisImaging(dataset=dataset)\n```\n\nSource: `PyAutoLens:autolens/imaging/model/analysis.py`.\n\n`analysis` + `model` are the two inputs to the non-linear search. Pass them to\n[`al_run_search`](./al_run_search.md).\n\n## Combine\n\nNatural next steps:\n\n- [`al_configure_search`](./al_configure_search.md) — pick Nautilus (default), Dynesty,\n Emcee, or another search; tune live points / walkers.\n- [`al_run_search`](./al_run_search.md) — `search.fit(model=model, analysis=analysis)`.\n- [`al_chain_searches`](./al_chain_searches.md) — chain a fast Sersic source fit into\n a slower pixelised one, inheriting priors.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Non-linear searches and parameter\n inference](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb):\n how non-linear searches find a best-fit model — parameter spaces, likelihoods,\n priors. The statistical foundation under model composition.\n- **General reference** — [RTD: Model cookbook](https://pyautolens.readthedocs.io/en/latest/general/model_cookbook.html):\n systematic reference for building lens models with `Model` and `Collection` —\n two-component to multi-galaxy, prior customisation, parameter pairing, MGE.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/modeling/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling/start_here.py):\n the canonical imaging-modeling script — light-profile choice (Sersic vs. MGE),\n non-linear-search configuration, JAX/GPU fitting.\n\n## Skill: al_run_search\n\n---\nname: al_run_search\ndescription: Execute a non-linear search on a configured model + analysis. Calls `search.fit(model=model, analysis=analysis)` and monitors progress to the search's `path_prefix/name/unique_id/` output folder. Includes the sandbox / test-mode wrapper so smoke tests don't burn hours on real sampling. Use after `al_build_imaging_model` (or interferometer) and `al_configure_search` have produced `model`, `analysis`, and `search` objects.\n---\n\n# Running a non-linear search\n\nThe actual fit. Inputs: a model, an analysis (which knows the dataset and how to\ncompute a log-likelihood), and a search (which knows how to explore parameter space).\nThe single call `search.fit(model=model, analysis=analysis)` does the work.\n\nThis skill assembles those three pieces into a runnable script, then runs it — either\nin `PYAUTO_TEST_MODE=1` for a smoke test or in production mode for the real fit.\n\n## Ask\n\n- *\"Have you built `model` and `analysis` (from `al_build_imaging_model`) and\n configured `search` (from `al_configure_search`)?\"* If not, route to those first.\n- *\"Smoke test or production run?\"* Smoke test runs in seconds with `PYAUTO_TEST_MODE=1`\n and a tiny dataset, just to prove the wiring is correct. Production run takes hours\n to a day depending on model complexity and number of likelihood evals.\n- *\"How long can the fit run?\"* Sets expectations and decides whether to launch it as\n a foreground or backgrounded process.\n\n## Branch — production run\n\nOperational reminder: if the search was configured with `live_visual_update=True`\n(`al_configure_search` \"Live visual updates\"), a foreground script opens a matplotlib viewer\nand a notebook cell refreshes in place — don't re-ask when the search configuration already\nrecords the choice, and keep it `False` for HPC/headless/background runs. `fit.png` is\nwritten to disk on every quick update either way.\n\nAssemble everything into one script (`scripts/run_fit.py`):\n\n```python\n# scripts/run_fit.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autofit as af\nimport autolens as al\n\n# --- Dataset (from al_prepare_imaging_data) ---\ndataset_path = Path(\"dataset/imaging/\")\ndataset = al.Imaging.from_fits(\n data_path=dataset_path / \"data.fits\",\n noise_map_path=dataset_path / \"noise_map.fits\",\n psf_path=dataset_path / \"psf.fits\",\n pixel_scales=0.06,\n)\nmask = al.Mask2D.circular(\n shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5\n)\ndataset = dataset.apply_mask(mask=mask)\n\n# --- Model (from al_build_imaging_model) ---\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=af.Model(al.lp.Sersic),\n mass=af.Model(al.mp.Isothermal),\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=af.Model(al.mp.ExternalShear))\nsource = af.Model(al.Galaxy, redshift=1.0, bulge=af.Model(al.lp.SersicCore))\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# --- Analysis ---\nanalysis = al.AnalysisImaging(dataset=dataset)\n\n# --- Search (from al_configure_search) ---\nsearch = af.Nautilus(\n path_prefix=\"imaging/\",\n name=\"sie_sersic\",\n n_live=200,\n number_of_cores=4,\n)\n\n# --- Fit ---\nresult = search.fit(model=model, analysis=analysis)\nprint(result.max_log_likelihood_instance)\n```\n\nRun with sandbox cache overrides if needed:\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/abstract_search.py` (the `fit` method).\nThe returned `Result` object is documented in `PyAutoFit:autofit/non_linear/result.py`.\n\n## Branch — smoke test (`PYAUTO_TEST_MODE=1`)\n\nWhen you've just written the script and want to know it runs end-to-end *without*\nwaiting for real sampling, set `PYAUTO_TEST_MODE=1`:\n\n```bash\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\nThe search will short-circuit after a small number of likelihood evaluations and\nreturn a `Result` so the script completes. Use this on every script you write, before\nlaunching a real run.\n\nFor an even faster smoke (sub-second per step), combine with PyAutoLens's small-dataset\nflags:\n\n```bash\nPYAUTO_TEST_MODE=2 PYAUTO_SKIP_FIT_OUTPUT=1 PYAUTO_SKIP_VISUALIZATION=1 \\\n PYAUTO_SMALL_DATASETS=1 PYAUTO_FAST_PLOTS=1 python scripts/run_fit.py\n```\n\nSee [`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md) for the full flag list.\n\n## Output\n\nThe fit writes to `output////` (see\n`al_configure_search` for the layout). Tail the search log live:\n\n```bash\ntail -f output/imaging//sie_sersic/*/search.log\n```\n\nSay this out loud the moment a production fit starts: results are written **on the fly**\nfrom the best model so far, so `model.results` and `image/fit.png` are already worth\nopening — no need to wait for the search to terminate. For a newcomer, or in teacher\nmode, tour the folder per `_style.md` \"Output folder announcement\" and point at\n`__Output Folder Layout__` in\n[`autolens_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling.py),\nwhich annotates every file the fit writes.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — once the fit completes (or even mid-run),\n load and inspect.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — visualise model vs data.\n- [`al_chain_searches`](./al_chain_searches.md) — feed the result into a follow-up\n search with tighter priors.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) — if the fit converged badly.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Output management and result\n interpretation](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running fits — output structure, reviewing results,\n managing run times.\n- **General reference** — [RTD: New user guide](https://pyautolens.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n decision-tree routing for a new user about which fit to run first.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit on GPU — production pattern this skill mirrors.\n" - } - }, - "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file 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 new file mode 100644 index 0000000..bd7821a --- /dev/null +++ b/notebooks/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.ipynb @@ -0,0 +1,1214 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Tutorial 3: Why Modeling Is Hard\n", + "================================\n", + "\n", + "We now have the tools to build a lens model, run a search and inspect its results. However, a search finishing does not\n", + "necessarily mean that it has found a satisfactory fit.\n", + "\n", + "As we add model components and free parameters, more combinations can produce similar images. Parameter space becomes\n", + "harder to explore, and a search can miss solutions that explain the data better.\n", + "\n", + "In this tutorial, we examine these difficulties using the lens-light, mass, shear and source-light model from\n", + "*Practicalities*. We then try three approaches: adjusting justified priors, simplifying the model and searching more\n", + "thoroughly.\n", + "\n", + "Each approach has benefits and costs. The aim is to understand which change addresses the problem we see, rather than\n", + "repeatedly changing settings until a fit looks convincing.\n", + "\n", + "__Contents__\n", + "\n", + "- **Overview**\n", + "- **Dataset and Mask**\n", + "- **Model and Analysis**\n", + "- **A Less Thorough Search**\n", + "- **Inspecting the Result**\n", + "- **Comparing Searches**\n", + "- **Why Modeling Is Hard**\n", + "- **Three Ways Forward**\n", + "- **Prior Tuning**\n", + "- **Profile Centres**\n", + "- **Lens-Light Shape**\n", + "- **Mass Shape**\n", + "- **Lens-Light Size**\n", + "- **Light Concentration**\n", + "- **Einstein Radius**\n", + "- **Source and Shear Priors**\n", + "- **Inspecting the Tuned Model**\n", + "- **Prior-Tuned Fit**\n", + "- **Assessing the Improvement**\n", + "- **Prior Tuning: Benefits and Limitations**\n", + "- **Reducing Complexity**\n", + "- **Linking Parameters**\n", + "- **Inspecting the Simpler Model**\n", + "- **Fitting the Simpler Model**\n", + "- **Reducing Complexity: Benefits and Limitations**\n", + "- **Search More Thoroughly**\n", + "- **Original Model**\n", + "- **More Thorough Search**\n", + "- **Comparing the Approaches**\n", + "- **Benefits and Weaknesses**\n", + "- **Run Times**\n", + "- **Model Mismatch**\n", + "- **Wrap Up**" + ] + }, + { + "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": "markdown", + "metadata": {}, + "source": [ + "__Overview__\n", + "\n", + "We will first run a less thorough search and inspect its result. It may find a satisfactory solution, or it may miss a\n", + "better-fitting region of parameter space. The outcome is not guaranteed because the search includes random sampling.\n", + "\n", + "We will use this experiment to understand why fits can struggle and how to investigate them. We will also distinguish a\n", + "search that has missed a good solution from a model that cannot adequately describe the data." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Dataset and Mask__\n", + "\n", + "We use the same `lens_sersic` imaging dataset as in *Practicalities*, with its S\u00e9rsic lens light, elliptical isothermal\n", + "mass, external shear and exponential source light.\n", + "\n", + "We also retain the circular mask with a radius of 2.5 arcseconds. Keeping the dataset and mask unchanged lets us\n", + "compare searches using the same measurements and likelihood calculation.\n", + "\n", + "Inspect the image again before fitting. Identify the central lens light and the lensed source emission: the model must\n", + "explain both." + ] + }, + { + "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", + "import numpy as np\n", + "\n", + "dataset_name = \"lens_sersic\"\n", + "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name\n", + "\n", + "if al.util.dataset.should_simulate(str(dataset_path)):\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.run([sys.executable, \"scripts/simulator/lens_sersic.py\"], check=True)\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)\n", + "\n", + "mask_radius = 2.5\n", + "mask = al.Mask2D.circular(\n", + " shape_native=dataset.shape_native,\n", + " pixel_scales=dataset.pixel_scales,\n", + " radius=mask_radius,\n", + ")\n", + "dataset = dataset.apply_mask(mask=mask)\n", + "aplt.subplot_imaging_dataset(dataset=dataset)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Model and Analysis__\n", + "\n", + "We reconstruct the same model used in *Practicalities*, with the same profiles, fixed redshifts and default priors.\n", + "\n", + "Print `model.info` and inspect its diagram to remind yourself which parameters are free. The lens light, lens mass,\n", + "shear and source light all contribute to the image, so changes in one component can sometimes be partly compensated by\n", + "changes in another.\n", + "\n", + "We again use `AnalysisImaging` to predict the image and evaluate its likelihood. At this stage, neither the model nor\n", + "the analysis has changed. We will change only how thoroughly Nautilus explores parameter space." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\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(\n", + " lens=af.Model(\n", + " al.Galaxy,\n", + " redshift=0.5,\n", + " bulge=al.lp.Sersic,\n", + " mass=al.mp.Isothermal,\n", + " ),\n", + " source=af.Model(\n", + " al.Galaxy,\n", + " redshift=1.0,\n", + " bulge=al.lp.ExponentialCore,\n", + " ),\n", + " ),\n", + " fields=field,\n", + ")\n", + "\n", + "print(model.info)\n", + "af.ModelPlotter(model).figure()\n", + "\n", + "analysis = al.AnalysisImaging(dataset=dataset)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__A Less Thorough Search__\n", + "\n", + "We deliberately reduce `n_live` from 200 to just 21. This gives Nautilus very few live points with which to explore\n", + "this complex model, making it more likely to miss a good solution.\n", + "\n", + "Nautilus requires at least one more live point than the number of non-linear parameters. This model has 20, so 21 is\n", + "the smallest valid setting; a value of 10 would raise an error rather than produce a fit.\n", + "\n", + "Inspect the resulting fit and residuals. Your run may still succeed because the search includes random sampling; a\n", + "successful run does not make this a reliable setting.\n", + "\n", + "We give this fit its own name so its output is kept separate from the *Practicalities* result." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "search = af.Nautilus(\n", + " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", + " name=\"tutorial_3_less_thorough\",\n", + " unique_tag=dataset_name,\n", + " n_live=21,\n", + " n_batch=50,\n", + " iterations_per_quick_update=2500,\n", + ")\n", + "\n", + "result = search.fit(model=model, analysis=analysis)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Inspecting the Result__\n", + "\n", + "Print the result summary and plot the fitted image.\n", + "\n", + "First, look at whether the model reproduces the central lens light and the lensed source. Then examine the normalised\n", + "residuals for coherent structures that remain unexplained.\n", + "\n", + "If the residuals contain a recognisable arc or a substantial mismatch around the lens galaxy, the fit needs further\n", + "investigation. Check the inferred parameters too, but do not judge the fit from plausible-looking values alone.\n", + "\n", + "Your run may produce a satisfactory fit despite the low number of live points. In either case, the next step is to\n", + "compare it with the more thorough search." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\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": [ + "__Comparing Searches__\n", + "\n", + "Compare this fit with the 200-live-point fit from *Practicalities*. We use the same dataset, mask and physical model,\n", + "so their maximum log likelihoods can be compared directly.\n", + "\n", + "A higher log likelihood means that the corresponding model explains these measurements better under the same noise\n", + "assumptions. Inspect the residuals alongside the numbers to see where the predictions differ.\n", + "\n", + "If the more thorough search finds a substantially higher likelihood, it demonstrates that the less thorough search\n", + "missed a better solution. It does not prove that the better result is the best possible solution.\n", + "\n", + "If the fits look similar and reach similar likelihoods, this run has not demonstrated a failure. Retain that outcome\n", + "rather than assuming the low-live-point fit must be wrong." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "search = af.Nautilus(\n", + " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", + " name=\"tutorial_2_practicalities\",\n", + " unique_tag=dataset_name,\n", + " n_live=200,\n", + " n_batch=50,\n", + " iterations_per_quick_update=2500,\n", + ")\n", + "\n", + "result_reference = search.fit(model=model, analysis=analysis)\n", + "\n", + "print(\"Less thorough maximum log likelihood:\")\n", + "print(result.max_log_likelihood_fit.log_likelihood)\n", + "print(\"Practicalities maximum log likelihood:\")\n", + "print(result_reference.max_log_likelihood_fit.log_likelihood)\n", + "aplt.subplot_fit_imaging(fit=result_reference.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "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", + "\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", + "\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", + "\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", + "\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*." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Three Ways Forward__\n", + "\n", + "We will try three approaches to making the fit more reliable:\n", + "\n", + "1. **Prior tuning:** use justified information to give more probability to plausible parameter values or exclude\n", + "inappropriate ranges. 2. **Reducing complexity:** fix or link selected parameters, giving the search fewer independent\n", + "quantities to explore. 3. **Searching more thoroughly:** increase the search effort while retaining the original model\n", + "and priors.\n", + "\n", + "The first two approaches change our modeling assumptions. The third changes the effort spent exploring them.\n", + "\n", + "We will start each experiment from the original setup, rather than accumulating changes from the previous experiment.\n", + "This helps us understand what each approach contributes.\n", + "\n", + "**\ud83e\udd16 Ask AI:** My lens fit has significant residuals. What observations would help me decide whether to adjust the\n", + "priors, simplify the model or search more thoroughly?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Prior Tuning__\n", + "\n", + "Our default priors cover a broad range of possible systems. For a particular image, we may have information that\n", + "justifies more specific choices.\n", + "\n", + "For example, we can inspect where the lens light is centred, how extended it appears and the approximate scale of the\n", + "lensed arcs. These observations can help us identify sensible parameter ranges.\n", + "\n", + "We must distinguish what the image tells us directly from additional assumptions. The lens-light centre is visible, but\n", + "assuming the mass is centred at exactly the same position is a physical assumption. Likewise, similar light and mass\n", + "shapes are not guaranteed.\n", + "\n", + "In this exercise, we will make these choices explicit and examine their effects. We will not use the known simulation\n", + "parameters as though they were information available for an unknown real lens.\n", + "\n", + "Priors chosen after inspecting the same image are practical modeling choices, not independent new measurements. Overly\n", + "restrictive choices can exclude good solutions and make the reported uncertainties misleadingly small." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Profile Centres__\n", + "\n", + "Look at the bright central lens galaxy. Its light is centred close to `(0.0, 0.0)` arcseconds, so we do not need to\n", + "give the search equal freedom to place it anywhere across the image.\n", + "\n", + "We restrict each coordinate of the light-profile centre to between \u22120.05 and +0.05 arcseconds. This lets the search\n", + "refine the position around our visual estimate.\n", + "\n", + "We also expect the lens mass to be centred near the light, so we apply the same limits to its centre. This is an\n", + "additional physical assumption: we see the light directly, whereas the mass distribution is inferred through its\n", + "lensing.\n", + "\n", + "The two centres remain independent within these bounds. We have not forced them to coincide." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "bulge = af.Model(al.lp.Sersic)\n", + "mass = af.Model(al.mp.Isothermal)\n", + "\n", + "bulge.centre.centre_0 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05)\n", + "bulge.centre.centre_1 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05)\n", + "\n", + "mass.centre.centre_0 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05)\n", + "mass.centre.centre_1 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Lens-Light Shape__\n", + "\n", + "Now inspect the shape of the lens light. It appears fairly round, with a slight elongation running approximately 45\u00b0\n", + "counter-clockwise from the positive x-axis.\n", + "\n", + "We can express this impression using an axis ratio and position angle. An axis ratio near one describes a nearly\n", + "circular profile; smaller values describe stronger flattening.\n", + "\n", + "As an approximate starting guess, we use an axis ratio of 0.8 and an angle of 45\u00b0. These are estimates to guide the\n", + "search, not precise measurements from the image.\n", + "\n", + "PyAutoLens uses elliptical components to describe the shape, so we convert our guess into those components and centre\n", + "Gaussian priors on them. Their widths allow the search to move away from our initial impression. This matters\n", + "especially for a nearly round galaxy, whose orientation can be difficult to judge." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "ell_comps = al.convert.ell_comps_from(axis_ratio=0.8, angle=45.0)\n", + "\n", + "bulge.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior(\n", + " mean=ell_comps[0], sigma=0.1, lower_limit=-1.0, upper_limit=1.0\n", + ")\n", + "bulge.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior(\n", + " mean=ell_comps[1], sigma=0.1, lower_limit=-1.0, upper_limit=1.0\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Mass Shape__\n", + "\n", + "The lens light also gives us a possible starting point for the mass shape. We might expect the two to have broadly\n", + "similar orientations, but the image does not directly establish this.\n", + "\n", + "We therefore centre the mass-shape priors on the same elliptical components, while making them wider than the\n", + "light-profile priors.\n", + "\n", + "This guides the search towards mass distributions resembling the visible galaxy, but allows it to infer a different\n", + "flattening or orientation. The mass includes dark matter as well as stars, so agreement with the light should remain an\n", + "assumption we assess." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "mass.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior(\n", + " mean=ell_comps[0], sigma=0.3, lower_limit=-1.0, upper_limit=1.0\n", + ")\n", + "mass.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior(\n", + " mean=ell_comps[1], sigma=0.3, lower_limit=-1.0, upper_limit=1.0\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Lens-Light Size__\n", + "\n", + "Look at how far the lens light extends from its centre. Its appearance suggests a characteristic scale of around an\n", + "arcsecond, rather than tens of arcseconds.\n", + "\n", + "We use this impression to place a broad prior on the effective radius, centred on 1.0 arcsecond with a standard\n", + "deviation of 0.8 arcseconds.\n", + "\n", + "The effective radius describes the profile\u2019s half-light scale; it is not the visible outer edge of the galaxy. Faint\n", + "light extends beyond the bright region we can easily inspect, so our prior leaves substantial room for the search to\n", + "refine the size.\n", + "\n", + "Truncating the prior at zero excludes negative radii." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "bulge.effective_radius = af.TruncatedGaussianPrior(\n", + " mean=1.0, sigma=0.8, lower_limit=0.0, upper_limit=np.inf\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Light Concentration__\n", + "\n", + "The lens galaxy has a bright central concentration surrounded by fainter, extended light. This appearance motivates\n", + "trying a concentrated S\u00e9rsic profile.\n", + "\n", + "A S\u00e9rsic index near one gives an exponential profile, often used for disks. Higher indices produce a more concentrated\n", + "centre and more extended wings; a value near four is a familiar starting description for elliptical-galaxy light.\n", + "\n", + "We therefore centre the prior on 4.0, with a standard deviation of 1.0. We are using the galaxy\u2019s appearance to choose\n", + "a plausible range, rather than claiming that its S\u00e9rsic index can be measured accurately by eye.\n", + "\n", + "After fitting, we should inspect whether the model reproduces both the central light and the surrounding emission.\n", + "Persistent structure in the residuals may indicate that a single S\u00e9rsic profile is insufficient." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "bulge.sersic_index = af.TruncatedGaussianPrior(\n", + " mean=4.0, sigma=1.0, lower_limit=0.0, upper_limit=np.inf\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Einstein Radius__\n", + "\n", + "Look at the distance between the lens centre and the bright lensed arcs. They lie roughly 1.6 arcseconds from the\n", + "centre, giving us an initial estimate of the lens\u2019s Einstein radius.\n", + "\n", + "For an elliptical lens with external shear, the arcs need not trace a circle of exactly this radius. Their distance\n", + "from the centre nevertheless gives a useful indication of the mass scale.\n", + "\n", + "We centre a Gaussian prior on 1.6 arcseconds, with a standard deviation of 0.2 arcseconds. This directs the search\n", + "towards mass models capable of producing lensed images at approximately the observed separation, while allowing it to\n", + "refine our estimate." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "mass.einstein_radius = af.TruncatedGaussianPrior(\n", + " mean=1.6, sigma=0.2, lower_limit=0.0, upper_limit=np.inf\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Source and Shear Priors__\n", + "\n", + "We could estimate the lens-light properties by looking directly at the foreground galaxy. The source is less\n", + "straightforward: we see its stretched and distorted images, rather than its original appearance.\n", + "\n", + "Inferring its unlensed position, size and shape requires interpreting those images through a mass model. With\n", + "experience, the image configuration can guide these choices, but we will leave the source priors unchanged here.\n", + "\n", + "We also retain the default shear priors. The appearance of the arcs reflects both the lens mass and external shear,\n", + "making their separate contributions difficult to estimate by eye.\n", + "\n", + "Our changes therefore concentrate on quantities for which the image provides a useful initial impression, with the\n", + "assumptions about the mass stated explicitly." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "lens = af.Model(al.Galaxy, redshift=0.5, bulge=bulge, mass=mass)\n", + "\n", + "field = af.Model(\n", + " al.MassField,\n", + " redshift=0.5,\n", + " shear=al.mp.ExternalShear,\n", + ")\n", + "\n", + "source = af.Model(\n", + " al.Galaxy,\n", + " redshift=1.0,\n", + " bulge=al.lp.ExponentialCore,\n", + ")\n", + "\n", + "model = af.Collection(\n", + " galaxies=af.Collection(lens=lens, source=source),\n", + " fields=field,\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Inspecting the Tuned Model__\n", + "\n", + "Print the model summary and inspect its diagram before starting the search.\n", + "\n", + "Connect each changed prior back to the image: the central lens position, its approximate orientation and flattening,\n", + "its light distribution, and the separation of the arcs from the centre.\n", + "\n", + "The model still contains the same physical components and the same number of free parameters. We have changed the\n", + "probability assigned to their values, rather than removed quantities from the fit.\n", + "\n", + "Check that the source and shear priors remain unchanged. This helps us keep track of which assumptions we are testing." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "print(model.info)\n", + "\n", + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Prior-Tuned Fit__\n", + "\n", + "We now repeat the fit using our revised priors.\n", + "\n", + "We use 75 live points for the prior-tuned fit. Our aim is to see whether image-informed priors help us obtain a\n", + "satisfactory fit with less search effort than the 200-live-point setup in Practicalities.\n", + "\n", + "This changes both the priors and the live-point count relative to the 21-live-point experiment, so any improvement\n", + "cannot be attributed to prior tuning alone.\n", + "\n", + "Give this search a separate name so its output can be compared with the original broad-prior fit." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "search = af.Nautilus(\n", + " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", + " name=\"tutorial_3_prior_tuning\",\n", + " unique_tag=dataset_name,\n", + " n_live=75,\n", + " n_batch=50,\n", + " iterations_per_quick_update=2500,\n", + ")\n", + "\n", + "result_custom_priors = search.fit(model=model, analysis=analysis)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Assessing the Improvement__\n", + "\n", + "Plot the new fit and compare it with the original 21-live-point result.\n", + "\n", + "Look first at the lens centre and the lensed arcs. Has the model reproduced their brightness and structure more\n", + "closely? Have coherent patterns in the residuals become smaller?\n", + "\n", + "Compare the maximum log likelihoods too. Because the dataset, mask and likelihood calculation are unchanged, a higher\n", + "value shows that the new search found a model that fits these measurements better.\n", + "\n", + "If the fit improves, we have demonstrated how visual inspection can help guide a search. We have not proved that the\n", + "new priors are uniquely correct or that every relevant solution has been explored.\n", + "\n", + "If it does not improve, inspect where the mismatch remains. The priors may be inappropriate, or the search may still\n", + "need more thorough exploration. Both outcomes are useful evidence for deciding what to try next." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "print(result_custom_priors.info)\n", + "\n", + "aplt.subplot_fit_imaging(\n", + " fit=result_custom_priors.max_log_likelihood_fit\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Prior Tuning: Benefits and Limitations__\n", + "\n", + "Looking at the image helped us identify plausible centres, shapes and scales. Encoding those impressions in the priors\n", + "can reduce the effort spent exploring models that bear little resemblance to the observed lens.\n", + "\n", + "This can improve the reliability and speed of a fit. However, the benefit depends on the quality of our choices: a\n", + "prior that excludes a good solution prevents the search from finding it, however thoroughly it explores.\n", + "\n", + "Some properties are also easier to estimate visually than others. The foreground light is directly visible, whereas the\n", + "source structure and mass distribution must be inferred through the lensing.\n", + "\n", + "Finally, these choices are specific to this image. Inspecting and tuning every lens may be practical for a small study,\n", + "but becomes time-consuming for hundreds or thousands of systems.\n", + "\n", + "We therefore need other ways to make complex models easier to fit." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Reducing Complexity__\n", + "\n", + "Return to the image and consider how much freedom we gave the lens model. Its light and mass can each have their own\n", + "centre, flattening and orientation.\n", + "\n", + "That flexibility allows them to differ, but it also gives the search more combinations to explore. As a simplifying\n", + "experiment, we will require the mass and light to share their centre and elliptical components.\n", + "\n", + "The visible lens light will then help constrain quantities that also determine the lensing. This reduces the number of\n", + "independent parameters, potentially making the model easier to fit.\n", + "\n", + "Sharing these quantities is a physical assumption, not simply a faster way to calculate the same model. It excludes\n", + "lenses whose light and mass have different centres or shapes." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Linking Parameters__\n", + "\n", + "We create fresh light and mass models with their default priors. This removes the prior tuning from the previous\n", + "experiment, so we can examine parameter linking separately.\n", + "\n", + "Setting `mass.centre = bulge.centre` makes the two profiles use the same centre parameters. Setting `mass.ell_comps =\n", + "bulge.ell_comps` does the same for their shapes.\n", + "\n", + "These quantities are still fitted. The search chooses their values, but each choice now applies to both profiles.\n", + "\n", + "This links four pairs of parameters: two centre coordinates and two elliptical components. It therefore removes four\n", + "independent dimensions from the search.\n", + "\n", + "The S\u00e9rsic light profile and isothermal mass profile still have different radial forms. Sharing their centre and shape\n", + "does not make the full mass distribution proportional to the light." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "bulge = af.Model(al.lp.Sersic)\n", + "mass = af.Model(al.mp.Isothermal)\n", + "\n", + "mass.centre = bulge.centre\n", + "mass.ell_comps = bulge.ell_comps" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Inspecting the Simpler Model__\n", + "\n", + "We assemble the lens, source and shear as before, then inspect the model summary and diagram.\n", + "\n", + "Find the shared centre and elliptical components. They should appear as linked quantities rather than separate choices\n", + "for the light and mass.\n", + "\n", + "The source and shear remain free to vary as in the original model. We have simplified one relationship within the lens\n", + "model, rather than fixing the whole lens or changing the observations.\n", + "\n", + "Compare the parameter count with the original model and confirm that it has fallen by four. The diagram is particularly\n", + "useful here: an unintended link can be difficult to spot in a long list of parameters." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "lens = af.Model(al.Galaxy, redshift=0.5, bulge=bulge, mass=mass)\n", + "\n", + "field = af.Model(\n", + " al.MassField,\n", + " redshift=0.5,\n", + " shear=al.mp.ExternalShear,\n", + ")\n", + "\n", + "source = af.Model(\n", + " al.Galaxy,\n", + " redshift=1.0,\n", + " bulge=al.lp.ExponentialCore,\n", + ")\n", + "\n", + "model = af.Collection(\n", + " galaxies=af.Collection(lens=lens, source=source),\n", + " fields=field,\n", + ")\n", + "\n", + "print(model.info)\n", + "\n", + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Fitting the Simpler Model__\n", + "\n", + "We use 75 live points for the reduced-complexity fit. This changes both the model and the live-point count relative to\n", + "the original broad-prior experiment, so any improvement cannot be attributed to parameter linking alone.\n", + "\n", + "After the fit, inspect both the foreground light and the lensed arcs. A satisfactory model must explain both while\n", + "using the shared centre and shape.\n", + "\n", + "In the current simulation, the lens light and mass were given matching centres and elliptical components. This makes it\n", + "a useful controlled example of simplifying a model when the assumption is compatible with the system.\n", + "\n", + "For a real lens, we would not know that in advance. If linking improves a difficult fit, it provides a useful starting\n", + "model; it does not establish that the light and mass truly share the same geometry." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "search = af.Nautilus(\n", + " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", + " name=\"tutorial_3_reducing_complexity\",\n", + " unique_tag=dataset_name,\n", + " n_live=75,\n", + " n_batch=50,\n", + " iterations_per_quick_update=2500,\n", + ")\n", + "\n", + "result_linked = search.fit(model=model, analysis=analysis)\n", + "\n", + "print(result_linked.info)\n", + "\n", + "aplt.subplot_fit_imaging(fit=result_linked.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Reducing Complexity: Benefits and Limitations__\n", + "\n", + "Linking the light and mass centres and shapes reduces the number of quantities the search must determine independently.\n", + "When these assumptions are appropriate, this can make a fit easier and faster.\n", + "\n", + "Unlike priors chosen by inspecting one image, the same linking rule can be applied to many lenses. However, being easy\n", + "to apply does not make it appropriate for every system.\n", + "\n", + "Imagine a lens whose light is elongated in one direction while its mass is oriented differently. Our linked model\n", + "cannot represent that difference. It may reproduce the foreground light but leave structured residuals around the arcs,\n", + "or distort other parameters to compensate.\n", + "\n", + "Inspecting both parts of the image is therefore essential. Even apparently good residuals do not establish that the\n", + "linking assumption is harmless: some biases can be absorbed by other model components.\n", + "\n", + "A simplified model can provide a useful first fit. For scientific measurements, we should also assess what changes when\n", + "its restrictions are relaxed." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__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", + "\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", + "\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", + "\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." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Original Model__\n", + "\n", + "We create fresh model components so that neither the tuned priors nor the parameter links carry over from the previous\n", + "experiments.\n", + "\n", + "Check `model.info` and the diagram carefully. The light and mass should again have independent centres and elliptical\n", + "components, and the priors should match the original broad-prior model.\n", + "\n", + "The dataset, mask and Analysis object remain unchanged. We are giving the search more opportunity to explore the same\n", + "physical model used at the start of this tutorial." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "lens = af.Model(\n", + " al.Galaxy,\n", + " redshift=0.5,\n", + " bulge=al.lp.Sersic,\n", + " mass=al.mp.Isothermal,\n", + ")\n", + "\n", + "field = af.Model(\n", + " al.MassField,\n", + " redshift=0.5,\n", + " shear=al.mp.ExternalShear,\n", + ")\n", + "\n", + "source = af.Model(\n", + " al.Galaxy,\n", + " redshift=1.0,\n", + " bulge=al.lp.ExponentialCore,\n", + ")\n", + "\n", + "model = af.Collection(\n", + " galaxies=af.Collection(lens=lens, source=source),\n", + " fields=field,\n", + ")\n", + "\n", + "print(model.info)\n", + "\n", + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__More Thorough Search__\n", + "\n", + "Run Nautilus with 300 live points, keeping the batch size and output-update frequency unchanged.\n", + "\n", + "Watch the saved fit images as the search progresses. Early models may explain only part of the image; allow the search\n", + "to finish before comparing its final result with the earlier fits.\n", + "\n", + "More live points improve the opportunity for exploration, but do not guarantee that every important solution is found.\n", + "We still judge the result through the image comparison, inferred parameters and consistency with other searches." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "search = af.Nautilus(\n", + " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", + " name=\"tutorial_3_search_more_thoroughly\",\n", + " unique_tag=dataset_name,\n", + " n_live=300,\n", + " n_batch=50,\n", + " iterations_per_quick_update=2500,\n", + ")\n", + "\n", + "result_thorough = search.fit(model=model, analysis=analysis)\n", + "\n", + "print(result_thorough.info)\n", + "\n", + "aplt.subplot_fit_imaging(fit=result_thorough.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Comparing the Approaches__\n", + "\n", + "Compare the fitted images and normalised residuals from the different searches. Look at the central lens light and the\n", + "arcs separately: an improvement in one region can reveal a remaining mismatch elsewhere.\n", + "\n", + "Then compare the maximum log likelihoods and inferred parameters. The dataset and likelihood calculation are unchanged,\n", + "so the likelihood values tell us which returned models fit these measurements better. They do not, by themselves,\n", + "establish which modeling assumptions are scientifically preferable.\n", + "\n", + "Keep the changes made in each experiment in mind:\n", + "\n", + "| Fit | Priors and model | Live points |\n", + "|---|---|---:|\n", + "| Deliberately under-resourced | Original priors and independent parameters | 21 |\n", + "| Prior tuning | Image-informed priors; parameters remain independent | 75 |\n", + "| Reduced complexity | Default priors; linked light and mass geometry | 75 |\n", + "| More thorough search | Original priors and independent parameters | 300 |\n", + "\n", + "The prior-tuned and reduced-complexity fits change both the modeling choices and the number of live points relative to\n", + "the first experiment. Any improvement therefore cannot be attributed to prior tuning or parameter linking alone.\n", + "\n", + "Agreement between satisfactory fits increases our confidence, while differences tell us what needs investigation. For\n", + "example, a shift in the inferred mass parameters after removing the light\u2013mass links would make those assumptions worth\n", + "examining more closely.\n", + "\n", + "**\ud83e\udd16 Ask AI:** My linked and independent light\u2013mass models both produce small residuals, but infer different mass\n", + "parameters. What comparisons would help me assess whether the linking assumption affects my scientific conclusions?" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "for label, fit_result in [\n", + " (\"Less thorough\", result),\n", + " (\"Practicalities\", result_reference),\n", + " (\"Prior tuning\", result_custom_priors),\n", + " (\"Reduced complexity\", result_linked),\n", + " (\"More thorough\", result_thorough),\n", + "]:\n", + " print(label, fit_result.max_log_likelihood_fit.log_likelihood)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Benefits and Weaknesses__\n", + "\n", + "Each approach helps the search in a different way, and each has a cost.\n", + "\n", + "| Approach | Benefits | Weaknesses |\n", + "|---|---|---|\n", + "| **Prior tuning** | Uses our interpretation of the image to guide exploration towards plausible solutions. Can make fitting faster and more reliable. | Incorrect priors can exclude good solutions or bias inference. Some parameters are difficult to estimate visually, and tailoring priors for every lens becomes time-consuming for large samples. |\n", + "| **Reducing complexity** | Fewer independent parameters can make the model easier to fit. The same simplifying rule can be applied across many lenses. | The assumptions may exclude real differences between components. A simpler model can produce biased parameters, even when its residuals look acceptable. |\n", + "| **Searching more thoroughly** | Easy to configure and retains the original model\u2019s flexibility and priors. Does not require additional assumptions about this particular lens. | Requires more computation and may become impractical for demanding models. More searching cannot compensate for a model that cannot describe the data. |\n", + "\n", + "The appropriate choice depends on what the image and previous fits tell us. A clear visual estimate may justify tuning\n", + "a prior; a useful physical approximation may justify simplifying the model. When the existing model and priors are\n", + "appropriate, more thorough exploration may be the best next step." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Run Times__\n", + "\n", + "Compare the time taken by the fits alongside their results. A quick search is useful only if its output is adequate for\n", + "the question we want to answer.\n", + "\n", + "Prior tuning leaves the model\u2019s image calculation largely unchanged, but can reduce the exploration needed to find good\n", + "solutions. Linking parameters reduces the number of independent quantities being searched, while retaining the same\n", + "light and mass profiles. Increasing the number of live points generally requires more evaluations.\n", + "\n", + "The first two approaches therefore aim to make the search\u2019s task easier; the third gives it more resources.\n", + "\n", + "Our tuned-prior and reduced-complexity fits each used 75 live points, compared with 300 for the more thorough search.\n", + "Their elapsed times reflect both the modeling choices and these different search settings.\n", + "\n", + "Compilation and output also contribute to the elapsed time, as discussed in *Practicalities*. Treat these runs as\n", + "examples of the trade-offs on your computer, rather than universal speed comparisons." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Model Mismatch__\n", + "\n", + "So far, our simulated data have been described by the same profile families used in the unrestricted model. This gives\n", + "the search an opportunity to reproduce the image to the noise level.\n", + "\n", + "Real galaxies are less accommodating. Imagine that the source contains a bright star-forming knot, but our model allows\n", + "only one smooth exponential light profile. The fitted arc might reproduce the overall brightness distribution while\n", + "leaving a compact feature in the residuals.\n", + "\n", + "Searching longer cannot give that smooth profile a feature it does not possess. Even the highest-likelihood solution\n", + "available within this model may leave significant residuals.\n", + "\n", + "Similar problems arise if the lens light contains a disk or other structure missing from its S\u00e9rsic description.\n", + "Incorrect assumptions about the PSF, noise or contaminating objects can also produce mismatches.\n", + "\n", + "We must therefore distinguish **an inadequately explored model** from **an inadequate description of the\n", + "observations**. The residual image helps us investigate this distinction, although it rarely identifies the cause on\n", + "its own." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Wrap Up__\n", + "\n", + "More realistic lens models give us greater freedom to explain an image, but that freedom makes fitting harder. We have\n", + "explored three responses: use visual information to guide priors, simplify the model through explicit assumptions, or\n", + "search more thoroughly.\n", + "\n", + "Each can help, but none removes the need to inspect the fit and question its assumptions.\n", + "\n", + "These trade-offs are a major reason why **search chaining is central to practical lens modeling**. It helps us balance\n", + "model realism, reliable fitting and manageable run times, drawing on the strengths of the approaches above.\n", + "\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." + ] + } + ], + "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_3_why_modeling_is_hard.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_4_dealing_with_failure.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.ipynb deleted file mode 100644 index 62d2ebb..0000000 --- a/notebooks/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.ipynb +++ /dev/null @@ -1,898 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 4: Dealing With Failure\n", - "================================\n", - "\n", - "In the previous tutorial we intentionally made our non-linear search infer a local maxima solution and therefore return\n", - "a physically incorrect lens model. In this tutorial, we will pretend that we have modeled our lens and inferred a local\n", - "maxima. We introduce three approaches one can take that changes how we fit the model, all of which have the aim of\n", - "ensuring we infer the global maxima:\n", - "\n", - " 1) Prior Tuning: Tell the non-linear search where to search parameter space.\n", - " 2) Reduce Complexity: Fit a lens model with fewer parameters and therefore a simpler parameter space.\n", - " 3) Look Harder: Brute force a global maxima by telling the non-linear search to sample parameter space more thoroughly.\n", - "\n", - "Each approach has its benefits and disadvantages and we will discuss them in detail.\n", - "\n", - "In the previous tutorial, when we inferred a local maxima we knew that we had done so. For modeling a real lens,\n", - "we do not know the true lens model and it may be unclear if the solution we infered is a global or local maxima. The\n", - "methods we learn in this tutorial are therefore equally important for verifying that a solution that looks like a\n", - "global maxima solution is in indeed the global maxima.\n", - "\n", - "__Contents__\n", - "\n", - "- **Initial Setup:** we'll use the same strong lensing data as the previous tutorial, 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", - "- **Prior Tuning:** First, we will try to assist our non-linear search by tuning our priors.\n", - "- **Run Time:** Profiling the expected run time of the model-fit.\n", - "- **Result:** Overview of the results of the model-fit.\n", - "- **Discussion:** By tuning our priors to the specific lens model we are fitting, we increase the chances of finding.\n", - "- **Approach 2: Reducing Complexity:** Simplify the lens model, for example by assuming light-traces-mass.\n", - "- **Approach 3: Look Harder:** Brute force the global maxima with more thorough non-linear search settings.\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 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`." - ] - }, - { - "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": [ - "if al.util.dataset.should_simulate(str(dataset_path)):\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulator/lens_sersic.py\"],\n", - " check=True,\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", - "we'll create and use a smaller 2.6\" `Mask2D` again." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "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)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "When plotted, the lens light`s is clearly visible in the centre of the image." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_imaging_dataset(dataset=dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Prior Tuning__\n", - "\n", - "First, we will try to assist our non-linear search by tuning our priors. Priors guide the non-linear search on where \n", - "to look in the parameter space. By setting our priors more accurately ('tuning' them), we can help the search find the \n", - "global solution instead of getting stuck at a local maxima.\n", - "\n", - "In a previous tutorial, we learned how to fully customize priors. Let's apply this knowledge \n", - "now. I've set up a custom search below with priors adjusted to give the non-linear search a better chance of finding \n", - "the global maxima solution. I'll also explain how each prior has been changed from the default values specified in\n", - " the `config/priors` configuration files.\n", - "\n", - "We will call our lens and source galaxies `lens` and `source` this time, for shorter more readable code.\n", - "\n", - "In a previous tutorial, we customized the priors of a model by creating a `Galaxy` as a `Model` and customizing each\n", - "prior:" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "lens = af.Model(al.Galaxy, redshift=0.5, mass=al.mp.IsothermalSph)\n", - "lens.mass.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", - "lens.mass.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can alternatively create the light and mass profiles as a `Model` and customize their parameters, and then pass them\n", - "to the model galaxy and overall model. These two approaches are equivalent, but in this example the style below \n", - "provides more concise and readable code. We will therefore switch to this code style in this tutorial, but may swap \n", - "back and forth between the two styles throughout **HowToLEns** depending on what is more readable." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge = af.Model(al.lp.Sersic)\n", - "mass = af.Model(al.mp.Isothermal)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "By default, the prior on the $(y,x)$ coordinates of a `LightProfile` / `MassProfile` is a TruncatedGaussianPrior with \n", - "`mean=0.0` and `sigma=0.3`. However, visual inspection of our strong lens image tells us that its centre (based on the\n", - "lens galaxy's luminous emission) is at x = 0.0\" and y = 0.0\", so lets reduce the `sigma` value on this prior so the\n", - "non-linear search looks over a very narrow range of `centre` values in parameter space." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge.centre.centre_0 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05)\n", - "bulge.centre.centre_1 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05)\n", - "mass.centre.centre_0 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05)\n", - "mass.centre.centre_1 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "By default, the elliptical components of the of our lens galaxy's elliptical `LightProfile` are `GaussianPrior`'s \n", - "with `mean=0.0` and `sigma=0.5`. Note that the solution `ell_comps=(0.0, 0.0)` corresponds to a spherical system\n", - "and that all physical solutions (e.g. with axis-ratios running from 0.0 -> 1.0 and position angles 0.0 -> 180.0 degrees) \n", - "are encapsulated for solutions where each component runs from -1.0 -> 1.0). \n", - "\n", - "However, through visual inspection of the image we can often determine the position angle of the lens's light, which \n", - "for this data is clearly 45.0 degrees counter-clockwise from the x-axis. We can update the priors on our elliptical \n", - "components to reflect this. The `lower_limit` and `upper_limit` on a `GaussianPrior` ensure the solutions cannot go\n", - "outside the physically plausible range -1.0 -> 1.0." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior(\n", - " mean=0.333333, sigma=0.1, lower_limit=-1.0, upper_limit=1.0\n", - ")\n", - "bulge.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior(\n", - " mean=0.0, sigma=0.1, lower_limit=-1.0, upper_limit=1.0\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Lets also assume that the ellipticity of the light profile can be used as a prior on that of the mass profile. This may \n", - "not be strictly true (e.g. because of dark matter) so we will use a wider prior, such that the non-linear search can \n", - "change the mass model's ellipticity from that of the light if fitting the data necessitates it." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mass.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior(\n", - " mean=0.333333, sigma=0.3, lower_limit=-1.0, upper_limit=1.0\n", - ")\n", - "mass.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior(\n", - " mean=0.0, sigma=0.3, lower_limit=-1.0, upper_limit=1.0\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `effective_radius` of light profile is its 'half-light' radius, the radius at which 50% of its total luminosity \n", - "is internal to a circle defined within that radius. **PyAutoLens** assumes a `UniformPrior` on this quantity between \n", - "0.0\" and 30.0\". This large range of values is required to cover the size of all possible strong lenses that can be \n", - "observed in the Universe.\n", - "\n", - "However, inspection of this image shows the lens's light does not extend anywhere near 30.0\", so lets reduce it." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge.effective_radius = af.TruncatedGaussianPrior(\n", - " mean=1.0, sigma=0.8, lower_limit=0.0, upper_limit=np.inf\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `sersic_index` defines how concentrated the light profile is. In galaxy structure studies, values of Sersic index\n", - "around 1.0 indicate a disk galaxy, whereas higher values of 3 or 4 indicate an elliptical galaxy. **PyAutoLens**\n", - "assumes a `UniformPrior` between 0.8 and 8.0 by default on this parameter, as a user could model strong lenses\n", - "where the lens is of any morphology.\n", - "\n", - "We often have knowledge of the lens's morphology before we fit it, so in this example we will assume our lens is\n", - "a massive elliptical galaxy with a `sersic_index` near 4." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge.sersic_index = af.TruncatedGaussianPrior(\n", - " mean=4.0, sigma=1.0, lower_limit=0.0, upper_limit=np.inf\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Finally, the `ring` that the lensed source forms clearly has a radius of about 1.6\". This is its Einstein radius, so \n", - "lets change the prior from a UniformPrior between 0.0\" and 4.0\"." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mass.einstein_radius = af.TruncatedGaussianPrior(\n", - " mean=1.6, sigma=0.2, lower_limit=0.0, upper_limit=np.inf\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now compose the overall model, where the lens galaxy model uses the `Model` components above which had their\n", - "priors customizes.\n", - "\n", - "In this exercise, I'm not going to change any priors on the source galaxy. Whilst lens modeling experts can look at a \n", - "strong lens and often tell you roughly where the source-galaxy is located (in the source-plane), it is something of art \n", - "form. Furthermore, the source's morphology can be pretty complex, making it difficult to come up with a good source \n", - "prior!" - ] - }, - { - "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.ExponentialCore)\n", - "\n", - "model = 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, including the priors specified above." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(model.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 model has twenty free parameters against the six of tutorial 1, which is why this fit is so much harder.\n", - "Note also that it uses *ordinary* light profiles rather than the linear ones we have been using, so the search\n", - "has to sample each `intensity` itself. Tutorial 5 will take those two dimensions back." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "af.ModelPlotter(model).figure()" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can now create this custom search and run it. Our non-linear search will now start by sampling higher likelihood \n", - "regions of parameter space, given our improved and more informed priors." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search = af.Nautilus(\n", - " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", - " name=\"tutorial_4_custom_priors\",\n", - " unique_tag=dataset_name,\n", - " n_live=150,\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", - "The run time of the `log_likelihood_function` is around the usual value. \n", - "\n", - "Due to prior tuning, the model-fit should take less than 10000 iterations per free parameter to converge.\n", - "\n", - "Run the non-linear search." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(\n", - " \"The non-linear search has begun running - checkout the output/howtolens/chapter_2/tutorial_4_custom_priors\"\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_custom_priors = search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"Search has finished run - you may now continue the notebook.\")\n", - "\n", - "print(result_custom_priors.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Result__\n", - "\n", - "Bam! We get a good model, which corresponds to the global maxima. By giving our non-linear search a helping hand and \n", - "informing it of where to sample parameter space, we can increase the odds that we find the global maxima solution." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_fit_imaging(fit=result_custom_priors.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Discussion__\n", - "\n", - "By tuning our priors to the specific lens model we are fitting, we increase the chances of finding the global maxima. \n", - "This approach can also speed up the search, as it spends less time in regions of parameter space that do not \n", - "correspond to good solutions.\n", - "\n", - "Before moving on to the next approach, let\u2019s consider the pros and cons of prior tuning:\n", - "\n", - "**Advantages:**\n", - "\n", - "- Higher likelihood of finding the global maximum log likelihood solutions in parameter space.\n", - "\n", - "- Faster search times, as the non-linear search explores less of the parameter space.\n", - "\n", - "**Disadvantages:**\n", - "\n", - "- Incorrectly specified priors could lead the non-linear search to an incorrect solution.\n", - "\n", - "- It is not always clear how the priors should be tuned, especially for complex lens models.\n", - "\n", - "- Priors tailored to a specific lens need customization for each fit. For large samples of lenses, \n", - "this process would be very time-consuming.\n", - "\n", - "__Approach 2: Reducing Complexity__\n", - "\n", - "The non-linear search may fail because the lens model is too complex, making its parameter space too difficult to \n", - "sample accurately. To address this, we can simplify the lens model while ensuring it remains realistic enough for \n", - "our scientific study. By making certain assumptions, we can reduce the number of model parameters, thereby lowering \n", - "the dimensionality of the parameter space and improving the search's performance." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge = af.Model(al.lp.Sersic)\n", - "mass = af.Model(al.mp.Isothermal)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First, we create a search that assumes that light-traces-mass. That is, the light profile centre and elliptical \n", - "components are perfectly aligned with the centre and elliptical components of the mass profile. This may, or may \n", - "not, be a reasonable assumption, but it`ll remove 4 parameters from the lens model (the centre and elliptical \n", - "components of the mass profile), so it is worth trying!\n", - "\n", - "To apply our assumption that light traces mass to the model, we `pair` the `centre` and `ell_comps` parameters \n", - "by setting them equal to one another. This removes the parameter on the left-hand side of the pairing from the lens \n", - "model such that when a model is created it has the same value as the parameter on the right-hand side." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mass.centre = bulge.centre\n", - "mass.ell_comps = bulge.ell_comps" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now compose the model, which will have a non-linear parameter space with 4 less dimensions than the fit performed\n", - "previously. " - ] - }, - { - "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.ExponentialCore)\n", - "\n", - "model = 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, including the parameter links specified above." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(model.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `mass \u00b7 Isothermal`'s `centre` and `ell_comps` are no longer free parameters of their own: each is tied to\n", - "the matching parameter of the `bulge \u00b7 Sersic`. That pairing *is* the light-traces-mass assumption, and it takes\n", - "the model from twenty free parameters down to sixteen.\n", - "\n", - "Pairing parameters is easy to get subtly wrong and hard to spot in a long `info` listing." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "af.ModelPlotter(model).figure()" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now create this search and run it." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search = af.Nautilus(\n", - " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", - " name=\"tutorial_4_reducing_complexity\",\n", - " unique_tag=dataset_name,\n", - " n_live=200,\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", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Run Time__\n", - "\n", - "The run time of the `log_likelihood_function` is around the usual value. \n", - "\n", - "Due to the simplest model parameterization, the model-fit should take less than 10000 iterations per free parameter to \n", - "converge.\n", - "\n", - "Run the non-linear search." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(\n", - " \"The non-linear search has begun running - checkout the output/howtolens/chapter_2/tutorial_4_reducing_complexity\"\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_light_trace_mass = search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"Search has finished run - you may now continue the notebook.\")\n", - "\n", - "print(result_light_trace_mass.info)\n", - "\n", - "aplt.subplot_fit_imaging(fit=result_light_trace_mass.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Result__\n", - "\n", - "The results look pretty good. Our source galaxy fits the data pretty well and we've clearly inferred a model that \n", - "looks similar to the one above. However, inspection of the residuals shows that the fit was not quite as good as the \n", - "first search.\n", - "\n", - "It turns out that for this simulated lens, light did not perfectly trace mass. The quality of the fit suffered and the \n", - "highest value of log likelihood the search inferred was lower as a result.\n", - "\n", - "Herein lies the pitfalls of making assumptions, they may make your model less realistic and your fits worse! \n", - "\n", - "__Discussion__\n", - "\n", - "Let\u2019s consider the advantages and disadvantages of simplifying the model:\n", - "\n", - "Advantages:\n", - "\n", - "- By reducing the complexity of the parameter space, we increase the chances of finding the global maximum log \n", - "likelihood, and the search requires less time to do so.\n", - "\n", - "- Unlike with tuned priors, this approach is not specific to a single lens, allowing us to use it on many strong lens \n", - "images.\n", - "\n", - "Disadvantages:\n", - "\n", - "- Our model is less realistic, which may negatively impact the accuracy of our fit and the scientific results we\n", - "derive from it.\n", - "\n", - "__Approach 3: Look Harder__\n", - "\n", - "In approaches 1 and 2, we assisted our non-linear search to find the highest log likelihood regions of parameter \n", - "space. In approach 3, we're simply going to tell it to \"look harder.\"\n", - "\n", - "Every non-linear search has settings that control how thoroughly it explores parameter space. One such setting is the \n", - "number of live points used by `Nautilus`. The more thoroughly the search examines the space, the more likely it is to \n", - "find the global maximum lens model. However, this also means the search will take longer!\n", - "\n", - "Below, we configure a more thorough Nautilus search with `n_live=300`. These settings and what they change are\n", - "discussed in the optional tutorial `chapter_optional/tutorial_searches.ipynb`." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "lens = af.Model(\n", - " al.Galaxy,\n", - " redshift=0.5,\n", - " bulge=al.lp.Sersic,\n", - " mass=al.mp.Isothermal,\n", - ")\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.ExponentialCore)\n", - "\n", - "model = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n", - "\n", - "search = af.Nautilus(\n", - " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", - " name=\"tutorial_4_look_harder\",\n", - " unique_tag=dataset_name,\n", - " n_live=300,\n", - " iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Run Time__\n", - "\n", - "The run time of the `log_likelihood_function` is around the usual value. \n", - "\n", - "Due to the more thorough Nautilus settings, the the model-fit should take more than 10000 iterations per free parameter \n", - "to converge and thus take longer than we are used too.\n", - "\n", - "Run the non-linear search." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(\n", - " \"The non-linear search has begun running - checkout the output/howtolens/chapter_2/tutorial_4_look_harder\"\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_look_harder = search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"Search has finished run - you may now continue the notebook.\")\n", - "\n", - "print(result_look_harder.info)\n", - "\n", - "aplt.subplot_fit_imaging(fit=result_look_harder.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Let's list the advantages and disadvantages of simply adjusting the non-linear search:\n", - "\n", - "**Advantages:**\n", - "\n", - "- It\u2019s easy to set up; just change the settings of the non-linear search.\n", - "\n", - "- It generalizes to any strong lens.\n", - "\n", - "- We can retain a more complex lens model.\n", - "\n", - "**Disadvantage:**\n", - "\n", - "- It can be very expensive in terms of time. For very complex models, the run times can extend to hours, days, \n", - "weeks, or even months!\n", - "\n", - "In conclusion, we can now fit strong lenses effectively. When the process fails, we know how to make it work.\n", - "In tutorials 9 and 10 of this chapter, we will introduce a technique called 'non-linear search chaining', which performs\n", - "a model fit by chaining together multiple searches back-to-back. This allows us to combine the 3 different approaches\n", - "discussed and exploit the advantages of each, whilst not being hindered by their disadvantages.\n", - "\n", - "With search chaining, we can:\n", - "\n", - " - Fit simpler models with lower dimensionality parameter spaces in the earlier searches and gradually increase the\n", - " lens model complexity search-by-search, guiding the model-fit to a sufficiently realistic lens model. \n", - " \n", - " - In these earlier searches (with easier to sample parameter spaces), use fast non-linear search settings to compute \n", - " the results quickly and switch to slower settings in later searches when we fit more complex lens models.\n", - "\n", - " - Use 'prior passing' to setup the priors of each parameter in the later searches, based on the lens models inferred \n", - " by the earlier searches. We can therefore guide each search on how to sample a complex lens model's parameter space \n", - " in a way that can be fully generalized to any strong lens.\n", - " \n", - "__Wrap Up__\n", - "\n", - "Before we get to search chaining, we have a few more tutorials, where we will discuss masking in more detail, the\n", - "`Result` object and how to make **PyAutoLens** run faster." - ] - } - ], - "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_4_dealing_with_failure.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_debug_fit_failure\n\n---\nname: al_debug_fit_failure\ndescription: Diagnose a non-linear search that didn't converge, returned unphysical parameters, or produced an inversion that fitted noise rather than signal. Walks the canonical post-mortem checks \u2014 log inspection, residual maps, prior coverage, multimodality, inversion regularisation, position penalties \u2014 and proposes targeted fixes (tighten priors, switch search, add positions, increase live points). Use after `al_run_search` returns a result that looks wrong.\n---\n\n# Debugging a fit that went wrong\n\nA finished search isn't automatically a successful one. PyAutoFit will return a\n`Result` regardless of whether the posterior is sensible. This skill walks the user\nthrough the symptom \u2192 diagnosis \u2192 fix loop for common lens-fit failures.\n\nReference reading: `autolens_workspace:scripts/guides/modeling/bug_fix.py`.\n\n## Ask\n\nBefore diagnosing, get the user to describe the failure mode:\n\n- *\"Did the search complete, or did it crash with an exception?\"* \u2014 different\n branches.\n- *\"What looks wrong \u2014 the residuals, the parameter values, the chi-squared, the\n source reconstruction?\"* \u2014 picks the diagnostic.\n- *\"Have you compared against an `PYAUTO_TEST_MODE=1` smoke run?\"* \u2014 sometimes the\n symptom is just a bug in the script that the smoke test would have caught.\n\n## Branch \u2014 search crashed mid-run\n\nRead the search log: `output//.../search.log`. Common causes:\n\n- **Likelihood evaluation crashed.** Read the traceback. Often a profile parameter\n has gone unphysical (negative effective radius, zero einstein radius). Tighten the\n prior bounds with `af.UniformPrior(lower_limit=..., upper_limit=...)`.\n- **Numba cache write failure.** Set `NUMBA_CACHE_DIR=/tmp/numba_cache` and rerun.\n- **JAX out-of-memory.** Reduce `n_live`, mask radius, or pixelisation resolution; or\n disable JAX for this run.\n\n## Branch \u2014 search completed but residuals are huge\n\nLoad the result and look at the fit (same pattern as\n[`al_load_results`](./al_load_results.md) \u2014 load the max-log-likelihood tracer from\nJSON, reload the dataset, rebuild the fit):\n\n```python\nfrom pathlib import Path\nfrom autonerves.dictable import from_json\nimport autolens as al\nimport autolens.plot as aplt\n\nout = Path(\"output/imaging///\")\ntracer = from_json(file_path=out / \"files\" / \"tracer.json\")\n\n# Reload the dataset exactly as the fit script did (path, pixel_scales, mask).\ndataset = ... # see al_prepare_imaging_data\n\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\naplt.subplot_fit_imaging(\n fit=fit, output_path=\"scripts/scratch/debug/\", output_filename=\"fit\",\n output_format=\"png\",\n)\n```\n\nLook at the residual map. Common signatures:\n\n- **Mass model off-axis.** Residuals form a \"double-image\" pattern where the model\n positions don't match the data positions. Fix: add image positions and a\n `PositionsLH` (see `al_run_slam_pipeline` for the pattern).\n- **Source too constrained.** The source reconstruction looks like a single Sersic\n but the data shows a complex arc. Fix: switch to a pixelised source via\n [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md).\n- **Lens light leaking into source plane.** Residuals show systematic structure at\n the lens centre. Fix: add or refine the lens light model.\n\n## Branch \u2014 search completed but converged to a clearly wrong mode\n\nSymptoms: parameter posteriors are tight but at unphysical values (einstein radius\n~0.01\", lens at the edge of the mask, source at the lens centre).\n\n- **Multi-modal posterior, picked the wrong mode.** Switch to or rerun with more live\n points: `af.Nautilus(n_live=400)`. Nested sampling handles multimodality better\n than MCMC.\n- **Prior pulling the search into a bad region.** Widen or recentre priors on the\n parameters that look wrong. Inspect with `model.info` before fitting.\n- **Mask cropping out part of the lensed signal.** Widen the mask radius and refit.\n\n## Branch \u2014 pixelised source looks like noise\n\nThe inversion has over-fitted background noise into the source plane.\n\n- **Regularisation too low.** Bump the regularisation coefficient range \u2014 see\n `PyAutoArray:autoarray/inversion/regularization/`. The `ConstantSplit` regularisation\n with sensible coefficients usually works.\n- **No positions penalty.** Add a `PositionsLH` to prevent the inversion from\n demagnifying the source into infinity.\n- **Pixelisation grid too fine.** Coarsen the `mesh_shape` (e.g. from (50, 50) to\n (30, 30)).\n\n[`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\ncovers regularisation and pixelisation theory.\n\n## Branch \u2014 fit looks fine but evidence is much worse than a competing model\n\nThe fit may have converged to a local maximum. Run again with different priors or\na different `unique_tag` so the search starts fresh, and compare evidences.\n\n## Generic fixes that often help\n\n- **Add positions.** `al.PositionsLH` (with the user's measured image\n positions) eliminates a large class of mass-model failures.\n- **Tighten the prior on the lens centre.** It's often the parameter with the worst\n multi-modality.\n- **Smoke-test with `PYAUTO_TEST_MODE=1`** to confirm there's no scripting bug masquerading\n as a fit bug.\n- **Run with a coarser model first** (single Sersic source, SIE mass) before adding\n pixelisations. Use [`al_chain_searches`](./al_chain_searches.md) to chain.\n\n## Combine\n\nOnce you've identified the issue, the fix usually means re-running with adjusted\ninputs \u2014 [`al_run_search`](./al_run_search.md) \u2014 and re-loading the new result \u2014\n[`al_load_results`](./al_load_results.md). If the diagnosis was wrong, iterate.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Recovering from local maxima](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.ipynb):\n the three canonical recoveries \u2014 prior tuning, multi-start, model simplification.\n- **General reference** \u2014 [RTD: Demagnified solutions](https://pyautolens.readthedocs.io/en/latest/general/demagnified_solutions.html):\n how unphysical demagnified-source reconstructions arise in pixelised fits, and how\n `PositionsLH` penalties prevent them.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n inspecting an inferred model via `Tracer` \u2014 the patterns this skill uses to\n pull apart a failed fit.\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_4_linear_profiles.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_4_linear_profiles.ipynb new file mode 100644 index 0000000..f7cf75f --- /dev/null +++ b/notebooks/chapter_2_lens_modeling/tutorial_4_linear_profiles.ipynb @@ -0,0 +1,976 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Tutorial 4: Linear Profiles\n", + "===========================\n", + "\n", + "In the previous tutorial, we made a lens model easier to fit by tuning priors, linking parameters or searching more\n", + "thoroughly. Each approach involved a trade-off between flexibility, assumptions and computation.\n", + "\n", + "Linear light profiles offer another possibility: reduce the number of parameters explored by the non-linear search\n", + "while retaining the same light-profile shapes.\n", + "\n", + "Their intensities are still fitted to the data, but are calculated using linear algebra for each proposed model.\n", + "Nautilus can therefore concentrate on the remaining parameters.\n", + "\n", + "We briefly used a linear source profile in Tutorial 1. Here, we examine how this works, then combine many linear\n", + "profiles to describe more detailed light distributions without introducing a separate non-linear intensity parameter\n", + "for each one.\n", + "\n", + "__Contents__\n", + "\n", + "- **Overview**\n", + "- **Dataset and Mask**\n", + "- **Linear Light Profiles**\n", + "- **Why This Helps**\n", + "- **Model**\n", + "- **Search and Run Time**\n", + "- **Result**\n", + "- **Intensities**\n", + "- **Visualisation**\n", + "- **Basis**\n", + "- **A First Gaussian Basis**\n", + "- **Evaluating the Basis**\n", + "- **Inspecting the Basis Fit**\n", + "- **Lens MGE**\n", + "- **Source MGE**\n", + "- **Combined Model**\n", + "- **Inspecting the Model**\n", + "- **Model Fit**\n", + "- **Multi-Gaussian Expansion Benefits**\n", + "- **Benefits Have Costs**\n", + "- **Positive Intensities**\n", + "- **Other Basis Functions**\n", + "- **Wrap Up**" + ] + }, + { + "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": "markdown", + "metadata": {}, + "source": [ + "__Overview__\n", + "\n", + "We first replace the ordinary lens and source light profiles with their linear equivalents. We will inspect the model,\n", + "run the fit and retrieve the intensities calculated during the analysis.\n", + "\n", + "We then combine Gaussian light profiles of different sizes into a **multi-Gaussian expansion**, or **MGE**. Their\n", + "summed light can describe a wider range of radial structures than a single profile.\n", + "\n", + "The key idea is to separate the parameters that require non-linear exploration from the intensities that can be solved\n", + "together for each proposed model." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Dataset and Mask__\n", + "\n", + "We use the same `lens_sersic` dataset as before. Look again at the bright central lens galaxy and the lensed source\n", + "around it: both contribute light that our model must reproduce.\n", + "\n", + "We retain the 2.5-arcsecond circular mask used in the preceding tutorials. The observations and selected pixels are\n", + "unchanged; this time, we change how the model\u2019s light-profile intensities are determined.\n", + "\n", + "The following code loads the dataset, generating it if necessary, applies the mask and plots the image." + ] + }, + { + "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", + "import numpy as np\n", + "\n", + "dataset_name = \"lens_sersic\"\n", + "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name\n", + "\n", + "if al.util.dataset.should_simulate(str(dataset_path)):\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.run([sys.executable, \"scripts/simulator/lens_sersic.py\"], check=True)\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)\n", + "\n", + "mask_radius = 2.5\n", + "mask = al.Mask2D.circular(\n", + " shape_native=dataset.shape_native,\n", + " pixel_scales=dataset.pixel_scales,\n", + " radius=mask_radius,\n", + ")\n", + "dataset = dataset.apply_mask(mask=mask)\n", + "aplt.subplot_imaging_dataset(dataset=dataset)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Linear Light Profiles__\n", + "\n", + "Imagine holding a light profile\u2019s centre, size and shape fixed, then doubling its intensity. Its predicted brightness\n", + "doubles at every point, without changing its shape.\n", + "\n", + "The same scaling holds after ray tracing through a fixed mass model and blurring by the PSF. This simple relationship\n", + "is what makes the intensity a **linear parameter**.\n", + "\n", + "For a proposed set of profile shapes and mass parameters, we can therefore calculate the intensities that best\n", + "reproduce the image using linear algebra. This calculation is often called an **inversion**.\n", + "\n", + "The lens and source intensities are solved together, accounting for the fact that their light overlaps in the observed\n", + "image.\n", + "\n", + "The calculation is repeated whenever the non-linear search proposes different parameter values. The intensities are\n", + "fitted quantities, not fixed numbers chosen in advance." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Why This Helps__\n", + "\n", + "With ordinary light profiles, Nautilus must explore intensity alongside parameters such as effective radius and S\u00e9rsic\n", + "index. Different combinations can produce similar images, making these relationships difficult to explore.\n", + "\n", + "With linear light profiles, each proposed combination of the remaining parameters is evaluated using its best-fitting\n", + "intensities, subject to the solver\u2019s constraints. Nautilus no longer needs to search along the intensity dimensions\n", + "itself.\n", + "\n", + "In our example, this removes two dimensions from the non-linear search: one intensity for the lens light and one for\n", + "the source light. The S\u00e9rsic and exponential profile shapes remain available, so we have not simplified the physical\n", + "description in the way that linking light and mass did.\n", + "\n", + "This does not remove the underlying relationships between brightness, size and shape. It changes how we handle them\n", + "computationally, often making the non-linear exploration easier.\n", + "\n", + "The benefit becomes particularly useful when we combine many light profiles: their intensities can be solved together\n", + "rather than adding a new search dimension for every profile." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Model__\n", + "\n", + "We replace the lens and source light profiles with their equivalents from `al.lp_linear`.\n", + "\n", + "The lens still has a S\u00e9rsic light profile and an elliptical isothermal mass profile, alongside external shear. The\n", + "source still has an exponential light profile. Their physical roles are unchanged.\n", + "\n", + "Using `al.lp_linear` tells the analysis to solve the two light-profile intensities whenever it evaluates a proposed\n", + "model. The other free parameters remain the responsibility of Nautilus." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "bulge = af.Model(al.lp_linear.Sersic)\n", + "mass = af.Model(al.mp.Isothermal)\n", + "\n", + "lens = af.Model(al.Galaxy, redshift=0.5, bulge=bulge, mass=mass)\n", + "\n", + "field = af.Model(\n", + " al.MassField,\n", + " redshift=0.5,\n", + " shear=al.mp.ExternalShear,\n", + ")\n", + "\n", + "source = af.Model(\n", + " al.Galaxy,\n", + " redshift=1.0,\n", + " bulge=al.lp_linear.ExponentialCore,\n", + ")\n", + "\n", + "model = af.Collection(\n", + " galaxies=af.Collection(lens=lens, source=source),\n", + " fields=field,\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Print the model summary and inspect its diagram.\n", + "\n", + "Find the lens and source light profiles. Their intensities no longer have priors for the non-linear search: they are\n", + "identified as quantities solved during the fit.\n", + "\n", + "Compare this with the ordinary-profile model from *Practicalities*. There are two fewer non-linear parameters, while\n", + "the centres, shapes, sizes and mass parameters remain available for exploration.\n", + "\n", + "This distinction matters when interpreting the parameter count. Fewer non-linear parameters does not mean that we have\n", + "stopped fitting the brightness of either galaxy." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "print(model.info)\n", + "\n", + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Search and Run Time__\n", + "\n", + "We use 100 live points for this example, compared with 200 for the ordinary-profile fit in *Practicalities*. The\n", + "simpler non-linear parameter space gives us a reason to try fewer live points, but we must still inspect the result.\n", + "\n", + "Solving the intensities adds work to each likelihood evaluation. In return, the search no longer explores their values\n", + "or has to navigate their relationships with the other parameters directly.\n", + "\n", + "The overall run time depends on the balance between these costs. A linear-profile fit is not guaranteed to finish\n", + "faster, particularly for a model with only two light profiles. Its advantages become more substantial as we introduce\n", + "larger collections of profiles.\n", + "\n", + "This example changes both the treatment of intensities and the live-point count, so it is a practical demonstration\n", + "rather than a controlled timing comparison." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "search = af.Nautilus(\n", + " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", + " name=\"tutorial_4_linear_profiles\",\n", + " unique_tag=dataset_name,\n", + " n_live=100,\n", + " n_batch=50,\n", + " iterations_per_quick_update=2500,\n", + ")\n", + "\n", + "analysis = al.AnalysisImaging(dataset=dataset)\n", + "\n", + "result_linear = search.fit(model=model, analysis=analysis)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Result__\n", + "\n", + "Plot the fitted image and inspect the central lens light and lensed arcs.\n", + "\n", + "Although Nautilus did not explore the intensities, the analysis has adjusted them to reproduce the observed brightness\n", + "for each proposed model. Both galaxies should therefore contribute to the final image.\n", + "\n", + "Examine the normalised residuals as before. Changing how intensities are determined does not remove the need to check\n", + "whether the model describes the observations.\n", + "\n", + "The result summary describes the parameters explored by the non-linear search. We will retrieve the solved intensities\n", + "separately below." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "print(result_linear.info)\n", + "\n", + "aplt.subplot_fit_imaging(fit=result_linear.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Intensities__\n", + "\n", + "The intensities are calculated during the image fit rather than sampled directly by Nautilus.\n", + "\n", + "To inspect their values, retrieve `result_linear.max_log_likelihood_tracer`. This tracer contains ordinary light\n", + "profiles with the solved intensities inserted, corresponding to the highest-likelihood fit found by the search.\n", + "\n", + "In this two-galaxy example, the first galaxy is the foreground lens and the second is the background source. Print\n", + "their intensities below.\n", + "\n", + "These are the intensities associated with one fitted model. They are not uncertainty estimates: their preferred values\n", + "can change as the other profile and mass parameters change." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "tracer = result_linear.max_log_likelihood_tracer\n", + "\n", + "print(tracer.galaxies[0].bulge.intensity)\n", + "print(tracer.galaxies[1].bulge.intensity)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Visualisation__\n", + "\n", + "The tracer retrieved above contains ordinary light profiles with their solved intensities. We can therefore use it to\n", + "calculate and plot an image.\n", + "\n", + "This shows the light predicted by the tracer before PSF blurring. To assess agreement with the observed image, use the\n", + "`FitImaging` plot, which includes that blurring and displays the residuals.\n", + "\n", + "Keep this distinction in mind: the original linear profiles describe components whose intensities still need to be\n", + "solved, whereas this tracer contains the intensities determined by the fit." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "tracer = result_linear.max_log_likelihood_tracer\n", + "\n", + "aplt.plot_array(\n", + " array=tracer.image_2d_from(grid=dataset.grid),\n", + " title=\"Model image before PSF blurring\",\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Basis__\n", + "\n", + "Look again at the foreground lens galaxy. A single S\u00e9rsic profile describes its light using smooth ellipses with one\n", + "axis ratio and orientation. Real galaxies can have rounder central regions, flatter outer light, or an orientation that\n", + "gradually changes with radius. These changes can leave structured residuals when we fit a single S\u00e9rsic profile.\n", + "\n", + "An alternative is to add together Gaussian light profiles of different sizes. Narrow Gaussians describe concentrated\n", + "central light, while broader Gaussians describe the surrounding emission. Their intensities determine how much each\n", + "contributes to the combined brightness distribution.\n", + "\n", + "PyAutoLens groups these profiles into a `Basis`. When they are Gaussians, this description is called a **multi-Gaussian\n", + "expansion**, or **MGE**.\n", + "\n", + "The flexibility depends on how we arrange the Gaussians. One group sharing a centre and shape gives a flexible radial\n", + "profile. Multiple groups with different shapes and orientations can describe changes in flattening and twists in the\n", + "light distribution. Describing genuinely lopsided light requires additional freedom, such as offset centres.\n", + "\n", + "The workspace example uses two groups with different elliptical shapes but a shared centre. These can represent, for\n", + "example, rounder central light and a flatter outer component. Their changing contributions with radius let the combined\n", + "image vary in shape without assigning independent geometry to every Gaussian.\n", + "\n", + "Crucially, the Gaussian widths can be fixed and their intensities solved by linear algebra. The non-linear search then\n", + "explores only the chosen geometric parameters. This gives us a way to describe more complex light distributions while\n", + "keeping the non-linear parameter space manageable.\n", + "\n", + "We begin here with a single Gaussian group to understand the method. It will not capture every structure described\n", + "above; the workspace demonstrates the more flexible arrangements.\n", + "\n", + "Individual Gaussians need not represent separate physical structures. We interpret their summed light distribution,\n", + "rather than identifying each Gaussian as a distinct part of the galaxy." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__A First Gaussian Basis__\n", + "\n", + "We begin with 30 circular Gaussians, all centred at `(0.0, 0.0)` arcseconds. Their sizes are fixed and spaced\n", + "logarithmically, giving us a range of narrow and broad components.\n", + "\n", + "The smallest Gaussian has a width of one tenth of the image pixel scale; the largest has a width of 3.0 arcseconds.\n", + "These are profile widths, not the extent of the fitted region: our image mask remains at 2.5 arcseconds.\n", + "\n", + "This first example deliberately keeps the geometry simple. We solve the intensities without searching for a better\n", + "centre or ellipticity, then inspect what that restriction leaves unexplained." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "total_gaussians = 30\n", + "\n", + "sigma_values = np.logspace(\n", + " np.log10(dataset.pixel_scales[0] / 10.0),\n", + " np.log10(3.0),\n", + " total_gaussians,\n", + ")\n", + "\n", + "gaussian_list = [\n", + " al.lp_linear.Gaussian(\n", + " centre=(0.0, 0.0),\n", + " ell_comps=(0.0, 0.0),\n", + " sigma=sigma,\n", + " )\n", + " for sigma in sigma_values\n", + "]\n", + "\n", + "bulge = al.lp_basis.Basis(profile_list=gaussian_list)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Evaluating the Basis__\n", + "\n", + "We replace the lens\u2019s S\u00e9rsic light profile with this Gaussian basis. We retain the mass, shear and source geometry from\n", + "the previous fit.\n", + "\n", + "Creating `FitImaging` solves the linear intensities for this fixed geometry, including the source intensity. It does\n", + "not run a new non-linear search.\n", + "\n", + "This lets us examine what the Gaussian basis can achieve before giving it freedom to adjust its centre and shape." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "lens = al.Galaxy(\n", + " redshift=0.5,\n", + " bulge=bulge,\n", + " mass=result_linear.instance.galaxies.lens.mass,\n", + ")\n", + "\n", + "source = result_linear.instance.galaxies.source\n", + "\n", + "tracer = al.Tracer(\n", + " galaxies=[lens, source],\n", + " fields=result_linear.max_log_likelihood_fields,\n", + ")\n", + "\n", + "fit = al.FitImaging(dataset=dataset, tracer=tracer)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Inspecting the Basis Fit__\n", + "\n", + "Plot the fit and examine the foreground galaxy, especially the transition from its bright centre to its fainter outer\n", + "light.\n", + "\n", + "The range of Gaussian sizes gives the model flexibility to reproduce this radial brightness distribution. However,\n", + "every Gaussian is currently circular, whereas the lens light is slightly elongated.\n", + "\n", + "Look for residual structure around the lens galaxy that could reflect this difference. Adjusting intensities changes\n", + "how much light each Gaussian contributes, but cannot make circular Gaussians reproduce an elliptical shape.\n", + "\n", + "We have also fixed their common centre rather than fitted it. In the next step, we let the non-linear search determine\n", + "a shared centre and ellipticity while the linear solve continues to determine the individual intensities.\n", + "\n", + "This illustrates two distinct kinds of flexibility: the Gaussian intensities control the radial light distribution,\n", + "while their centres and shapes control its geometry. Adding more Gaussians with the same circular shape cannot, by\n", + "itself, reproduce an elongated or asymmetric galaxy.\n", + "\n", + "**\ud83e\udd16 Ask AI:** My circular Gaussian basis leaves elongated residuals around the lens galaxy. Why might changing the\n", + "Gaussian intensities fail to remove them, and which geometric parameters could I investigate?" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "aplt.subplot_fit_imaging(fit=fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Lens MGE__\n", + "\n", + "The circular Gaussian basis could adjust its radial brightness distribution, but could not reproduce the slight\n", + "elongation of the lens light.\n", + "\n", + "We now let Nautilus fit a common centre and elliptical shape for the 30 Gaussians. Their widths remain fixed, and their\n", + "intensities are solved together during each likelihood evaluation.\n", + "\n", + "This gives the lens-light model just four non-linear parameters: two centre coordinates and two elliptical components.\n", + "\n", + "The Gaussians share these parameters, so they move and change shape together. Their individual intensities still allow\n", + "the combined brightness to vary with radius. This arrangement remains elliptically symmetric; more complicated geometry\n", + "requires the additional Gaussian groups discussed earlier." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We create the centre priors once and assign those same prior objects to every Gaussian. This links their centres,\n", + "rather than giving each Gaussian an independent position within the same limits.\n", + "\n", + "We also link every Gaussian\u2019s elliptical components to those of the first Gaussian. Each width is assigned a fixed\n", + "numerical value.\n", + "\n", + "Inspect these assignments carefully: giving every Gaussian independent geometry would create a much larger non-linear\n", + "search problem." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "lens_centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", + "lens_centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", + "\n", + "lens_sigmas = np.logspace(\n", + " np.log10(dataset.pixel_scales[0] / 10.0),\n", + " np.log10(3.0),\n", + " 30,\n", + ")\n", + "\n", + "lens_gaussians = af.Collection(\n", + " af.Model(al.lp_linear.Gaussian) for _ in range(30)\n", + ")\n", + "\n", + "for i, gaussian in enumerate(lens_gaussians):\n", + " gaussian.centre.centre_0 = lens_centre_0\n", + " gaussian.centre.centre_1 = lens_centre_1\n", + " gaussian.ell_comps = lens_gaussians[0].ell_comps\n", + " gaussian.sigma = lens_sigmas[i]\n", + "\n", + "bulge = af.Model(\n", + " al.lp_basis.Basis,\n", + " profile_list=list(lens_gaussians),\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Source MGE__\n", + "\n", + "We can use the same approach for the source galaxy. Its predicted light is ray-traced through the mass model before\n", + "being compared with the observed arcs.\n", + "\n", + "Here, we use 15 Gaussians with widths spanning 0.0001 to 1.0 arcseconds in the source plane. This range includes\n", + "compact components and broader emission appropriate for the example; it does not mean the data resolve the smallest\n", + "Gaussian individually.\n", + "\n", + "The source Gaussians share a centre and elliptical shape with one another, but these parameters must be independent of\n", + "the lens-light MGE. We therefore create new prior objects for the source centre.\n", + "\n", + "This source model can adjust its radial light distribution without making Nautilus explore an intensity or width for\n", + "every Gaussian. It still describes one smooth, elliptically symmetric source, rather than arbitrary clumps or multiple\n", + "galaxies." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "source_centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", + "source_centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", + "\n", + "source_sigmas = np.logspace(-4, 0, 15)\n", + "\n", + "source_gaussians = af.Collection(\n", + " af.Model(al.lp_linear.Gaussian) for _ in range(15)\n", + ")\n", + "\n", + "for i, gaussian in enumerate(source_gaussians):\n", + " gaussian.centre.centre_0 = source_centre_0\n", + " gaussian.centre.centre_1 = source_centre_1\n", + " gaussian.ell_comps = source_gaussians[0].ell_comps\n", + " gaussian.sigma = source_sigmas[i]\n", + "\n", + "source_bulge = af.Model(\n", + " al.lp_basis.Basis,\n", + " profile_list=list(source_gaussians),\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Combined Model__\n", + "\n", + "We now combine the lens-light MGE, the isothermal mass profile, external shear and the source-light MGE.\n", + "\n", + "There are 45 Gaussian light profiles, but only 15 non-linear parameters:\n", + "\n", + "- Four describe the shared lens-light geometry.\n", + "- Four describe the shared source-light geometry.\n", + "- Five describe the isothermal mass profile.\n", + "- Two describe external shear.\n", + "\n", + "The Gaussian intensities are solved during each likelihood evaluation, and their widths are fixed. The number of light\n", + "profiles is therefore very different from the number of parameters Nautilus must explore.\n", + "\n", + "Retaining external shear keeps the mass description consistent with our earlier fits." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "lens = af.Model(\n", + " al.Galaxy,\n", + " redshift=0.5,\n", + " bulge=bulge,\n", + " mass=al.mp.Isothermal,\n", + ")\n", + "\n", + "source = af.Model(\n", + " al.Galaxy,\n", + " redshift=1.0,\n", + " bulge=source_bulge,\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", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Inspecting the Model__\n", + "\n", + "The model summary is long because it lists all 45 Gaussians. Use the diagram alongside it to identify the much smaller\n", + "set of independent parameters.\n", + "\n", + "Within each basis, check that the centres and elliptical components are shared, the widths are fixed and the\n", + "intensities are solved linearly.\n", + "\n", + "Then check that the lens and source have separate geometry. Accidentally linking them would impose a relationship\n", + "between the foreground galaxy and the unlensed source that we do not intend.\n", + "\n", + "This is the main benefit of the construction: many light components can describe the brightness distribution while the\n", + "non-linear search handles a comparatively small set of geometric and mass parameters." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "print(model.info)\n", + "\n", + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Model Fit__\n", + "\n", + "We now fit the lens and source MGEs together with the mass model and external shear.\n", + "\n", + "Nautilus explores their geometric and mass parameters. For every proposed model, the analysis solves the Gaussian\n", + "intensities together, accounting for the overlapping lens and lensed-source light.\n", + "\n", + "We use 100 live points as a starting configuration for this example. As before, we must inspect the result rather than\n", + "assume that the simpler parameter space guarantees success." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "search = af.Nautilus(\n", + " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", + " name=\"tutorial_4_mge\",\n", + " unique_tag=dataset_name,\n", + " n_live=100,\n", + " n_batch=50,\n", + " iterations_per_quick_update=2500,\n", + ")\n", + "\n", + "result_basis = search.fit(model=model, analysis=analysis)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Result__\n", + "\n", + "Inspect the fitted image and normalised residuals. Look separately at the central lens galaxy and the surrounding arcs.\n", + "\n", + "The shared geometry lets each Gaussian group adjust its centre and ellipticity, while its intensities determine the\n", + "radial brightness distribution. Compare this fit with the earlier demonstration that fixed the lens Gaussians to be\n", + "circular.\n", + "\n", + "The highest-likelihood tracer contains all 45 Gaussian profiles with their solved intensities, so we can plot the\n", + "inferred light distribution directly.\n", + "\n", + "Check what the figures show before drawing a conclusion. The model may reproduce this smooth simulated system well, but\n", + "that does not demonstrate that the same arrangement can describe every real galaxy." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "print(result_basis.info)\n", + "\n", + "tracer = result_basis.max_log_likelihood_tracer\n", + "\n", + "aplt.subplot_tracer(tracer=tracer, grid=dataset.grid)\n", + "\n", + "aplt.subplot_fit_imaging(fit=result_basis.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Multi-Gaussian Expansion Benefits__\n", + "\n", + "An MGE separates flexibility in the brightness distribution from the number of parameters explored by the non-linear\n", + "search.\n", + "\n", + "Our lens and source each use only four non-linear geometric parameters, despite containing 30 and 15 Gaussian profiles\n", + "respectively. Their fixed widths cover a range of scales, and the linear solve determines how much light belongs on\n", + "each scale.\n", + "\n", + "More flexible arrangements can describe changes in flattening and orientation with radius. The workspace\u2019s\n", + "`multi_gaussian_expansion/modeling.py` example demonstrates multiple Gaussian groups with different shapes.\n", + "\n", + "This makes MGE a valuable tool for lens modeling: it can improve the description of galaxy light while keeping the\n", + "non-linear exploration manageable.\n", + "\n", + "The approach is also useful for obtaining an initial source model. However, our single-centre source MGE remains a\n", + "restricted description, especially when the source contains separate bright knots or irregular features." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Benefits Have Costs__\n", + "\n", + "Evaluating many Gaussian profiles and solving their intensities adds work to each likelihood calculation. A simpler\n", + "non-linear parameter space can compensate for that cost, but the overall speed depends on the dataset and model.\n", + "\n", + "An MGE can also be less straightforward to interpret physically than a S\u00e9rsic profile. A S\u00e9rsic effective radius and\n", + "index directly describe its size and concentration; individual Gaussian widths and intensities are primarily\n", + "ingredients of the summed light distribution.\n", + "\n", + "Finally, flexibility depends on the geometry we allow. Adding more Gaussians with one shared centre and shape improves\n", + "radial freedom, but cannot create an independently positioned clump.\n", + "\n", + "Inspect residual structure with these restrictions in mind. A detailed-looking model is useful only if it has the\n", + "freedom needed to describe the features relevant to the analysis." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Positive Intensities__\n", + "\n", + "Without a positivity constraint, a linear solver can combine positive and negative Gaussian intensities to reproduce an\n", + "image. Large contributions can cancel one another, producing a fitted sum from components that do not represent\n", + "physical light emission.\n", + "\n", + "PyAutoLens constrains the Gaussian intensities to be non-negative. A Gaussian can contribute light or have zero\n", + "intensity, but cannot subtract light through a negative brightness.\n", + "\n", + "This is particularly useful when many overlapping Gaussians describe the same region. It prevents alternating positive\n", + "and negative contributions from being used to manufacture structure.\n", + "\n", + "Non-negative intensities do not guarantee that the overall model is correct. We still need to assess its geometry and\n", + "inspect the residuals." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Other Basis Functions__\n", + "\n", + "Gaussians are not the only functions we can combine to describe galaxy light. PyAutoLens also supports **shapelets**,\n", + "which provide another set of spatial patterns for constructing a light distribution.\n", + "\n", + "Different basis functions offer different kinds of flexibility and computational costs. Their usefulness depends on the\n", + "structures in the image and the model we want to fit.\n", + "\n", + "You do not need to explore every option to continue HowToLens. The workspace example\n", + "`scripts/imaging/features/advanced/shapelets/modeling.py` provides a starting point if your analysis would benefit from\n", + "investigating an alternative.\n", + "\n", + "For now, the important distinction is between the individual functions and the freedom of their combined model. A basis\n", + "can only reproduce structures allowed by its arrangement and parameters." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Wrap Up__\n", + "\n", + "Linear light profiles let us solve intensities separately from the non-linear search. We used this first with S\u00e9rsic\n", + "and exponential profiles, then with Gaussian groups describing the lens and source light.\n", + "\n", + "An MGE gives us flexibility in the brightness distribution without requiring Nautilus to explore an intensity for every\n", + "Gaussian. More elaborate arrangements can describe changes in shape and orientation, while our shared-shape example\n", + "keeps the geometry simple.\n", + "\n", + "This flexibility still has limits. A source containing several distinct star-forming knots may leave structured\n", + "residuals when fitted with one smooth, common-centre MGE. Chapter 3 introduces pixelized sources as a way to describe\n", + "more complicated spatial structure.\n", + "\n", + "Before that, *Data and Likelihoods* returns to the observations: which measurements enter the fit, how we handle\n", + "contamination, and how the same model\u2013Analysis\u2013search approach applies to the other types of lensing data introduced in\n", + "Chapter 1.\n", + "\n", + "We will then bring these tools together in search chaining, balancing model flexibility, reliable fitting and run time." + ] + } + ], + "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_4_linear_profiles.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_debug_fit_failure\n\n---\nname: al_debug_fit_failure\ndescription: Diagnose a non-linear search that didn't converge, returned unphysical parameters, or produced an inversion that fitted noise rather than signal. Walks the canonical post-mortem checks \u2014 log inspection, residual maps, prior coverage, multimodality, inversion regularisation, position penalties \u2014 and proposes targeted fixes (tighten priors, switch search, add positions, increase live points). Use after `al_run_search` returns a result that looks wrong.\n---\n\n# Debugging a fit that went wrong\n\nA finished search isn't automatically a successful one. PyAutoFit will return a\n`Result` regardless of whether the posterior is sensible. This skill walks the user\nthrough the symptom \u2192 diagnosis \u2192 fix loop for common lens-fit failures.\n\nReference reading: `autolens_workspace:scripts/guides/modeling/bug_fix.py`.\n\n## Ask\n\nBefore diagnosing, get the user to describe the failure mode:\n\n- *\"Did the search complete, or did it crash with an exception?\"* \u2014 different\n branches.\n- *\"What looks wrong \u2014 the residuals, the parameter values, the chi-squared, the\n source reconstruction?\"* \u2014 picks the diagnostic.\n- *\"Have you compared against an `PYAUTO_TEST_MODE=1` smoke run?\"* \u2014 sometimes the\n symptom is just a bug in the script that the smoke test would have caught.\n\n## Branch \u2014 search crashed mid-run\n\nRead the search log: `output//.../search.log`. Common causes:\n\n- **Likelihood evaluation crashed.** Read the traceback. Often a profile parameter\n has gone unphysical (negative effective radius, zero einstein radius). Tighten the\n prior bounds with `af.UniformPrior(lower_limit=..., upper_limit=...)`.\n- **Numba cache write failure.** Set `NUMBA_CACHE_DIR=/tmp/numba_cache` and rerun.\n- **JAX out-of-memory.** Reduce `n_live`, mask radius, or pixelisation resolution; or\n disable JAX for this run.\n\n## Branch \u2014 search completed but residuals are huge\n\nLoad the result and look at the fit (same pattern as\n[`al_load_results`](./al_load_results.md) \u2014 load the max-log-likelihood tracer from\nJSON, reload the dataset, rebuild the fit):\n\n```python\nfrom pathlib import Path\nfrom autonerves.dictable import from_json\nimport autolens as al\nimport autolens.plot as aplt\n\nout = Path(\"output/imaging///\")\ntracer = from_json(file_path=out / \"files\" / \"tracer.json\")\n\n# Reload the dataset exactly as the fit script did (path, pixel_scales, mask).\ndataset = ... # see al_prepare_imaging_data\n\nfit = al.FitImaging(dataset=dataset, tracer=tracer)\naplt.subplot_fit_imaging(\n fit=fit, output_path=\"scripts/scratch/debug/\", output_filename=\"fit\",\n output_format=\"png\",\n)\n```\n\nLook at the residual map. Common signatures:\n\n- **Mass model off-axis.** Residuals form a \"double-image\" pattern where the model\n positions don't match the data positions. Fix: add image positions and a\n `PositionsLH` (see `al_run_slam_pipeline` for the pattern).\n- **Source too constrained.** The source reconstruction looks like a single Sersic\n but the data shows a complex arc. Fix: switch to a pixelised source via\n [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md).\n- **Lens light leaking into source plane.** Residuals show systematic structure at\n the lens centre. Fix: add or refine the lens light model.\n\n## Branch \u2014 search completed but converged to a clearly wrong mode\n\nSymptoms: parameter posteriors are tight but at unphysical values (einstein radius\n~0.01\", lens at the edge of the mask, source at the lens centre).\n\n- **Multi-modal posterior, picked the wrong mode.** Switch to or rerun with more live\n points: `af.Nautilus(n_live=400)`. Nested sampling handles multimodality better\n than MCMC.\n- **Prior pulling the search into a bad region.** Widen or recentre priors on the\n parameters that look wrong. Inspect with `model.info` before fitting.\n- **Mask cropping out part of the lensed signal.** Widen the mask radius and refit.\n\n## Branch \u2014 pixelised source looks like noise\n\nThe inversion has over-fitted background noise into the source plane.\n\n- **Regularisation too low.** Bump the regularisation coefficient range \u2014 see\n `PyAutoArray:autoarray/inversion/regularization/`. The `ConstantSplit` regularisation\n with sensible coefficients usually works.\n- **No positions penalty.** Add a `PositionsLH` to prevent the inversion from\n demagnifying the source into infinity.\n- **Pixelisation grid too fine.** Coarsen the `mesh_shape` (e.g. from (50, 50) to\n (30, 30)).\n\n[`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md)\ncovers regularisation and pixelisation theory.\n\n## Branch \u2014 fit looks fine but evidence is much worse than a competing model\n\nThe fit may have converged to a local maximum. Run again with different priors or\na different `unique_tag` so the search starts fresh, and compare evidences.\n\n## Generic fixes that often help\n\n- **Add positions.** `al.PositionsLH` (with the user's measured image\n positions) eliminates a large class of mass-model failures.\n- **Tighten the prior on the lens centre.** It's often the parameter with the worst\n multi-modality.\n- **Smoke-test with `PYAUTO_TEST_MODE=1`** to confirm there's no scripting bug masquerading\n as a fit bug.\n- **Run with a coarser model first** (single Sersic source, SIE mass) before adding\n pixelisations. Use [`al_chain_searches`](./al_chain_searches.md) to chain.\n\n## Combine\n\nOnce you've identified the issue, the fix usually means re-running with adjusted\ninputs \u2014 [`al_run_search`](./al_run_search.md) \u2014 and re-loading the new result \u2014\n[`al_load_results`](./al_load_results.md). If the diagnosis was wrong, iterate.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Recovering from local maxima](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.ipynb):\n the three canonical recoveries \u2014 prior tuning, multi-start, model simplification.\n- **General reference** \u2014 [RTD: Demagnified solutions](https://pyautolens.readthedocs.io/en/latest/general/demagnified_solutions.html):\n how unphysical demagnified-source reconstructions arise in pixelised fits, and how\n `PositionsLH` penalties prevent them.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n inspecting an inferred model via `Tracer` \u2014 the patterns this skill uses to\n pull apart a failed fit.\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_5_linear_profiles.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_5_linear_profiles.ipynb deleted file mode 100644 index 3a3df78..0000000 --- a/notebooks/chapter_2_lens_modeling/tutorial_5_linear_profiles.ipynb +++ /dev/null @@ -1,941 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 5: Linear Profiles\n", - "===========================\n", - "\n", - "In the previous tutorial we learned how to balance model complexity with our non-linear search in order to infer\n", - "accurate lens model solutions and avoid failure. We saw how in order to fit a model accurately one may have to\n", - "parameterize and fit a simpler model with fewer non-linear parameters, at the expense of fitting the data less\n", - "accurately.\n", - "\n", - "It would be desirable if we could make our model have more flexibility enabling it to fit more complex galaxy\n", - "structures, but in a way that does not increase (or perhaps even decreases) the number of non-linear parameters.\n", - "This would keep the `Nautilus` model-fit efficient and accurate.\n", - "\n", - "This is possible using linear light profiles, which solve for their `intensity` parameter via efficient linear\n", - "algebra, using a process called an inversion. The inversion always computes `intensity` values that give the best\n", - "fit to the data (e.g. they minimize the chi-squared and therefore maximize the likelihood).\n", - "\n", - "This tutorial will first fit a model using two linear light profiles. Because their `intensity` values are solved for\n", - "implicitly, this means they are not a dimension of the non-linear parameter space fitted by `Nautilus`, therefore\n", - "reducing the complexity of parameter space and making the fit faster and more accurate.\n", - "\n", - "This tutorial will then show how many linear light profiles can be combined into a `Basis`, which comes from the term\n", - "'basis function'. By combining many linear light profiles models can be composed which are able to fit complex galaxy\n", - "structures (e.g. asymmetries, twists) with just N=6-8 non-linear parameters.\n", - "\n", - "__Contents__\n", - "\n", - "- **Initial Setup:** we'll use the same strong lensing data as the previous tutorial, 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", - "- **Linear Light Profiles:** We use a variant of a light profile discussed called a \"linear light profile\", which is accessed.\n", - "- **Run Time:** Profiling the expected run time of the model-fit.\n", - "- **Result:** Overview of the results of the model-fit.\n", - "- **Intensities:** The intensities of linear light profiles are not a part of the model parameterization and therefore.\n", - "- **Visualization:** Linear light profiles and objects containing them (e.g.\n", - "- **Basis:** We can use many linear light profiles to build a `Basis`.\n", - "- **Model Fit:** Perform the model-fit using the search and analysis.\n", - "- **Source MGE:** We now compose a second `Basis` of 15 Gaussians to represent the source galaxy.\n", - "- **Multi Gaussian Expansion Benefits:** Fitting a galaxy's light with a superposition of Gaussians is called a Multi-Gaussian Expansion.\n", - "- **Disadvantage of Basis Functions:** For many science cases, the MGE can also be a less intuitive model to interpret than a Sersic.\n", - "- **Positive Only Solver:** Ensuring positive-only solutions for linear light profile intensities.\n", - "- **Other Basis Functions:** In addition to the Gaussians used in this example, there is another basis function implemented in.\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 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`." - ] - }, - { - "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": [ - "if al.util.dataset.should_simulate(str(dataset_path)):\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulator/lens_sersic.py\"],\n", - " check=True,\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", - "we'll create and use a smaller 2.6\" `Mask2D` again." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "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)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "When plotted, the lens light`s is clearly visible in the centre of the image." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_imaging_dataset(dataset=dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Linear Light Profiles__\n", - "\n", - "We use a variant of a light profile discussed called a \"linear light profile\", which is accessed via the \n", - "command `al.lp_linear`. \n", - "\n", - "A \"linear light profile\" is a variant of a standard light profile where the `intensity` parameter is solved for\n", - "via linear algebra every time the model is fitted to the data. This uses a process called an \"inversion\" and it\n", - "always computes the `intensity` values that give the best fit to the data (e.g. maximize the likelihood)\n", - "given the light profile's other parameters.\n", - " \n", - "Each light profile's `intensity` parameter is therefore not a free parameter in the model-fit, reducing the\n", - "dimensionality of non-linear parameter space by the number of light profiles (in this example by 2 dimensions).\n", - "\n", - "This also removes the degeneracies that occur between the `intensity` and other light profile parameters\n", - "(e.g. `effective_radius`, `sersic_index`), which are difficult degeneracies for the non-linear search to map out\n", - "accurately. This produces more reliable lens model results and the fit converges in fewer iterations, speeding up the\n", - "overall analysis.\n", - "\n", - "This is a rare example where we are able to reduce the complexity of parameter space without making the model itself \n", - "any simpler. There is really no downside to using linear light profiles, so I would recommend you adopt them as \n", - "standard for your own model-fits from here on!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge = af.Model(al.lp_linear.Sersic)\n", - "mass = af.Model(al.mp.Isothermal)\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 = 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 linear light profiles.\n", - "\n", - "Note how the `intensity` is no longer listed and does not have a prior associated with it." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(model.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." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "af.ModelPlotter(model).figure()" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now create this search and run it.\n", - "\n", - "Note that the number of live points has been reduced to 100, whereas previous tutorials typically used values of\n", - "150 - 250. \n", - "\n", - "This is possible because the linear light profiles make the parameter space much simpler, meaning we can obtain a \n", - "reliable model with fewer live points. This means the overall run-time of the search will be faster." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search = af.Nautilus(\n", - " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", - " name=\"tutorial_5_linear_light_profile\",\n", - " unique_tag=dataset_name,\n", - " n_live=100,\n", - " n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2.\n", - " 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", - "For standard light profiles, the log likelihood evaluation time is of order ~0.01 seconds for this dataset.\n", - "\n", - "For linear light profiles, the log likelihood evaluation increases to around ~0.05 seconds per likelihood evaluation.\n", - "This is still fast, but it does mean that the fit may take around five times longer to run.\n", - "\n", - "However, because two free parameters have been removed from the model (the `intensity` of the lens bulge and \n", - "source bulge), the total number of likelihood evaluations will reduce. Furthermore, the simpler parameter space\n", - "likely means that the fit will take less than 10000 per free parameter to converge. This is aided further\n", - "by the reduction in `n_live` to 100.\n", - "\n", - "Fits using standard light profiles and linear light profiles therefore take roughly the same time to run. However,\n", - "the simpler parameter space of linear light profiles means that the model-fit is more reliable, less susceptible to\n", - "converging to an incorrect solution and scales better if even more light profiles are included in the model.\n", - "\n", - "Run the non-linear search." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(\n", - " \"The non-linear search has begun running - checkout the output/howtolens/chapter_2/tutorial_5_linear_light_profile\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell with progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", - "result_linear_light_profile = search.fit(model=model, analysis=analysis)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Result__\n", - "\n", - "The `info` attribute shows the resulting model, which does not display the `intensity` values for each light profile." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result_linear_light_profile.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Intensities__\n", - "\n", - "The intensities of linear light profiles are not a part of the model parameterization and therefore are not displayed\n", - "in the `model.results` file.\n", - "\n", - "To extract the `intensity` values of a specific component in the model, we use the `max_log_likelihood_tracer`,\n", - "which has already performed the inversion and therefore the galaxy light profiles have their solved for\n", - "`intensity`'s associated with them." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "tracer = result_linear_light_profile.max_log_likelihood_tracer\n", - "\n", - "print(tracer.galaxies[0].bulge.intensity)\n", - "print(tracer.galaxies[1].bulge.intensity)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Above, we access these values using the list index entry of each galaxy in the tracer. However, we may not be certain\n", - "of the order of the galaxies in the tracer, and therefore which galaxy index corresponds to the lens and source.\n", - "\n", - "We can therefore use the model composition API to access these values." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(tracer.galaxies[0].bulge.intensity)\n", - "print(tracer.galaxies[-1].bulge.intensity)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `Tracer` contained in the `max_log_likelihood_fit` also has the solved for `intensity` values:" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "fit = result_linear_light_profile.max_log_likelihood_fit\n", - "\n", - "tracer = fit.tracer\n", - "\n", - "print(tracer.galaxies[0].bulge.intensity)\n", - "print(tracer.galaxies[-1].bulge.intensity)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Visualization__\n", - "\n", - "Linear light profiles and objects containing them (e.g. galaxies, a tracer) cannot be plotted because they do not \n", - "have an `intensity` value.\n", - "\n", - "Therefore, the object created above which replaces all linear light profiles with ordinary light profiles must be\n", - "used for visualization:" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "tracer = fit.model_obj_linear_light_profiles_to_light_profiles\n", - "aplt.plot_array(array=tracer.image_2d_from(grid=dataset.grid), title=\"Image\")\n" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Basis__\n", - "\n", - "We can use many linear light profiles to build a `Basis`. \n", - "\n", - "For example, below, we make a `Basis` out of 30 elliptical Gaussian linear light profiles which: \n", - "\n", - " - All share the same centre and elliptical components.\n", - " - The `sigma` size of the Gaussians increases in log10 increments." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "total_gaussians = 30\n", - "\n", - "# The sigma values of the Gaussians will be fixed to values spanning a tenth of the pixel scale to the mask radius, 3.0\".\n", - "\n", - "mask_radius = 3.0\n", - "log10_sigma_list = np.linspace(\n", - " np.log10(dataset.pixel_scales[0] / 10.0), np.log10(mask_radius), total_gaussians\n", - ")\n", - "\n", - "# A list of linear light profile `Gaussians` will be input here, which will then be used to fit the data.\n", - "\n", - "bulge_gaussian_list = []\n", - "\n", - "# Iterate over every Gaussian and create it, with it centered at (0.0\", 0.0\") and assuming spherical symmetry.\n", - "\n", - "for i in range(total_gaussians):\n", - " gaussian = al.lp_linear.Gaussian(\n", - " centre=(0.0, 0.0),\n", - " ell_comps=(0.0, 0.0),\n", - " sigma=10 ** log10_sigma_list[i],\n", - " )\n", - "\n", - " bulge_gaussian_list.append(gaussian)\n", - "\n", - "# The Basis object groups many light profiles together into a single model component and is used to fit the data.\n", - "\n", - "bulge = al.lp_basis.Basis(profile_list=bulge_gaussian_list)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Once we have a `Basis`, we can treat it like any other light profile in order to create a `Galaxy` and `Tracer` and \n", - "use it to fit data.\n", - "\n", - "We use the lens mass and source galaxy light profiles inferred above to fit this model with the basis functions." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "lens = al.Galaxy(\n", - " redshift=0.5,\n", - " bulge=bulge,\n", - " mass=result_linear_light_profile.instance.galaxies.lens.mass,\n", - ")\n", - "\n", - "source = result_linear_light_profile.instance.galaxies.source\n", - "\n", - "tracer = al.Tracer(galaxies=[lens, source])\n", - "\n", - "fit = al.FitImaging(dataset=dataset, tracer=tracer)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "By plotting the fit, we see that the `Basis` does a reasonable job at capturing the appearance of the lens galaxy.\n", - "\n", - "There are imperfections, but this is because we did not fit the model via a non-linear search in order to determine\n", - "the optimal values of the Gaussians in the basis. In particular, the Gaussians above were all spherical, when the\n", - "lens galaxy is elliptical. \n", - "\n", - "We rectify this below, where we use a non-linear search to determine the optimal values of the Gaussians!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_fit_imaging(fit=fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Model Fit__\n", - "\n", - "To fit a model using `Basis` functions, the API is very similar to that shown throughout this chapter, using both\n", - "the `af.Model()` and `af.Collection()` objects.\n", - "\n", - "In this example we fit a `Basis` model for the lens galaxy bulge where:\n", - "\n", - " - The bulge is a superposition of 30 linear `Gaussian` profiles [4 parameters]. \n", - " - The centres and elliptical components of each family of Gaussians are all linked together.\n", - " - The `sigma` size of the Gaussians increases in log10 increments.\n", - "\n", - "The number of free parameters and therefore the dimensionality of the MGe is just N=4." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "total_gaussians = 30\n", - "\n", - "# The sigma values of the Gaussians will be fixed to values spanning a tenth of the pixel scale to the mask radius, 3.0\".\n", - "mask_radius = 3.0\n", - "log10_sigma_list = np.linspace(\n", - " np.log10(dataset.pixel_scales[0] / 10.0), np.log10(mask_radius), total_gaussians\n", - ")\n", - "\n", - "# By defining the centre here, it creates two free parameters that are assigned below to all Gaussians.\n", - "\n", - "centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", - "centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", - "\n", - "bulge_gaussian_list = []\n", - "\n", - "# A list of Gaussian model components whose parameters are customized belows.\n", - "\n", - "gaussian_list = af.Collection(\n", - " af.Model(al.lp_linear.Gaussian) for _ in range(total_gaussians)\n", - ")\n", - "\n", - "# Iterate over every Gaussian and customize its parameters.\n", - "\n", - "for i, gaussian in enumerate(gaussian_list):\n", - " gaussian.centre.centre_0 = centre_0 # All Gaussians have same y centre.\n", - " gaussian.centre.centre_1 = centre_1 # All Gaussians have same x centre.\n", - " gaussian.ell_comps = gaussian_list[\n", - " 0\n", - " ].ell_comps # All Gaussians have same elliptical components.\n", - " gaussian.sigma = (\n", - " 10 ** log10_sigma_list[i]\n", - " ) # All Gaussian sigmas are fixed to values above.\n", - "\n", - "bulge_gaussian_list += gaussian_list\n", - "\n", - "# The Basis object groups many light profiles together into a single model component.\n", - "\n", - "bulge = af.Model(\n", - " al.lp_basis.Basis,\n", - " profile_list=bulge_gaussian_list,\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Source MGE__\n", - "\n", - "We now compose a second `Basis` of 15 Gaussians to represent the source galaxy. \n", - "\n", - "This is parameterized the same as the lens galaxy `bulge` (e.g. all Gaussians share the same `centre` and `ell_comps`) \n", - "but is treated as a completely independent set of parameters.\n", - "\n", - "However, the sigma values of the Gaussians span a smaller range of values, as the source galaxy is smaller than the\n", - "lens galaxy." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "total_gaussians = 15\n", - "\n", - "# The sigma values of the Gaussians will be fixed to values spanning 0.0001\" to 1.0\".\n", - "\n", - "log10_sigma_list = np.linspace(-4, np.log10(1.0), total_gaussians)\n", - "\n", - "bulge_gaussian_list = []\n", - "\n", - "# By defining a new the centre here, it creates two free parameters that are assigned below to all Gaussians. These\n", - "# new centre priors must be defined again in order for the source MGE not to use the same centre as the lens light\n", - "# MGE\n", - "\n", - "centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", - "centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", - "\n", - "gaussian_list = af.Collection(\n", - " af.Model(al.lp_linear.Gaussian) for _ in range(total_gaussians)\n", - ")\n", - "\n", - "for i, gaussian in enumerate(gaussian_list):\n", - " gaussian.centre.centre_0 = centre_0\n", - " gaussian.centre.centre_1 = centre_1\n", - " gaussian.ell_comps = gaussian_list[0].ell_comps\n", - " gaussian.sigma = 10 ** log10_sigma_list[i]\n", - "\n", - "bulge_gaussian_list += gaussian_list\n", - "\n", - "source_bulge = af.Model(\n", - " al.lp_basis.Basis,\n", - " profile_list=bulge_gaussian_list,\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now compose the overall model which uses both sets of Gaussians to represent separately the lens and source.\n", - "\n", - "The overall dimensionality of non-linear parameter space is just N=13, which is fairly remarkable if you\n", - "think about just how complex the structures are that a `Basis` of Gaussians can capture!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "lens = af.Model(al.Galaxy, redshift=0.5, bulge=bulge, mass=af.Model(al.mp.Isothermal))\n", - "source = af.Model(al.Galaxy, redshift=1.0, bulge=source_bulge)\n", - "\n", - "model = af.Collection(galaxies=af.Collection(lens=lens, source=source))" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `info` attribute shows the model, which is a lot longer than we have seen previously, given that is \n", - "composed of 45 Gaussians in total (30 for the lens, 15 for the source)!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(model.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `info` for this model is enormous \u2014 forty-five Gaussians, each with its own block of parameters \u2014 but the\n", - "model itself is small. Each `bulge \u00b7 Basis` holds a single `Gaussian` repeated thirty times on the lens and\n", - "fifteen times on the source, and every member of a basis shares one `centre` and one `ell_comps`, has its own\n", - "fixed `sigma`, and has its `intensity` solved by the inversion.\n", - "\n", - "That is the whole MGE trick: forty-five Gaussians, thirteen dimensions \u2014 the N=13 quoted above." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "af.ModelPlotter(model).figure()" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now fit the model." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search = af.Nautilus(\n", - " path_prefix=Path(\"howtolens\") / \"chapter_2\",\n", - " name=\"tutorial_5_basis\",\n", - " unique_tag=dataset_name,\n", - " n_live=100,\n", - " n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2.\n", - " 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_5_basis\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell with progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", - "result_basis = search.fit(model=model, analysis=analysis)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Result__\n", - "\n", - "The result `info` attribute shows the result, which is again longer than usual given the large number of Gaussians\n", - "used in the fit." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result_basis.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Visualizing the fit shows that we successfully fit the data to the noise level.\n", - "\n", - "Note that the result objects `max_log_likelihood_tracer` and `max_log_likelihood_fit` automatically convert\n", - "all linear light profiles to ordinary light profiles, including every single one of the 20 Gaussians fitted\n", - "above. \n", - "\n", - "This means we can use them directly to perform the visualization below." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result_basis.max_log_likelihood_instance)\n", - "\n", - "aplt.subplot_tracer(tracer=tracer, grid=dataset.grid)\n", - "\n", - "aplt.subplot_fit_imaging(fit=result_basis.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Multi Gaussian Expansion Benefits__\n", - "\n", - "Fitting a galaxy's light with a superposition of Gaussians is called a Multi-Gaussian Expansion (MGE). It is a\n", - "is a powerful tool for modeling the light of galaxies, and offers a compelling method to fit complex light profiles \n", - "with a small number of parameters\n", - "\n", - "Symmetric light profiles (e.g. elliptical Sersics) may leave significant residuals, because they fail to capture \n", - "irregular and asymmetric morphological of galaxies (e.g. isophotal twists, an ellipticity which varies radially). \n", - "An MGE fully captures these features and can therefore much better represent the emission of complex lens galaxies.\n", - "\n", - "As seen above, the MGE model can be composed in a way that has fewer non-linear parameters than an elliptical Sersic. \n", - "In this example, 30 Gaussians were used to represent the `bulge` of the lens, which in total correspond to just N=4 \n", - "non-linear parameters (a `bulge` and `disk` comprising two linear Sersics has N=10 parameters). The source dimensionality\n", - "was also just N=4.\n", - "\n", - "The MGE model parameterization is also composed such that neither the `intensity` parameters or any of the\n", - "parameters controlling the size of the Gaussians (their `sigma` values) are non-linear parameters sampled by Nautilus.\n", - "This removes the most significant degeneracies in parameter space, making the model much more reliable and efficient\n", - "to fit.\n", - "\n", - "Therefore, not only does an MGE fit more complex galaxy morphologies, it does so using fewer non-linear parameters\n", - "in a much simpler non-linear parameter space which has far less significant parameter degeneracies!\n", - "\n", - "We strongly recommend that you adopt an MGE in your own lens modeling pipelines from here on. The script \n", - "`autolens_workspace/*/imaging/features/multi_gaussian_expansion/modeling.py` gives examples on fitting even more complex\n", - "MGE models, where for example the Gaussians have different axis-ratios and position angles.\n", - "\n", - "__Disadvantage of Basis Functions__\n", - "\n", - "For many science cases, the MGE can also be a less intuitive model to interpret than a Sersic profile. For example,\n", - "it is straight forward to understand how the effective radius of a Sersic profile relates to a galaxy's size,\n", - "or the serisc index relates to its concentration. The results of an MGE are less intuitive, and require more\n", - "thought to interpret physically.\n", - "\n", - "__Positive Only Solver__\n", - "\n", - "Many codes which use linear algebra typically rely on a linear algabra solver which allows for positive and negative\n", - "values of the solution (e.g. `np.linalg.solve`), because they are computationally fast. \n", - "\n", - "This is problematic, as it means that negative surface brightnesses values can be computed to represent a galaxy's \n", - "light, which is clearly unphysical. For an MGE, this produces a positive-negative \"ringing\", where the\n", - "Gaussians alternate between large positive and negative values. This is clearly undesirable and unphysical.\n", - "\n", - "**PyAutoLens** (and therefore all examples above) uses a positive only linear algebra solver which has been \n", - "extensively optimized to ensure it is as fast as positive-negative solvers. This ensures that all light profile \n", - "intensities are positive and therefore physical. \n", - "\n", - "__Other Basis Functions__\n", - "\n", - "In addition to the Gaussians used in this example, there is another basis function implemented in PyAutoLens \n", - "that is commonly used to represent the light of galaxies, called a `Shapelet`. \n", - "\n", - "Shapelets are basis functions with analytic properties that are appropriate for capturing the exponential / disk-like \n", - "features of a galaxy. They do so over a wide range of scales, and can often represent features in source galaxies \n", - "that a single Sersic function or MGE cannot.\n", - "\n", - "An example using shapelets is given at `autolens_workspace/scripts/imaging/features/advanced/shapelets/modeling.py`.\n", - " \n", - "Feel free to experiment with using shapelets as the source galaxy by yourself. However they incur higher computational \n", - "overheads than the MGE and include a free parameter which governs the size of the basis functions and therefore source,\n", - "slowing down convergence of the non-linear search. We have found that MGEs perform better than shapelets in most \n", - "lens modeling problems. \n", - "\n", - "If you have a desire to fit sources with even more complex morphologies we recommend you look at how to reconstruct \n", - "sources using pixelizations in the `modeling/features` section or chapter 3 of **HowToLens**.\n", - " \n", - "__Wrap Up__\n", - "\n", - "In this tutorial we described how linearizing light profiles allows us to fit more complex light profiles to\n", - "galaxies using fewer non-linear parameters, keeping the fit performed by the non-linear search fast, accurate\n", - "and robust.\n", - "\n", - "Perhaps the biggest downside to basis functions is that they are only as good as the features they can capture\n", - "in the data. For example, a basis of Gaussians still assumes that they have a well defined centre, but there are\n", - "galaxies which may have multiple components with multiple centres (e.g. many star forming knots) which such a \n", - "basis cannot capture.\n", - "\n", - "In chapter 3 of **HowToLens** we introduce non-parametric pixelizations, which reconstruct the data in way\n", - "that does not make assumptions like a centre and can thus reconstruct even more complex, asymmetric and irregular\n", - "galaxy morphologies." - ] - } - ], - "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_linear_profiles.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 index 2b5c36e..0cda41e 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_6_masking_and_positions.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_6_masking_and_positions.ipynb @@ -13,7 +13,7 @@ "\n", "__Contents__\n", "\n", - "- **Initial Setup:** we'll use the same strong lensing data as tutorials 1 & 2, where.\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", @@ -85,7 +85,7 @@ "source": [ "__Initial Setup__\n", "\n", - "we'll use the same strong lensing data as tutorials 1 & 2, where:\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`." diff --git a/notebooks/chapter_2_lens_modeling/tutorial_8_need_for_speed.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_8_need_for_speed.ipynb index 2397469..c8f684a 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_8_need_for_speed.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_8_need_for_speed.ipynb @@ -47,7 +47,7 @@ "\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 5 remove every `intensity` parameter from the non-linear parameter space, reducing its\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", @@ -74,12 +74,12 @@ " 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 5 and the pixelizations of chapter 3, solving\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 5, this trade often still favours the more advanced technique, because the simpler parameter\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", diff --git a/notebooks/chapter_2_lens_modeling/tutorial_9_search_chaining.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_9_search_chaining.ipynb index b84cf1d..a17e42e 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_9_search_chaining.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_9_search_chaining.ipynb @@ -17,7 +17,7 @@ "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 4 of this chapter. We learnt there were three approaches one could take fitting a lens\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", @@ -33,7 +33,7 @@ "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 4. We saw that this\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", @@ -122,7 +122,7 @@ "source": [ "__Initial Setup__\n", "\n", - "we'll use the same strong lensing data as tutorials 3, 4 and 5 of this chapter, where:\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", diff --git a/notebooks/chapter_optional/tutorial_searches.ipynb b/notebooks/chapter_optional/tutorial_searches.ipynb index 9a02540..8f96184 100644 --- a/notebooks/chapter_optional/tutorial_searches.ipynb +++ b/notebooks/chapter_optional/tutorial_searches.ipynb @@ -7,19 +7,16 @@ "Tutorial: Alternative Searches\n", "==============================\n", "\n", - "Up to now, we've always used the non-linear search Nautilus and not considered the input parameters that control its\n", - "sampling. In this tutorial, we'll consider how we can change these setting to balance finding the global maxima\n", - "solution with fast run time.\n", + "Chapter 2 introduces lens modeling using Nautilus. This optional tutorial explores alternative search settings,\n", + "optimisation and Markov chain Monte Carlo (MCMC) after you have completed HowToLens.\n", "\n", - "We will also discuss other types of non-linear searches, such as MCMC and optimizers, which we can use to perform lens\n", - "modeling. So far, we have no found any of these alternatives to give anywhere near as robust and efficient results as\n", - "Nautilus, and we recommend users use Nautilus unless they are particularly interested in investigating different\n", - "model-fitting techniques.\n", + "The dataset, model and Analysis object retain the same roles. Changing the search changes how parameter space is\n", + "explored and which information is returned. Inspect the fits and assess the exploration before trusting the results.\n", "\n", "__Contents__\n", "\n", "- **Nested Sampling:** Lets first perform the model-fit using Nautilus, but look at different parameters that control how.\n", - "- **Optimizers:** There are a class of non-linear searches called optimizers, which seek to optimize the log likelihood.\n", + "- **Optimisation:** Improve parameter values from multiple starting points using Prodigy.\n", "- **MCMC:** For users familiar with Markov Chain Monte Carlo (MCMC) non-linear samplers, PyAutoFit supports the." ] }, @@ -349,35 +346,66 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Optimizers__\n", - "\n", - "Nested sampling algorithms like Nautilus provides the errors on all of the model parameters, by fully mapping out all \n", - "of the high likelihood regions of parameter space. This provides knowledge on the complete *range* of models that do \n", - "and do not provide high likelihood fits to the data, but takes many extra iterations to perform. If we require precise \n", - "error estimates (perhaps this is our final lens model fit before we publish the results in a paper), these extra\n", - "iterations are acceptable. \n", - "\n", - "However, we often don't care about the errors. For example, in chapter 2's search chaining tutorial, the only\n", - "result we used from the fit performed in the first search was the maximum log likelihood model, omitting the errors\n", - "entirely! Its seems wasteful to use a nested sampling algorithm like Nautilus to map out the entirity of parameter\n", - "space when we don't use this information!\n", - "\n", - "There are a class of non-linear searches called `optimizers`, which seek to optimize just one thing, the log\n", - "likelihood. They want to find the model that maximizes the log likelihood, with no regard for the errors, thus not\n", - "wasting time mapping out in intricate detail every facet of parameter space.\n", - "\n", - "PyAutoFit supports a number of optimizers, which can be used as an alternative to nested sampling when only the\n", - "maximum likelihood model is needed. These include `LBFGS` and `BFGS` (from scipy), which descend the likelihood from a\n", - "single starting point. A single-start optimizer generally needs a good starting point to work well, and in our\n", - "experience the parameter spaces fitted by lens models are often too complex for it without careful setup of initialization\n", - "priors.\n", - "\n", - "PyAutoFit also supports multi-start gradient optimizers (`MultiStartProdigy`, `MultiStartAdam`, `MultiStartADABelief`\n", - "and `MultiStartLion`), which use JAX to launch many optimizations from starting points spread across parameter space\n", - "in parallel and return the best one. This makes them far more robust to complex parameter spaces, and\n", - "`MultiStartProdigy` is the optimizer used by many of the `start_here.py` examples in the `autolens_workspace`. Like any optimizer, they\n", - "return only the best-fit model with no errors. The `autolens_workspace` script `scripts/guides/modeling/searches.py` describes\n", - "every search, including these optimizers, in detail.\n", + "__Optimisation__\n", + "\n", + "An optimiser repeatedly tries to improve a model. Starting from one set of parameter values, it works out which\n", + "changes are likely to produce a better fit, updates the parameters and evaluates the new model. Repeating this process\n", + "moves it towards a peak: a region where nearby parameter values no longer improve the fit.\n", + "\n", + "You can think of this as making increasingly informed guesses, aiming for higher-likelihood solutions. Prodigy also\n", + "takes the priors into account, so it balances how well the model fits with the probability assigned to its parameter\n", + "values. This is maximum a posteriori (MAP) optimisation.\n", + "\n", + "A peak need not be the best solution overall. Prodigy therefore repeats this process from several starting points,\n", + "giving it more opportunities to find a good model.\n", + "\n", + "Prodigy uses gradients to guide its updates: these describe how changing each parameter affects the posterior\n", + "probability. PyAutoLens calculates these gradients automatically using a numerical computing library called **JAX**.\n", + "You do not need to use JAX directly to run this example.\n", + "\n", + "We use 48 starting points, with up to 300 optimisation steps for each. The search can stop earlier when its stopping\n", + "criteria are met. Increasing either setting allows more exploration but also requires more computation. The batch size\n", + "of 4 limits how many starts are processed together; it does not reduce the total number of starts." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "search = af.MultiStartProdigy(\n", + " path_prefix=Path(\"howtolens\") / \"chapter_optional\",\n", + " name=\"tutorial_searches_prodigy\",\n", + " unique_tag=dataset_name,\n", + " n_starts=48,\n", + " n_steps=300,\n", + " batch_size=4,\n", + ")\n", + "\n", + "result_prodigy = search.fit(model=model, analysis=analysis)\n", + "\n", + "print(result_prodigy.info)\n", + "\n", + "aplt.subplot_fit_imaging(fit=result_prodigy.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Prodigy finds a best-fitting set of parameter values, but it does not tell us how uncertain those values are. An\n", + "Einstein radius of 1.6 arcseconds, for example, does not tell us whether values of 1.5 or 1.7 arcseconds would also be\n", + "consistent with the data.\n", + "\n", + "Look for whether the model reproduces the location, shape and brightness of the lensed emission. In the normalised\n", + "residuals, inspect whether coherent structures remain that the model has failed to explain.\n", + "\n", + "A plausible parameter value does not establish that the fit is good. Likewise, small residuals do not prove that the\n", + "search has found the best possible solution or measured parameter uncertainty.\n", + "\n", + "**\ud83e\udd16 Ask AI:** My optimised lens model leaves an arc-shaped pattern in the normalised residuals. What should I\n", + "investigate before trusting its inferred parameters?\n", "\n", "__MCMC__\n", "\n", @@ -511,7 +539,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_optional/tutorial_searches.ipynb in HowToLens).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoLens calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoLens docs (https://pyautolens.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_configure_search\n\n---\nname: al_configure_search\ndescription: Pick and tune a non-linear search for a lens-modelling fit. Defaults to Nautilus (nested sampling, the recommended choice); covers Dynesty, Emcee, Zeus, and the JAX multi-start gradient optimizers (MultiStartProdigy recommended when a fast MAP point estimate on a parametric source is wanted — not pixelized). Sets sampler-specific knobs (live points, walkers, tolerance) and the output `path_prefix` / `name` that determine where results land. Pairs with `al_run_search`, which actually calls `search.fit`.\n---\n\n# Configuring a non-linear search\n\nThe non-linear search is *how* PyAutoFit explores the model's parameter space. PyAutoLens\nexposes the same searches PyAutoFit ships, with Nautilus as the default. Picking the\nright one — and tuning its knobs sensibly — is often the difference between a fit that\nconverges in hours and one that doesn't converge at all.\n\nFor the catalogue of available searches and when to use each,\n[`wiki/core/api/searches.md`](../wiki/core/api/searches.md). For the *concept* of a non-linear\nsearch (what nested sampling does, what MCMC does, what gradient descent does),\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md).\n\n## Ask\n\n- *\"How complex is the model?\"* — number of free parameters and whether any are\n expected to be multi-modal. Multi-modality strongly favours nested sampling\n (Nautilus / Dynesty) over MCMC.\n- *\"How fast does the likelihood evaluate?\"* — fast (<1s with JAX) → can afford more\n live points or walkers. Slow → tighten the search.\n- *\"Is this a first exploratory fit, or a final production run?\"* — exploratory fits\n use fewer live points and looser tolerance to fail fast.\n- *\"Where should the output go?\"* — `output//modeling///` is the\n convention; the user chooses `` and ``.\n\n## Branch — Nautilus (recommended default)\n\nFor most lens models — parametric, pixelised, simple, complex — Nautilus is the right\nfirst pick. It handles multi-modal posteriors and is fast enough on modern CPUs.\n\n```python\n# scripts/configure_search.py\nimport autofit as af\n\nsearch = af.Nautilus(\n path_prefix=\"imaging/\",\n name=\"modeling_sie_sersic\",\n unique_tag=\"\",\n n_live=200, # 100 for exploration, 200 for production, 400+ for complex models\n iterations_per_full_update=2500,\n number_of_cores=4, # parallel likelihood evaluations\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/nautilus/`.\n\nKnobs to know:\n- `n_live` — more = more accurate posterior, slower. Start at 200; go to 400+ only if\n the posterior looks multi-modal or thin.\n- `number_of_cores` — parallel likelihood evaluations via Python multiprocessing, **only when\n JAX is off**. JAX disables multiprocessing, so a JAX fit gains nothing from it — leave it\n unset there (it defaults to 1; passing `1` explicitly just implies a parallelism that isn't\n there). Set it to your core count only for non-JAX CPU fits — see\n \"Branch — CPU acceleration\" below, which decides *which* regime a fit belongs to.\n- `iterations_per_full_update` / `iterations_per_quick_update` — how often the search\n writes full output (samples, visualisation) vs quick intermediate updates to disk.\n **Actively choose `iterations_per_quick_update` so the user always has quick access to\n result inspection** — don't just take the default. Judge it against the likelihood cost so\n the first on-the-fly `fit.png` / `samples` lands within a few minutes and refreshes\n regularly, but not so often that per-update visualisation overhead eats into throughput.\n Rules of thumb: ~500–1000 is a good interactive default; **lower it for a slow/expensive\n likelihood** (large MGE, pixelised source, GPU-batched fit, high `n_live`) so an inspection\n point still appears early; only **raise it** (≈2500–5000) when the likelihood is very fast\n and frequent updates would measurably dominate runtime. A common failure is leaving it high\n on a heavy fit, so the run shows *nothing* to inspect for an hour — avoid that. On HPC/batch\n runs the same value governs what a `sync pull` surfaces, so pick it before submitting.\n - **Set it the right way — directly on the search.** Pass `iterations_per_quick_update=…`\n straight to the search constructor, e.g. `af.Nautilus(..., iterations_per_quick_update=…)`\n (the idiom used throughout `autolens_workspace`, e.g. `point_source/modeling.py`,\n `weak/modeling.py`). Do **not** try to set it via `settings_search.search_dict[...] = …`:\n `SettingsSearch.search_dict` is a fixed-key property (`path_prefix`, `unique_tag`,\n `number_of_cores`, `session`, `use_jax_vmap`), so assigning a new key to it is a **silent\n no-op** — the value never reaches the search and the config default (often `1e99`, i.e.\n *never* quick-update) silently wins. To set it globally for a whole pipeline without\n editing every search, write it to the live config once after `conf.instance.push(...)`:\n `conf.instance[\"general\"][\"updates\"][\"iterations_per_quick_update\"] = N`.\n\n## Branch — CPU acceleration (JAX vs sparse operators)\n\nOn CPU the right accelerator depends on the **source model**. This is the single biggest CPU\nruntime lever in lens modelling, and getting it backwards costs days, not minutes — a full SLaM\nrun misconfigured here spends >12 h stuck in its first search.\n\n| Fit type | Accelerator | `use_jax` | `number_of_cores` | Dataset |\n|---|---|---|---|---|\n| **Parametric source** (`source_lp`, most non-pixelised fits) | JAX — vectorises the likelihood, parallelises well **on CPU** | `True` | leave unset (JAX disables multiprocessing) | plain |\n| **Pixelised source** (`source_pix`, `light`, `mass` — any fit with a `Pixelization`) | Sparse operator formalism (numba) | `False` | your core count | `dataset.apply_sparse_operator_cpu()` |\n\nTwo rules that are easy to get wrong:\n\n- **JAX is not GPU-only.** It is the correct accelerator for *parametric* fits on CPU too. Do\n not reach for `use_jax=False` + many cores just because there is no GPU.\n- **The sparse operator does not support JAX.** It is numba-based, so never combine them: a\n pixelised CPU fit is `apply_sparse_operator_cpu()` + `use_jax=False` + `number_of_cores=N`.\n `apply_sparse_operator_cpu()` precomputes operator matrices once (seconds to minutes) and\n every later pixelised fit reuses them, exploiting the sparsity of the pixelisation linear\n algebra for a large CPU speed-up.\n\n```python\n# Parametric source on CPU — JAX, no number_of_cores.\nanalysis = al.AnalysisImaging(dataset=dataset, use_jax=True)\nsettings_search = af.SettingsSearch(path_prefix=..., unique_tag=..., session=None)\n\n# Pixelised source on CPU — sparse operators, JAX off, multiprocessing on.\ndataset_pix = dataset.apply_sparse_operator_cpu()\nanalysis = al.AnalysisImaging(dataset=dataset_pix, use_jax=False)\nsettings_search = af.SettingsSearch(\n path_prefix=..., unique_tag=..., session=None, number_of_cores=8\n)\n```\n\n`number_of_cores` reaches the search through `af.SettingsSearch` (it is one of `search_dict`'s\nfixed keys), so pass it there rather than to the search constructor.\n\n**A SLaM pipeline spans both regimes.** SOURCE LP is parametric (JAX); every stage after it uses\na pixelised source (sparse/CPU). So build **two** `af.SettingsSearch` objects — one without\n`number_of_cores` for SOURCE LP, one with N for the pixelised stages — and hand each stage the\nright dataset (`dataset` vs `dataset_pix`). On **GPU**, JAX is used throughout and the sparse\noperator is not applied at all.\n\nSource / worked example:\n`autolens_workspace:scripts/imaging/features/pixelization/cpu_fast_modeling.py`.\n\n## Branch — MultiStartProdigy (JAX gradient optimizer, parametric sources)\n\nWhen the user explicitly wants a **JAX gradient optimizer** — a fast maximum-a-posteriori (MAP)\n*point* estimate rather than a full posterior — the recommended default is `MultiStartProdigy`.\nReach for it when the goal is speed to a best-fit model on a **parametric source** (MGE, Sersic)\nand errors are not yet needed; otherwise keep Nautilus.\n\n```python\nimport autofit as af\n\nsearch = af.MultiStartProdigy(\n path_prefix=\"imaging/\",\n name=\"modeling_sie_sersic\",\n unique_tag=\"\",\n n_starts=50, # broad starts run in parallel via jax.vmap\n n_steps=500,\n)\n```\n\nRequires a JAX-traceable analysis: `al.AnalysisImaging(dataset=dataset, use_jax=True)` (the\nparametric-source regime of \"Branch — CPU acceleration\" above).\n\nWhy Prodigy, and what the family is:\n\n- The **multi-start** approach — launch many broad starts in parallel and keep the best — was\n introduced for strong-lens modelling by **GIGA-Lens** (Gu, Huang et al. 2022, arXiv:2202.07663;\n GIGA-Lens 2.0, arXiv:2606.30633). It is what makes a gradient optimizer robust on the\n multi-modal lens likelihood, where a single-start optimizer gets stuck.\n- **`MultiStartProdigy`** uses the *learning-rate free* Prodigy rule (Mishchenko & Defazio 2024,\n arXiv:2306.06101): it tunes its own step size, so there is no `learning_rate` to set, and it\n reaches the same maximum as a hand-tuned `MultiStartAdam`. Recommend it as the default.\n- **`MultiStartAdam`** is the GIGA-Lens original (needs a chosen `learning_rate`);\n **`MultiStartADABelief`** is a drop-in Adam-variant alternative. (`MultiStartLion` is a further\n sign-based option that prefers a ~10x smaller `learning_rate`.)\n\n**Parametric sources only, for now.** These optimizers are validated and recommended for\nparametric sources. For a **pixelised source** (any fit with a `Pixelization`) they do **not**\nyet reliably work: the pixelised likelihood has regions where the gradient becomes non-finite,\nso the optimizer stalls short of the best fit, and `Nautilus` is both more reliable and faster\nthere. Making the JAX multi-start optimizers work on pixelised sources is ongoing work — so for\nany pixelised fit recommend Nautilus (with the sparse-operator CPU regime above), not a gradient\noptimizer.\n\nLike every optimizer it returns a single best-fit model, no errors — hand it to Nautilus / MCMC\nafterwards if a posterior is needed.\n\nSource: `PyAutoFit:autofit/non_linear/search/mle/multi_start_gradient/`.\n\n## Branch — Dynesty\n\nUse Dynesty for problems where you specifically want its dynamic sampling features\n(e.g. focusing samples in the posterior tails for precise evidence estimation).\n\n```python\nsearch = af.DynestyStatic(\n path_prefix=\"...\",\n name=\"...\",\n nlive=150,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/dynesty/`.\n\n## Branch — Emcee (MCMC)\n\nUse Emcee for posterior characterisation on a *known unimodal* posterior, when you\nalready have a tight initial guess (e.g. from a chained earlier fit). Don't use for\nexploration of multi-modal spaces.\n\n```python\nsearch = af.Emcee(\n path_prefix=\"...\",\n name=\"...\",\n nwalkers=50,\n nsteps=10000,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/mcmc/emcee/`.\n\n## Branch — Other searches\n\nEvery search PyAutoFit ships, generated from the installed release's search manifest\n(`python -m autofit search-manifest --json`; regenerate with PyAutoHands\n`autohands regenerate_search_roster --root .`, never by hand):\n\n\n\n- **Markov chain Monte Carlo** (`mcmc`): `af.Emcee`, `af.Zeus`, `af.BlackJAXNUTS`, `af.SMC` (experimental) — example: `autofit_workspace:scripts/searches/mcmc.py`\n- **Nested sampling** (`nest`): `af.DynestyStatic`, `af.DynestyDynamic`, `af.Nautilus`, `af.NSS` (experimental) — example: `autofit_workspace:scripts/searches/nest.py`\n- **Maximum likelihood / maximum a posteriori** (`mle`): `af.Drawer`, `af.BFGS`, `af.LBFGS`, `af.MultiStartAdam`, `af.MultiStartADABelief` (experimental), `af.MultiStartLion` (experimental), `af.MultiStartProdigy` — example: `autofit_workspace:scripts/searches/mle.py`\n\n\nZeus (ensemble slice MCMC), DynestyDynamic (dynamic nested sampling), NSS (JAX nested slice\nsampling), BlackJAXNUTS and SMC (JAX gradient MCMC; SMC also returns the evidence), BFGS / LBFGS\n(single-start gradient descent for MLE), Drawer (random prior draws — debugging only). NSS,\nBlackJAXNUTS and SMC need a JAX-traceable analysis (`use_jax=True`). See\n[`wiki/core/api/searches.md`](../wiki/core/api/searches.md) for the comparison table. For a\n*JAX* gradient optimizer, prefer the multi-start family (`MultiStartProdigy` and friends) in\n\"Branch — MultiStartProdigy\" above over single-start `BFGS`/`LBFGS`.\n\n## Branch — Live visual updates\n\nWhen configuring an **interactive production fit** (foreground script or notebook), ask once:\n*watch the fit update live?* The quick-update image (`fit.png`) is **always written to disk**\nevery `iterations_per_quick_update` iterations regardless; `live_visual_update=True` (default\n`False`) additionally pushes it to a live display surface:\n\n- **foreground Python script** — a matplotlib viewer opens and refreshes with each quick\n update;\n- **Jupyter / Colab** — the cell that ran `search.fit(...)` refreshes one image in place;\n- **HPC, headless, background, or unattended runs** — keep it `False` (nothing to attach to;\n HPC mode disables it in config).\n\n```python\nsearch = af.Nautilus(\n ...,\n iterations_per_quick_update=1000, # quick-update (and live refresh) cadence\n live_visual_update=True, # script: matplotlib viewer; notebook: in-place cell\n)\n```\n\nBoth are shared search options (accepted by every search via the common base class), with\nconfig fallbacks in `config/general.yaml` `updates:`. Don't re-ask on later runs — the\nchoice is recorded in the search configuration.\n\nSource: `PyAutoFit:autofit/non_linear/search/abstract_search.py`.\n\n## Output folder layout\n\nAfter `search.fit(...)` runs, results land at:\n\n```\noutput////\n files/\n tracer.json\n model.json\n samples.csv\n samples_summary.json\n search.json\n image/\n dataset.fits\n fit.fits\n ...\n model.info\n model.results\n```\n\nThe `unique_id` hash is derived from the model + dataset + search settings, so identical\nre-runs land in the same folder (and resume from where they stopped).\n\nThe abbreviated tree above is enough to configure a search; the fuller, always-current\nannotation of every file — plus the fact that all of it is written **on the fly** while\nthe search runs — is `__Output Folder Layout__` in\n[`autolens_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling.py).\nPoint a newcomer (or a teacher-mode session) there rather than expanding this block —\n`_style.md` \"Output folder announcement\" has the rule.\n\nSee [`al_load_results`](./al_load_results.md) for the inverse — loading what\n`search.fit` writes.\n\n## Combine\n\n- [`al_run_search`](./al_run_search.md) — call `search.fit(model=..., analysis=...)`.\n- [`al_chain_searches`](./al_chain_searches.md) — feed this search's result into a\n follow-up.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) — when the search runs but the\n result is wrong.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens (optional): Alternative non-linear search\n algorithms](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_searches.ipynb):\n the menu of searches beyond Nautilus (MCMC, optimizers) and how to think about\n tuning them.\n- **General reference** — [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n tour of advanced capabilities; search configuration interacts directly with most\n of them (especially pixelization, MGE, point-source).\n- **Experienced PyAutoLens user** — [workspace/lens: guides/modeling/slam_start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/modeling/slam_start_here.py):\n the SLaM pipeline pre-configures sensible searches per stage — a reference for\n *which* knobs matter at *which* phase.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_optional/tutorial_searches.ipynb in HowToLens).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoLens calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoLens docs (https://pyautolens.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_configure_search\n\n---\nname: al_configure_search\ndescription: Pick and tune a non-linear search for a lens-modelling fit. Defaults to Nautilus (nested sampling, the recommended choice); covers Dynesty, Emcee, Zeus, and the JAX multi-start gradient optimizers (MultiStartProdigy recommended when a fast MAP point estimate on a parametric source is wanted \u2014 not pixelized). Sets sampler-specific knobs (live points, walkers, tolerance) and the output `path_prefix` / `name` that determine where results land. Pairs with `al_run_search`, which actually calls `search.fit`.\n---\n\n# Configuring a non-linear search\n\nThe non-linear search is *how* PyAutoFit explores the model's parameter space. PyAutoLens\nexposes the same searches PyAutoFit ships, with Nautilus as the default. Picking the\nright one \u2014 and tuning its knobs sensibly \u2014 is often the difference between a fit that\nconverges in hours and one that doesn't converge at all.\n\nFor the catalogue of available searches and when to use each,\n[`wiki/core/api/searches.md`](../wiki/core/api/searches.md). For the *concept* of a non-linear\nsearch (what nested sampling does, what MCMC does, what gradient descent does),\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md).\n\n## Ask\n\n- *\"How complex is the model?\"* \u2014 number of free parameters and whether any are\n expected to be multi-modal. Multi-modality strongly favours nested sampling\n (Nautilus / Dynesty) over MCMC.\n- *\"How fast does the likelihood evaluate?\"* \u2014 fast (<1s with JAX) \u2192 can afford more\n live points or walkers. Slow \u2192 tighten the search.\n- *\"Is this a first exploratory fit, or a final production run?\"* \u2014 exploratory fits\n use fewer live points and looser tolerance to fail fast.\n- *\"Where should the output go?\"* \u2014 `output//modeling///` is the\n convention; the user chooses `` and ``.\n\n## Branch \u2014 Nautilus (recommended default)\n\nFor most lens models \u2014 parametric, pixelised, simple, complex \u2014 Nautilus is the right\nfirst pick. It handles multi-modal posteriors and is fast enough on modern CPUs.\n\n```python\n# scripts/configure_search.py\nimport autofit as af\n\nsearch = af.Nautilus(\n path_prefix=\"imaging/\",\n name=\"modeling_sie_sersic\",\n unique_tag=\"\",\n n_live=200, # 100 for exploration, 200 for production, 400+ for complex models\n iterations_per_full_update=2500,\n number_of_cores=4, # parallel likelihood evaluations\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/nautilus/`.\n\nKnobs to know:\n- `n_live` \u2014 more = more accurate posterior, slower. Start at 200; go to 400+ only if\n the posterior looks multi-modal or thin.\n- `number_of_cores` \u2014 parallel likelihood evaluations via Python multiprocessing, **only when\n JAX is off**. JAX disables multiprocessing, so a JAX fit gains nothing from it \u2014 leave it\n unset there (it defaults to 1; passing `1` explicitly just implies a parallelism that isn't\n there). Set it to your core count only for non-JAX CPU fits \u2014 see\n \"Branch \u2014 CPU acceleration\" below, which decides *which* regime a fit belongs to.\n- `iterations_per_full_update` / `iterations_per_quick_update` \u2014 how often the search\n writes full output (samples, visualisation) vs quick intermediate updates to disk.\n **Actively choose `iterations_per_quick_update` so the user always has quick access to\n result inspection** \u2014 don't just take the default. Judge it against the likelihood cost so\n the first on-the-fly `fit.png` / `samples` lands within a few minutes and refreshes\n regularly, but not so often that per-update visualisation overhead eats into throughput.\n Rules of thumb: ~500\u20131000 is a good interactive default; **lower it for a slow/expensive\n likelihood** (large MGE, pixelised source, GPU-batched fit, high `n_live`) so an inspection\n point still appears early; only **raise it** (\u22482500\u20135000) when the likelihood is very fast\n and frequent updates would measurably dominate runtime. A common failure is leaving it high\n on a heavy fit, so the run shows *nothing* to inspect for an hour \u2014 avoid that. On HPC/batch\n runs the same value governs what a `sync pull` surfaces, so pick it before submitting.\n - **Set it the right way \u2014 directly on the search.** Pass `iterations_per_quick_update=\u2026`\n straight to the search constructor, e.g. `af.Nautilus(..., iterations_per_quick_update=\u2026)`\n (the idiom used throughout `autolens_workspace`, e.g. `point_source/modeling.py`,\n `weak/modeling.py`). Do **not** try to set it via `settings_search.search_dict[...] = \u2026`:\n `SettingsSearch.search_dict` is a fixed-key property (`path_prefix`, `unique_tag`,\n `number_of_cores`, `session`, `use_jax_vmap`), so assigning a new key to it is a **silent\n no-op** \u2014 the value never reaches the search and the config default (often `1e99`, i.e.\n *never* quick-update) silently wins. To set it globally for a whole pipeline without\n editing every search, write it to the live config once after `conf.instance.push(...)`:\n `conf.instance[\"general\"][\"updates\"][\"iterations_per_quick_update\"] = N`.\n\n## Branch \u2014 CPU acceleration (JAX vs sparse operators)\n\nOn CPU the right accelerator depends on the **source model**. This is the single biggest CPU\nruntime lever in lens modelling, and getting it backwards costs days, not minutes \u2014 a full SLaM\nrun misconfigured here spends >12 h stuck in its first search.\n\n| Fit type | Accelerator | `use_jax` | `number_of_cores` | Dataset |\n|---|---|---|---|---|\n| **Parametric source** (`source_lp`, most non-pixelised fits) | JAX \u2014 vectorises the likelihood, parallelises well **on CPU** | `True` | leave unset (JAX disables multiprocessing) | plain |\n| **Pixelised source** (`source_pix`, `light`, `mass` \u2014 any fit with a `Pixelization`) | Sparse operator formalism (numba) | `False` | your core count | `dataset.apply_sparse_operator_cpu()` |\n\nTwo rules that are easy to get wrong:\n\n- **JAX is not GPU-only.** It is the correct accelerator for *parametric* fits on CPU too. Do\n not reach for `use_jax=False` + many cores just because there is no GPU.\n- **The sparse operator does not support JAX.** It is numba-based, so never combine them: a\n pixelised CPU fit is `apply_sparse_operator_cpu()` + `use_jax=False` + `number_of_cores=N`.\n `apply_sparse_operator_cpu()` precomputes operator matrices once (seconds to minutes) and\n every later pixelised fit reuses them, exploiting the sparsity of the pixelisation linear\n algebra for a large CPU speed-up.\n\n```python\n# Parametric source on CPU \u2014 JAX, no number_of_cores.\nanalysis = al.AnalysisImaging(dataset=dataset, use_jax=True)\nsettings_search = af.SettingsSearch(path_prefix=..., unique_tag=..., session=None)\n\n# Pixelised source on CPU \u2014 sparse operators, JAX off, multiprocessing on.\ndataset_pix = dataset.apply_sparse_operator_cpu()\nanalysis = al.AnalysisImaging(dataset=dataset_pix, use_jax=False)\nsettings_search = af.SettingsSearch(\n path_prefix=..., unique_tag=..., session=None, number_of_cores=8\n)\n```\n\n`number_of_cores` reaches the search through `af.SettingsSearch` (it is one of `search_dict`'s\nfixed keys), so pass it there rather than to the search constructor.\n\n**A SLaM pipeline spans both regimes.** SOURCE LP is parametric (JAX); every stage after it uses\na pixelised source (sparse/CPU). So build **two** `af.SettingsSearch` objects \u2014 one without\n`number_of_cores` for SOURCE LP, one with N for the pixelised stages \u2014 and hand each stage the\nright dataset (`dataset` vs `dataset_pix`). On **GPU**, JAX is used throughout and the sparse\noperator is not applied at all.\n\nSource / worked example:\n`autolens_workspace:scripts/imaging/features/pixelization/cpu_fast_modeling.py`.\n\n## Branch \u2014 MultiStartProdigy (JAX gradient optimizer, parametric sources)\n\nWhen the user explicitly wants a **JAX gradient optimizer** \u2014 a fast maximum-a-posteriori (MAP)\n*point* estimate rather than a full posterior \u2014 the recommended default is `MultiStartProdigy`.\nReach for it when the goal is speed to a best-fit model on a **parametric source** (MGE, Sersic)\nand errors are not yet needed; otherwise keep Nautilus.\n\n```python\nimport autofit as af\n\nsearch = af.MultiStartProdigy(\n path_prefix=\"imaging/\",\n name=\"modeling_sie_sersic\",\n unique_tag=\"\",\n n_starts=50, # broad starts run in parallel via jax.vmap\n n_steps=500,\n)\n```\n\nRequires a JAX-traceable analysis: `al.AnalysisImaging(dataset=dataset, use_jax=True)` (the\nparametric-source regime of \"Branch \u2014 CPU acceleration\" above).\n\nWhy Prodigy, and what the family is:\n\n- The **multi-start** approach \u2014 launch many broad starts in parallel and keep the best \u2014 was\n introduced for strong-lens modelling by **GIGA-Lens** (Gu, Huang et al. 2022, arXiv:2202.07663;\n GIGA-Lens 2.0, arXiv:2606.30633). It is what makes a gradient optimizer robust on the\n multi-modal lens likelihood, where a single-start optimizer gets stuck.\n- **`MultiStartProdigy`** uses the *learning-rate free* Prodigy rule (Mishchenko & Defazio 2024,\n arXiv:2306.06101): it tunes its own step size, so there is no `learning_rate` to set, and it\n reaches the same maximum as a hand-tuned `MultiStartAdam`. Recommend it as the default.\n- **`MultiStartAdam`** is the GIGA-Lens original (needs a chosen `learning_rate`);\n **`MultiStartADABelief`** is a drop-in Adam-variant alternative. (`MultiStartLion` is a further\n sign-based option that prefers a ~10x smaller `learning_rate`.)\n\n**Parametric sources only, for now.** These optimizers are validated and recommended for\nparametric sources. For a **pixelised source** (any fit with a `Pixelization`) they do **not**\nyet reliably work: the pixelised likelihood has regions where the gradient becomes non-finite,\nso the optimizer stalls short of the best fit, and `Nautilus` is both more reliable and faster\nthere. Making the JAX multi-start optimizers work on pixelised sources is ongoing work \u2014 so for\nany pixelised fit recommend Nautilus (with the sparse-operator CPU regime above), not a gradient\noptimizer.\n\nLike every optimizer it returns a single best-fit model, no errors \u2014 hand it to Nautilus / MCMC\nafterwards if a posterior is needed.\n\nSource: `PyAutoFit:autofit/non_linear/search/mle/multi_start_gradient/`.\n\n## Branch \u2014 Dynesty\n\nUse Dynesty for problems where you specifically want its dynamic sampling features\n(e.g. focusing samples in the posterior tails for precise evidence estimation).\n\n```python\nsearch = af.DynestyStatic(\n path_prefix=\"...\",\n name=\"...\",\n nlive=150,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/dynesty/`.\n\n## Branch \u2014 Emcee (MCMC)\n\nUse Emcee for posterior characterisation on a *known unimodal* posterior, when you\nalready have a tight initial guess (e.g. from a chained earlier fit). Don't use for\nexploration of multi-modal spaces.\n\n```python\nsearch = af.Emcee(\n path_prefix=\"...\",\n name=\"...\",\n nwalkers=50,\n nsteps=10000,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/mcmc/emcee/`.\n\n## Branch \u2014 Other searches\n\nEvery search PyAutoFit ships, generated from the installed release's search manifest\n(`python -m autofit search-manifest --json`; regenerate with PyAutoHands\n`autohands regenerate_search_roster --root .`, never by hand):\n\n\n\n- **Markov chain Monte Carlo** (`mcmc`): `af.Emcee`, `af.Zeus`, `af.BlackJAXNUTS`, `af.SMC` (experimental) \u2014 example: `autofit_workspace:scripts/searches/mcmc.py`\n- **Nested sampling** (`nest`): `af.DynestyStatic`, `af.DynestyDynamic`, `af.Nautilus`, `af.NSS` (experimental) \u2014 example: `autofit_workspace:scripts/searches/nest.py`\n- **Maximum likelihood / maximum a posteriori** (`mle`): `af.Drawer`, `af.BFGS`, `af.LBFGS`, `af.MultiStartAdam`, `af.MultiStartADABelief` (experimental), `af.MultiStartLion` (experimental), `af.MultiStartProdigy` \u2014 example: `autofit_workspace:scripts/searches/mle.py`\n\n\nZeus (ensemble slice MCMC), DynestyDynamic (dynamic nested sampling), NSS (JAX nested slice\nsampling), BlackJAXNUTS and SMC (JAX gradient MCMC; SMC also returns the evidence), BFGS / LBFGS\n(single-start gradient descent for MLE), Drawer (random prior draws \u2014 debugging only). NSS,\nBlackJAXNUTS and SMC need a JAX-traceable analysis (`use_jax=True`). See\n[`wiki/core/api/searches.md`](../wiki/core/api/searches.md) for the comparison table. For a\n*JAX* gradient optimizer, prefer the multi-start family (`MultiStartProdigy` and friends) in\n\"Branch \u2014 MultiStartProdigy\" above over single-start `BFGS`/`LBFGS`.\n\n## Branch \u2014 Live visual updates\n\nWhen configuring an **interactive production fit** (foreground script or notebook), ask once:\n*watch the fit update live?* The quick-update image (`fit.png`) is **always written to disk**\nevery `iterations_per_quick_update` iterations regardless; `live_visual_update=True` (default\n`False`) additionally pushes it to a live display surface:\n\n- **foreground Python script** \u2014 a matplotlib viewer opens and refreshes with each quick\n update;\n- **Jupyter / Colab** \u2014 the cell that ran `search.fit(...)` refreshes one image in place;\n- **HPC, headless, background, or unattended runs** \u2014 keep it `False` (nothing to attach to;\n HPC mode disables it in config).\n\n```python\nsearch = af.Nautilus(\n ...,\n iterations_per_quick_update=1000, # quick-update (and live refresh) cadence\n live_visual_update=True, # script: matplotlib viewer; notebook: in-place cell\n)\n```\n\nBoth are shared search options (accepted by every search via the common base class), with\nconfig fallbacks in `config/general.yaml` `updates:`. Don't re-ask on later runs \u2014 the\nchoice is recorded in the search configuration.\n\nSource: `PyAutoFit:autofit/non_linear/search/abstract_search.py`.\n\n## Output folder layout\n\nAfter `search.fit(...)` runs, results land at:\n\n```\noutput////\n files/\n tracer.json\n model.json\n samples.csv\n samples_summary.json\n search.json\n image/\n dataset.fits\n fit.fits\n ...\n model.info\n model.results\n```\n\nThe `unique_id` hash is derived from the model + dataset + search settings, so identical\nre-runs land in the same folder (and resume from where they stopped).\n\nThe abbreviated tree above is enough to configure a search; the fuller, always-current\nannotation of every file \u2014 plus the fact that all of it is written **on the fly** while\nthe search runs \u2014 is `__Output Folder Layout__` in\n[`autolens_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling.py).\nPoint a newcomer (or a teacher-mode session) there rather than expanding this block \u2014\n`_style.md` \"Output folder announcement\" has the rule.\n\nSee [`al_load_results`](./al_load_results.md) for the inverse \u2014 loading what\n`search.fit` writes.\n\n## Combine\n\n- [`al_run_search`](./al_run_search.md) \u2014 call `search.fit(model=..., analysis=...)`.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 feed this search's result into a\n follow-up.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) \u2014 when the search runs but the\n result is wrong.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens (optional): Alternative non-linear search\n algorithms](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_searches.ipynb):\n the menu of searches beyond Nautilus (MCMC, optimizers) and how to think about\n tuning them.\n- **General reference** \u2014 [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n tour of advanced capabilities; search configuration interacts directly with most\n of them (especially pixelization, MGE, point-source).\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/modeling/slam_start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/modeling/slam_start_here.py):\n the SLaM pipeline pre-configures sensible searches per stage \u2014 a reference for\n *which* knobs matter at *which* phase.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/scripts/chapter_2_lens_modeling/README.md b/scripts/chapter_2_lens_modeling/README.md index 031e045..d5ab32a 100644 --- a/scripts/chapter_2_lens_modeling/README.md +++ b/scripts/chapter_2_lens_modeling/README.md @@ -5,15 +5,14 @@ searches are chained together into automated lens modeling pipelines. # Files -- [Tutorial 1: Non-linear Search](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/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 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/2026.10.29.1/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 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: Realism and Complexity](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_2_lens_modeling/tutorial_3_realism_and_complexity.ipynb) — Finding a balance between realism and complexity when composing and fitting a lens model. -- [Tutorial 4: Dealing with Failure](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.ipynb) — What to do when PyAutoLens finds an inaccurate lens model. +- [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: Linear Profiles](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_2_lens_modeling/tutorial_5_linear_profiles.ipynb) — Light profiles which capture complex morphologies in a reduced number of non-linear parameters. +- [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: Masking and Positions](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.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. 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 55a302e..907e1e8 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,164 +1,102 @@ -r""" +""" Tutorial 1: Non-linear Search ============================= -The starting point for most scientific analysis conducted by an Astronomer is that they have observations of a strong lens -using a telescope like the Hubble Space Telescope, and seek to learn about the lens galaxy, source galaxy and the -Universe from these observations. With **PyAutoLens**, we seek to learn about the lens's mass and ray-tracing, asking questions like -how big is the lens galaxy and what does the unlensed source galaxy look like? +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. -To answer these questions, we must therefore fit the dataset with a lens model, where the lens model defines the -light and mass profiles that make up the lens and source galaxies we fit. Our goal is the find the combination of -light and mass profile parameters that best-fit the data, such that the model represents the strong lens, and therefore -the Universe, as well as possible. +By changing the parameters yourself, you could improve the fit and increase its log likelihood. This demonstrated how +the data constrain a lens model, but manually adjusting parameters becomes difficult as the model grows. -This process is called model-fitting, or "modeling" for short, and we actually did our first example of this in the -previous chapter. If you recall, in the fitting tutorial we set up a fit to a simulated dataset where the parameter -used to simulate the data were unknown, and you guessed the values of the parameters that best fit the data. You -iteratively improved the model-fit by guessing new parameters, over and over, finding solutions which produced -higher `log_likelihood` values. +In this chapter, we use a non-linear search to explore possible parameter values automatically. We will learn how to +find models that explain the observations, assess their uncertainties and recognise when a fit needs further attention. -However, this approach was not optimal: it was manual and slow, we had no certainty that we had found the best -(e.g. maximum likelihood) solution and for more complex models, with more parameters and profiles, it would -have been completely unfeasible. +We begin with simulated imaging, where we know the model used to generate the data. This lets us examine the fitting +process before tackling the additional challenges of real observations. -In this chapter, we perform modeling as a scientist would actually do it, and introduce the statistical inference -techniques that will ultimately allow us to fit complex models made of many light profiles to real strong lens data, -and begin learning about real galaxies in the Universe. +__Contents__ -This first tutorial introduces a number of key statistical concepts that are fundamental to understanding how -model-fitting works, both for **PyAutoLens** and in general. +- **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** +""" +""" __Overview__ -In this tutorial, we will use a non-linear search to fit a lens model to simulated imaging of strong lens. We will: - -- Introduce concept like a "parameter space", "likelihood surface" and "priors", and relate them to how a non-linear - search works. +This tutorial introduces the main pieces of an automated model fit: -- Introduce the `Analysis` class, which defines the `log_likelihood_function` that quantifies the goodness of fit of a - model instance to the data. +- The **dataset** contains the measurements and their uncertainties. +- The **model** describes the physical components and identifies which parameters are free to vary. +- The **Analysis** object connects the model to the dataset: it predicts the observables for a particular set of parameter values and evaluates their log likelihood. +- The **search** explores parameter space using this likelihood and the specified priors. -- Fit datasets with different non-linear searches, including a maximum likelihood estimator (MLE), - Markov Chain Monte Carlo (MCMC) and nested sampling. - -__Contents__ - -- **Overview:** In this tutorial, we will use a non-linear search to fit a lens model to simulated imaging of. -- **Parameter Space:** In mathematics, a function is defined by its parameters, which map inputs to outputs. -- **Non-Linear Search:** The method used to fit the model to the data, by sampling the non-linear parameter space. -- **Search Types:** There are different types of non-linear searches, each of which explores parameter space in a. -- **Deeper Background:** **The descriptions of how searches work in this example are simplified and phenomenological and do. -- **PyAutoFit:** Modeling uses the probabilistic programming language. -- **Initial Setup:** Let's first load the `Imaging` dataset, which we will use to fit a model with a non-linear search. -- **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:** Compose the lens model fitted to the data. -- **Priors:** When we examine the `.info` of our model, we notice that each parameter (like `centre`. -- **Analysis:** Create the Analysis object that defines how the model is fitted to the data. -- **Searches:** To perform a non-linear search, we create an instance of a `NonLinearSearch` object. -- **Maximum Likelihood Estimation (MLE):** The simplest search type, which moves "up" the likelihood gradient. -- **Markov Chain Monte Carlo (MCMC):** Walkers explore parameter space, mapping out the likelihood surface. -- **Nested Sampling:** **Nested Sampling** is an advanced method for model-fitting that excels in handling complex models. -- **What is The Best Search To Use?:** Choosing between MLE, MCMC and nested sampling for lens modeling. -- **Wrap Up:** Summary of the script and next steps. +We will explain parameter spaces, likelihood surfaces and priors, then use Nautilus to fit the model and inspect its +inferred parameters and uncertainties. +""" +""" __Parameter Space__ -In mathematics, a function is defined by its parameters, which map inputs to outputs. For example, consider the simple function: - -\[ -f(x) = x^2 -\] - -Here, \(x\) is the input parameter, and \(f(x)\) returns the output \(x^2\). This relationship defines -the "parameter space" of the function, which in this case forms a parabola. - -Functions can also have multiple parameters, such as: - -\[ -f(x, y, z) = x + y^2 - z^3 -\] - -This defines a parameter space in three dimensions, representing the relationships between \(x\), \(y\), \(z\), -and the output \(f(x, y, z)\). - -This concept of parameter space is closely related to how we approach model-fitting. For instance, in chapter 1, -we created instances of `Galaxy` objects with -parameters like \( (\text{`centre_0`}, \text{`centre_1`}, \text{`ell_comps_0`}, \text{`ell_comps_1`}, \text{`intensity`}, \text{`effective_radius`}, \text{`sersic_index`}) \). -These parameters were used to fit data and compute a log likelihood. - -We can think of this process as analogous to the function \(f(\( (\text{`centre_0`}, \text{`centre_1`}, \text{`ell_comps_0`}, \text{`ell_comps_1`}, \text{`intensity`}, \text{`effective_radius`}, \text{`sersic_index`}) \))\), -where the output is the log likelihood. This function, which maps parameter values to a log likelihood, is known -as the "likelihood function" in statistical inference. To be explicit, we’ll refer to it as the `log_likelihood_function` -since it deals with the log of the likelihood function. - -By framing the likelihood this way, we can think of our model as having its own parameter space—a multidimensional -surface defined by all possible values of the -parameters \( (\text{`centre_0`}, \text{`centre_1`}, \text{`ell_comps_0`}, \text{`ell_comps_1`}, \text{`intensity`}, \text{`effective_radius`}, \text{`sersic_index`}) \). -This surface, known as the "likelihood surface," represents how the log likelihood changes across different parameter -values. During model-fitting, our goal is to find the peak of this surface, where the fit to the data is optimal. - -This parameter space is "non-linear," meaning the relationship between the model parameters and the log likelihood is -not a simple linear one. Because of this non-linearity, we cannot predict the log likelihood from a given set of model -parameters without actually performing a fit to the data, as we did in tutorial 1. - -__Non-Linear Search__ +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**. -Now that we understand our problem in terms of a non-linear parameter space with a likelihood surface, we can -introduce the method used to fit the model to the data —- the "non-linear search". +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. -Previously, our approach involved manually guessing models until finding one with a good fit and high log likelihood. -Surprisingly, this random guessing forms the basis of how model-fitting using a non-linear search actually works! +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. -A non-linear search involves systematically guessing many models while tracking their log likelihoods. As the -algorithm progresses, it tends to favor models with parameter combinations that have previously yielded higher -log likelihoods. This iterative refinement helps to efficiently explore the vast parameter space. +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. -There are two key differences between guessing random models and using a non-linear search: - -- **Computational Efficiency**: The non-linear search can evaluate the log likelihood of a model parameter - combinations in milliseconds and therefore many thousands of models in minutes. This computational speed enables - it to thoroughly sample potential solutions, which would be impractical for a human. - -- **Effective Sampling**: The search algorithm maintains a robust memory of previously guessed models and their log - likelihoods. This allows it to sample potential solutions more thoroughly and converge on the highest - likelihood solutions more efficiently, which is again impractical for a human. - -Think of the non-linear search as systematically exploring parameter space to pinpoint regions with the highest log -likelihood values. Its primary goal is to identify and converge on the parameter values that best describe the data. - -__Search Types__ - -There are different types of non-linear searches, each of which explores parameter space in a unique way. -In this example, we will use three types of searches, which broadly represent the various approaches to non-linear -searches used in statistical inference. - -These are: +**🤖 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? +""" -- **Maximum Likelihood Estimation (MLE)**: This method aims to find the model that maximizes the likelihood function. - It does so by testing nearby models and adjusting parameters in the direction that increases the likelihood. +""" +__Automated Exploration__ -- **Markov Chain Monte Carlo (MCMC)**: This approach uses a group of "walkers" that explore parameter space randomly. - The likelihood at each walker's position influences the probability of the walker moving to a new position. +A non-linear search automates the exploration you performed manually in Chapter 1. -- **Nested Sampling**: This technique samples points from the parameter space iteratively. Lower likelihood points - are replaced by higher likelihood ones, gradually concentrating the samples in regions of high likelihood. +The search proposes parameter values. The Analysis object uses the corresponding model to predict the data and returns +a log likelihood. The search then uses its algorithm to decide which parameter values to evaluate next. -We will provide more details on each of these searches below. +Automating this process allows us to evaluate many more models than we could inspect by hand. It does not guarantee +that every search finds the best solution: its starting conditions, settings and the structure of parameter space all +matter. We will see examples of this later in the chapter. +""" +""" __Deeper Background__ -**The descriptions of how searches work in this example are simplified and phenomenological and do not give a full -description of how they work at a deep statistical level. The goal is to provide you with an intuition for how to use -them and when different searches are appropriate for different problems. Later tutorials will provide a more formal -description of how these searches work.** +The explanations here introduce what the search does and how to interpret its results. You do not need to understand +every detail of an algorithm to start using it, but you should understand what it estimates and how it can fail. -If you're interested in learning more about these principles, you can explore resources such as: +For now, work through the example and inspect its fit. After completing HowToLens, the optional searches tutorial and +the background resources linked below provide further detail on the methods. +- [Nested Sampling](https://www.imperial.ac.uk/media/imperial-college/research-centres-and-groups/astrophysics/public/icic/data-analysis-workshop/2016/NestedSampling_JRP.pdf) - [Markov Chain Monte Carlo (MCMC)](https://en.wikipedia.org/wiki/Markov_chain_Monte_Carlo) - [Introduction to MCMC Sampling](https://twiecki.io/blog/2015/11/10/mcmc-sampling/) -- [Nested Sampling](https://www.imperial.ac.uk/media/imperial-college/research-centres-and-groups/astrophysics/public/icic/data-analysis-workshop/2016/NestedSampling_JRP.pdf) - [A Zero-Math Introduction to MCMC Methods](https://towardsdatascience.com/a-zero-math-introduction-to-markov-chain-monte-carlo-methods-dcba889e0c50) """ @@ -173,47 +111,53 @@ """ __PyAutoFit__ -Modeling uses the probabilistic programming language -[PyAutoFit](https://github.com/PyAutoLabs/PyAutoFit), an open-source project that allows complex model -fitting techniques to be straightforwardly integrated into scientific modeling software. +PyAutoLens uses [PyAutoFit](https://github.com/PyAutoLabs/PyAutoFit) to define free parameters and priors, run non-linear searches and organise their results. -**PyAutoFit** is actually a spin-off project of **PyAutoLens**, whereby we found that the statistical techniques and -methods we applied to model galaxies could be used in a more general setting to many different scientific -problems. Check it out if you are interested in developing your own software to perform advanced model-fitting! +We import PyAutoFit as `af`. Its modeling and search tools work alongside the lensing components and Analysis objects +provided by PyAutoLens, which we import as `al`. -We import this library separately from **PyAutoLens**. +The same PyAutoFit tools can be used for other scientific problems by supplying a suitable model and Analysis object. """ + import autofit as af """ __Initial Setup__ -Let's first load the `Imaging` dataset, which we will use to fit a model with a non-linear search. +We begin with a simulated image containing a lensed source and no foreground lens light. The simulation uses an +`IsothermalSph` mass profile for the lens and an `ExponentialCoreSph` light profile for the source. -The strong lens in this image was generated using an `IsothermalSph` lens mass profile and `ExponentialCoreSph` source light profile, -which we'll also use in our model fitting in this tutorial. This means the model we are going to fit is identical to -the one used to simulate the data, allowing us to assess the fitting process under controlled conditions. +We will fit the same profile families, allowing their parameters to vary. This gives us a controlled example: the model +can represent the system that generated the data, so we can focus on how the search explores its parameters. -The dataset, as well as all subsequent datasets used in future tutorials, is stored in the HowToLens -repository's `dataset/imaging` folder (simulated at runtime by the simulator scripts, as shown below). +Noise still affects the inferred values. Even a successful search need not recover the simulation’s input parameters +exactly. + +The following code selects the dataset folder. The next cell generates the data if needed and loads the image, noise +map and point-spread function (PSF). """ + 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. +If the dataset is missing, this cell runs the simulator to create it. It then loads the files into an `Imaging` object +and plots the dataset. + +Inspect the lensed emission in the image and its strength relative to the noise map. The PSF describes the telescope’s +blurring, which must be included when predicting the observed image. + +Loading the dataset does not fit a model. It supplies the measurements and observational information that the Analysis +object will use later. """ + if al.util.dataset.should_simulate(str(dataset_path)): import subprocess import sys - subprocess.run( - [sys.executable, "scripts/simulator/no_lens_light__mass_sis.py"], - check=True, - ) + subprocess.run([sys.executable, "scripts/simulator/no_lens_light__mass_sis.py"], check=True) dataset = al.Imaging.from_fits( data_path=dataset_path / "data.fits", @@ -227,120 +171,115 @@ """ __Mask__ -The fit requires a mask, which we define as a 3.0" circle. +We apply a circular mask with a radius of 3.0 arcseconds to select the region used for the fit. + +Check the plotted mask against the image: the selected region should contain the lensed emission whose structure we +want to explain. + +Masking changes which measurements enter the fit. It does not change the lens model or fix any of its parameters. Later +in this chapter, *Data and Likelihoods* explores mask choices and the treatment of contaminating objects. """ -mask_radius = 3.0 +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__ -To compose a lens model, we will set up each `Galaxy` using a `af.Model`. Instead of manually specifying every parameter -for the galaxy's light and mass profiles (as we did before), we will now define each galaxy using only the class of each -profile. Using a `Model` object tells **PyAutoLens** that the parameters of the profiles should be fitted for -during the non-linear search. +In Chapter 1, we created profile instances by supplying specific parameter values. To fit those parameters, we instead +wrap the profile class in `af.Model`. + +For example, `af.Model(al.mp.IsothermalSph)` describes a spherical isothermal mass profile whose centre and Einstein +radius are free to vary. During the search, specific values are supplied to create an instance of this profile. -In this case, we'll model the lens galaxy with an `IsothermalSph` mass profile and no light component (what it -was simulated with). +We place the mass profile inside a lens galaxy at a fixed redshift of 0.5. We do not include lens light because this +simulated image contains only the lensed source. """ -# Lens: mass = af.Model(al.mp.IsothermalSph) - lens = af.Model(al.Galaxy, redshift=0.5, mass=mass) """ -We model the source galaxy with a linear `ExponentialCoreSph` light profile (again, what it was simulated with). +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. """ -bulge = af.Model(al.lp_linear.ExponentialCoreSph) +bulge = af.Model(al.lp_linear.ExponentialCoreSph) source = af.Model(al.Galaxy, redshift=1.0, bulge=bulge) """ -We now have multiple `Model` components, which we bring together into a final lens model via the `Collection` object. +We combine the lens and source into an `af.Collection`, giving each galaxy a descriptive name. -Just like we are used to giving profiles descriptive names, like `bulge`, `disk` and `mass` we also name the galaxies -that make up our model. Of course, its good practise for us to give them descriptive names and we'll use `lens` and -`source` to do this throughout the tutorials. +The resulting structure lets us refer to individual components through paths such as `model.galaxies.lens.mass` and +`model.galaxies.source.bulge`. We will use these paths shortly to customise their priors. -It may seem odd that we define two `Collections`, with the `Collection` in the outer loop only having a `galaxies` -attribute. In future tutorials, we'll see that we can add additional model-components to a model other than just -galaxies, and the API below therefore makes it simple to extend the model to include these components. +The outer collection contains a `galaxies` collection. Keeping galaxies together leaves room for other kinds of +components, such as external shear fields, alongside them in later models. """ -# Overall Lens Model: model = af.Collection(galaxies=af.Collection(lens=lens, source=source)) """ -The `info` attribute shows the model in a readable format. +The `model.info` attribute summarises the model before we fit it. -[The `info` below may not display optimally on your computer screen, for example the whitespace between parameter -names on the left and parameter priors on the right may lead them to appear across multiple lines. This is a -common issue in Jupyter notebooks. +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. -The`info_whitespace_length` parameter in the file `config/general.yaml` in the [output] section can be changed to -increase or decrease the amount of whitespace (The Jupyter notebook kernel will need to be reset for this change to -appear in a notebook).] +This describes what we intend to fit. It contains no inferred parameter values yet, because the search has not run. """ + print(model.info) """ -The same model can also be visualized as a figure, making its structure easier to understand at a glance. +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. -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. +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. -Each galaxy is labelled with its redshift, `redshift = 0.5` for the lens and `redshift = 1.0` for the source. -That is how **PyAutoLens** knows which galaxy does the lensing and which one is lensed. +Like `model.info`, this diagram describes the model’s structure; it does not show whether the model fits the data. """ + af.ModelPlotter(model).figure() """ __Priors__ -When we examine the `.info` of our model, we notice that each parameter (like `centre`, `effective_radius`, -and `sersic_index` in our `Sersic` model) is associated with priors, such as `UniformPrior`. Priors define the -range of permissible values that each parameter can assume during the model fitting process, for example a uniform -prior means that a parameter is equally likely to be any value within the given range, but cannot be outside of it. - -The priors displayed above use default values defined in the `config/priors` directory. These default values have -been chosen to be broad, and contain the breadth of plausible solutions one should expect when fitting light and mass -profiles of a real galaxy. - -For instance, consider the `centre` parameter of our `IsothermalSph` mass profile. In theory, it could take on any value from -negative to positive infinity. However, imaging datasets are typically reduced such that the galaxy centre is close -to (0.0", 0.0"). Therefore, a `GaussianPrior` with `mean=0.0` and `sigma=0.1` is a good description of where the -galaxy `centre` is. +Each free parameter in `model.info` has a **prior**, which describes the probability assigned to its possible values +before using this dataset’s likelihood. -If the galaxy had a different centre in the dataset, we would change the mean of the prior to reflect this. -However, in general, we advise all galaxy images are reduced such that the galaxy is at (0.0", 0.0"). +A `UniformPrior` assigns equal probability density within specified limits and excludes values outside them. A +`GaussianPrior` places more probability near its mean, with its width controlled by `sigma`. -Priors serve two primary purposes: +PyAutoLens supplies default priors, but we should check whether they are appropriate for our dataset. For example, a +prior centred on zero is suitable for a galaxy’s position only if the image coordinates place it near the origin. -**Defining Valid Parameter Space:** Priors specify the range of parameter values that constitute valid solutions. -This ensures that our model explores only those solutions that are consistent with our observed data and physical -constraints. +Below, we assign Gaussian priors to the lens and source centres and uniform priors to the Einstein radius and source +effective radius. Positions and radii are expressed in arcseconds. -**Incorporating Prior Knowledge:** Priors also encapsulate our prior beliefs or expectations about the model -parameters. For instance, if we have previously fitted a similar model to another dataset and obtained certain -parameter values, we can incorporate this knowledge into our priors for a new dataset. This approach guides the -model fitting process towards parameter values that are more probable based on our prior understanding. +These choices are part of our inference assumptions. A narrow prior can exclude plausible solutions, while a broad +prior gives the search more parameter space to explore. Priors should therefore reflect justified information about the +system, rather than simply being adjusted until a preferred answer appears. -Below, we manually specify the priors on all parameter of our lens model. The custom priors below are -close to the default priors drawn via configfiles, with the main purpose of the code below to show you how to -customize priors yourself. +Combining the priors with the likelihood gives the **posterior distribution**: the probability distribution of the +parameters given the data and our modeling assumptions. """ + model.galaxies.lens.mass.centre.centre_0 = af.GaussianPrior(mean=0.0, sigma=0.1) model.galaxies.lens.mass.centre.centre_1 = af.GaussianPrior(mean=0.0, sigma=0.1) model.galaxies.lens.mass.einstein_radius = af.UniformPrior( @@ -356,412 +295,172 @@ model = af.Collection(galaxies=af.Collection(lens=lens, source=source)) """ -By reprinting the `model.info`, we can see that the priors have been updated to the values we specified. -""" -print(model.info) +Print `model.info` again and find the priors we have changed. -""" -Customizing priors changes many numbers in the `info` and nothing at all about the model itself. When you tune -priors you are changing where the search looks, not what it is looking for. -""" -af.ModelPlotter(model).figure() +The lens-centre coordinates now have Gaussian priors with a mean of 0.0 and a standard deviation of 0.1 arcseconds. The +source-centre priors are broader, with a standard deviation of 0.3 arcseconds. +The Einstein radius has a uniform prior between 0.0 and 8.0 arcseconds, and the source effective radius has a uniform +prior between 0.0 and 1.0 arcseconds. These are inputs to the fit, not uncertainties measured from the data. """ -__Analysis__ - -The `AnalysisImaging` object defines how an instance of a model, consisting of a set of parameters values for the -light and mass profiles, is fitted to the `Imaging` dataset. - -The fit is performed using the analysis class's `log_likelihood_function`, which in model-fitting is a commonly used -term to describe a function that given a model and data, fits the model to the data to return a value of log -likelihood. - -In the fitting tutorial in chapter 1 you essentially performed this likelihood function yourself by hand, when you -entered different models to a `FitImaging` object and used its `log_likelihood` property to quantify how well it -fitted the data. -A detailed step-by-step visual guide of the likelihood function is provided -at `autolens_workspace/*/imaging/likelihood_function.ipynb`. -""" -analysis = al.AnalysisImaging(dataset=dataset) +print(model.info) """ -__Searches__ - -To perform a non-linear search, we create an instance of a `NonLinearSearch` object. **PyAutoFit** offers many options -for this. A detailed description of each search method and guidance on when to use them can be found in -the [search cookbook](https://pyautofit.readthedocs.io/en/latest/cookbooks/search.html). - -In this tutorial, we’ll focus on three searches that represent different approaches to model fitting: +The model diagram still contains the same galaxies, profiles and free parameters. -1. **Maximum Likelihood Estimation (MLE)** using the `LBFGS` non-linear search. -2. **Markov Chain Monte Carlo (MCMC)** using the `Emcee` non-linear search. -3. **Nested Sampling** using the `Nautilus` non-linear search. +Changing the priors has not changed how those profiles predict an image. It has changed the probability assigned to +their parameter values, which can affect both the search and the inferred posterior. -In this example, non-linear search results are stored in memory rather and not written to hard disk because the fits -are fast and can therefore be easily regenerated. The next tutorial will perform fits which write results to the -hard-disk and discuss the outputs that are generated. - -__Maximum Likelihood Estimation (MLE)__ - -Maximum likelihood estimation (MLE) is the most straightforward type of non-linear search. Here is a simplified -overview of how it works: - -1. Starts at a point in parameter space with a set of initial values for the model parameters. -2. Calculates the likelihood of the model at this starting point. -3. Evaluates the likelihood at nearby points to estimate the gradient, determining the direction in which to move "up" in parameter space. -4. Moves to a new point where, based on the gradient, the likelihood is higher. - -This process repeats until the search finds a point where the likelihood can no longer be improved, indicating that -the maximum likelihood has been reached. +This is different from changing the model’s physical components—for example, replacing a spherical mass profile with an +elliptical one. +""" -The `LBFGS` search is an example of an MLE algorithm that follows this iterative procedure. Let’s see how it -performs on our Sersic model. +af.ModelPlotter(model).figure() -In the example below, we do not specify a starting point for the MLE, so it begins at the center of the prior -range for each parameter. """ -search = af.LBFGS() +__Analysis__ -""" -To begin the model-fit via the non-linear search, we pass it our model and analysis and begin the fit. +We have defined the dataset and the model separately. The `AnalysisImaging` object provides the interface between them. -The fit will take a few minutes on GPU to run. +When the search supplies a model instance with specific parameter values, the analysis constructs its predicted image, +including ray tracing and PSF convolution. It compares that prediction with the masked imaging data, using the noise +map to evaluate the log likelihood. -**Run Time Error:** On certain operating systems (e.g. Windows, Linux) and Python versions, the code below may produce -an error. If this occurs, see the `autolens_workspace/guides/modeling/bug_fix` example for a fix. -""" -print( - """ - The non-linear search has begun running. - - This Jupyter notebook cell with progress once the search has completed - this could take a few minutes! - - On-the-fly updates every iterations_per_quick_update are printed to the notebook. - """ -) +For our linear source profile, this evaluation also solves for the intensity before calculating the likelihood. -result = search.fit(model=model, analysis=analysis) +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 +model instances. -print("The search has finished run - you may now continue the notebook.") +Creating the Analysis object does not start a search. It defines how proposed models will be evaluated. +A detailed step-by-step visual guide is provided at `autolens_workspace/scripts/imaging/likelihood_function.py`. """ -Upon completion the non-linear search returns a `Result` object, which contains information about the model-fit. -The `info` attribute shows the result in a readable format. +analysis = al.AnalysisImaging(dataset=dataset) -[Above, we discussed that the `info_whitespace_length` parameter in the config files could b changed to make -the `model.info` attribute display optimally on your computer. This attribute also controls the whitespace of the -`result.info` attribute.] """ -print(result.info) +__Non-linear Search__ +We are ready to fit the lens model using **Nautilus**, a non-linear search. -""" -One thing the result contains we'll use now is the `FitImaging` object that corresponds to the set of model -parameters that gave the maximum log likelihood solution. +Nautilus explores combinations of parameter values within the priors. For each combination, the Analysis object +predicts the image and calculates its log likelihood. This tells the search how well that model explains the data. -We plot this object to inspect how good our fit was. -""" -aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) +As the search progresses, it concentrates its exploration on regions containing higher-likelihood models. It explores a +range of possible solutions, allowing us to find a best-fitting model and estimate how uncertain its parameters are. +Nautilus uses a method called **nested sampling**. You do not need to understand its statistical details to work +through HowToLens. Here, we will focus on configuring a fit and interpreting what it returns. """ -The fit quality is poor, with significant residuals, meaning that the MLE failed to identify the correct model. - -This happened because the starting point of the search was a poor match to the data, placing it far from the true -solution in parameter space. As a result, after moving "up" the likelihood gradient several times, the search -settled into a "local maximum", a local peak in the likelihood surface that was better than models that surrounded -it in parameter space, but far from the global maximum solution. -To achieve a better fit with MLE, the search needs to begin in a region of parameter space where the log likelihood -is higher. This process is known as "initialization" and it involves providing the search with an -appropriate "starting point" in parameter space. - -The code below shows how we can customize the starting point of the search to provide a better initialization, -with the values input below close to the true values used to simulate the dataset. """ -initializer = af.InitializerParamStartPoints( - { - model.galaxies.lens.mass.centre.centre_0: 0.0, - model.galaxies.lens.mass.centre.centre_1: 0.0, - model.galaxies.lens.mass.einstein_radius: 1.55, - model.galaxies.source.bulge.centre.centre_0: 0.0, - model.galaxies.source.bulge.centre.centre_1: 0.0, - model.galaxies.source.bulge.effective_radius: 0.1, - } -) +__Search Settings__ -search = af.LBFGS(initializer=initializer) +One of Nautilus’s main settings is `n_live`, the number of “live points”. Each live point represents a set of model +parameters being used to explore parameter space. -print( - """ - The non-linear search has begun running. - This Jupyter notebook cell with progress once the search has completed - this could take a few minutes! - """ -) - -model = af.Collection(galaxies=af.Collection(lens=lens, source=source)) - -result = search.fit(model=model, analysis=analysis) +Using more live points generally allows a more thorough exploration, but requires more computation. Too few can leave +important regions unexplored, particularly for complex models. -print("The search has finished run - you may now continue the notebook.") +We use 100 live points for this introductory example. This is a starting setting, not a guarantee that every fit will +succeed. The following tutorials explain how to recognise difficulties and adjust the search. +The `n_batch` setting controls how many proposed models are evaluated together. It affects computational speed and +memory use, rather than setting the number of live points. """ -By printing `result.info` and looking at the maximum log likelihood model, we can confirm the search provided a -good model fit with a much higher likelihood than the incorrect model above. -""" -print(result.info) -aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) +search = af.Nautilus( + n_live=100, + n_batch=50, + iterations_per_quick_update=2500, +) """ -The MLE is a great starting point for model-fitting because it’s fast, conceptually simple, and often yields -accurate results. It is especially effective if you can provide a good initialization, allowing it to find the -best-fit solution quickly. - -However, MLE has its limitations. As seen above, it can get "stuck" in a local maximum, particularly if the -starting point is poorly chosen. In complex model-fitting problems, providing a suitable starting point can be -challenging. While MLE performed well in the example with just three parameters, it struggles with models that have -many parameters, as the complexity of the likelihood surface makes simply moving "up" the gradient less effective. - -The MLE also does not provide any information on the errors on the parameters, which is a significant limitation. -The next two types of searches "map out" the likelihood surface, such that they not only infer the maximum likelihood -solution but also quantify the errors on the parameters. - -__Markov Chain Monte Carlo (MCMC)__ - -Markov Chain Monte Carlo (MCMC) is a more powerful method for model-fitting, though it is also more computationally -intensive and conceptually complex. Here’s a simplified overview: +__Model Fit__ -1. Place a set of "walkers" in parameter space, each with random parameter values. -2. Calculate the likelihood of each walker's position. -3. Move the walkers to new positions, guided by the likelihood of their current positions. Walkers in high-likelihood -regions encourage those in lower regions to move closer to them. +We start the fit by passing our model and analysis to the search. -This process repeats, with the walkers converging on the highest-likelihood regions of parameter space. +The model supplies the components, free parameters and priors. The analysis defines how each proposed model is compared +with the data. Nautilus controls which parameter values are explored. -Unlike MLE, MCMC thoroughly explores parameter space. While MLE moves a single point up the likelihood gradient, -MCMC uses many walkers to explore high-likelihood regions, making it more effective at finding the global maximum, -though slower. +When using JAX, the numerical computing library used by PyAutoLens, the calculations are first compiled for repeated +use. You may therefore see an initial pause before the search begins reporting progress. -There is a reduced risk of getting stuck in local maxima, because whilst some walkers may temporarily get stuck in -one, other walkers will explore other regions of parameter space and encourage the walker in local maxima to move -away from it and head towards higher likelihood regions. - -In the example below, we use the `Emcee` MCMC search to fit the strong lens. The search starts with walkers -initialized in a "ball" around the center of the model’s priors, similar to the MLE search that failed earlier. +Let the search finish before continuing. Its completion means that it has met its stopping criteria; we must still +inspect the result to assess whether the fit is satisfactory. """ -search = af.Emcee( - nwalkers=20, # The number of walkers we'll use to sample parameter space. - nsteps=300, # The number of steps each walker takes, after which 20 * 300 = 6000 steps the non-linear search ends. -) - -print( - """ - The non-linear search has begun running. - This Jupyter notebook cell with progress once the search has completed - this could take a few minutes! - """ -) - -model = af.Collection(galaxies=af.Collection(lens=lens, source=source)) result = search.fit(model=model, analysis=analysis) -print("The search has finished run - you may now continue the notebook.") - -print(result.info) - -aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) - """ -The MCMC search succeeded, finding the same high-likelihood model that the MLE search with a good starting point -identified, even without a good initialization. Its use of multiple walkers exploring parameter space allowed it to -avoid the local maxima that had trapped the MLE search. +__Result__ -A major advantage of MCMC is that it provides estimates of parameter uncertainties by "mapping out" the likelihood -surface, unlike MLE, which only finds the maximum likelihood solution. These error estimates are accessible in -the `result.info` string and through the `result.samples` object, which is explained fully in tutorial 7. +The search returns a `Result` object. Print its `info` attribute to see the inferred parameter values and their +estimated uncertainties. -While a good starting point wasn't necessary for this simple model, it becomes essential for efficiently mapping the -likelihood surface in more complex models with many parameters. The code below shows an MCMC fit using a good starting -point, with two key differences from the MLE initialization: +Compare this with the earlier `model.info`: that described what we allowed to vary, whereas `result.info` summarises +what we have inferred from the data. -1. Instead of single starting values, we provide bounds for each parameter. MCMC initializes each walker in a -small "ball" in parameter space, requiring a defined range for each parameter from which values are randomly drawn. +An uncertainty describes the range of parameter values supported by the fit. For example, the data might constrain the +Einstein radius closely while allowing a wider range of source sizes. -2. We do not specify a starting point for the `ell_comps` parameters, allowing its initial values to be drawn from its -priors. This illustrates that with MCMC, it’s not necessary to know a good starting point for every parameter. +These estimates depend on our model, priors and noise assumptions, as well as the search having explored the relevant +solutions. We should inspect the fit before trusting the reported values. """ -initializer = af.InitializerParamBounds( - { - model.galaxies.lens.mass.centre.centre_0: (-0.01, 0.01), - model.galaxies.lens.mass.centre.centre_1: (-0.01, 0.01), - model.galaxies.source.bulge.centre.centre_0: (-0.01, 0.01), - model.galaxies.source.bulge.centre.centre_1: (-0.01, 0.01), - model.galaxies.source.bulge.effective_radius: (0.05, 0.15), - } -) - -search = af.Emcee( - nwalkers=20, # The number of walkers we'll use to sample parameter space. - nsteps=300, # The number of steps each walker takes, after which 10 * 200 = 2000 steps the non-linear search ends. - initializer=initializer, -) - -print( - """ - The non-linear search has begun running. - This Jupyter notebook cell with progress once the search has completed - this could take a few minutes! - """ -) - -model = af.Collection(galaxies=af.Collection(lens=lens, source=source)) - -result = search.fit(model=model, analysis=analysis) - -print("The search has finished run - you may now continue the notebook.") print(result.info) """ -MCMC is a powerful tool for model-fitting, providing accurate parameter estimates and uncertainties. For simple models -without a starting point, MCMC can still find the correct solution, and if a good starting point is provided, it can -efficiently scale to more complex models with more parameters. - -The main limitation of MCMC is that one has to supply the number of steps the walkers take (`nsteps`). If this value -is too low, the walkers may not explore the likelihood surface sufficiently. It can be challenging to know the right -number of steps, especially if models of different complexity are being fitted or if datasets of varying quality are -used. One often ends up having to perform "trial and error" to verify a sufficient number of steps are used. - -MCMC can perform badly in parameter spaces with certain types of complexity, for example when there are -are many local maxima "peaks" that many of the walkers can become stuck walking around them, so many walkers that -when they communicate with one another they cannot gain enough information to move away from the local peak. - -__Nested Sampling__ - -**Nested Sampling** is an advanced method for model-fitting that excels in handling complex models with intricate -parameter spaces. Here’s a simplified overview of its process: +__Inspecting the Fit__ -1. Start with a set of "live points" in parameter space, each initialized with random parameter values drawn from their respective priors. +Plot the highest-likelihood model found by the search alongside the data and residuals. -2. Compute the log likelihood for each live point. +Check whether it reproduces the position, shape and brightness of the lensed emission. Then examine the normalised +residuals for coherent patterns, such as an arc that the model has failed to reproduce. -3. Draw a new point based on the likelihood of the current live points, favoring regions of higher likelihood. +Our simulated data were generated using the same profile families we fitted. A successful fit should therefore leave +residuals broadly consistent with the noise. We do not expect every pixel to have a residual of zero. -4. If the new point has a higher likelihood than any existing live point, it becomes a live point, and the lowest likelihood live point is discarded. - -This iterative process continues, gradually focusing the live points around higher likelihood regions of parameter -space until they converge on the highest likelihood solution. - -Like MCMC, Nested Sampling effectively maps out parameter space, providing accurate estimates of parameters and -their uncertainties. -""" -search = af.Nautilus( - n_live=100, - n_batch=50, # Explained in next tutorial - iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations -) +Good residuals and sensible parameter estimates provide useful checks, but neither guarantees that every relevant +solution has been explored. The next tutorials develop the practical skills needed to assess this. +**🤖 Ask AI:** My fitted lens model leaves an arc-shaped pattern in the normalised residuals. What could cause this, and +what should I check before trusting the inferred parameters? """ -To begin the model-fit via the non-linear search, we pass it our model and analysis and begin the fit. - -The fit will take a minute or so to run. -""" -print( - """ - The non-linear search has begun running. - This Jupyter notebook cell with progress once the search has completed - this could take a few minutes! - """ -) - -model = af.Collection(galaxies=af.Collection(lens=lens, source=source)) - -result = search.fit(model=model, analysis=analysis) - -print("The search has finished run - you may now continue the notebook.") - -print(result.info) aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) """ -The **Nested Sampling** search was successful, identifying the same high-likelihood model as the MLE and MCMC searches. -One of the main benefits of Nested Sampling is its ability to provide accurate parameter estimates and uncertainties, -similar to MCMC. Additionally, it features a built-in stopping criterion, which eliminates the need for users to -specify the number of steps the search should take. - -This method also excels in handling complex parameter spaces, particularly those with multiple local peaks. This is because -the live points will identify each peak and converge around them, but then begin to be discarded from a peak if higher -likelihood points are found elsewhere in parameter space. In MCMC, the walkers can get stuck indefinitely in -peaks, causing the method to stall. - -Another significant advantage is that Nested Sampling estimates an important statistical quantity -known as "evidence." This value quantifies how well the model fits the data while considering the model's complexity, -making it essential for Bayesian model comparison, which will be covered in later tutorials. - -Nested sampling cannot use a starting point, as it always samples parameter space from scratch by drawing live points -from the priors. This is both good and bad, depending on if you have access to a good starting point or not. If you do -not, your MCMC / MLE fit will likely struggle with initialization compared to Nested Sampling. Conversely, if you do -possess a robust starting point, it can significantly enhance the performance of MCMC, allowing it to begin closer to -the highest likelihood regions of parameter space. This proximity can lead to faster convergence and more reliable results. - -However, Nested Sampling does have limitations; it often scales poorly with increased model complexity. For example, -once a model has around 50 or more parameters, Nested Sampling can become very slow, whereas MCMC remains efficient -even in such complex parameter spaces. +__Other Searches__ -__What is The Best Search To Use?__ +Nautilus provides the model fit and parameter uncertainties we need for this introductory example. We will continue +using it throughout much of HowToLens. -In statistical inference, the choice of the best search method depends on several factors specific to the problem, -such as model complexity, availability of a starting point, and whether error estimates are required. More subtle -aspects, like the shape of the likelihood surface and the presence of multiple peaks, also play a role, as you'll -explore in later tutorials. +Other searches can also be useful. Later in this chapter, we will use a fast optimiser for an initial fit before +running a more thorough Nautilus search. -When approaching a model-fitting problem, it's usually advisable to try various search methods to find the most -effective one. - -However, after extensive testing within **PyAutoLens**, a clear recommendation has emerged for fitting strong lens models. -The nested sampling method `Nautilus` consistently proves to be the most effective. It requires fewer iterations than -MCMC or MLE methods (when no starting point is used), provides robust sampling even for complex models, includes a -built-in stopping criterion, and delivers reliable error estimates. - -All examples in the `autolens_workspace` use the `Nautilus` search, and future tutorials in the **HowToLens** -series will also use it. We strongly recommend using `Nautilus` from now on. - -That said, MLE and MCMC searches can still be effective, and you're encouraged to experiment with them. If you have -a reliable starting point, MLE and MCMC can outperform `Nautilus` in terms of speed and efficiency. Additionally, -for very complex models (e.g., with 30+ parameters), `Nautilus` may struggle, while MCMC might handle the complexity -better—though you're unlikely to encounter that level of complexity soon. - -Lastly, MLE, MCMC, and nested sampling are just three categories of non-linear searches, each containing different -algorithms with their own strengths and weaknesses. Exploring these options could help you find the best approach -for your model-fitting needs. For more details on each method, see the [search cookbook](https://pyautofit.readthedocs.io/en/latest/cookbooks/search.html). +You can explore these alternatives in the optional searches tutorial after completing HowToLens. For now, focus on +building appropriate models and assessing how well they explain the data. +""" +""" __Wrap Up__ -This tutorial has laid the foundation with several fundamental concepts in model fitting and statistical inference: - -1. **Parameter Space**: This refers to the range of possible values that each parameter in a model can take. It -defines the dimensions over which the likelihood of different parameter values is evaluated. - -2. **Likelihood Function**: This function receives as input a model with specific parameter values and returns a -log likelihood value that quantifies how well the model describes the data. - -3. **Likelihood Surface**: This surface represents how the likelihood of the model varies across the parameter space. -It helps in identifying the best-fit parameters that maximize the likelihood of the model given the data. +You have now fitted a lens model automatically, using the same image prediction and likelihood calculation that you +explored manually in Chapter 1. -4. **Non-linear Search**: This is an optimization technique used to explore the parameter space and find the -combination of parameter values that best describe the data. It iteratively adjusts the parameters to maximize the -likelihood. Many different search algorithms exist, each with their own strengths and weaknesses, and this tutorial -used the MLE, MCMC, and nested sampling searches. +The fit brings together four pieces: -5. **Priors**: Priors are probabilities assigned to different values of parameters before considering the data. -They encapsulate our prior knowledge or assumptions about the parameter values. Priors can constrain the parameter -space, making the search more efficient and realistic. +- **Data:** the measurements, uncertainties and observational information. +- **Model:** the physical components, their free parameters and their priors. +- **Analysis:** the connection between model and data, predicting the observations and evaluating their likelihood. +- **Search:** the method that explores parameter values and returns the inferred results. -6. **Model Fitting**: The process of adjusting model parameters to minimize the difference between model predictions -and observed data, quantified by the likelihood function. +Keeping these pieces separate lets us change the model, dataset or search while retaining the same overall approach. +Later in the chapter, we will see how this applies to the other types of lensing data introduced in Chapter 1. -Understanding these concepts is crucial as they form the backbone of model fitting and parameter estimation in -scientific research and data analysis. In the next tutorials, these concepts will be further expanded upon to -deepen your understanding and provide more advanced techniques for model fitting and analysis. +In the next tutorial, *Practicalities*, we include the foreground lens galaxy’s light and fit a more complex model. We +will also learn how to follow a search’s progress, navigate its output folder and inspect its saved results. """ diff --git a/scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py b/scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py index 450f3cf..34105ed 100755 --- a/scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py +++ b/scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py @@ -2,78 +2,56 @@ Tutorial 2: Practicalities ========================== -In the last tutorial, we introduced foundational statistical concepts essential for model-fitting, such as parameter -spaces, likelihoods, priors, and non-linear searches. Understanding these statistical concepts is crucial for -performing model fits effectively. +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. -However, achieving successful model-fitting also requires practical skills, including how to manage outputs, -review results, interpret model quality, and ensure run-times are efficient enough for your scientific needs. +Fitting this image requires additional model components and more free parameters. Alongside building that model, we +will learn how to configure the search, follow its progress, find its saved output and inspect the resulting fit. -This tutorial will focus on these practical aspects of model-fitting, including: +The overall approach remains the same: the dataset holds the observations, the model describes the physical components, +and the Analysis object connects them. Nautilus explores the model parameters using the likelihood and priors. -- How to save results to your hard disk. -- How to navigate the output folder and examine model-fit results to assess quality. -- How to estimate the run-time of a model-fit before initiating it, and change settings to make it faster or run the analysis in parallel. +By the end, you should be comfortable running a fit and finding the information needed to assess it. The next tutorial +examines why more complex models can be difficult to fit and what to do when a search struggles. __Contents__ -- **PyAutoFit:** Modeling uses the probabilistic programming language. -- **Initial Setup:** Lets first load the `Imaging` dataset we'll fit a model with using a non-linear search. -- **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:** Compose the lens model fitted to the data. -- **Search:** Configure the non-linear search used to fit the model. -- **Search Settings:** Nautilus samples parameter space by placing "live points" representing different galaxy models. -- **Iterations Per Update:** Every N iterations, the non-linear search outputs the current results to the folder. -- **Analysis:** Create the Analysis object that defines how the model is fitted to the data. -- **VRAM Use:** When running AutoLens with JAX on a GPU, the analysis must fit within the GPU’s available VRAM. -- **Run Times:** Profiling the expected run time of the model-fit. -- **Model-Fit:** Begin the model-fit by passing the model and analysis to the search. -- **Result Info:** A concise readable summary of the results is given by printing its `info` attribute. -- **Output Folder:** Now checkout the `output` folder. -- **Unique Identifier:** In the output folder, you will note that results are in a folder which is a collection of random. -- **Output Folder Contents:** Now this is running you should checkout the `output` folder. -- **Result:** Overview of the results of the model-fit. -- **Other Practicalities:** The following are examples of other practicalities which I will document fully in this example. -- **Wrap Up:** Summary of the script and next steps. - -__Search Settings__ - -Nautilus samples parameter space by placing "live points" representing different galaxy models. Each point has an -associated `log_likelihood` that reflects how well it fits the data. By mapping where high-likelihood solutions are -located, it can focus on searching those regions. - -The main setting to balance is the **number of live points**. More live points allow Nautilus to map parameter space -more thoroughly, increasing accuracy but also runtime. Fewer live points reduce run-time but may make the search less -reliable, possibly getting stuck in local maxima. - -The ideal number of live points depends on model complexity. More parameters generally require more live points, but -the default of 200 is sufficient for most lens models. Lower values can still yield reliable results, particularly -for simpler models. For this example (6 parameters), we reduce the live points to 100 to speed up runtime without -compromising accuracy. - -Tuning non-linear search settings (e.g., the number of live points) to match model complexity is essential. We aim -for enough live points to ensure accurate results (i.e., finding a global maximum) but not so many that runtime -is excessive. - -In practice, the optimal number of live points is often found through trial and error, guided by summary statistics -on how well the search is performing, which we’ll cover below. For the simple model fitted here, with a linear light -profile, 100 live points is sufficient to achieve reliable results. +- **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** +""" -__Iterations Per Update__ +""" +__Dataset__ -Every N iterations, the non-linear search outputs the current results to the folder `output`, -which includes producing visualization. +Our new simulated image contains a bright foreground lens galaxy as well as the lensed source. -Depending on how long it takes for the model to be fitted to the data (see discussion about run times below), -this can take up a large fraction of the run-time of the non-linear search. +The simulation uses a Sérsic light profile for the lens galaxy, an elliptical isothermal mass profile, external shear +and an exponential light profile for the source. We will build a model with these components shortly. -For this fit, the fit is very fast, thus we set a high value of `iterations_per_quick_update=2500` to ensure these updates -do not slow down the overall speed of the model-fit. +As before, the dataset includes the image, its noise map and the telescope’s point-spread function (PSF). If the files +are missing, the following cell runs the simulator before loading them. -**If the iteration per update is too low, the model-fit may be significantly slowed down by the time it takes to -output results and visualization frequently to hard-disk. If your fit is consistent displaying a log saying that it -is outputting results, try increasing this value to ensure the model-fit runs efficiently.** +In the plotted image, look for the central lens galaxy and the extended lensed emission around it. Both contribute to +the measured light, so our model must account for both. """ from autolens import jax_wrapper # Sets JAX environment before other imports @@ -81,46 +59,18 @@ # from autolens import setup_notebook; setup_notebook() from pathlib import Path +import autofit as af import autolens as al import autolens.plot as aplt -""" -__PyAutoFit__ - -Modeling uses the probabilistic programming language -[PyAutoFit](https://github.com/PyAutoLabs/PyAutoFit), an open-source project that allows complex model -fitting techniques to be straightforwardly integrated into scientific modeling software. - -The majority of tools that make model-fitting practical are provided by PyAutoFit, for example it handles -all output of the non-linear search to hard-disk, the visualization of results and the estimation of run-times. -""" -import autofit as af - -""" -__Initial Setup__ - -Lets first load the `Imaging` dataset we'll fit a model with using a non-linear search. - -This is the same dataset we fitted in the previous tutorial, and we'll repeat the same fit, as we simply want -to illustrate the practicalities of model-fitting in this tutorial. -""" -dataset_name = "simple__no_lens_light__mass_sis" +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. -""" if al.util.dataset.should_simulate(str(dataset_path)): import subprocess import sys - subprocess.run( - [sys.executable, "scripts/simulator/no_lens_light__mass_sis.py"], - check=True, - ) + subprocess.run([sys.executable, "scripts/simulator/lens_sersic.py"], check=True) dataset = al.Imaging.from_fits( data_path=dataset_path / "data.fits", @@ -134,304 +84,463 @@ """ __Mask__ -The non-linear fit also needs a `Mask2D`, lets use a 3.0" circle. +We use a circular mask with a radius of 2.5 arcseconds to select the central region for this fit. + +Inspect the masked image: the selected region should contain the lensed emission and enough of the lens galaxy’s light +to constrain its profile. The mask changes which measurements contribute to the fit; it does not change the physical +model. + +Later in this chapter, *Data and Likelihoods* examines mask choices and how to handle contaminating objects. """ -mask_radius = 3.0 +mask_radius = 2.5 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 compose the model using the same API as the previous tutorial. +The previous model contained a spherical lens mass profile and a spherical source-light profile, with no foreground +lens light. We now include four components: + +- A **Sérsic light profile** to describe the foreground lens galaxy. +- An **elliptical isothermal mass profile** to describe its gravitational lensing. +- An **external shear field** to describe an additional tidal contribution to the lensing. +- An **exponential light profile** to describe the source galaxy. + +The lens galaxy’s light and mass are separate components. Fitting its brightness does not, by itself, determine its +mass distribution. + +These additions let the model describe more structure in the image, but introduce more free parameters for the search +to explore. This is a recurring balance in modeling: we need enough flexibility to explain the data, while recognising +that a more complex model can be harder to fit. + +We use the model construction from the previous tutorial, adding the lens-light profile and placing external shear in a +separate `fields` component. +""" -This model is the same as the previous tutorial, an `IsothermalSph` spherical mass profile representing the lens -galaxy and a `ExponentialCoreSph` light profile representing the source galaxy. """ -# Lens: +We construct the model using the same approach as Tutorial 1. Passing a profile class into `af.Model` makes its +parameters available for fitting; supplying a value, such as a galaxy’s redshift, keeps that quantity fixed. -mass = af.Model(al.mp.IsothermalSph) +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. -lens = af.Model(al.Galaxy, redshift=0.5, mass=mass) +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. +""" + +field = af.Model( + al.MassField, + redshift=0.5, + shear=al.mp.ExternalShear, +) -# Source: +model = af.Collection( + galaxies=af.Collection( + lens=af.Model( + al.Galaxy, + redshift=0.5, + bulge=al.lp.Sersic, + mass=al.mp.Isothermal, + ), + source=af.Model( + al.Galaxy, + redshift=1.0, + bulge=al.lp.ExponentialCore, + ), + ), + fields=field, +) -bulge = af.Model(al.lp_linear.ExponentialCoreSph) +""" +Print `model.info` and examine the model diagram below. -source = af.Model(al.Galaxy, redshift=1.0, bulge=bulge) +Find the lens-light, lens-mass, source-light and shear components. Notice how each contributes free parameters, while +the galaxy and field redshifts remain fixed. -# Overall Lens Model: +The parameter count tells us how many quantities the non-linear search must explore. More parameters generally make +exploration harder, but their relationships matter too: different combinations can produce similar images. -model = af.Collection(galaxies=af.Collection(lens=lens, source=source)) +These displays describe the model we are about to fit. They do not yet tell us whether it explains the data. +""" print(model.info) +af.ModelPlotter(model).figure() + """ -The same model can also be visualized as a figure, making its structure easier to understand at a glance. +__Analysis__ + +We again use `AnalysisImaging` to connect the model to the dataset. -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. +For each proposed model, the analysis predicts the combined lens and lensed-source light, accounts for PSF blurring and +evaluates the log likelihood using the selected image pixels and their noise values. -Nothing in this tutorial changes the model — every setting we discuss below belongs to the search. +Although our model has become more complex, the interface is unchanged: the analysis receives a model instance and +returns its log likelihood. """ -af.ModelPlotter(model).figure() + +analysis = al.AnalysisImaging(dataset=dataset) """ __Search__ -We again use the `Nautilus` non-linear search, with settings chosen following the Search Settings discussion above. +We configure Nautilus with a location for its saved output as well as settings controlling the search. + +- `path_prefix` groups the results under `output/howtolens/chapter_2`. +- `name` identifies this tutorial’s fit. +- `unique_tag` distinguishes the dataset being fitted. + +Together, these organise our results so that fits to different datasets do not become mixed together. PyAutoFit also +adds an automatically generated identifier, explained in the **Unique Identifier** section below. """ + search = af.Nautilus( path_prefix=Path("howtolens") / "chapter_2", name="tutorial_2_practicalities", unique_tag=dataset_name, - n_live=100, - n_batch=50, # GPU batching and VRAM use explained in VRAM section below. - iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations + n_live=200, + n_batch=50, + iterations_per_quick_update=2500, ) """ -__Analysis__ +__Search Settings__ + +We increase `n_live` from 100 in Tutorial 1 to 200 for this more complex model. More live points generally allow a more +thorough exploration, at the cost of additional computation. We must still inspect the result rather than assume this +setting guarantees a successful fit. + +`n_batch=50` allows likelihood evaluations to be processed in batches. Evaluating several models together can improve +performance, particularly on a GPU, but also requires more memory. -We again create the `AnalysisImaging` object which contains the `log_likelihood_function` that the non-linear search -calls to fit the model to the data. +These settings serve different purposes: `n_live` controls the live-point population used to explore parameter space, +whereas `n_batch` controls how evaluations are grouped for computation. + +Keep these values for the initial run. The following **VRAM Use** section explains how to check memory requirements and +when to reduce the batch size. """ -analysis = al.AnalysisImaging(dataset=dataset) """ -__VRAM Use__ +__Output Updates__ -When running AutoLens with JAX on a GPU, the analysis must fit within the GPU’s -available VRAM. If insufficient VRAM is available, the analysis will fail with an -out-of-memory error, typically during JIT compilation or the first likelihood call. +While the search runs, PyAutoLens can save updated figures showing the best-fitting model found so far. These let you +follow its progress without waiting for the fit to finish. -Two factors dictate the VRAM usage of an analysis: +We set `iterations_per_quick_update=2500` to request a quick update approximately every 2,500 likelihood evaluations. +This counts evaluated models, not seconds. -- The number of arrays and other data structures JAX must store in VRAM to fit the model - to the data in the likelihood function. This is dictated by the model complexity and dataset size. +Producing figures takes time. If updates occur almost continuously, increasing this value lets the search spend more +time exploring models between updates. Decreasing it gives more frequent views of progress. -- The `batch_size` sets how many likelihood evaluations are performed simultaneously. - Increasing the batch size increases VRAM usage but can reduce overall run time, - while decreasing it lowers VRAM usage at the cost of slower execution. +Quick updates are intended for monitoring. More extensive output is controlled separately by +`iterations_per_full_update`, and final results are produced when the search finishes. -Before running an analysis, users should check that the estimated VRAM usage for the -chosen batch size is comfortably below their GPU’s total VRAM. +Keep the current setting for the first run. If you experiment with a different update frequency, restore it to 2,500 +afterwards. +""" + +""" +__VRAM Use__ + +If you run the fit on a GPU, its calculations must fit within the GPU’s memory, usually called **VRAM**. Insufficient +memory can cause an out-of-memory error during compilation or evaluation. + +Memory requirements depend on the dataset, the model and how many models are evaluated together. Larger images and more +demanding calculations can require more memory. Increasing Nautilus’s `n_batch` also increases the amount of work held +in memory at once. + +The following call estimates the memory used by the batched likelihood calculation. `search.batch_size` reports the +batch size set through Nautilus’s `n_batch` argument. -The method below prints the VRAM usage estimate for the analysis and model with the specified batch size, -it takes about 20-30 seconds to run so you may want to comment it out once you are familiar with your GPU's VRAM limits. +Compare the estimate with the GPU memory available, leaving room for other allocations and applications. This is an +estimate for the likelihood calculation, rather than a guarantee of the total memory used by the process. -For the simple model and low resolution dataset fitted in this example VRAM use is relatively low (~0.027GB). For other -models (e.g. pixelized sources) and higher resolution datasets it can be much higher (> 1GB going beyond 10GB). +If memory is insufficient, try reducing `n_batch` from 50 to 10 and recreate the search before checking again. This +keeps the same model and live-point setting, but evaluates fewer models together. + +The estimate itself requires some preparation and may take time. Once you understand the requirements of an unchanged +setup, you can skip this diagnostic on subsequent runs. On a CPU, the relevant limit is system memory rather than GPU +VRAM. """ -analysis.print_vram_use(model=model, batch_size=search.batch_size) + +analysis.print_vram_use( + model=model, + batch_size=search.batch_size, +) """ __Run Times__ -Lens modeling can be a computationally expensive process. When fitting complex models to high resolution datasets -run times can be of order hours, days, weeks or even months. +Two main factors determine how much computation a fit requires: -Run times are dictated by two factors: +- How expensive it is to predict the data and calculate the likelihood for a proposed model. +- How many models the search must evaluate before it finishes. - - **The log likelihood evaluation time:** the time it takes for a single `instance` of the model to be fitted to - the dataset such that a log likelihood is returned. +Adding lens light and allowing elliptical profiles increases the work involved in each prediction. The additional free +parameters can also make parameter space harder to explore, requiring more evaluations. - - **The number of iterations (e.g. log likelihood evaluations) performed by the non-linear search:** more complex lens - models require more iterations to converge to a solution (and as discussed above, settings like the number of live - points also control this). +With JAX, the initial compilation takes time before repeated evaluations become faster. On a GPU, several evaluations +can run together, so multiplying a single-model evaluation time by the number of models does not necessarily predict +the total run time. -For this analysis, the log likelihood evaluation time is < 0.01 seconds on CPU, < 0.001 seconds on GPU, which is -extremely fast for lens modeling. +Saving figures and results adds further time. The elapsed time therefore includes compilation, searching and output—not +just the likelihood calculation. -The more advanced fitting techniques discussed at the end of chapter 1 (e.g. shapelets, multi Gaussian expansions, -pixelizations) have longer log likelihood evaluation times. However, on GPU, they can be so fast they may not produce -significantly longer overall run-time feasible. +Watch the progress of your first run to develop an expectation for your computer. The optional *Need for Speed* +tutorial explains how to investigate performance in more detail. +""" -To estimate the expected overall run time of the model-fit we multiply the log likelihood evaluation time by an -estimate of the number of iterations the non-linear search will perform, which is around 50000 to 100000 for this model. +""" +__Notebooks and Scripts__ -Tests thus far reveal CPU run times are around 30 minutes, and GPU run times around 10 minutes. +In a notebook, the cell containing `search.fit` remains busy until the search finishes. You can inspect files already +written to the output folder while it runs, but later cells in the same notebook kernel must wait. -__Model-Fit__ +For a longer fit, you may prefer to run the corresponding Python script from the HowToLens repository root: -To begin the model-fit, we pass the model and analysis objects to the search, which performs a non-linear search to -identify models that best fit the data. +```bash +python3 scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py +``` -Running model fits via non-linear search can take significant time. While the fit in this tutorial should -complete in a few minutes, more complex models may require longer run times. In Jupyter notebooks, this can be -limiting, as the notebook cell will only complete once the fit finishes, preventing you from advancing through the -tutorial or running additional code. +The notebook and script perform the same analysis, and both save results using the output settings we supplied. Running +a script does not inherently make the search faster; it lets the fit run separately from your interactive notebook. -To work around this, we recommend running tutorial scripts as standalone Python scripts, found -in the `scripts/` folder of the HowToLens repository. These scripts mirror the notebook tutorials but run independently of -Jupyter notebooks. For example, you can start a script with: +Notebooks remain useful for inspecting data, plotting results and exploring their interpretation. Scripts are +convenient for unattended runs and computing clusters. -`python3 scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py` +Once the fit has completed, rerunning the same setup can load its saved result. We will explain how PyAutoFit +recognises that setup in **Unique Identifier**. +""" -Using scripts allows results to be saved to the hard drive in the `output` folder, enabling you to inspect results -immediately once the script completes. When rerun, the script loads results directly from disk, so any Jupyter -notebook cells will quickly load and display the complete model-fit results if they’re already saved. +""" +__Model Fit__ -This approach not only avoids the slowdowns associated with notebook cells during lengthy runs but is also essential -for using super-computers for fitting tasks, as they require separate Python scripts. +We now pass the model and analysis to Nautilus and begin the fit. -For tasks like loading results, inspecting data, plotting, and interpreting results, Jupyter notebooks remain ideal. +Expect an initial compilation stage, followed by search progress and periodic output updates. Use those updates to +follow how the predicted image improves, but wait for completion before interpreting the final parameter uncertainties. + +The output is organised beneath `output/howtolens/chapter_2/lens_sersic/tutorial_2_practicalities`. The dataset tag and +automatically generated identifier distinguish this particular fit within that folder. """ -print( - "The non-linear search has begun running - checkout the output/howtolens/chapter_2/tutorial_2_practicalities" - " 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 = search.fit(model=model, analysis=analysis) -print("Search has finished run - you may now continue the notebook.") - """ __Result Info__ -A concise readable summary of the results is given by printing its `info` attribute. +Once the search finishes, print `result.info` to inspect the inferred parameter values and their uncertainties. + +Compare the lens-light, mass, shear and source-light parameters with the model we defined earlier. Then inspect the fit +image and residuals, as in Tutorial 1. Sensible-looking parameter values alone do not establish that the model explains +the data. -[Above, we discussed that the `info_whitespace_length` parameter in the config files could b changed to make -the `model.info` attribute display optimally on your computer. This attribute also controls the whitespace of the -`result.info` attribute.] +The same fit summary is saved as `model.results`, so you can read it without rerunning the notebook. """ + print(result.info) +aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) + """ __Output Folder__ -Now checkout the `output` folder. +Open the `output` directory inside your HowToLens repository. Our search settings organise this fit beneath: + +```text +output/howtolens/chapter_2/lens_sersic/tutorial_2_practicalities/ +``` + +Inside is a folder with a long identifier as its name. This contains the saved model, results, figures and information +needed to load or resume the fit. + +The tree below shows the main output structure. Some products appear only after completion or when enabled in the +output and plotting configuration. + +```text +output/ +`-- howtolens/ + `-- chapter_2/ + `-- lens_sersic/ # unique_tag: the dataset name + `-- tutorial_2_practicalities/ # name: this analysis + `-- / + |-- model.info # Model components and priors + |-- model.results # Inferred parameters and uncertainties + |-- search.summary # Search progress and timing summary + |-- search.log # Messages written during the run + | + |-- image/ + | |-- dataset.fits # Saved imaging data, noise map and PSF + | |-- dataset.png # Dataset visualisation + | |-- fit.fits # Model and residual-related arrays + | |-- fit.png # Visual comparison of model and data + | `-- ... # Additional configured figures and FITS + | + `-- files/ + |-- model.json # Saved model definition + |-- tracer.json # Highest-likelihood tracer + |-- search.json # Saved search configuration + |-- samples.csv # Parameter samples and weights + |-- samples_info.json # Information about the samples + |-- samples_summary.json # Summary of inferred parameters + |-- covariance.csv # Parameter covariance matrix + |-- dataset_identity.json # Record of the input dataset + `-- search_internal/ # Search checkpoints, when retained +``` +""" + +""" +__Unique Identifier__ -This is where the results of the search are written to hard-disk (in the `tutorial_2_practicalities` folder). +The identifier looks like a random string, but it is calculated from the model, the identifying search settings and the +`unique_tag`. -Once completed images, results and information about the fit appear in this folder, meaning that you don't need -to keep running Python code to see the result. +Rerunning an unchanged setup produces the same identifier and points PyAutoFit to the existing output. Changing the +model or a search setting that contributes to the identifier produces a different identifier. -__Unique Identifier__ +The `unique_tag` lets us distinguish datasets fitted with the same model and search. Here, we set it to `dataset_name`, +giving the tag `lens_sersic`. + +Do not assume that editing a data file, changing a mask or changing every analysis option automatically creates a new +identifier. When deliberately fitting a revised dataset or analysis, use a descriptive new tag or search name to keep +its results separate. -In the output folder, you will note that results are in a folder which is a collection of random characters. This acts -as a `unique_identifier` of the model-fit, where this identifier is generated based on the model, search and dataset -that are used in the fit. - -An identical combination of model, search and dataset generates the same identifier, meaning that rerunning the -script will use the existing results to resume the model-fit. In contrast, if you change the model, search or dataset, -a new unique identifier will be generated, ensuring that the model-fit results are output into a separate folder. +Display settings, such as how often progress figures are produced, need not define a scientifically different fit and +do not necessarily change the identifier. +""" + +""" +__Resuming and Loading__ + +If a Nautilus run is interrupted, rerun the same setup with its output and checkpoint files intact. The search can +resume from its saved state, rather than starting from scratch. Work performed since the latest checkpoint may need to +be repeated. -We additionally want the unique identifier to be specific to the dataset fitted, so that if we fit different datasets -with the same model and search results are output to a different folder. We achieved this for the fit above by passing -the `dataset_name` to the search's `unique_tag`. +If the fit has already completed, rerunning the same setup loads the saved result instead of repeating the search. This +is useful when reopening a notebook to inspect or plot a completed analysis. + +Keep the output files together. The human-readable summaries are useful for inspection, but they do not replace the +saved samples and other files used to reconstruct results. + +The `search_internal` directory contains search-specific state. This tutorial’s output configuration removes it after +completion to save space; that does not prevent the completed result from being loaded. +""" +""" __Output Folder Contents__ -Now this is running you should checkout the `output` folder. This is where the results of the -search are written to hard-disk (in the `tutorial_2_practicalities` folder), where all outputs are human readable -(e.g. as .json, .csv or text files). - -As the fit progresses, results are written to the `output` folder on the fly using the highest likelihood model found -by the non-linear search so far. This means you can inspect the results of the model-fit as it runs, without having to -wait for the non-linear search to terminate. - -The `output` folder includes: - - - `model.info`: Summarizes the model, its parameters and their priors discussed in the next tutorial. - - - `model.results`: Summarizes the highest likelihood model inferred so far including errors. - - - `images`: Visualization of the highest likelihood model-fit to the dataset, (e.g. a fit subplot showing the - galaxies, model data and residuals). - - - `files`: A folder containing .fits files of the dataset, the model as a human-readable .json file, - a `.csv` table of every non-linear search sample and other files containing information about the model-fit. - - - `search.summary`: A file providing summary statistics on the performance of the non-linear search. - - - `search_internal`: Internal files of the non-linear search (in this case Nautilus) used for resuming the fit and - visualizing the search. - -__Result__ - -The `search.fit` method produces a `result` object, packed with useful information about the model fit that we’ll -explore in detail in a later tutorial. - -One component of the `result` object we’ll use now is the `FitImaging` object, which corresponds to the set of model -parameters that yielded the maximum log-likelihood solution. Plotting this object lets us visually inspect how well -the model fits the data. - -In this example, the fit to the data is excellent, with residuals near zero, as expected since the same model was -used both to simulate and fit the data. +Begin with `image/fit.png`. Inspect whether the predicted image reproduces the lens and source light, and whether +coherent structures remain in the residuals. + +Then open `model.results` for the inferred parameters and uncertainties. Use `model.info` alongside it to remind +yourself which components, fixed values and priors were specified. + +`search.summary` and `search.log` help you understand the run’s progress and timing. While the search is still running, +treat saved fits and summaries as provisional. + +The `files` directory supports more detailed analysis in Python. You do not need to manipulate these files to continue +HowToLens; later we will point you to the workspace examples for loading and analysing completed results. + +Output is configurable. `config/output.yaml` controls saved products such as samples and retained search state, while +files under `config/visualize/` control plotting. Keep the tutorial defaults while learning the workflow. """ -aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) """ -The Probability Density Functions (PDF's) of the results can be plotted using an in-built visualization -library, which is wrapped via the `corner_anesthetic` function. +__Parameter Uncertainties__ + +A corner plot shows the parameter uncertainties inferred by the search and the relationships between them. -The PDF shows the 1D and 2D probabilities estimated for every parameter after the model-fit. The two dimensional -figures can show the degeneracies between different parameters, for example how increasing the intensity $I$ of the -source galaxy and decreasing its effective radius $R_{Eff}$ lead to similar likelihoods and probabilities. +The plots along the diagonal show the distribution of each parameter individually. The other panels show pairs of +parameters: an elongated or curved distribution indicates that changing one parameter can be compensated by changing +another. -This PDF will be discussed more in the next tutorial. +For example, a galaxy’s light-profile intensity and effective radius can trade off against one another, producing +similar images over the fitted region. -The plot is labeled with short hand parameter names (e.g. `sersic_index` is mapped to the short hand -parameter `n`). These mappings ate specified in the `config/notation.yaml` file and can be customized by users. +Compare these distributions with the uncertainties in `result.info`. A narrow distribution indicates a tightly +constrained parameter under the assumptions of this fit; it does not account for every possible source of error, such +as an inappropriate model. -The superscripts of labels are the path of names each component was given in the model (e.g. for the `Isothermal` -mass, `lens.mass`: the galaxy's name `lens` and its name `mass` defined when making the `Model` above). +**🤖 Ask AI:** My lens model has small image residuals, but two parameters form a long curved distribution in the corner +plot. What does this tell me about what the data constrain? """ + aplt.corner_anesthetic(samples=result.samples) +r""" +__Plot Labels__ -""" -Components in different named galaxy or profile paths can be distinguished by their superscripts. Profiles within -the same path, such as Gaussians in a basis, can share a superscript. When the model has more than one top-level -component, each also gets its own -corner plot in the output folder (`corner_anesthetic_.png`, switched in `config/visualize/plots_search.yaml`). +Corner plots use abbreviated parameter names to keep their labels readable. For example, the Sérsic index may be +labelled \(n\). These labels can be customised in `config/notation.yaml`. + +Superscripts distinguish components using their names in the model, such as `lens.mass` and `source.bulge`. Use these +alongside `model.info` to identify which parameter each panel represents. + +The plotting configuration can also produce separate corner plots for individual components, which are easier to +inspect when the full model contains many parameters. -The parameters a model is sampled in are not always the ones it is read in: a profile's elliptical components are an -axis ratio and a position angle, a shear's two components a magnitude and an angle. Passing `latent=True` plots -these latent parameters instead. The same figure is written to the output folder as `corner_anesthetic_latent.png` -when `corner_anesthetic_latent` is switched on in `config/visualize/plots_search.yaml` (off by default), once the fit -is complete. With `latent_model_parameters` enabled, full-sample latent output (`latent_draw_via_pdf: false`) -writes these columns to `files/latent/samples.csv` with the other latent variables. Periodic angles are recentred -for the plot; saved values retain the conversion's original range. +Some quantities are easier to interpret after conversion. For example, elliptical components can be expressed as an +axis ratio and position angle. The following plot displays supported derived quantities using `latent=True`; it +interprets the same fit rather than running another search. """ + aplt.corner_anesthetic(samples=result.samples, latent=True) """ -__Other Practicalities__ +__Configuration__ -The following are examples of other practicalities which I will document fully in this example script in the future, -but so far have no found the time: +The `config` folder controls defaults used throughout HowToLens. You do not need to customise everything before fitting +your own data, but it helps to know where the main settings live: -- `config`: The files in the `config` folder which control many aspects of how **PyAutoLens** runs, - including visualization, the non-linear search settings. +- `config/priors/` supplies default priors for model components. Assigning priors explicitly in your script makes those choices visible beside the model. +- `config/output.yaml` controls saved products, including sample tables and whether internal search files are retained after completion. +- `config/visualize/` controls which figures are produced. Search plots, including corner plots, are configured in `plots_search.yaml`. +- `config/notation.yaml` controls parameter labels used in plots. -- `config/priors`: Folder containing the default priors on all model components. +Keep the tutorial defaults initially. Saving fewer products can reduce disk usage, but may limit what you can calculate +later without rerunning the fit. -- `results`: How to load the results of a model-fit from the output folder to a Python script or Jupyter notebook. +In particular, a saved summary is not a substitute for the full sample table when you want to perform new calculations +using the parameter distributions. +""" -- `output.yaml`: What files are output to control file size. +""" +__Further Results__ +You now know how to inspect a fit, read its parameter estimates and find its saved output. That is enough to continue +HowToLens. + +The results also support more detailed work: loading fitted galaxies and tracers, calculating derived quantities, +making customised figures and comparing many fits. + +Once you are comfortable building models and obtaining satisfactory fits to real data, explore the `autolens_workspace` +results guide, beginning with `scripts/guides/results/start_here.py` or its notebook counterpart. + +HowToLens focuses on learning the analysis tools needed to model lenses. The workspace provides the next steps for +using and manipulating the results of those analyses. +""" + +""" __Wrap Up__ -This tutorial has illustrated how to handle a number of practicalities that are key to performing model-fitting -effectively. These include: +We have fitted a model containing lens light, lens mass, external shear and source light, while retaining the same +data–model–Analysis–search structure introduced in Tutorial 1. -- How to save results to your hard disk. +You have also learned how to configure search and output settings, check GPU memory requirements, run a notebook or +script, and navigate the saved results. The unique identifier allows an unchanged fit to reuse its output, while +descriptive names and dataset tags help keep different analyses organised. -- How to navigate the output folder and examine model-fit results to assess quality. +These practical tools make it easier to run and inspect a fit, but they do not guarantee that the search finds a +satisfactory solution. -- How to estimate the run-time of a model-fit before initiating it, and change settings to make it faster or run the - analysis in parallel. +In the next tutorial, *Why Modeling Is Hard*, we examine what can go wrong as models become more complex, how to +recognise the problem and which changes can help. """ diff --git a/scripts/chapter_2_lens_modeling/tutorial_3_realism_and_complexity.py b/scripts/chapter_2_lens_modeling/tutorial_3_realism_and_complexity.py deleted file mode 100644 index 6bfcd49..0000000 --- a/scripts/chapter_2_lens_modeling/tutorial_3_realism_and_complexity.py +++ /dev/null @@ -1,277 +0,0 @@ -""" -Tutorial 3: Realism and Complexity -================================== - -In the previous two tutorials, we fitted a fairly crude and unrealistic model: the lens's mass was spherical, as was -the source's light. Given most lens galaxies are literally called 'elliptical galaxies' we should probably model their -mass as elliptical! Furthermore, we have completely omitted the lens galaxy's light, which in real observations -outshines the source's light and therefore must be included in the lens model. - -In this tutorial, we'll use a more realistic lens model, which consists of the following light and mass profiles: - - - An `Sersic` light profile for the lens galaxy's light [7 parameters]. - - A `Isothermal` mass profile for the lens galaxy's mass [5 parameters]. - - An `ExternalShear` which accounts for additional lensing by other galaxies nearby the lens [2 parameters]. - - An `Exponential` light profile for the source-galaxy's light (this is probably still too simple for most - strong lenses, but we will worry about that later) [6 parameters]. - -This lens model has 20 free parameters, meaning that the parameter space and likelihood function it defines has a -dimensionality of N=20. This is over double the number of parameters and dimensions of the models we fitted in the -previous tutorials and in future exercises, we will fit even more complex models with some 30+ parameters. - -Therefore, take note, as we make our lens model more realistic, we also make its parameter space more complex, this is -an important concept to keep in mind for the remainder of this chapter! - -__Contents__ - -- **Initial Setup:** we'll use new strong lensing data, 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:** Compose the lens model fitted to the data. -- **Search + Analysis:** Create the non-linear search and analysis used to fit the model. -- **Run Time:** Profiling the expected run time of the model-fit. -- **Result:** Overview of the results of the model-fit. -- **Global and Local Maxima:** Up to now, all our non-linear searches have successfully found lens models that provide visibly. -- **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 new strong lensing data, 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. -""" -if al.util.dataset.should_simulate(str(dataset_path)): - import subprocess - import sys - - subprocess.run( - [sys.executable, "scripts/simulator/lens_sersic.py"], - check=True, - ) - -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__ - -We'll create and use a 2.5" `Mask2D`, which is slightly smaller than the masks we used in previous tutorials. -""" -mask_radius = 2.5 - -mask = al.Mask2D.circular( - shape_native=dataset.shape_native, - pixel_scales=dataset.pixel_scales, - radius=mask_radius, -) - -dataset = dataset.apply_mask(mask=mask) - -""" -When plotted, the lens light`s is clearly visible in the centre of the image. -""" -aplt.subplot_imaging_dataset(dataset=dataset) - -""" -__Model__ - -Now lets fit the dataset using a search. - -Below, we write the `model` using the **PyAutoFit** concise API, which means that we do not have to specify that -each component of the model is a `Model` object. This is because we are passing the light and mass profiles directly -to the `Collection` object, which assumes they are `Model` objects. - -We will use this consistent API throughout the chapter, so you should get used to it! -""" -field = af.Model(al.MassField, redshift=0.5, shear=al.mp.ExternalShear) -model = af.Collection( - galaxies=af.Collection( - lens=af.Model( - al.Galaxy, - redshift=0.5, - bulge=al.lp.Sersic, - mass=al.mp.Isothermal, - ), - source=af.Model(al.Galaxy, redshift=1.0, bulge=al.lp.ExponentialCore), - ), - fields=field, -) - -""" -__Search + Analysis__ - -We set up `Nautilus` as we did in the previous tutorial, however given the increase in model complexity we'll use -a higher `n_live` value of 200 to ensure we sample the complex parameter space efficiently. -""" -search = af.Nautilus( - path_prefix=Path("howtolens") / "chapter_2", - name="tutorial_3_realism_and_complexity", - unique_tag=dataset_name, - n_live=200, - 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__ - -The run time of the `log_likelihood_function` is a little bit more than previous tutorials, because we added more -light and mass profiles to the model. It is the increased number of parameters that increases the expected run time -more. - -Run the non-linear search. -""" -print( - "The non-linear search has begun running - checkout the output/howtolens/chapter_2/tutorial_3_realism_and_complexity" - " 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 = search.fit(model=model, analysis=analysis) - -print("Search has finished run - you may now continue the notebook.") - -""" -__Result__ - -Inspection of the `info` summary of the result suggests the model has gone to reasonable values. -""" -print(result.info) - -""" -And lets look at how well the model fits the imaging data, which as we are used to fits the data brilliantly! -""" -aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) - -""" -__Global and Local Maxima__ - -Up to now, all our non-linear searches have successfully found lens models that provide visibly good fits to the data, -minimizing residuals and inferring high log likelihood values. These optimal solutions, known as 'global maxima,' -correspond to the highest likelihood regions across the entire parameter space. In other words, no other lens model -in the parameter space would yield a higher likelihood. This is the ideal model we always aim to infer. - -However, non-linear searches do not always locate these global maxima. They may instead infer 'local maxima' -solutions, which have high log likelihood values relative to nearby models in the parameter space, but -significantly lower log likelihoods compared to the true global maxima situated elsewhere. - -Why might a non-linear search end up at these local maxima? As previously discussed, the search iterates through -many models, focusing more on regions of the parameter space where previous guesses yielded higher likelihoods. -The search gradually 'converges' around any solution with a higher likelihood than surrounding models. If the -search is not thorough enough, it may settle on a local maxima, appearing to offer a high likelihood -relative to nearby models but failing to reach the global maxima. - -Inferring local maxima is a failure of our non-linear search, and it's something we want to avoid. To illustrate -this, we can intentionally infer a local maxima by reducing the number of live points (`n_live`) Nautilus uses to -map out the parameter space. By using very few live points, the initial search over the parameter space has a low -probability of approaching the global maxima, thus it converges on a local maxima. -""" -search = af.Nautilus( - path_prefix=Path("howtolens") / "chapter_2", - name="tutorial_3_realism_and_complexity__local_maxima", - unique_tag=dataset_name, - n_live=75, - 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_3_realism_and_complexity__local_maxima" - " 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!" -) - -""" -__Run Time__ - -Due to the decreased number of live points, the estimate of 10000 iterations per free parameter is now a significant -overestimate. The actual run time of the model-fit will be much less than this. - -Run the non-linear search. -""" -result_local_maxima = search.fit(model=model, analysis=analysis) - -print("Search has finished run - you may now continue the notebook.") - -""" -__Result__ - -Inspection of the `info` summary of the result suggests certain parameters have gone to different values to the fit -performed above. -""" -print(result_local_maxima.info) - -""" -Lats look at the fit to the `Imaging` data, which is clearly worse than our original fit above. -""" -aplt.subplot_fit_imaging(fit=result_local_maxima.max_log_likelihood_fit) - -""" -Finally, just to be sure we hit a local maxima, lets compare the maximum log likelihood values of the two results - -The local maxima value is significantly lower, confirming that our non-linear search simply failed to locate lens -models which fit the data better when it searched parameter space. -""" -print("Likelihood of Global Model:") -print(result.max_log_likelihood_fit.log_likelihood) -print("Likelihood of Local Model:") -print(result_local_maxima.max_log_likelihood_fit.log_likelihood) - -""" -__Wrap Up__ - -In this example, we intentionally made our non-linear search fail, by using so few live points it had no hope of -sampling parameter space thoroughly. For modeling real lenses we wouldn't do this intentionally, but the risk of -inferring a local maxima is still very real, especially as we make our lens model more complex. - -Lets think about *complexity*. As we make our lens model more realistic, we also made it more complex. For this -tutorial, our non-linear parameter space went from 6 dimensions to 20. This means there was a much larger *volume* of -parameter space to search. As this volume grows, there becomes a higher chance that our non-linear search gets lost -and infers a local maxima, especially if we don't set it up with enough live points! - -At its core, lens modeling is all about learning how to get a non-linear search to find the global maxima region of -parameter space, even when the lens model is complex. This will be the main theme throughout the rest of this chapter, -culminating in the search chaining technique introduced in tutorials 9 and 10. - -In the next exercise, we'll learn how to deal with failure and begin thinking about how we can ensure our non-linear -search finds the global-maximum log likelihood solution. First, think about the following: - - 1) When you look at an image of a strong lens, do you get a sense of roughly what values certain lens model - parameters are? - - 2) The non-linear search failed because parameter space was too complex. Could we make it less complex, whilst - still keeping our lens model fairly realistic? - - 3) The source galaxy in this example had only 6 non-linear parameters. Real source galaxies may have multiple - components (e.g. a disk, bulge, bar, star-forming knot) and there may even be more than 1 source galaxy! Do you - think there is any hope of us navigating a parameter space if the source contributes 20+ parameters by itself? -""" 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 new file mode 100644 index 0000000..fc1c620 --- /dev/null +++ b/scripts/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.py @@ -0,0 +1,869 @@ +""" +Tutorial 3: Why Modeling Is Hard +================================ + +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. + +As we add model components and free parameters, more combinations can produce similar images. Parameter space becomes +harder to explore, and a search can miss solutions that explain the data better. + +In this tutorial, we examine these difficulties using the lens-light, mass, shear and source-light model from +*Practicalities*. We then try three approaches: adjusting justified priors, simplifying the model and searching more +thoroughly. + +Each approach has benefits and costs. The aim is to understand which change addresses the problem we see, rather than +repeatedly changing settings until a fit looks convincing. + +__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** +""" + +""" +__Overview__ + +We will first run a less thorough search and inspect its result. It may find a satisfactory solution, or it may miss a +better-fitting region of parameter space. The outcome is not guaranteed because the search includes random sampling. + +We will use this experiment to understand why fits can struggle and how to investigate them. We will also distinguish a +search that has missed a good solution from a model that cannot adequately describe the data. +""" + +""" +__Dataset and Mask__ + +We use the same `lens_sersic` imaging dataset as in *Practicalities*, with its Sérsic lens light, elliptical isothermal +mass, external shear and exponential source light. + +We also retain the circular mask with a radius of 2.5 arcseconds. Keeping the dataset and mask unchanged lets us +compare searches using the same measurements and likelihood calculation. + +Inspect the image again before fitting. Identify the central lens light and the lensed source emission: the model must +explain both. +""" + +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 +import numpy as np + +dataset_name = "lens_sersic" +dataset_path = Path("dataset") / "imaging" / dataset_name + +if al.util.dataset.should_simulate(str(dataset_path)): + import subprocess + import sys + + subprocess.run([sys.executable, "scripts/simulator/lens_sersic.py"], check=True) + +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) + +mask_radius = 2.5 +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 and Analysis__ + +We reconstruct the same model used in *Practicalities*, with the same profiles, fixed redshifts and default priors. + +Print `model.info` and inspect its diagram to remind yourself which parameters are free. The lens light, lens mass, +shear and source light all contribute to the image, so changes in one component can sometimes be partly compensated by +changes in another. + +We again use `AnalysisImaging` to predict the image and evaluate its likelihood. At this stage, neither the model nor +the analysis has changed. We will change only how thoroughly Nautilus explores parameter space. +""" + +field = af.Model( + al.MassField, + redshift=0.5, + shear=al.mp.ExternalShear, +) + +model = af.Collection( + galaxies=af.Collection( + lens=af.Model( + al.Galaxy, + redshift=0.5, + bulge=al.lp.Sersic, + mass=al.mp.Isothermal, + ), + source=af.Model( + al.Galaxy, + redshift=1.0, + bulge=al.lp.ExponentialCore, + ), + ), + fields=field, +) + +print(model.info) +af.ModelPlotter(model).figure() + +analysis = al.AnalysisImaging(dataset=dataset) + +""" +__A Less Thorough Search__ + +We deliberately reduce `n_live` from 200 to just 21. This gives Nautilus very few live points with which to explore +this complex model, making it more likely to miss a good solution. + +Nautilus requires at least one more live point than the number of non-linear parameters. This model has 20, so 21 is +the smallest valid setting; a value of 10 would raise an error rather than produce a fit. + +Inspect the resulting fit and residuals. Your run may still succeed because the search includes random sampling; a +successful run does not make this a reliable setting. + +We give this fit its own name so its output is kept separate from the *Practicalities* result. +""" + +search = af.Nautilus( + path_prefix=Path("howtolens") / "chapter_2", + name="tutorial_3_less_thorough", + unique_tag=dataset_name, + n_live=21, + n_batch=50, + iterations_per_quick_update=2500, +) + +result = search.fit(model=model, analysis=analysis) + +""" +__Inspecting the Result__ + +Print the result summary and plot the fitted image. + +First, look at whether the model reproduces the central lens light and the lensed source. Then examine the normalised +residuals for coherent structures that remain unexplained. + +If the residuals contain a recognisable arc or a substantial mismatch around the lens galaxy, the fit needs further +investigation. Check the inferred parameters too, but do not judge the fit from plausible-looking values alone. + +Your run may produce a satisfactory fit despite the low number of live points. In either case, the next step is to +compare it with the more thorough search. +""" + +print(result.info) + +aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) + +""" +__Comparing Searches__ + +Compare this fit with the 200-live-point fit from *Practicalities*. We use the same dataset, mask and physical model, +so their maximum log likelihoods can be compared directly. + +A higher log likelihood means that the corresponding model explains these measurements better under the same noise +assumptions. Inspect the residuals alongside the numbers to see where the predictions differ. + +If the more thorough search finds a substantially higher likelihood, it demonstrates that the less thorough search +missed a better solution. It does not prove that the better result is the best possible solution. + +If the fits look similar and reach similar likelihoods, this run has not demonstrated a failure. Retain that outcome +rather than assuming the low-live-point fit must be wrong. +""" + +search = af.Nautilus( + path_prefix=Path("howtolens") / "chapter_2", + name="tutorial_2_practicalities", + unique_tag=dataset_name, + n_live=200, + n_batch=50, + iterations_per_quick_update=2500, +) + +result_reference = search.fit(model=model, analysis=analysis) + +print("Less thorough maximum log likelihood:") +print(result.max_log_likelihood_fit.log_likelihood) +print("Practicalities maximum log likelihood:") +print(result_reference.max_log_likelihood_fit.log_likelihood) +aplt.subplot_fit_imaging(fit=result_reference.max_log_likelihood_fit) + +""" +__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. + +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. + +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. + +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. + +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*. +""" + +""" +__Three Ways Forward__ + +We will try three approaches to making the fit more reliable: + +1. **Prior tuning:** use justified information to give more probability to plausible parameter values or exclude +inappropriate ranges. 2. **Reducing complexity:** fix or link selected parameters, giving the search fewer independent +quantities to explore. 3. **Searching more thoroughly:** increase the search effort while retaining the original model +and priors. + +The first two approaches change our modeling assumptions. The third changes the effort spent exploring them. + +We will start each experiment from the original setup, rather than accumulating changes from the previous experiment. +This helps us understand what each approach contributes. + +**🤖 Ask AI:** My lens fit has significant residuals. What observations would help me decide whether to adjust the +priors, simplify the model or search more thoroughly? +""" + +""" +__Prior Tuning__ + +Our default priors cover a broad range of possible systems. For a particular image, we may have information that +justifies more specific choices. + +For example, we can inspect where the lens light is centred, how extended it appears and the approximate scale of the +lensed arcs. These observations can help us identify sensible parameter ranges. + +We must distinguish what the image tells us directly from additional assumptions. The lens-light centre is visible, but +assuming the mass is centred at exactly the same position is a physical assumption. Likewise, similar light and mass +shapes are not guaranteed. + +In this exercise, we will make these choices explicit and examine their effects. We will not use the known simulation +parameters as though they were information available for an unknown real lens. + +Priors chosen after inspecting the same image are practical modeling choices, not independent new measurements. Overly +restrictive choices can exclude good solutions and make the reported uncertainties misleadingly small. +""" + +""" +__Profile Centres__ + +Look at the bright central lens galaxy. Its light is centred close to `(0.0, 0.0)` arcseconds, so we do not need to +give the search equal freedom to place it anywhere across the image. + +We restrict each coordinate of the light-profile centre to between −0.05 and +0.05 arcseconds. This lets the search +refine the position around our visual estimate. + +We also expect the lens mass to be centred near the light, so we apply the same limits to its centre. This is an +additional physical assumption: we see the light directly, whereas the mass distribution is inferred through its +lensing. + +The two centres remain independent within these bounds. We have not forced them to coincide. +""" + +bulge = af.Model(al.lp.Sersic) +mass = af.Model(al.mp.Isothermal) + +bulge.centre.centre_0 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05) +bulge.centre.centre_1 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05) + +mass.centre.centre_0 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05) +mass.centre.centre_1 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05) + +""" +__Lens-Light Shape__ + +Now inspect the shape of the lens light. It appears fairly round, with a slight elongation running approximately 45° +counter-clockwise from the positive x-axis. + +We can express this impression using an axis ratio and position angle. An axis ratio near one describes a nearly +circular profile; smaller values describe stronger flattening. + +As an approximate starting guess, we use an axis ratio of 0.8 and an angle of 45°. These are estimates to guide the +search, not precise measurements from the image. + +PyAutoLens uses elliptical components to describe the shape, so we convert our guess into those components and centre +Gaussian priors on them. Their widths allow the search to move away from our initial impression. This matters +especially for a nearly round galaxy, whose orientation can be difficult to judge. +""" + +ell_comps = al.convert.ell_comps_from(axis_ratio=0.8, angle=45.0) + +bulge.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior( + mean=ell_comps[0], sigma=0.1, lower_limit=-1.0, upper_limit=1.0 +) +bulge.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior( + mean=ell_comps[1], sigma=0.1, lower_limit=-1.0, upper_limit=1.0 +) + +""" +__Mass Shape__ + +The lens light also gives us a possible starting point for the mass shape. We might expect the two to have broadly +similar orientations, but the image does not directly establish this. + +We therefore centre the mass-shape priors on the same elliptical components, while making them wider than the +light-profile priors. + +This guides the search towards mass distributions resembling the visible galaxy, but allows it to infer a different +flattening or orientation. The mass includes dark matter as well as stars, so agreement with the light should remain an +assumption we assess. +""" + +mass.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior( + mean=ell_comps[0], sigma=0.3, lower_limit=-1.0, upper_limit=1.0 +) +mass.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior( + mean=ell_comps[1], sigma=0.3, lower_limit=-1.0, upper_limit=1.0 +) + +""" +__Lens-Light Size__ + +Look at how far the lens light extends from its centre. Its appearance suggests a characteristic scale of around an +arcsecond, rather than tens of arcseconds. + +We use this impression to place a broad prior on the effective radius, centred on 1.0 arcsecond with a standard +deviation of 0.8 arcseconds. + +The effective radius describes the profile’s half-light scale; it is not the visible outer edge of the galaxy. Faint +light extends beyond the bright region we can easily inspect, so our prior leaves substantial room for the search to +refine the size. + +Truncating the prior at zero excludes negative radii. +""" + +bulge.effective_radius = af.TruncatedGaussianPrior( + mean=1.0, sigma=0.8, lower_limit=0.0, upper_limit=np.inf +) + +""" +__Light Concentration__ + +The lens galaxy has a bright central concentration surrounded by fainter, extended light. This appearance motivates +trying a concentrated Sérsic profile. + +A Sérsic index near one gives an exponential profile, often used for disks. Higher indices produce a more concentrated +centre and more extended wings; a value near four is a familiar starting description for elliptical-galaxy light. + +We therefore centre the prior on 4.0, with a standard deviation of 1.0. We are using the galaxy’s appearance to choose +a plausible range, rather than claiming that its Sérsic index can be measured accurately by eye. + +After fitting, we should inspect whether the model reproduces both the central light and the surrounding emission. +Persistent structure in the residuals may indicate that a single Sérsic profile is insufficient. +""" + +bulge.sersic_index = af.TruncatedGaussianPrior( + mean=4.0, sigma=1.0, lower_limit=0.0, upper_limit=np.inf +) + +""" +__Einstein Radius__ + +Look at the distance between the lens centre and the bright lensed arcs. They lie roughly 1.6 arcseconds from the +centre, giving us an initial estimate of the lens’s Einstein radius. + +For an elliptical lens with external shear, the arcs need not trace a circle of exactly this radius. Their distance +from the centre nevertheless gives a useful indication of the mass scale. + +We centre a Gaussian prior on 1.6 arcseconds, with a standard deviation of 0.2 arcseconds. This directs the search +towards mass models capable of producing lensed images at approximately the observed separation, while allowing it to +refine our estimate. +""" + +mass.einstein_radius = af.TruncatedGaussianPrior( + mean=1.6, sigma=0.2, lower_limit=0.0, upper_limit=np.inf +) + +""" +__Source and Shear Priors__ + +We could estimate the lens-light properties by looking directly at the foreground galaxy. The source is less +straightforward: we see its stretched and distorted images, rather than its original appearance. + +Inferring its unlensed position, size and shape requires interpreting those images through a mass model. With +experience, the image configuration can guide these choices, but we will leave the source priors unchanged here. + +We also retain the default shear priors. The appearance of the arcs reflects both the lens mass and external shear, +making their separate contributions difficult to estimate by eye. + +Our changes therefore concentrate on quantities for which the image provides a useful initial impression, with the +assumptions about the mass stated explicitly. +""" + +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.ExponentialCore, +) + +model = af.Collection( + galaxies=af.Collection(lens=lens, source=source), + fields=field, +) + +""" +__Inspecting the Tuned Model__ + +Print the model summary and inspect its diagram before starting the search. + +Connect each changed prior back to the image: the central lens position, its approximate orientation and flattening, +its light distribution, and the separation of the arcs from the centre. + +The model still contains the same physical components and the same number of free parameters. We have changed the +probability assigned to their values, rather than removed quantities from the fit. + +Check that the source and shear priors remain unchanged. This helps us keep track of which assumptions we are testing. +""" + +print(model.info) + +af.ModelPlotter(model).figure() + +""" +__Prior-Tuned Fit__ + +We now repeat the fit using our revised priors. + +We use 75 live points for the prior-tuned fit. Our aim is to see whether image-informed priors help us obtain a +satisfactory fit with less search effort than the 200-live-point setup in Practicalities. + +This changes both the priors and the live-point count relative to the 21-live-point experiment, so any improvement +cannot be attributed to prior tuning alone. + +Give this search a separate name so its output can be compared with the original broad-prior fit. +""" + +search = af.Nautilus( + path_prefix=Path("howtolens") / "chapter_2", + name="tutorial_3_prior_tuning", + unique_tag=dataset_name, + n_live=75, + n_batch=50, + iterations_per_quick_update=2500, +) + +result_custom_priors = search.fit(model=model, analysis=analysis) + +""" +__Assessing the Improvement__ + +Plot the new fit and compare it with the original 21-live-point result. + +Look first at the lens centre and the lensed arcs. Has the model reproduced their brightness and structure more +closely? Have coherent patterns in the residuals become smaller? + +Compare the maximum log likelihoods too. Because the dataset, mask and likelihood calculation are unchanged, a higher +value shows that the new search found a model that fits these measurements better. + +If the fit improves, we have demonstrated how visual inspection can help guide a search. We have not proved that the +new priors are uniquely correct or that every relevant solution has been explored. + +If it does not improve, inspect where the mismatch remains. The priors may be inappropriate, or the search may still +need more thorough exploration. Both outcomes are useful evidence for deciding what to try next. +""" + +print(result_custom_priors.info) + +aplt.subplot_fit_imaging( + fit=result_custom_priors.max_log_likelihood_fit +) + +""" +__Prior Tuning: Benefits and Limitations__ + +Looking at the image helped us identify plausible centres, shapes and scales. Encoding those impressions in the priors +can reduce the effort spent exploring models that bear little resemblance to the observed lens. + +This can improve the reliability and speed of a fit. However, the benefit depends on the quality of our choices: a +prior that excludes a good solution prevents the search from finding it, however thoroughly it explores. + +Some properties are also easier to estimate visually than others. The foreground light is directly visible, whereas the +source structure and mass distribution must be inferred through the lensing. + +Finally, these choices are specific to this image. Inspecting and tuning every lens may be practical for a small study, +but becomes time-consuming for hundreds or thousands of systems. + +We therefore need other ways to make complex models easier to fit. +""" + +""" +__Reducing Complexity__ + +Return to the image and consider how much freedom we gave the lens model. Its light and mass can each have their own +centre, flattening and orientation. + +That flexibility allows them to differ, but it also gives the search more combinations to explore. As a simplifying +experiment, we will require the mass and light to share their centre and elliptical components. + +The visible lens light will then help constrain quantities that also determine the lensing. This reduces the number of +independent parameters, potentially making the model easier to fit. + +Sharing these quantities is a physical assumption, not simply a faster way to calculate the same model. It excludes +lenses whose light and mass have different centres or shapes. +""" + +""" +__Linking Parameters__ + +We create fresh light and mass models with their default priors. This removes the prior tuning from the previous +experiment, so we can examine parameter linking separately. + +Setting `mass.centre = bulge.centre` makes the two profiles use the same centre parameters. Setting `mass.ell_comps = +bulge.ell_comps` does the same for their shapes. + +These quantities are still fitted. The search chooses their values, but each choice now applies to both profiles. + +This links four pairs of parameters: two centre coordinates and two elliptical components. It therefore removes four +independent dimensions from the search. + +The Sérsic light profile and isothermal mass profile still have different radial forms. Sharing their centre and shape +does not make the full mass distribution proportional to the light. +""" + +bulge = af.Model(al.lp.Sersic) +mass = af.Model(al.mp.Isothermal) + +mass.centre = bulge.centre +mass.ell_comps = bulge.ell_comps + +""" +__Inspecting the Simpler Model__ + +We assemble the lens, source and shear as before, then inspect the model summary and diagram. + +Find the shared centre and elliptical components. They should appear as linked quantities rather than separate choices +for the light and mass. + +The source and shear remain free to vary as in the original model. We have simplified one relationship within the lens +model, rather than fixing the whole lens or changing the observations. + +Compare the parameter count with the original model and confirm that it has fallen by four. The diagram is particularly +useful here: an unintended link can be difficult to spot in a long list of parameters. +""" + +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.ExponentialCore, +) + +model = af.Collection( + galaxies=af.Collection(lens=lens, source=source), + fields=field, +) + +print(model.info) + +af.ModelPlotter(model).figure() + +""" +__Fitting the Simpler Model__ + +We use 75 live points for the reduced-complexity fit. This changes both the model and the live-point count relative to +the original broad-prior experiment, so any improvement cannot be attributed to parameter linking alone. + +After the fit, inspect both the foreground light and the lensed arcs. A satisfactory model must explain both while +using the shared centre and shape. + +In the current simulation, the lens light and mass were given matching centres and elliptical components. This makes it +a useful controlled example of simplifying a model when the assumption is compatible with the system. + +For a real lens, we would not know that in advance. If linking improves a difficult fit, it provides a useful starting +model; it does not establish that the light and mass truly share the same geometry. +""" + +search = af.Nautilus( + path_prefix=Path("howtolens") / "chapter_2", + name="tutorial_3_reducing_complexity", + unique_tag=dataset_name, + n_live=75, + n_batch=50, + iterations_per_quick_update=2500, +) + +result_linked = search.fit(model=model, analysis=analysis) + +print(result_linked.info) + +aplt.subplot_fit_imaging(fit=result_linked.max_log_likelihood_fit) + +""" +__Reducing Complexity: Benefits and Limitations__ + +Linking the light and mass centres and shapes reduces the number of quantities the search must determine independently. +When these assumptions are appropriate, this can make a fit easier and faster. + +Unlike priors chosen by inspecting one image, the same linking rule can be applied to many lenses. However, being easy +to apply does not make it appropriate for every system. + +Imagine a lens whose light is elongated in one direction while its mass is oriented differently. Our linked model +cannot represent that difference. It may reproduce the foreground light but leave structured residuals around the arcs, +or distort other parameters to compensate. + +Inspecting both parts of the image is therefore essential. Even apparently good residuals do not establish that the +linking assumption is harmless: some biases can be absorbed by other model components. + +A simplified model can provide a useful first fit. For scientific measurements, we should also assess what changes when +its restrictions are relaxed. +""" + +""" +__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. + +This retains separate centres and shapes for the lens light and mass, allowing the image to constrain them without the +links introduced above. + +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. + +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. +""" + +""" +__Original Model__ + +We create fresh model components so that neither the tuned priors nor the parameter links carry over from the previous +experiments. + +Check `model.info` and the diagram carefully. The light and mass should again have independent centres and elliptical +components, and the priors should match the original broad-prior model. + +The dataset, mask and Analysis object remain unchanged. We are giving the search more opportunity to explore the same +physical model used at the start of this tutorial. +""" + +lens = af.Model( + al.Galaxy, + redshift=0.5, + bulge=al.lp.Sersic, + mass=al.mp.Isothermal, +) + +field = af.Model( + al.MassField, + redshift=0.5, + shear=al.mp.ExternalShear, +) + +source = af.Model( + al.Galaxy, + redshift=1.0, + bulge=al.lp.ExponentialCore, +) + +model = af.Collection( + galaxies=af.Collection(lens=lens, source=source), + fields=field, +) + +print(model.info) + +af.ModelPlotter(model).figure() + +""" +__More Thorough Search__ + +Run Nautilus with 300 live points, keeping the batch size and output-update frequency unchanged. + +Watch the saved fit images as the search progresses. Early models may explain only part of the image; allow the search +to finish before comparing its final result with the earlier fits. + +More live points improve the opportunity for exploration, but do not guarantee that every important solution is found. +We still judge the result through the image comparison, inferred parameters and consistency with other searches. +""" + +search = af.Nautilus( + path_prefix=Path("howtolens") / "chapter_2", + name="tutorial_3_search_more_thoroughly", + unique_tag=dataset_name, + n_live=300, + n_batch=50, + iterations_per_quick_update=2500, +) + +result_thorough = search.fit(model=model, analysis=analysis) + +print(result_thorough.info) + +aplt.subplot_fit_imaging(fit=result_thorough.max_log_likelihood_fit) + +""" +__Comparing the Approaches__ + +Compare the fitted images and normalised residuals from the different searches. Look at the central lens light and the +arcs separately: an improvement in one region can reveal a remaining mismatch elsewhere. + +Then compare the maximum log likelihoods and inferred parameters. The dataset and likelihood calculation are unchanged, +so the likelihood values tell us which returned models fit these measurements better. They do not, by themselves, +establish which modeling assumptions are scientifically preferable. + +Keep the changes made in each experiment in mind: + +| Fit | Priors and model | Live points | +|---|---|---:| +| Deliberately under-resourced | Original priors and independent parameters | 21 | +| Prior tuning | Image-informed priors; parameters remain independent | 75 | +| Reduced complexity | Default priors; linked light and mass geometry | 75 | +| More thorough search | Original priors and independent parameters | 300 | + +The prior-tuned and reduced-complexity fits change both the modeling choices and the number of live points relative to +the first experiment. Any improvement therefore cannot be attributed to prior tuning or parameter linking alone. + +Agreement between satisfactory fits increases our confidence, while differences tell us what needs investigation. For +example, a shift in the inferred mass parameters after removing the light–mass links would make those assumptions worth +examining more closely. + +**🤖 Ask AI:** My linked and independent light–mass models both produce small residuals, but infer different mass +parameters. What comparisons would help me assess whether the linking assumption affects my scientific conclusions? +""" + +for label, fit_result in [ + ("Less thorough", result), + ("Practicalities", result_reference), + ("Prior tuning", result_custom_priors), + ("Reduced complexity", result_linked), + ("More thorough", result_thorough), +]: + print(label, fit_result.max_log_likelihood_fit.log_likelihood) + +""" +__Benefits and Weaknesses__ + +Each approach helps the search in a different way, and each has a cost. + +| Approach | Benefits | Weaknesses | +|---|---|---| +| **Prior tuning** | Uses our interpretation of the image to guide exploration towards plausible solutions. Can make fitting faster and more reliable. | Incorrect priors can exclude good solutions or bias inference. Some parameters are difficult to estimate visually, and tailoring priors for every lens becomes time-consuming for large samples. | +| **Reducing complexity** | Fewer independent parameters can make the model easier to fit. The same simplifying rule can be applied across many lenses. | The assumptions may exclude real differences between components. A simpler model can produce biased parameters, even when its residuals look acceptable. | +| **Searching more thoroughly** | Easy to configure and retains the original model’s flexibility and priors. Does not require additional assumptions about this particular lens. | Requires more computation and may become impractical for demanding models. More searching cannot compensate for a model that cannot describe the data. | + +The appropriate choice depends on what the image and previous fits tell us. A clear visual estimate may justify tuning +a prior; a useful physical approximation may justify simplifying the model. When the existing model and priors are +appropriate, more thorough exploration may be the best next step. +""" + +""" +__Run Times__ + +Compare the time taken by the fits alongside their results. A quick search is useful only if its output is adequate for +the question we want to answer. + +Prior tuning leaves the model’s image calculation largely unchanged, but can reduce the exploration needed to find good +solutions. Linking parameters reduces the number of independent quantities being searched, while retaining the same +light and mass profiles. Increasing the number of live points generally requires more evaluations. + +The first two approaches therefore aim to make the search’s task easier; the third gives it more resources. + +Our tuned-prior and reduced-complexity fits each used 75 live points, compared with 300 for the more thorough search. +Their elapsed times reflect both the modeling choices and these different search settings. + +Compilation and output also contribute to the elapsed time, as discussed in *Practicalities*. Treat these runs as +examples of the trade-offs on your computer, rather than universal speed comparisons. +""" + +""" +__Model Mismatch__ + +So far, our simulated data have been described by the same profile families used in the unrestricted model. This gives +the search an opportunity to reproduce the image to the noise level. + +Real galaxies are less accommodating. Imagine that the source contains a bright star-forming knot, but our model allows +only one smooth exponential light profile. The fitted arc might reproduce the overall brightness distribution while +leaving a compact feature in the residuals. + +Searching longer cannot give that smooth profile a feature it does not possess. Even the highest-likelihood solution +available within this model may leave significant residuals. + +Similar problems arise if the lens light contains a disk or other structure missing from its Sérsic description. +Incorrect assumptions about the PSF, noise or contaminating objects can also produce mismatches. + +We must therefore distinguish **an inadequately explored model** from **an inadequate description of the +observations**. The residual image helps us investigate this distinction, although it rarely identifies the cause on +its own. +""" + +""" +__Wrap Up__ + +More realistic lens models give us greater freedom to explain an image, but that freedom makes fitting harder. We have +explored three responses: use visual information to guide priors, simplify the model through explicit assumptions, or +search more thoroughly. + +Each can help, but none removes the need to inspect the fit and question its assumptions. + +These trade-offs are a major reason why **search chaining is central to practical lens modeling**. It helps us balance +model realism, reliable fitting and manageable run times, drawing on the strengths of the approaches above. + +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. +""" diff --git a/scripts/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.py b/scripts/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.py deleted file mode 100644 index 9014190..0000000 --- a/scripts/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.py +++ /dev/null @@ -1,512 +0,0 @@ -""" -Tutorial 4: Dealing With Failure -================================ - -In the previous tutorial we intentionally made our non-linear search infer a local maxima solution and therefore return -a physically incorrect lens model. In this tutorial, we will pretend that we have modeled our lens and inferred a local -maxima. We introduce three approaches one can take that changes how we fit the model, all of which have the aim of -ensuring we infer the global maxima: - - 1) Prior Tuning: Tell the non-linear search where to search parameter space. - 2) Reduce Complexity: Fit a lens model with fewer parameters and therefore a simpler parameter space. - 3) Look Harder: Brute force a global maxima by telling the non-linear search to sample parameter space more thoroughly. - -Each approach has its benefits and disadvantages and we will discuss them in detail. - -In the previous tutorial, when we inferred a local maxima we knew that we had done so. For modeling a real lens, -we do not know the true lens model and it may be unclear if the solution we infered is a global or local maxima. The -methods we learn in this tutorial are therefore equally important for verifying that a solution that looks like a -global maxima solution is in indeed the global maxima. - -__Contents__ - -- **Initial Setup:** we'll use the same strong lensing data as the previous tutorial, 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. -- **Prior Tuning:** First, we will try to assist our non-linear search by tuning our priors. -- **Run Time:** Profiling the expected run time of the model-fit. -- **Result:** Overview of the results of the model-fit. -- **Discussion:** By tuning our priors to the specific lens model we are fitting, we increase the chances of finding. -- **Approach 2: Reducing Complexity:** Simplify the lens model, for example by assuming light-traces-mass. -- **Approach 3: Look Harder:** Brute force the global maxima with more thorough non-linear search settings. -- **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 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`. -""" -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. -""" -if al.util.dataset.should_simulate(str(dataset_path)): - import subprocess - import sys - - subprocess.run( - [sys.executable, "scripts/simulator/lens_sersic.py"], - check=True, - ) - -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__ - -we'll create and use a smaller 2.6" `Mask2D` again. -""" -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) - -""" -When plotted, the lens light`s is clearly visible in the centre of the image. -""" -aplt.subplot_imaging_dataset(dataset=dataset) - -""" -__Prior Tuning__ - -First, we will try to assist our non-linear search by tuning our priors. Priors guide the non-linear search on where -to look in the parameter space. By setting our priors more accurately ('tuning' them), we can help the search find the -global solution instead of getting stuck at a local maxima. - -In a previous tutorial, we learned how to fully customize priors. Let's apply this knowledge -now. I've set up a custom search below with priors adjusted to give the non-linear search a better chance of finding -the global maxima solution. I'll also explain how each prior has been changed from the default values specified in - the `config/priors` configuration files. - -We will call our lens and source galaxies `lens` and `source` this time, for shorter more readable code. - -In a previous tutorial, we customized the priors of a model by creating a `Galaxy` as a `Model` and customizing each -prior: -""" -lens = af.Model(al.Galaxy, redshift=0.5, mass=al.mp.IsothermalSph) -lens.mass.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) -lens.mass.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) - -""" -We can alternatively create the light and mass profiles as a `Model` and customize their parameters, and then pass them -to the model galaxy and overall model. These two approaches are equivalent, but in this example the style below -provides more concise and readable code. We will therefore switch to this code style in this tutorial, but may swap -back and forth between the two styles throughout **HowToLEns** depending on what is more readable. -""" -bulge = af.Model(al.lp.Sersic) -mass = af.Model(al.mp.Isothermal) - -""" -By default, the prior on the $(y,x)$ coordinates of a `LightProfile` / `MassProfile` is a TruncatedGaussianPrior with -`mean=0.0` and `sigma=0.3`. However, visual inspection of our strong lens image tells us that its centre (based on the -lens galaxy's luminous emission) is at x = 0.0" and y = 0.0", so lets reduce the `sigma` value on this prior so the -non-linear search looks over a very narrow range of `centre` values in parameter space. -""" -bulge.centre.centre_0 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05) -bulge.centre.centre_1 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05) -mass.centre.centre_0 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05) -mass.centre.centre_1 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05) - -""" -By default, the elliptical components of the of our lens galaxy's elliptical `LightProfile` are `GaussianPrior`'s -with `mean=0.0` and `sigma=0.5`. Note that the solution `ell_comps=(0.0, 0.0)` corresponds to a spherical system -and that all physical solutions (e.g. with axis-ratios running from 0.0 -> 1.0 and position angles 0.0 -> 180.0 degrees) -are encapsulated for solutions where each component runs from -1.0 -> 1.0). - -However, through visual inspection of the image we can often determine the position angle of the lens's light, which -for this data is clearly 45.0 degrees counter-clockwise from the x-axis. We can update the priors on our elliptical -components to reflect this. The `lower_limit` and `upper_limit` on a `GaussianPrior` ensure the solutions cannot go -outside the physically plausible range -1.0 -> 1.0. -""" -bulge.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior( - mean=0.333333, sigma=0.1, lower_limit=-1.0, upper_limit=1.0 -) -bulge.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior( - mean=0.0, sigma=0.1, lower_limit=-1.0, upper_limit=1.0 -) - -""" -Lets also assume that the ellipticity of the light profile can be used as a prior on that of the mass profile. This may -not be strictly true (e.g. because of dark matter) so we will use a wider prior, such that the non-linear search can -change the mass model's ellipticity from that of the light if fitting the data necessitates it. -""" -mass.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior( - mean=0.333333, sigma=0.3, lower_limit=-1.0, upper_limit=1.0 -) -mass.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior( - mean=0.0, sigma=0.3, lower_limit=-1.0, upper_limit=1.0 -) - -""" -The `effective_radius` of light profile is its 'half-light' radius, the radius at which 50% of its total luminosity -is internal to a circle defined within that radius. **PyAutoLens** assumes a `UniformPrior` on this quantity between -0.0" and 30.0". This large range of values is required to cover the size of all possible strong lenses that can be -observed in the Universe. - -However, inspection of this image shows the lens's light does not extend anywhere near 30.0", so lets reduce it. -""" -bulge.effective_radius = af.TruncatedGaussianPrior( - mean=1.0, sigma=0.8, lower_limit=0.0, upper_limit=np.inf -) - -""" -The `sersic_index` defines how concentrated the light profile is. In galaxy structure studies, values of Sersic index -around 1.0 indicate a disk galaxy, whereas higher values of 3 or 4 indicate an elliptical galaxy. **PyAutoLens** -assumes a `UniformPrior` between 0.8 and 8.0 by default on this parameter, as a user could model strong lenses -where the lens is of any morphology. - -We often have knowledge of the lens's morphology before we fit it, so in this example we will assume our lens is -a massive elliptical galaxy with a `sersic_index` near 4. -""" -bulge.sersic_index = af.TruncatedGaussianPrior( - mean=4.0, sigma=1.0, lower_limit=0.0, upper_limit=np.inf -) - -""" -Finally, the `ring` that the lensed source forms clearly has a radius of about 1.6". This is its Einstein radius, so -lets change the prior from a UniformPrior between 0.0" and 4.0". -""" -mass.einstein_radius = af.TruncatedGaussianPrior( - mean=1.6, sigma=0.2, lower_limit=0.0, upper_limit=np.inf -) - -""" -We now compose the overall model, where the lens galaxy model uses the `Model` components above which had their -priors customizes. - -In this exercise, I'm not going to change any priors on the source galaxy. Whilst lens modeling experts can look at a -strong lens and often tell you roughly where the source-galaxy is located (in the source-plane), it is something of art -form. Furthermore, the source's morphology can be pretty complex, making it difficult to come up with a good source -prior! -""" -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.ExponentialCore) - -model = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field) - -""" -The `info` attribute shows the model in a readable format, including the priors specified above. -""" -print(model.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 model has twenty free parameters against the six of tutorial 1, which is why this fit is so much harder. -Note also that it uses *ordinary* light profiles rather than the linear ones we have been using, so the search -has to sample each `intensity` itself. Tutorial 5 will take those two dimensions back. -""" -af.ModelPlotter(model).figure() - -""" -We can now create this custom search and run it. Our non-linear search will now start by sampling higher likelihood -regions of parameter space, given our improved and more informed priors. -""" -search = af.Nautilus( - path_prefix=Path("howtolens") / "chapter_2", - name="tutorial_4_custom_priors", - unique_tag=dataset_name, - n_live=150, - 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__ - -The run time of the `log_likelihood_function` is around the usual value. - -Due to prior tuning, the model-fit should take less than 10000 iterations per free parameter to converge. - -Run the non-linear search. -""" -print( - "The non-linear search has begun running - checkout the output/howtolens/chapter_2/tutorial_4_custom_priors" - " 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_custom_priors = search.fit(model=model, analysis=analysis) - -print("Search has finished run - you may now continue the notebook.") - -print(result_custom_priors.info) - -""" -__Result__ - -Bam! We get a good model, which corresponds to the global maxima. By giving our non-linear search a helping hand and -informing it of where to sample parameter space, we can increase the odds that we find the global maxima solution. -""" -aplt.subplot_fit_imaging(fit=result_custom_priors.max_log_likelihood_fit) - -""" -__Discussion__ - -By tuning our priors to the specific lens model we are fitting, we increase the chances of finding the global maxima. -This approach can also speed up the search, as it spends less time in regions of parameter space that do not -correspond to good solutions. - -Before moving on to the next approach, let’s consider the pros and cons of prior tuning: - -**Advantages:** - -- Higher likelihood of finding the global maximum log likelihood solutions in parameter space. - -- Faster search times, as the non-linear search explores less of the parameter space. - -**Disadvantages:** - -- Incorrectly specified priors could lead the non-linear search to an incorrect solution. - -- It is not always clear how the priors should be tuned, especially for complex lens models. - -- Priors tailored to a specific lens need customization for each fit. For large samples of lenses, -this process would be very time-consuming. - -__Approach 2: Reducing Complexity__ - -The non-linear search may fail because the lens model is too complex, making its parameter space too difficult to -sample accurately. To address this, we can simplify the lens model while ensuring it remains realistic enough for -our scientific study. By making certain assumptions, we can reduce the number of model parameters, thereby lowering -the dimensionality of the parameter space and improving the search's performance. -""" -bulge = af.Model(al.lp.Sersic) -mass = af.Model(al.mp.Isothermal) - -""" -First, we create a search that assumes that light-traces-mass. That is, the light profile centre and elliptical -components are perfectly aligned with the centre and elliptical components of the mass profile. This may, or may -not, be a reasonable assumption, but it`ll remove 4 parameters from the lens model (the centre and elliptical -components of the mass profile), so it is worth trying! - -To apply our assumption that light traces mass to the model, we `pair` the `centre` and `ell_comps` parameters -by setting them equal to one another. This removes the parameter on the left-hand side of the pairing from the lens -model such that when a model is created it has the same value as the parameter on the right-hand side. -""" -mass.centre = bulge.centre -mass.ell_comps = bulge.ell_comps - -""" -We now compose the model, which will have a non-linear parameter space with 4 less dimensions than the fit performed -previously. -""" -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.ExponentialCore) - -model = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field) - -""" -The `info` attribute shows the model in a readable format, including the parameter links specified above. -""" -print(model.info) - -""" -The `mass · Isothermal`'s `centre` and `ell_comps` are no longer free parameters of their own: each is tied to -the matching parameter of the `bulge · Sersic`. That pairing *is* the light-traces-mass assumption, and it takes -the model from twenty free parameters down to sixteen. - -Pairing parameters is easy to get subtly wrong and hard to spot in a long `info` listing. -""" -af.ModelPlotter(model).figure() - -""" -We now create this search and run it. -""" -search = af.Nautilus( - path_prefix=Path("howtolens") / "chapter_2", - name="tutorial_4_reducing_complexity", - unique_tag=dataset_name, - n_live=200, - 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 -) - -""" -__Run Time__ - -The run time of the `log_likelihood_function` is around the usual value. - -Due to the simplest model parameterization, the model-fit should take less than 10000 iterations per free parameter to -converge. - -Run the non-linear search. -""" -print( - "The non-linear search has begun running - checkout the output/howtolens/chapter_2/tutorial_4_reducing_complexity" - " 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_light_trace_mass = search.fit(model=model, analysis=analysis) - -print("Search has finished run - you may now continue the notebook.") - -print(result_light_trace_mass.info) - -aplt.subplot_fit_imaging(fit=result_light_trace_mass.max_log_likelihood_fit) - -""" -__Result__ - -The results look pretty good. Our source galaxy fits the data pretty well and we've clearly inferred a model that -looks similar to the one above. However, inspection of the residuals shows that the fit was not quite as good as the -first search. - -It turns out that for this simulated lens, light did not perfectly trace mass. The quality of the fit suffered and the -highest value of log likelihood the search inferred was lower as a result. - -Herein lies the pitfalls of making assumptions, they may make your model less realistic and your fits worse! - -__Discussion__ - -Let’s consider the advantages and disadvantages of simplifying the model: - -Advantages: - -- By reducing the complexity of the parameter space, we increase the chances of finding the global maximum log -likelihood, and the search requires less time to do so. - -- Unlike with tuned priors, this approach is not specific to a single lens, allowing us to use it on many strong lens -images. - -Disadvantages: - -- Our model is less realistic, which may negatively impact the accuracy of our fit and the scientific results we -derive from it. - -__Approach 3: Look Harder__ - -In approaches 1 and 2, we assisted our non-linear search to find the highest log likelihood regions of parameter -space. In approach 3, we're simply going to tell it to "look harder." - -Every non-linear search has settings that control how thoroughly it explores parameter space. One such setting is the -number of live points used by `Nautilus`. The more thoroughly the search examines the space, the more likely it is to -find the global maximum lens model. However, this also means the search will take longer! - -Below, we configure a more thorough Nautilus search with `n_live=300`. These settings and what they change are -discussed in the optional tutorial `chapter_optional/tutorial_searches.ipynb`. -""" -lens = af.Model( - al.Galaxy, - redshift=0.5, - bulge=al.lp.Sersic, - mass=al.mp.Isothermal, -) -field = af.Model(al.MassField, redshift=0.5, shear=al.mp.ExternalShear) - -source = af.Model(al.Galaxy, redshift=1.0, bulge=al.lp.ExponentialCore) - -model = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field) - -search = af.Nautilus( - path_prefix=Path("howtolens") / "chapter_2", - name="tutorial_4_look_harder", - unique_tag=dataset_name, - n_live=300, - iterations_per_quick_update=2500, # Outputs Notebook visualization of max likelihood model every N iterations -) -""" -__Run Time__ - -The run time of the `log_likelihood_function` is around the usual value. - -Due to the more thorough Nautilus settings, the the model-fit should take more than 10000 iterations per free parameter -to converge and thus take longer than we are used too. - -Run the non-linear search. -""" -print( - "The non-linear search has begun running - checkout the output/howtolens/chapter_2/tutorial_4_look_harder" - " 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_look_harder = search.fit(model=model, analysis=analysis) - -print("Search has finished run - you may now continue the notebook.") - -print(result_look_harder.info) - -aplt.subplot_fit_imaging(fit=result_look_harder.max_log_likelihood_fit) - -""" -Let's list the advantages and disadvantages of simply adjusting the non-linear search: - -**Advantages:** - -- It’s easy to set up; just change the settings of the non-linear search. - -- It generalizes to any strong lens. - -- We can retain a more complex lens model. - -**Disadvantage:** - -- It can be very expensive in terms of time. For very complex models, the run times can extend to hours, days, -weeks, or even months! - -In conclusion, we can now fit strong lenses effectively. When the process fails, we know how to make it work. -In tutorials 9 and 10 of this chapter, we will introduce a technique called 'non-linear search chaining', which performs -a model fit by chaining together multiple searches back-to-back. This allows us to combine the 3 different approaches -discussed and exploit the advantages of each, whilst not being hindered by their disadvantages. - -With search chaining, we can: - - - Fit simpler models with lower dimensionality parameter spaces in the earlier searches and gradually increase the - lens model complexity search-by-search, guiding the model-fit to a sufficiently realistic lens model. - - - In these earlier searches (with easier to sample parameter spaces), use fast non-linear search settings to compute - the results quickly and switch to slower settings in later searches when we fit more complex lens models. - - - Use 'prior passing' to setup the priors of each parameter in the later searches, based on the lens models inferred - by the earlier searches. We can therefore guide each search on how to sample a complex lens model's parameter space - in a way that can be fully generalized to any strong lens. - -__Wrap Up__ - -Before we get to search chaining, we have a few more tutorials, where we will discuss masking in more detail, the -`Result` object and how to make **PyAutoLens** run faster. -""" diff --git a/scripts/chapter_2_lens_modeling/tutorial_4_linear_profiles.py b/scripts/chapter_2_lens_modeling/tutorial_4_linear_profiles.py new file mode 100644 index 0000000..1ffbb30 --- /dev/null +++ b/scripts/chapter_2_lens_modeling/tutorial_4_linear_profiles.py @@ -0,0 +1,692 @@ +""" +Tutorial 4: Linear Profiles +=========================== + +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. + +Linear light profiles offer another possibility: reduce the number of parameters explored by the non-linear search +while retaining the same light-profile shapes. + +Their intensities are still fitted to the data, but are calculated using linear algebra for each proposed model. +Nautilus can therefore concentrate on the remaining parameters. + +We briefly used a linear source profile in Tutorial 1. Here, we examine how this works, then combine many linear +profiles to describe more detailed light distributions without introducing a separate non-linear intensity parameter +for each one. + +__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** +- **Multi-Gaussian Expansion Benefits** +- **Benefits Have Costs** +- **Positive Intensities** +- **Other Basis Functions** +- **Wrap Up** +""" + +""" +__Overview__ + +We first replace the ordinary lens and source light profiles with their linear equivalents. We will inspect the model, +run the fit and retrieve the intensities calculated during the analysis. + +We then combine Gaussian light profiles of different sizes into a **multi-Gaussian expansion**, or **MGE**. Their +summed light can describe a wider range of radial structures than a single profile. + +The key idea is to separate the parameters that require non-linear exploration from the intensities that can be solved +together for each proposed model. +""" + +""" +__Dataset and Mask__ + +We use the same `lens_sersic` dataset as before. Look again at the bright central lens galaxy and the lensed source +around it: both contribute light that our model must reproduce. + +We retain the 2.5-arcsecond circular mask used in the preceding tutorials. The observations and selected pixels are +unchanged; this time, we change how the model’s light-profile intensities are determined. + +The following code loads the dataset, generating it if necessary, applies the mask and plots the image. +""" + +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 +import numpy as np + +dataset_name = "lens_sersic" +dataset_path = Path("dataset") / "imaging" / dataset_name + +if al.util.dataset.should_simulate(str(dataset_path)): + import subprocess + import sys + + subprocess.run([sys.executable, "scripts/simulator/lens_sersic.py"], check=True) + +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) + +mask_radius = 2.5 +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) + +""" +__Linear Light Profiles__ + +Imagine holding a light profile’s centre, size and shape fixed, then doubling its intensity. Its predicted brightness +doubles at every point, without changing its shape. + +The same scaling holds after ray tracing through a fixed mass model and blurring by the PSF. This simple relationship +is what makes the intensity a **linear parameter**. + +For a proposed set of profile shapes and mass parameters, we can therefore calculate the intensities that best +reproduce the image using linear algebra. This calculation is often called an **inversion**. + +The lens and source intensities are solved together, accounting for the fact that their light overlaps in the observed +image. + +The calculation is repeated whenever the non-linear search proposes different parameter values. The intensities are +fitted quantities, not fixed numbers chosen in advance. +""" + +""" +__Why This Helps__ + +With ordinary light profiles, Nautilus must explore intensity alongside parameters such as effective radius and Sérsic +index. Different combinations can produce similar images, making these relationships difficult to explore. + +With linear light profiles, each proposed combination of the remaining parameters is evaluated using its best-fitting +intensities, subject to the solver’s constraints. Nautilus no longer needs to search along the intensity dimensions +itself. + +In our example, this removes two dimensions from the non-linear search: one intensity for the lens light and one for +the source light. The Sérsic and exponential profile shapes remain available, so we have not simplified the physical +description in the way that linking light and mass did. + +This does not remove the underlying relationships between brightness, size and shape. It changes how we handle them +computationally, often making the non-linear exploration easier. + +The benefit becomes particularly useful when we combine many light profiles: their intensities can be solved together +rather than adding a new search dimension for every profile. +""" + +""" +__Model__ + +We replace the lens and source light profiles with their equivalents from `al.lp_linear`. + +The lens still has a Sérsic light profile and an elliptical isothermal mass profile, alongside external shear. The +source still has an exponential light profile. Their physical roles are unchanged. + +Using `al.lp_linear` tells the analysis to solve the two light-profile intensities whenever it evaluates a proposed +model. The other free parameters remain the responsibility of Nautilus. +""" + +bulge = af.Model(al.lp_linear.Sersic) +mass = af.Model(al.mp.Isothermal) + +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 = af.Collection( + galaxies=af.Collection(lens=lens, source=source), + fields=field, +) + +""" +Print the model summary and inspect its diagram. + +Find the lens and source light profiles. Their intensities no longer have priors for the non-linear search: they are +identified as quantities solved during the fit. + +Compare this with the ordinary-profile model from *Practicalities*. There are two fewer non-linear parameters, while +the centres, shapes, sizes and mass parameters remain available for exploration. + +This distinction matters when interpreting the parameter count. Fewer non-linear parameters does not mean that we have +stopped fitting the brightness of either galaxy. +""" + +print(model.info) + +af.ModelPlotter(model).figure() + +""" +__Search and Run Time__ + +We use 100 live points for this example, compared with 200 for the ordinary-profile fit in *Practicalities*. The +simpler non-linear parameter space gives us a reason to try fewer live points, but we must still inspect the result. + +Solving the intensities adds work to each likelihood evaluation. In return, the search no longer explores their values +or has to navigate their relationships with the other parameters directly. + +The overall run time depends on the balance between these costs. A linear-profile fit is not guaranteed to finish +faster, particularly for a model with only two light profiles. Its advantages become more substantial as we introduce +larger collections of profiles. + +This example changes both the treatment of intensities and the live-point count, so it is a practical demonstration +rather than a controlled timing comparison. +""" + +search = af.Nautilus( + path_prefix=Path("howtolens") / "chapter_2", + name="tutorial_4_linear_profiles", + unique_tag=dataset_name, + n_live=100, + n_batch=50, + iterations_per_quick_update=2500, +) + +analysis = al.AnalysisImaging(dataset=dataset) + +result_linear = search.fit(model=model, analysis=analysis) + +""" +__Result__ + +Plot the fitted image and inspect the central lens light and lensed arcs. + +Although Nautilus did not explore the intensities, the analysis has adjusted them to reproduce the observed brightness +for each proposed model. Both galaxies should therefore contribute to the final image. + +Examine the normalised residuals as before. Changing how intensities are determined does not remove the need to check +whether the model describes the observations. + +The result summary describes the parameters explored by the non-linear search. We will retrieve the solved intensities +separately below. +""" + +print(result_linear.info) + +aplt.subplot_fit_imaging(fit=result_linear.max_log_likelihood_fit) + +""" +__Intensities__ + +The intensities are calculated during the image fit rather than sampled directly by Nautilus. + +To inspect their values, retrieve `result_linear.max_log_likelihood_tracer`. This tracer contains ordinary light +profiles with the solved intensities inserted, corresponding to the highest-likelihood fit found by the search. + +In this two-galaxy example, the first galaxy is the foreground lens and the second is the background source. Print +their intensities below. + +These are the intensities associated with one fitted model. They are not uncertainty estimates: their preferred values +can change as the other profile and mass parameters change. +""" + +tracer = result_linear.max_log_likelihood_tracer + +print(tracer.galaxies[0].bulge.intensity) +print(tracer.galaxies[1].bulge.intensity) + +""" +__Visualisation__ + +The tracer retrieved above contains ordinary light profiles with their solved intensities. We can therefore use it to +calculate and plot an image. + +This shows the light predicted by the tracer before PSF blurring. To assess agreement with the observed image, use the +`FitImaging` plot, which includes that blurring and displays the residuals. + +Keep this distinction in mind: the original linear profiles describe components whose intensities still need to be +solved, whereas this tracer contains the intensities determined by the fit. +""" + +tracer = result_linear.max_log_likelihood_tracer + +aplt.plot_array( + array=tracer.image_2d_from(grid=dataset.grid), + title="Model image before PSF blurring", +) + +""" +__Basis__ + +Look again at the foreground lens galaxy. A single Sérsic profile describes its light using smooth ellipses with one +axis ratio and orientation. Real galaxies can have rounder central regions, flatter outer light, or an orientation that +gradually changes with radius. These changes can leave structured residuals when we fit a single Sérsic profile. + +An alternative is to add together Gaussian light profiles of different sizes. Narrow Gaussians describe concentrated +central light, while broader Gaussians describe the surrounding emission. Their intensities determine how much each +contributes to the combined brightness distribution. + +PyAutoLens groups these profiles into a `Basis`. When they are Gaussians, this description is called a **multi-Gaussian +expansion**, or **MGE**. + +The flexibility depends on how we arrange the Gaussians. One group sharing a centre and shape gives a flexible radial +profile. Multiple groups with different shapes and orientations can describe changes in flattening and twists in the +light distribution. Describing genuinely lopsided light requires additional freedom, such as offset centres. + +The workspace example uses two groups with different elliptical shapes but a shared centre. These can represent, for +example, rounder central light and a flatter outer component. Their changing contributions with radius let the combined +image vary in shape without assigning independent geometry to every Gaussian. + +Crucially, the Gaussian widths can be fixed and their intensities solved by linear algebra. The non-linear search then +explores only the chosen geometric parameters. This gives us a way to describe more complex light distributions while +keeping the non-linear parameter space manageable. + +We begin here with a single Gaussian group to understand the method. It will not capture every structure described +above; the workspace demonstrates the more flexible arrangements. + +Individual Gaussians need not represent separate physical structures. We interpret their summed light distribution, +rather than identifying each Gaussian as a distinct part of the galaxy. +""" + +""" +__A First Gaussian Basis__ + +We begin with 30 circular Gaussians, all centred at `(0.0, 0.0)` arcseconds. Their sizes are fixed and spaced +logarithmically, giving us a range of narrow and broad components. + +The smallest Gaussian has a width of one tenth of the image pixel scale; the largest has a width of 3.0 arcseconds. +These are profile widths, not the extent of the fitted region: our image mask remains at 2.5 arcseconds. + +This first example deliberately keeps the geometry simple. We solve the intensities without searching for a better +centre or ellipticity, then inspect what that restriction leaves unexplained. +""" + +total_gaussians = 30 + +sigma_values = np.logspace( + np.log10(dataset.pixel_scales[0] / 10.0), + np.log10(3.0), + total_gaussians, +) + +gaussian_list = [ + al.lp_linear.Gaussian( + centre=(0.0, 0.0), + ell_comps=(0.0, 0.0), + sigma=sigma, + ) + for sigma in sigma_values +] + +bulge = al.lp_basis.Basis(profile_list=gaussian_list) + +""" +__Evaluating the Basis__ + +We replace the lens’s Sérsic light profile with this Gaussian basis. We retain the mass, shear and source geometry from +the previous fit. + +Creating `FitImaging` solves the linear intensities for this fixed geometry, including the source intensity. It does +not run a new non-linear search. + +This lets us examine what the Gaussian basis can achieve before giving it freedom to adjust its centre and shape. +""" + +lens = al.Galaxy( + redshift=0.5, + bulge=bulge, + mass=result_linear.instance.galaxies.lens.mass, +) + +source = result_linear.instance.galaxies.source + +tracer = al.Tracer( + galaxies=[lens, source], + fields=result_linear.max_log_likelihood_fields, +) + +fit = al.FitImaging(dataset=dataset, tracer=tracer) + +""" +__Inspecting the Basis Fit__ + +Plot the fit and examine the foreground galaxy, especially the transition from its bright centre to its fainter outer +light. + +The range of Gaussian sizes gives the model flexibility to reproduce this radial brightness distribution. However, +every Gaussian is currently circular, whereas the lens light is slightly elongated. + +Look for residual structure around the lens galaxy that could reflect this difference. Adjusting intensities changes +how much light each Gaussian contributes, but cannot make circular Gaussians reproduce an elliptical shape. + +We have also fixed their common centre rather than fitted it. In the next step, we let the non-linear search determine +a shared centre and ellipticity while the linear solve continues to determine the individual intensities. + +This illustrates two distinct kinds of flexibility: the Gaussian intensities control the radial light distribution, +while their centres and shapes control its geometry. Adding more Gaussians with the same circular shape cannot, by +itself, reproduce an elongated or asymmetric galaxy. + +**🤖 Ask AI:** My circular Gaussian basis leaves elongated residuals around the lens galaxy. Why might changing the +Gaussian intensities fail to remove them, and which geometric parameters could I investigate? +""" + +aplt.subplot_fit_imaging(fit=fit) + +""" +__Lens MGE__ + +The circular Gaussian basis could adjust its radial brightness distribution, but could not reproduce the slight +elongation of the lens light. + +We now let Nautilus fit a common centre and elliptical shape for the 30 Gaussians. Their widths remain fixed, and their +intensities are solved together during each likelihood evaluation. + +This gives the lens-light model just four non-linear parameters: two centre coordinates and two elliptical components. + +The Gaussians share these parameters, so they move and change shape together. Their individual intensities still allow +the combined brightness to vary with radius. This arrangement remains elliptically symmetric; more complicated geometry +requires the additional Gaussian groups discussed earlier. +""" + +""" +We create the centre priors once and assign those same prior objects to every Gaussian. This links their centres, +rather than giving each Gaussian an independent position within the same limits. + +We also link every Gaussian’s elliptical components to those of the first Gaussian. Each width is assigned a fixed +numerical value. + +Inspect these assignments carefully: giving every Gaussian independent geometry would create a much larger non-linear +search problem. +""" + +lens_centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) +lens_centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) + +lens_sigmas = np.logspace( + np.log10(dataset.pixel_scales[0] / 10.0), + np.log10(3.0), + 30, +) + +lens_gaussians = af.Collection( + af.Model(al.lp_linear.Gaussian) for _ in range(30) +) + +for i, gaussian in enumerate(lens_gaussians): + gaussian.centre.centre_0 = lens_centre_0 + gaussian.centre.centre_1 = lens_centre_1 + gaussian.ell_comps = lens_gaussians[0].ell_comps + gaussian.sigma = lens_sigmas[i] + +bulge = af.Model( + al.lp_basis.Basis, + profile_list=list(lens_gaussians), +) + +""" +__Source MGE__ + +We can use the same approach for the source galaxy. Its predicted light is ray-traced through the mass model before +being compared with the observed arcs. + +Here, we use 15 Gaussians with widths spanning 0.0001 to 1.0 arcseconds in the source plane. This range includes +compact components and broader emission appropriate for the example; it does not mean the data resolve the smallest +Gaussian individually. + +The source Gaussians share a centre and elliptical shape with one another, but these parameters must be independent of +the lens-light MGE. We therefore create new prior objects for the source centre. + +This source model can adjust its radial light distribution without making Nautilus explore an intensity or width for +every Gaussian. It still describes one smooth, elliptically symmetric source, rather than arbitrary clumps or multiple +galaxies. +""" + +source_centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) +source_centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) + +source_sigmas = np.logspace(-4, 0, 15) + +source_gaussians = af.Collection( + af.Model(al.lp_linear.Gaussian) for _ in range(15) +) + +for i, gaussian in enumerate(source_gaussians): + gaussian.centre.centre_0 = source_centre_0 + gaussian.centre.centre_1 = source_centre_1 + gaussian.ell_comps = source_gaussians[0].ell_comps + gaussian.sigma = source_sigmas[i] + +source_bulge = af.Model( + al.lp_basis.Basis, + profile_list=list(source_gaussians), +) + +""" +__Combined Model__ + +We now combine the lens-light MGE, the isothermal mass profile, external shear and the source-light MGE. + +There are 45 Gaussian light profiles, but only 15 non-linear parameters: + +- Four describe the shared lens-light geometry. +- Four describe the shared source-light geometry. +- Five describe the isothermal mass profile. +- Two describe external shear. + +The Gaussian intensities are solved during each likelihood evaluation, and their widths are fixed. The number of light +profiles is therefore very different from the number of parameters Nautilus must explore. + +Retaining external shear keeps the mass description consistent with our earlier fits. +""" + +lens = af.Model( + al.Galaxy, + redshift=0.5, + bulge=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 = af.Collection( + galaxies=af.Collection(lens=lens, source=source), + fields=field, +) + +""" +__Inspecting the Model__ + +The model summary is long because it lists all 45 Gaussians. Use the diagram alongside it to identify the much smaller +set of independent parameters. + +Within each basis, check that the centres and elliptical components are shared, the widths are fixed and the +intensities are solved linearly. + +Then check that the lens and source have separate geometry. Accidentally linking them would impose a relationship +between the foreground galaxy and the unlensed source that we do not intend. + +This is the main benefit of the construction: many light components can describe the brightness distribution while the +non-linear search handles a comparatively small set of geometric and mass parameters. +""" + +print(model.info) + +af.ModelPlotter(model).figure() + +""" +__Model Fit__ + +We now fit the lens and source MGEs together with the mass model and external shear. + +Nautilus explores their geometric and mass parameters. For every proposed model, the analysis solves the Gaussian +intensities together, accounting for the overlapping lens and lensed-source light. + +We use 100 live points as a starting configuration for this example. As before, we must inspect the result rather than +assume that the simpler parameter space guarantees success. +""" + +search = af.Nautilus( + path_prefix=Path("howtolens") / "chapter_2", + name="tutorial_4_mge", + unique_tag=dataset_name, + n_live=100, + n_batch=50, + iterations_per_quick_update=2500, +) + +result_basis = search.fit(model=model, analysis=analysis) + +""" +__Result__ + +Inspect the fitted image and normalised residuals. Look separately at the central lens galaxy and the surrounding arcs. + +The shared geometry lets each Gaussian group adjust its centre and ellipticity, while its intensities determine the +radial brightness distribution. Compare this fit with the earlier demonstration that fixed the lens Gaussians to be +circular. + +The highest-likelihood tracer contains all 45 Gaussian profiles with their solved intensities, so we can plot the +inferred light distribution directly. + +Check what the figures show before drawing a conclusion. The model may reproduce this smooth simulated system well, but +that does not demonstrate that the same arrangement can describe every real galaxy. +""" + +print(result_basis.info) + +tracer = result_basis.max_log_likelihood_tracer + +aplt.subplot_tracer(tracer=tracer, grid=dataset.grid) + +aplt.subplot_fit_imaging(fit=result_basis.max_log_likelihood_fit) + +""" +__Multi-Gaussian Expansion Benefits__ + +An MGE separates flexibility in the brightness distribution from the number of parameters explored by the non-linear +search. + +Our lens and source each use only four non-linear geometric parameters, despite containing 30 and 15 Gaussian profiles +respectively. Their fixed widths cover a range of scales, and the linear solve determines how much light belongs on +each scale. + +More flexible arrangements can describe changes in flattening and orientation with radius. The workspace’s +`multi_gaussian_expansion/modeling.py` example demonstrates multiple Gaussian groups with different shapes. + +This makes MGE a valuable tool for lens modeling: it can improve the description of galaxy light while keeping the +non-linear exploration manageable. + +The approach is also useful for obtaining an initial source model. However, our single-centre source MGE remains a +restricted description, especially when the source contains separate bright knots or irregular features. +""" + +""" +__Benefits Have Costs__ + +Evaluating many Gaussian profiles and solving their intensities adds work to each likelihood calculation. A simpler +non-linear parameter space can compensate for that cost, but the overall speed depends on the dataset and model. + +An MGE can also be less straightforward to interpret physically than a Sérsic profile. A Sérsic effective radius and +index directly describe its size and concentration; individual Gaussian widths and intensities are primarily +ingredients of the summed light distribution. + +Finally, flexibility depends on the geometry we allow. Adding more Gaussians with one shared centre and shape improves +radial freedom, but cannot create an independently positioned clump. + +Inspect residual structure with these restrictions in mind. A detailed-looking model is useful only if it has the +freedom needed to describe the features relevant to the analysis. +""" + +""" +__Positive Intensities__ + +Without a positivity constraint, a linear solver can combine positive and negative Gaussian intensities to reproduce an +image. Large contributions can cancel one another, producing a fitted sum from components that do not represent +physical light emission. + +PyAutoLens constrains the Gaussian intensities to be non-negative. A Gaussian can contribute light or have zero +intensity, but cannot subtract light through a negative brightness. + +This is particularly useful when many overlapping Gaussians describe the same region. It prevents alternating positive +and negative contributions from being used to manufacture structure. + +Non-negative intensities do not guarantee that the overall model is correct. We still need to assess its geometry and +inspect the residuals. +""" + +""" +__Other Basis Functions__ + +Gaussians are not the only functions we can combine to describe galaxy light. PyAutoLens also supports **shapelets**, +which provide another set of spatial patterns for constructing a light distribution. + +Different basis functions offer different kinds of flexibility and computational costs. Their usefulness depends on the +structures in the image and the model we want to fit. + +You do not need to explore every option to continue HowToLens. The workspace example +`scripts/imaging/features/advanced/shapelets/modeling.py` provides a starting point if your analysis would benefit from +investigating an alternative. + +For now, the important distinction is between the individual functions and the freedom of their combined model. A basis +can only reproduce structures allowed by its arrangement and parameters. +""" + +""" +__Wrap Up__ + +Linear light profiles let us solve intensities separately from the non-linear search. We used this first with Sérsic +and exponential profiles, then with Gaussian groups describing the lens and source light. + +An MGE gives us flexibility in the brightness distribution without requiring Nautilus to explore an intensity for every +Gaussian. More elaborate arrangements can describe changes in shape and orientation, while our shared-shape example +keeps the geometry simple. + +This flexibility still has limits. A source containing several distinct star-forming knots may leave structured +residuals when fitted with one smooth, common-centre MGE. Chapter 3 introduces pixelized sources as a way to describe +more complicated spatial structure. + +Before that, *Data and Likelihoods* returns to the observations: which measurements enter the fit, how we handle +contamination, and how the same model–Analysis–search approach applies to the other types of lensing data introduced in +Chapter 1. + +We will then bring these tools together in search chaining, balancing model flexibility, reliable fitting and run time. +""" diff --git a/scripts/chapter_2_lens_modeling/tutorial_5_linear_profiles.py b/scripts/chapter_2_lens_modeling/tutorial_5_linear_profiles.py deleted file mode 100644 index b4b5022..0000000 --- a/scripts/chapter_2_lens_modeling/tutorial_5_linear_profiles.py +++ /dev/null @@ -1,579 +0,0 @@ -""" -Tutorial 5: Linear Profiles -=========================== - -In the previous tutorial we learned how to balance model complexity with our non-linear search in order to infer -accurate lens model solutions and avoid failure. We saw how in order to fit a model accurately one may have to -parameterize and fit a simpler model with fewer non-linear parameters, at the expense of fitting the data less -accurately. - -It would be desirable if we could make our model have more flexibility enabling it to fit more complex galaxy -structures, but in a way that does not increase (or perhaps even decreases) the number of non-linear parameters. -This would keep the `Nautilus` model-fit efficient and accurate. - -This is possible using linear light profiles, which solve for their `intensity` parameter via efficient linear -algebra, using a process called an inversion. The inversion always computes `intensity` values that give the best -fit to the data (e.g. they minimize the chi-squared and therefore maximize the likelihood). - -This tutorial will first fit a model using two linear light profiles. Because their `intensity` values are solved for -implicitly, this means they are not a dimension of the non-linear parameter space fitted by `Nautilus`, therefore -reducing the complexity of parameter space and making the fit faster and more accurate. - -This tutorial will then show how many linear light profiles can be combined into a `Basis`, which comes from the term -'basis function'. By combining many linear light profiles models can be composed which are able to fit complex galaxy -structures (e.g. asymmetries, twists) with just N=6-8 non-linear parameters. - -__Contents__ - -- **Initial Setup:** we'll use the same strong lensing data as the previous tutorial, 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. -- **Linear Light Profiles:** We use a variant of a light profile discussed called a "linear light profile", which is accessed. -- **Run Time:** Profiling the expected run time of the model-fit. -- **Result:** Overview of the results of the model-fit. -- **Intensities:** The intensities of linear light profiles are not a part of the model parameterization and therefore. -- **Visualization:** Linear light profiles and objects containing them (e.g. -- **Basis:** We can use many linear light profiles to build a `Basis`. -- **Model Fit:** Perform the model-fit using the search and analysis. -- **Source MGE:** We now compose a second `Basis` of 15 Gaussians to represent the source galaxy. -- **Multi Gaussian Expansion Benefits:** Fitting a galaxy's light with a superposition of Gaussians is called a Multi-Gaussian Expansion. -- **Disadvantage of Basis Functions:** For many science cases, the MGE can also be a less intuitive model to interpret than a Sersic. -- **Positive Only Solver:** Ensuring positive-only solutions for linear light profile intensities. -- **Other Basis Functions:** In addition to the Gaussians used in this example, there is another basis function implemented in. -- **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 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`. -""" -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. -""" -if al.util.dataset.should_simulate(str(dataset_path)): - import subprocess - import sys - - subprocess.run( - [sys.executable, "scripts/simulator/lens_sersic.py"], - check=True, - ) - -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__ - -we'll create and use a smaller 2.6" `Mask2D` again. -""" -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) - -""" -When plotted, the lens light`s is clearly visible in the centre of the image. -""" -aplt.subplot_imaging_dataset(dataset=dataset) - -""" -__Linear Light Profiles__ - -We use a variant of a light profile discussed called a "linear light profile", which is accessed via the -command `al.lp_linear`. - -A "linear light profile" is a variant of a standard light profile where the `intensity` parameter is solved for -via linear algebra every time the model is fitted to the data. This uses a process called an "inversion" and it -always computes the `intensity` values that give the best fit to the data (e.g. maximize the likelihood) -given the light profile's other parameters. - -Each light profile's `intensity` parameter is therefore not a free parameter in the model-fit, reducing the -dimensionality of non-linear parameter space by the number of light profiles (in this example by 2 dimensions). - -This also removes the degeneracies that occur between the `intensity` and other light profile parameters -(e.g. `effective_radius`, `sersic_index`), which are difficult degeneracies for the non-linear search to map out -accurately. This produces more reliable lens model results and the fit converges in fewer iterations, speeding up the -overall analysis. - -This is a rare example where we are able to reduce the complexity of parameter space without making the model itself -any simpler. There is really no downside to using linear light profiles, so I would recommend you adopt them as -standard for your own model-fits from here on! -""" -bulge = af.Model(al.lp_linear.Sersic) -mass = af.Model(al.mp.Isothermal) - -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 = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field) - -""" -The `info` attribute shows the model, including the linear light profiles. - -Note how the `intensity` is no longer listed and does not have a prior associated with it. -""" -print(model.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. -""" -af.ModelPlotter(model).figure() - -""" -We now create this search and run it. - -Note that the number of live points has been reduced to 100, whereas previous tutorials typically used values of -150 - 250. - -This is possible because the linear light profiles make the parameter space much simpler, meaning we can obtain a -reliable model with fewer live points. This means the overall run-time of the search will be faster. -""" -search = af.Nautilus( - path_prefix=Path("howtolens") / "chapter_2", - name="tutorial_5_linear_light_profile", - unique_tag=dataset_name, - n_live=100, - 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__ - -For standard light profiles, the log likelihood evaluation time is of order ~0.01 seconds for this dataset. - -For linear light profiles, the log likelihood evaluation increases to around ~0.05 seconds per likelihood evaluation. -This is still fast, but it does mean that the fit may take around five times longer to run. - -However, because two free parameters have been removed from the model (the `intensity` of the lens bulge and -source bulge), the total number of likelihood evaluations will reduce. Furthermore, the simpler parameter space -likely means that the fit will take less than 10000 per free parameter to converge. This is aided further -by the reduction in `n_live` to 100. - -Fits using standard light profiles and linear light profiles therefore take roughly the same time to run. However, -the simpler parameter space of linear light profiles means that the model-fit is more reliable, less susceptible to -converging to an incorrect solution and scales better if even more light profiles are included in the model. - -Run the non-linear search. -""" -print( - "The non-linear search has begun running - checkout the output/howtolens/chapter_2/tutorial_5_linear_light_profile" - " folder for live output of the results, images and model." - " This Jupyter notebook cell with progress once search has completed - this could take some time!" -) - -result_linear_light_profile = search.fit(model=model, analysis=analysis) - -""" -__Result__ - -The `info` attribute shows the resulting model, which does not display the `intensity` values for each light profile. -""" -print(result_linear_light_profile.info) - -""" -__Intensities__ - -The intensities of linear light profiles are not a part of the model parameterization and therefore are not displayed -in the `model.results` file. - -To extract the `intensity` values of a specific component in the model, we use the `max_log_likelihood_tracer`, -which has already performed the inversion and therefore the galaxy light profiles have their solved for -`intensity`'s associated with them. -""" -tracer = result_linear_light_profile.max_log_likelihood_tracer - -print(tracer.galaxies[0].bulge.intensity) -print(tracer.galaxies[1].bulge.intensity) - -""" -Above, we access these values using the list index entry of each galaxy in the tracer. However, we may not be certain -of the order of the galaxies in the tracer, and therefore which galaxy index corresponds to the lens and source. - -We can therefore use the model composition API to access these values. -""" -print(tracer.galaxies[0].bulge.intensity) -print(tracer.galaxies[-1].bulge.intensity) - -""" -The `Tracer` contained in the `max_log_likelihood_fit` also has the solved for `intensity` values: -""" -fit = result_linear_light_profile.max_log_likelihood_fit - -tracer = fit.tracer - -print(tracer.galaxies[0].bulge.intensity) -print(tracer.galaxies[-1].bulge.intensity) - -""" -__Visualization__ - -Linear light profiles and objects containing them (e.g. galaxies, a tracer) cannot be plotted because they do not -have an `intensity` value. - -Therefore, the object created above which replaces all linear light profiles with ordinary light profiles must be -used for visualization: -""" -tracer = fit.model_obj_linear_light_profiles_to_light_profiles -aplt.plot_array(array=tracer.image_2d_from(grid=dataset.grid), title="Image") - - -""" -__Basis__ - -We can use many linear light profiles to build a `Basis`. - -For example, below, we make a `Basis` out of 30 elliptical Gaussian linear light profiles which: - - - All share the same centre and elliptical components. - - The `sigma` size of the Gaussians increases in log10 increments. -""" -total_gaussians = 30 - -# The sigma values of the Gaussians will be fixed to values spanning a tenth of the pixel scale to the mask radius, 3.0". - -mask_radius = 3.0 -log10_sigma_list = np.linspace( - np.log10(dataset.pixel_scales[0] / 10.0), np.log10(mask_radius), total_gaussians -) - -# A list of linear light profile `Gaussians` will be input here, which will then be used to fit the data. - -bulge_gaussian_list = [] - -# Iterate over every Gaussian and create it, with it centered at (0.0", 0.0") and assuming spherical symmetry. - -for i in range(total_gaussians): - gaussian = al.lp_linear.Gaussian( - centre=(0.0, 0.0), - ell_comps=(0.0, 0.0), - sigma=10 ** log10_sigma_list[i], - ) - - bulge_gaussian_list.append(gaussian) - -# The Basis object groups many light profiles together into a single model component and is used to fit the data. - -bulge = al.lp_basis.Basis(profile_list=bulge_gaussian_list) - -""" -Once we have a `Basis`, we can treat it like any other light profile in order to create a `Galaxy` and `Tracer` and -use it to fit data. - -We use the lens mass and source galaxy light profiles inferred above to fit this model with the basis functions. -""" -lens = al.Galaxy( - redshift=0.5, - bulge=bulge, - mass=result_linear_light_profile.instance.galaxies.lens.mass, -) - -source = result_linear_light_profile.instance.galaxies.source - -tracer = al.Tracer(galaxies=[lens, source]) - -fit = al.FitImaging(dataset=dataset, tracer=tracer) - -""" -By plotting the fit, we see that the `Basis` does a reasonable job at capturing the appearance of the lens galaxy. - -There are imperfections, but this is because we did not fit the model via a non-linear search in order to determine -the optimal values of the Gaussians in the basis. In particular, the Gaussians above were all spherical, when the -lens galaxy is elliptical. - -We rectify this below, where we use a non-linear search to determine the optimal values of the Gaussians! -""" -aplt.subplot_fit_imaging(fit=fit) - -""" -__Model Fit__ - -To fit a model using `Basis` functions, the API is very similar to that shown throughout this chapter, using both -the `af.Model()` and `af.Collection()` objects. - -In this example we fit a `Basis` model for the lens galaxy bulge where: - - - The bulge is a superposition of 30 linear `Gaussian` profiles [4 parameters]. - - The centres and elliptical components of each family of Gaussians are all linked together. - - The `sigma` size of the Gaussians increases in log10 increments. - -The number of free parameters and therefore the dimensionality of the MGe is just N=4. -""" -total_gaussians = 30 - -# The sigma values of the Gaussians will be fixed to values spanning a tenth of the pixel scale to the mask radius, 3.0". -mask_radius = 3.0 -log10_sigma_list = np.linspace( - np.log10(dataset.pixel_scales[0] / 10.0), np.log10(mask_radius), total_gaussians -) - -# By defining the centre here, it creates two free parameters that are assigned below to all Gaussians. - -centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) -centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) - -bulge_gaussian_list = [] - -# A list of Gaussian model components whose parameters are customized belows. - -gaussian_list = af.Collection( - af.Model(al.lp_linear.Gaussian) for _ in range(total_gaussians) -) - -# Iterate over every Gaussian and customize its parameters. - -for i, gaussian in enumerate(gaussian_list): - gaussian.centre.centre_0 = centre_0 # All Gaussians have same y centre. - gaussian.centre.centre_1 = centre_1 # All Gaussians have same x centre. - gaussian.ell_comps = gaussian_list[ - 0 - ].ell_comps # All Gaussians have same elliptical components. - gaussian.sigma = ( - 10 ** log10_sigma_list[i] - ) # All Gaussian sigmas are fixed to values above. - -bulge_gaussian_list += gaussian_list - -# The Basis object groups many light profiles together into a single model component. - -bulge = af.Model( - al.lp_basis.Basis, - profile_list=bulge_gaussian_list, -) - -""" -__Source MGE__ - -We now compose a second `Basis` of 15 Gaussians to represent the source galaxy. - -This is parameterized the same as the lens galaxy `bulge` (e.g. all Gaussians share the same `centre` and `ell_comps`) -but is treated as a completely independent set of parameters. - -However, the sigma values of the Gaussians span a smaller range of values, as the source galaxy is smaller than the -lens galaxy. -""" -total_gaussians = 15 - -# The sigma values of the Gaussians will be fixed to values spanning 0.0001" to 1.0". - -log10_sigma_list = np.linspace(-4, np.log10(1.0), total_gaussians) - -bulge_gaussian_list = [] - -# By defining a new the centre here, it creates two free parameters that are assigned below to all Gaussians. These -# new centre priors must be defined again in order for the source MGE not to use the same centre as the lens light -# MGE - -centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) -centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) - -gaussian_list = af.Collection( - af.Model(al.lp_linear.Gaussian) for _ in range(total_gaussians) -) - -for i, gaussian in enumerate(gaussian_list): - gaussian.centre.centre_0 = centre_0 - gaussian.centre.centre_1 = centre_1 - gaussian.ell_comps = gaussian_list[0].ell_comps - gaussian.sigma = 10 ** log10_sigma_list[i] - -bulge_gaussian_list += gaussian_list - -source_bulge = af.Model( - al.lp_basis.Basis, - profile_list=bulge_gaussian_list, -) - -""" -We now compose the overall model which uses both sets of Gaussians to represent separately the lens and source. - -The overall dimensionality of non-linear parameter space is just N=13, which is fairly remarkable if you -think about just how complex the structures are that a `Basis` of Gaussians can capture! -""" -lens = af.Model(al.Galaxy, redshift=0.5, bulge=bulge, mass=af.Model(al.mp.Isothermal)) -source = af.Model(al.Galaxy, redshift=1.0, bulge=source_bulge) - -model = af.Collection(galaxies=af.Collection(lens=lens, source=source)) - -""" -The `info` attribute shows the model, which is a lot longer than we have seen previously, given that is -composed of 45 Gaussians in total (30 for the lens, 15 for the source)! -""" -print(model.info) - -""" -The `info` for this model is enormous — forty-five Gaussians, each with its own block of parameters — but the -model itself is small. Each `bulge · Basis` holds a single `Gaussian` repeated thirty times on the lens and -fifteen times on the source, and every member of a basis shares one `centre` and one `ell_comps`, has its own -fixed `sigma`, and has its `intensity` solved by the inversion. - -That is the whole MGE trick: forty-five Gaussians, thirteen dimensions — the N=13 quoted above. -""" -af.ModelPlotter(model).figure() - -""" -We now fit the model. -""" -search = af.Nautilus( - path_prefix=Path("howtolens") / "chapter_2", - name="tutorial_5_basis", - unique_tag=dataset_name, - n_live=100, - 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_5_basis" - " folder for live output of the results, images and model." - " This Jupyter notebook cell with progress once search has completed - this could take some time!" -) - -result_basis = search.fit(model=model, analysis=analysis) - -""" -__Result__ - -The result `info` attribute shows the result, which is again longer than usual given the large number of Gaussians -used in the fit. -""" -print(result_basis.info) - -""" -Visualizing the fit shows that we successfully fit the data to the noise level. - -Note that the result objects `max_log_likelihood_tracer` and `max_log_likelihood_fit` automatically convert -all linear light profiles to ordinary light profiles, including every single one of the 20 Gaussians fitted -above. - -This means we can use them directly to perform the visualization below. -""" -print(result_basis.max_log_likelihood_instance) - -aplt.subplot_tracer(tracer=tracer, grid=dataset.grid) - -aplt.subplot_fit_imaging(fit=result_basis.max_log_likelihood_fit) - -""" -__Multi Gaussian Expansion Benefits__ - -Fitting a galaxy's light with a superposition of Gaussians is called a Multi-Gaussian Expansion (MGE). It is a -is a powerful tool for modeling the light of galaxies, and offers a compelling method to fit complex light profiles -with a small number of parameters - -Symmetric light profiles (e.g. elliptical Sersics) may leave significant residuals, because they fail to capture -irregular and asymmetric morphological of galaxies (e.g. isophotal twists, an ellipticity which varies radially). -An MGE fully captures these features and can therefore much better represent the emission of complex lens galaxies. - -As seen above, the MGE model can be composed in a way that has fewer non-linear parameters than an elliptical Sersic. -In this example, 30 Gaussians were used to represent the `bulge` of the lens, which in total correspond to just N=4 -non-linear parameters (a `bulge` and `disk` comprising two linear Sersics has N=10 parameters). The source dimensionality -was also just N=4. - -The MGE model parameterization is also composed such that neither the `intensity` parameters or any of the -parameters controlling the size of the Gaussians (their `sigma` values) are non-linear parameters sampled by Nautilus. -This removes the most significant degeneracies in parameter space, making the model much more reliable and efficient -to fit. - -Therefore, not only does an MGE fit more complex galaxy morphologies, it does so using fewer non-linear parameters -in a much simpler non-linear parameter space which has far less significant parameter degeneracies! - -We strongly recommend that you adopt an MGE in your own lens modeling pipelines from here on. The script -`autolens_workspace/*/imaging/features/multi_gaussian_expansion/modeling.py` gives examples on fitting even more complex -MGE models, where for example the Gaussians have different axis-ratios and position angles. - -__Disadvantage of Basis Functions__ - -For many science cases, the MGE can also be a less intuitive model to interpret than a Sersic profile. For example, -it is straight forward to understand how the effective radius of a Sersic profile relates to a galaxy's size, -or the serisc index relates to its concentration. The results of an MGE are less intuitive, and require more -thought to interpret physically. - -__Positive Only Solver__ - -Many codes which use linear algebra typically rely on a linear algabra solver which allows for positive and negative -values of the solution (e.g. `np.linalg.solve`), because they are computationally fast. - -This is problematic, as it means that negative surface brightnesses values can be computed to represent a galaxy's -light, which is clearly unphysical. For an MGE, this produces a positive-negative "ringing", where the -Gaussians alternate between large positive and negative values. This is clearly undesirable and unphysical. - -**PyAutoLens** (and therefore all examples above) uses a positive only linear algebra solver which has been -extensively optimized to ensure it is as fast as positive-negative solvers. This ensures that all light profile -intensities are positive and therefore physical. - -__Other Basis Functions__ - -In addition to the Gaussians used in this example, there is another basis function implemented in PyAutoLens -that is commonly used to represent the light of galaxies, called a `Shapelet`. - -Shapelets are basis functions with analytic properties that are appropriate for capturing the exponential / disk-like -features of a galaxy. They do so over a wide range of scales, and can often represent features in source galaxies -that a single Sersic function or MGE cannot. - -An example using shapelets is given at `autolens_workspace/scripts/imaging/features/advanced/shapelets/modeling.py`. - -Feel free to experiment with using shapelets as the source galaxy by yourself. However they incur higher computational -overheads than the MGE and include a free parameter which governs the size of the basis functions and therefore source, -slowing down convergence of the non-linear search. We have found that MGEs perform better than shapelets in most -lens modeling problems. - -If you have a desire to fit sources with even more complex morphologies we recommend you look at how to reconstruct -sources using pixelizations in the `modeling/features` section or chapter 3 of **HowToLens**. - -__Wrap Up__ - -In this tutorial we described how linearizing light profiles allows us to fit more complex light profiles to -galaxies using fewer non-linear parameters, keeping the fit performed by the non-linear search fast, accurate -and robust. - -Perhaps the biggest downside to basis functions is that they are only as good as the features they can capture -in the data. For example, a basis of Gaussians still assumes that they have a well defined centre, but there are -galaxies which may have multiple components with multiple centres (e.g. many star forming knots) which such a -basis cannot capture. - -In chapter 3 of **HowToLens** we introduce non-parametric pixelizations, which reconstruct the data in way -that does not make assumptions like a centre and can thus reconstruct even more complex, asymmetric and irregular -galaxy morphologies. -""" 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 index 534c098..56fcba1 100644 --- a/scripts/chapter_2_lens_modeling/tutorial_6_masking_and_positions.py +++ b/scripts/chapter_2_lens_modeling/tutorial_6_masking_and_positions.py @@ -8,7 +8,7 @@ __Contents__ -- **Initial Setup:** we'll use the same strong lensing data as tutorials 1 & 2, where. +- **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. @@ -32,7 +32,7 @@ """ __Initial Setup__ -we'll use the same strong lensing data as tutorials 1 & 2, where: +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`. 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 index e326420..a5e799c 100755 --- a/scripts/chapter_2_lens_modeling/tutorial_8_need_for_speed.py +++ b/scripts/chapter_2_lens_modeling/tutorial_8_need_for_speed.py @@ -42,7 +42,7 @@ 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 5 remove every `intensity` parameter from the non-linear parameter space, reducing its +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 @@ -69,12 +69,12 @@ 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 5 and the pixelizations of chapter 3, solving + - 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 5, this trade often still favours the more advanced technique, because the simpler parameter +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__ diff --git a/scripts/chapter_2_lens_modeling/tutorial_9_search_chaining.py b/scripts/chapter_2_lens_modeling/tutorial_9_search_chaining.py index 77d878a..27ebf2d 100644 --- a/scripts/chapter_2_lens_modeling/tutorial_9_search_chaining.py +++ b/scripts/chapter_2_lens_modeling/tutorial_9_search_chaining.py @@ -12,7 +12,7 @@ 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 4 of this chapter. We learnt there were three approaches one could take fitting a lens +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. @@ -28,7 +28,7 @@ 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 4. We saw that this +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. @@ -69,7 +69,7 @@ """ __Initial Setup__ -we'll use the same strong lensing data as tutorials 3, 4 and 5 of this chapter, where: +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. diff --git a/scripts/chapter_optional/tutorial_searches.py b/scripts/chapter_optional/tutorial_searches.py index 4601bc6..dcab4c4 100644 --- a/scripts/chapter_optional/tutorial_searches.py +++ b/scripts/chapter_optional/tutorial_searches.py @@ -2,19 +2,16 @@ Tutorial: Alternative Searches ============================== -Up to now, we've always used the non-linear search Nautilus and not considered the input parameters that control its -sampling. In this tutorial, we'll consider how we can change these setting to balance finding the global maxima -solution with fast run time. +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. -We will also discuss other types of non-linear searches, such as MCMC and optimizers, which we can use to perform lens -modeling. So far, we have no found any of these alternatives to give anywhere near as robust and efficient results as -Nautilus, and we recommend users use Nautilus unless they are particularly interested in investigating different -model-fitting techniques. +The dataset, model and Analysis object retain the same roles. Changing the search changes how parameter space is +explored and which information is returned. Inspect the fits and assess the exploration before trusting the results. __Contents__ - **Nested Sampling:** Lets first perform the model-fit using Nautilus, but look at different parameters that control how. -- **Optimizers:** There are a class of non-linear searches called optimizers, which seek to optimize the log likelihood. +- **Optimisation:** Improve parameter values from multiple starting points using Prodigy. - **MCMC:** For users familiar with Markov Chain Monte Carlo (MCMC) non-linear samplers, PyAutoFit supports the. """ @@ -197,35 +194,55 @@ print("Fast settings: ", result_fast.samples.total_samples) """ -__Optimizers__ - -Nested sampling algorithms like Nautilus provides the errors on all of the model parameters, by fully mapping out all -of the high likelihood regions of parameter space. This provides knowledge on the complete *range* of models that do -and do not provide high likelihood fits to the data, but takes many extra iterations to perform. If we require precise -error estimates (perhaps this is our final lens model fit before we publish the results in a paper), these extra -iterations are acceptable. - -However, we often don't care about the errors. For example, in chapter 2's search chaining tutorial, the only -result we used from the fit performed in the first search was the maximum log likelihood model, omitting the errors -entirely! Its seems wasteful to use a nested sampling algorithm like Nautilus to map out the entirity of parameter -space when we don't use this information! - -There are a class of non-linear searches called `optimizers`, which seek to optimize just one thing, the log -likelihood. They want to find the model that maximizes the log likelihood, with no regard for the errors, thus not -wasting time mapping out in intricate detail every facet of parameter space. - -PyAutoFit supports a number of optimizers, which can be used as an alternative to nested sampling when only the -maximum likelihood model is needed. These include `LBFGS` and `BFGS` (from scipy), which descend the likelihood from a -single starting point. A single-start optimizer generally needs a good starting point to work well, and in our -experience the parameter spaces fitted by lens models are often too complex for it without careful setup of initialization -priors. - -PyAutoFit also supports multi-start gradient optimizers (`MultiStartProdigy`, `MultiStartAdam`, `MultiStartADABelief` -and `MultiStartLion`), which use JAX to launch many optimizations from starting points spread across parameter space -in parallel and return the best one. This makes them far more robust to complex parameter spaces, and -`MultiStartProdigy` is the optimizer used by many of the `start_here.py` examples in the `autolens_workspace`. Like any optimizer, they -return only the best-fit model with no errors. The `autolens_workspace` script `scripts/guides/modeling/searches.py` describes -every search, including these optimizers, in detail. +__Optimisation__ + +An optimiser repeatedly tries to improve a model. Starting from one set of parameter values, it works out which +changes are likely to produce a better fit, updates the parameters and evaluates the new model. Repeating this process +moves it towards a peak: a region where nearby parameter values no longer improve the fit. + +You can think of this as making increasingly informed guesses, aiming for higher-likelihood solutions. Prodigy also +takes the priors into account, so it balances how well the model fits with the probability assigned to its parameter +values. This is maximum a posteriori (MAP) optimisation. + +A peak need not be the best solution overall. Prodigy therefore repeats this process from several starting points, +giving it more opportunities to find a good model. + +Prodigy uses gradients to guide its updates: these describe how changing each parameter affects the posterior +probability. PyAutoLens calculates these gradients automatically using a numerical computing library called **JAX**. +You do not need to use JAX directly to run this example. + +We use 48 starting points, with up to 300 optimisation steps for each. The search can stop earlier when its stopping +criteria are met. Increasing either setting allows more exploration but also requires more computation. The batch size +of 4 limits how many starts are processed together; it does not reduce the total number of starts. +""" +search = af.MultiStartProdigy( + path_prefix=Path("howtolens") / "chapter_optional", + name="tutorial_searches_prodigy", + unique_tag=dataset_name, + n_starts=48, + n_steps=300, + batch_size=4, +) + +result_prodigy = search.fit(model=model, analysis=analysis) + +print(result_prodigy.info) + +aplt.subplot_fit_imaging(fit=result_prodigy.max_log_likelihood_fit) + +""" +Prodigy finds a best-fitting set of parameter values, but it does not tell us how uncertain those values are. An +Einstein radius of 1.6 arcseconds, for example, does not tell us whether values of 1.5 or 1.7 arcseconds would also be +consistent with the data. + +Look for whether the model reproduces the location, shape and brightness of the lensed emission. In the normalised +residuals, inspect whether coherent structures remain that the model has failed to explain. + +A plausible parameter value does not establish that the fit is good. Likewise, small residuals do not prove that the +search has found the best possible solution or measured parameter uncertainty. + +**🤖 Ask AI:** My optimised lens model leaves an arc-shaped pattern in the normalised residuals. What should I +investigate before trusting its inferred parameters? __MCMC__ diff --git a/workspace_index.json b/workspace_index.json index ef81a78..4cb9cdb 100644 --- a/workspace_index.json +++ b/workspace_index.json @@ -209,8 +209,7 @@ "contents": [ "Overview", "Parameter Space", - "Non-Linear Search", - "Search Types", + "Automated Exploration", "Deeper Background", "PyAutoFit", "Initial Setup", @@ -219,117 +218,131 @@ "Model", "Priors", "Analysis", - "Searches", - "Maximum Likelihood Estimation (MLE)", - "Markov Chain Monte Carlo (MCMC)", - "Nested Sampling", - "What is The Best Search To Use?", + "Non-linear Search", + "Search Settings", + "Model Fit", + "Result", + "Inspecting the Fit", + "Other Searches", "Wrap Up" ], "cross_refs": [ - "/imaging/likelihood_function.ipynb" + "autolens_workspace/scripts/imaging/likelihood_function.py" ], "notebook": "notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb", "path": "scripts/chapter_2_lens_modeling/tutorial_1_non_linear_search.py", - "summary": "The starting point for most scientific analysis conducted by an Astronomer is that they have observations of a strong lens using a telescope like the Hubble Space Telescope, and seek to learn about the lens galaxy, source galaxy and the Universe from these observations. With **PyAutoLens**, we seek to learn about the lens's mass and ray-tracing, asking questions like how big is the lens galaxy and what does the unlensed source galaxy look like?", + "summary": "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.", "title": "Tutorial 1: Non-linear Search" }, { "contents": [ - "PyAutoFit", - "Initial Setup", - "Dataset Auto-Simulation", + "Dataset", "Mask", "Model", + "Analysis", "Search", "Search Settings", - "Iterations Per Update", - "Analysis", + "Output Updates", "VRAM Use", "Run Times", - "Model-Fit", + "Notebooks and Scripts", + "Model Fit", "Result Info", "Output Folder", "Unique Identifier", + "Resuming and Loading", "Output Folder Contents", - "Result", - "Other Practicalities", + "Parameter Uncertainties", + "Plot Labels", + "Configuration", + "Further Results", "Wrap Up" ], "cross_refs": [ - "scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py" + "scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py", + "scripts/guides/results/start_here.py" ], "notebook": "notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb", "path": "scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py", - "summary": "In the last tutorial, we introduced foundational statistical concepts essential for model-fitting, such as parameter spaces, likelihoods, priors, and non-linear searches. Understanding these statistical concepts is crucial for performing model fits effectively.", + "summary": "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\u2019s light and the lensed source.", "title": "Tutorial 2: Practicalities" }, { "contents": [ - "Initial Setup", - "Dataset Auto-Simulation", - "Mask", - "Model", - "Search + Analysis", - "Run Time", - "Result", - "Global and Local Maxima", - "Wrap Up" - ], - "cross_refs": [], - "notebook": "notebooks/chapter_2_lens_modeling/tutorial_3_realism_and_complexity.ipynb", - "path": "scripts/chapter_2_lens_modeling/tutorial_3_realism_and_complexity.py", - "summary": "In the previous two tutorials, we fitted a fairly crude and unrealistic model: the lens's mass was spherical, as was the source's light. Given most lens galaxies are literally called 'elliptical galaxies' we should probably model their mass as elliptical! Furthermore, we have completely omitted the lens galaxy's light, which in real observations outshines the source's light and therefore must be included in the lens model.", - "title": "Tutorial 3: Realism and Complexity" - }, - { - "contents": [ - "Initial Setup", - "Dataset Auto-Simulation", - "Mask", + "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", - "Run Time", - "Result", - "Discussion", - "Approach 2: Reducing Complexity", - "Approach 3: Look Harder", + "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" ], - "cross_refs": [ - "chapter_optional/tutorial_searches.ipynb" - ], - "notebook": "notebooks/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.ipynb", - "path": "scripts/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.py", - "summary": "In the previous tutorial we intentionally made our non-linear search infer a local maxima solution and therefore return a physically incorrect lens model. In this tutorial, we will pretend that we have modeled our lens and inferred a local maxima. We introduce three approaches one can take that changes how we fit the model, all of which have the aim of ensuring we infer the global maxima:", - "title": "Tutorial 4: Dealing With Failure" + "cross_refs": [], + "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.", + "title": "Tutorial 3: Why Modeling Is Hard" }, { "contents": [ - "Initial Setup", - "Dataset Auto-Simulation", - "Mask", + "Overview", + "Dataset and Mask", "Linear Light Profiles", - "Run Time", + "Why This Helps", + "Model", + "Search and Run Time", "Result", "Intensities", - "Visualization", + "Visualisation", "Basis", - "Model Fit", + "A First Gaussian Basis", + "Evaluating the Basis", + "Inspecting the Basis Fit", + "Lens MGE", "Source MGE", - "Multi Gaussian Expansion Benefits", - "Disadvantage of Basis Functions", - "Positive Only Solver", + "Combined Model", + "Inspecting the Model", + "Model Fit", + "Multi-Gaussian Expansion Benefits", + "Benefits Have Costs", + "Positive Intensities", "Other Basis Functions", "Wrap Up" ], "cross_refs": [ - "/imaging/features/multi_gaussian_expansion/modeling.py", - "autolens_workspace/scripts/imaging/features/advanced/shapelets/modeling.py" + "multi_gaussian_expansion/modeling.py", + "scripts/imaging/features/advanced/shapelets/modeling.py" ], - "notebook": "notebooks/chapter_2_lens_modeling/tutorial_5_linear_profiles.ipynb", - "path": "scripts/chapter_2_lens_modeling/tutorial_5_linear_profiles.py", - "summary": "In the previous tutorial we learned how to balance model complexity with our non-linear search in order to infer accurate lens model solutions and avoid failure. We saw how in order to fit a model accurately one may have to parameterize and fit a simpler model with fewer non-linear parameters, at the expense of fitting the data less accurately.", - "title": "Tutorial 5: Linear Profiles" + "notebook": "notebooks/chapter_2_lens_modeling/tutorial_4_linear_profiles.ipynb", + "path": "scripts/chapter_2_lens_modeling/tutorial_4_linear_profiles.py", + "summary": "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.", + "title": "Tutorial 4: Linear Profiles" }, { "contents": [ @@ -669,16 +682,13 @@ { "contents": [ "Nested Sampling", - "Optimizers", + "Optimisation", "MCMC" ], - "cross_refs": [ - "scripts/guides/modeling/searches.py", - "start_here.py" - ], + "cross_refs": [], "notebook": "notebooks/chapter_optional/tutorial_searches.ipynb", "path": "scripts/chapter_optional/tutorial_searches.py", - "summary": "Up to now, we've always used the non-linear search Nautilus and not considered the input parameters that control its sampling. In this tutorial, we'll consider how we can change these setting to balance finding the global maxima solution with fast run time.", + "summary": "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.", "title": "Tutorial: Alternative Searches" }, {