From a9588b3102d889dfe8e2c545eddfd0237dc00aea Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sun, 1 Nov 2026 18:55:54 +0000 Subject: [PATCH] fix: recover tutorial demonstrations and notebook prose --- llms-full.txt | 2 +- .../tutorial_1_non_linear_search.ipynb | 127 +++----- .../tutorial_2_practicalities.ipynb | 133 +++----- .../tutorial_3_why_modeling_is_hard.ipynb | 159 ++++------ .../tutorial_4_linear_profiles.ipynb | 127 +++----- .../tutorial_6_masking_and_positions.ipynb | 10 +- .../tutorial_7_results.ipynb | 6 +- .../tutorial_8_need_for_speed.ipynb | 31 +- .../tutorial_11_brightness_adaption.ipynb | 271 ++++++++-------- .../tutorial_12_adaptive_regularization.ipynb | 176 +++++------ .../tutorial_1_pixelizations.ipynb | 243 ++++++++++----- .../tutorial_2_bayesian_regularization.ipynb | 266 +++++++++++----- .../tutorial_3_borders.ipynb | 192 ++++++++---- .../tutorial_4_lens_modeling.ipynb | 293 ++++++++++++------ .../tutorial_8_adaptive_pixelization.ipynb | 186 +++++++---- .../tutorial_1_non_linear_search.py | 12 - .../tutorial_2_practicalities.py | 24 -- .../tutorial_3_why_modeling_is_hard.py | 39 +-- .../tutorial_4_linear_profiles.py | 20 -- .../tutorial_6_masking_and_positions.py | 10 +- .../tutorial_7_results.py | 6 +- .../tutorial_8_need_for_speed.py | 31 +- .../tutorial_11_brightness_adaption.py | 267 +++++++++------- .../tutorial_12_adaptive_regularization.py | 159 +++++----- .../tutorial_1_pixelizations.py | 206 ++++++++---- .../tutorial_2_bayesian_regularization.py | 237 ++++++++++---- .../tutorial_3_borders.py | 175 +++++++---- .../tutorial_4_lens_modeling.py | 268 +++++++++++----- .../tutorial_8_adaptive_pixelization.py | 175 +++++++---- workspace_index.json | 1 + 30 files changed, 2283 insertions(+), 1569 deletions(-) diff --git a/llms-full.txt b/llms-full.txt index 679fbb6..4f34465 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -64,7 +64,7 @@ AUTO-GENERATED by PyAutoHands — do not edit by hand; regenerate with generate. - [Tutorial 4: Lens Modeling](scripts/chapter_3_pixelizations/tutorial_4_lens_modeling.py): (no summary in script docstring) - Contents: Lens modelling with a pixelized source, Giving the inversion an incorrect mass model, Comparing with the correct mass model, Seeing how the mass model changes the mappings, Why evidence does not remove the search difficulty, Starting with a simpler source model, Running and inspecting the initial search, Requiring corresponding images to trace together, Replacing the analytic source with a pixelization, Running the pixelized-source search, Establishing the foreground light model, Using that result in the pixelized-source fit - [Tutorial 8: Adaptive Pixelization](scripts/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.py): In this tutorial we will introduce a new `Pixelization` object, which uses an `Overlay` image-mesh and a `Delaunay` mesh. - - Contents: Initial Setup, Advantages and Disadvantages, Image Mesh, Regularization, Wrap Up + - Contents: Initial Setup, Advantages and Disadvantages, Image Mesh, Regularization, Source Compactness, Wrap Up ## chapter_4_scaling_up_lensing 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 1b030e1..992e5fe 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 @@ -38,51 +38,9 @@ "- **Result:** Inspect the inferred parameters and fitted image.\n", "- **Inspecting the Fit:** Compare the predicted image with the data and residuals.\n", "- **Other Searches:** Find the optional optimisation and MCMC examples.\n", - "- **Wrap Up:** Review the lesson and its connection to the next topic." - ] - }, - { - "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", + "- **Wrap Up:** Review the lesson and its connection to the next topic.\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", "This tutorial introduces the main pieces of an automated model fit:\n", @@ -93,13 +51,8 @@ "- 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": [ + "inferred parameters and uncertainties.\n", + "\n", "__Parameter Space__\n", "\n", "Imagine varying just two properties of a lens model: the lens\u2019s Einstein radius and the source\u2019s effective radius. Each\n", @@ -118,13 +71,8 @@ "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": [ + "images, and how could this appear on a likelihood surface?\n", + "\n", "__Automated Exploration__\n", "\n", "A non-linear search automates the exploration you performed manually in Chapter 1.\n", @@ -134,13 +82,8 @@ "\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": [ + "matter. We will see examples of this later in the chapter.\n", + "\n", "__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", @@ -155,6 +98,44 @@ "- [A Zero-Math Introduction to MCMC Methods](https://towardsdatascience.com/a-zero-math-introduction-to-markov-chain-monte-carlo-methods-dcba889e0c50)" ] }, + { + "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": {}, @@ -561,13 +542,8 @@ "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": "markdown", - "metadata": {}, - "source": [ + "through HowToLens. Here, we will focus on configuring a fit and interpreting what it returns.\n", + "\n", "__Search Settings__\n", "\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", @@ -698,13 +674,8 @@ "running a more thorough Nautilus search.\n", "\n", "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": [ + "building appropriate models and assessing how well they explain the data.\n", + "\n", "__Wrap Up__\n", "\n", "You have now fitted a lens model automatically, using the same image prediction and likelihood calculation that you\n", diff --git a/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb index b644ca4..3850c16 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb @@ -41,7 +41,21 @@ "- **Plot Labels:** Interpret abbreviated and latent-parameter labels.\n", "- **Configuration:** Find the settings controlling searches, plotting and output.\n", "- **Further Results:** Find the workspace guides for more detailed result analysis.\n", - "- **Wrap Up:** Review the lesson and its connection to the next topic." + "- **Wrap Up:** Review the lesson and its connection to the next topic.\n", + "\n", + "\n", + "__Dataset__\n", + "\n", + "Our new simulated image contains a bright foreground lens galaxy as well as the lensed source.\n", + "\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", + "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", + "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." ] }, { @@ -82,24 +96,6 @@ "_setup_colab.setup(\"howtolens\")" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Dataset__\n", - "\n", - "Our new simulated image contains a bright foreground lens galaxy as well as the lensed source.\n", - "\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", - "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", - "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": {}, @@ -189,13 +185,8 @@ "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": "markdown", - "metadata": {}, - "source": [ + "separate `fields` component.\n", + "\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", @@ -340,13 +331,8 @@ "whereas `n_batch` controls how evaluations are grouped for computation.\n", "\n", "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": "markdown", - "metadata": {}, - "source": [ + "when to reduce the batch size.\n", + "\n", "__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", @@ -362,13 +348,8 @@ "`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", - "metadata": {}, - "source": [ + "afterwards.\n", + "\n", "__VRAM Use__\n", "\n", "If you run the fit on a GPU, its calculations must fit within the GPU\u2019s memory, usually called **VRAM**. Insufficient\n", @@ -427,13 +408,8 @@ "just the likelihood calculation.\n", "\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": [ + "tutorial explains how to investigate performance in more detail.\n", + "\n", "__Notebooks and Scripts__\n", "\n", "In a notebook, the cell containing `search.fit` remains busy until the search finishes. You can inspect files already\n", @@ -452,13 +428,8 @@ "convenient for unattended runs and computing clusters.\n", "\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": [ + "recognises that setup in **Unique Identifier**.\n", + "\n", "__Model Fit__\n", "\n", "We now pass the model and analysis to Nautilus and begin the fit.\n", @@ -554,13 +525,8 @@ " |-- 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": [ + "```\n", + "\n", "__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", @@ -577,13 +543,8 @@ "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": [ + "do not necessarily change the identifier.\n", + "\n", "__Resuming and Loading__\n", "\n", "If a Nautilus run is interrupted, rerun the same setup with its output and checkpoint files intact. The search can\n", @@ -597,13 +558,8 @@ "saved samples and other files used to reconstruct results.\n", "\n", "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": "markdown", - "metadata": {}, - "source": [ + "completion to save space; that does not prevent the completed result from being loaded.\n", + "\n", "__Output Folder Contents__\n", "\n", "Begin with `image/fit.png`. Inspect whether the predicted image reproduces the lens and source light, and whether\n", @@ -619,13 +575,8 @@ "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": [ + "files under `config/visualize/` control plotting. Keep the tutorial defaults while learning the workflow.\n", + "\n", "__Parameter Uncertainties__\n", "\n", "A corner plot shows the parameter uncertainties inferred by the search and the relationships between them.\n", @@ -703,13 +654,8 @@ "later without rerunning the fit.\n", "\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": [ + "using the parameter distributions.\n", + "\n", "__Further Results__\n", "\n", "You now know how to inspect a fit, read its parameter estimates and find its saved output. That is enough to continue\n", @@ -722,13 +668,8 @@ "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": [ + "using and manipulating the results of those analyses.\n", + "\n", "__Wrap Up__\n", "\n", "We have fitted a model containing lens light, lens mass, external shear and source light, while retaining the same\n", diff --git a/notebooks/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.ipynb index a259117..39c75d7 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.ipynb @@ -54,7 +54,27 @@ "- **Benefits and Weaknesses:** Compare the practical trade-offs of the three approaches.\n", "- **Run Times:** Understand the costs that determine how long a fit takes.\n", "- **Model Mismatch:** Distinguish insufficient exploration from an inadequate model.\n", - "- **Wrap Up:** Review the lesson and its connection to the next topic." + "- **Wrap Up:** Review the lesson and its connection to the next topic.\n", + "\n", + "\n", + "__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.\n", + "\n", + "__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." ] }, { @@ -95,35 +115,6 @@ "_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": {}, @@ -353,13 +344,8 @@ "\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": [ + "this distinction under *Model Mismatch*.\n", + "\n", "__Three Ways Forward__\n", "\n", "We will try three approaches to making the fit more reliable:\n", @@ -375,13 +361,8 @@ "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": [ + "priors, simplify the model or search more thoroughly?\n", + "\n", "__Prior Tuning__\n", "\n", "Our default priors cover a broad range of possible systems. For a particular image, we may have information that\n", @@ -398,13 +379,8 @@ "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": [ + "restrictive choices can exclude good solutions and make the reported uncertainties misleadingly small.\n", + "\n", "__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", @@ -761,13 +737,8 @@ "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": [ + "We therefore need other ways to make complex models easier to fit.\n", + "\n", "__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", @@ -780,13 +751,8 @@ "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": [ + "lenses whose light and mass have different centres or shapes.\n", + "\n", "__Linking Parameters__\n", "\n", "We create fresh light and mass models with their default priors. This removes the prior tuning from the previous\n", @@ -929,13 +895,8 @@ "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": [ + "its restrictions are relaxed.\n", + "\n", "__Search More Thoroughly__\n", "\n", "Our first two approaches changed the priors or reduced the freedom of the model. We now return to the original model\n", @@ -948,13 +909,8 @@ "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": [ + "cost is computation: exploring more thoroughly generally takes longer.\n", + "\n", "__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", @@ -1107,13 +1063,8 @@ "\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": [ + "appropriate, more thorough exploration may be the best next step.\n", + "\n", "__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", @@ -1129,9 +1080,34 @@ "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." + "examples of the trade-offs on your computer, rather than universal speed comparisons.\n", + "\n", + "The following values come from each search's saved timer, so loading a completed result reports its recorded duration\n", + "rather than the time spent loading it. A resumed search includes the time since its original start, including any\n", + "interruption. Runs without recorded timing information are labelled accordingly." ] }, + { + "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", + " elapsed_seconds = fit_result.samples.time\n", + " if elapsed_seconds is None:\n", + " print(f\"{label}: elapsed time not recorded\")\n", + " else:\n", + " print(f\"{label}: recorded elapsed time = {float(elapsed_seconds):.1f} seconds\")" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -1153,13 +1129,8 @@ "\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": [ + "its own.\n", + "\n", "__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", diff --git a/notebooks/chapter_2_lens_modeling/tutorial_4_linear_profiles.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_4_linear_profiles.ipynb index 7b2464f..336b0c9 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_4_linear_profiles.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_4_linear_profiles.ipynb @@ -45,7 +45,29 @@ "- **Benefits Have Costs:** Consider computational cost, interpretation and geometric limits.\n", "- **Positive Intensities:** Require light profiles to contribute non-negative brightness.\n", "- **Other Basis Functions:** Find other ways to expand a galaxy\u2019s light distribution.\n", - "- **Wrap Up:** Review the lesson and its connection to the next topic." + "- **Wrap Up:** Review the lesson and its connection to the next topic.\n", + "\n", + "\n", + "__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.\n", + "\n", + "__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." ] }, { @@ -86,37 +108,6 @@ "_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": {}, @@ -181,13 +172,8 @@ "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": [ + "fitted quantities, not fixed numbers chosen in advance.\n", + "\n", "__Why This Helps__\n", "\n", "With ordinary light profiles, Nautilus must explore intensity alongside parameters such as effective radius and S\u00e9rsic\n", @@ -205,13 +191,8 @@ "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": [ + "rather than adding a new search dimension for every profile.\n", + "\n", "__Model__\n", "\n", "We replace the lens and source light profiles with their equivalents from `al.lp_linear`.\n", @@ -447,13 +428,8 @@ "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": [ + "rather than identifying each Gaussian as a distinct part of the galaxy.\n", + "\n", "__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", @@ -583,13 +559,8 @@ "\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": [ + "requires the additional Gaussian groups discussed earlier.\n", + "\n", "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", @@ -854,13 +825,8 @@ "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": [ + "restricted description, especially when the source contains separate bright knots or irregular features.\n", + "\n", "__Benefits Have Costs__\n", "\n", "Evaluating many Gaussian profiles and solving their intensities adds work to each likelihood calculation. A simpler\n", @@ -874,13 +840,8 @@ "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": [ + "freedom needed to describe the features relevant to the analysis.\n", + "\n", "__Positive Intensities__\n", "\n", "Without a positivity constraint, a linear solver can combine positive and negative Gaussian intensities to reproduce an\n", @@ -894,13 +855,8 @@ "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": [ + "inspect the residuals.\n", + "\n", "__Other Basis Functions__\n", "\n", "Gaussians are not the only functions we can combine to describe galaxy light. PyAutoLens also supports **shapelets**,\n", @@ -914,13 +870,8 @@ "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": [ + "can only reproduce structures allowed by its arrangement and parameters.\n", + "\n", "__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", 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 0cda41e..7174d8b 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 @@ -339,8 +339,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "To check the image-positions are accurate we can plot them using the `lines=`/`positions=` overlays object (they are the magenta dots on \n", - "the image)." + "To check that the image positions are accurate, we plot them as marked points on the image using `positions=`." ] }, { @@ -348,7 +347,7 @@ "metadata": {}, "source": [ "\n", - "aplt.subplot_imaging_dataset(dataset=dataset)" + "aplt.subplot_imaging_dataset(dataset=dataset, positions=positions)" ], "outputs": [], "execution_count": null @@ -395,9 +394,8 @@ "source": [ "__Run Time__\n", "\n", - "The likelihood evaluation time of the position threshold is below 0.001 seconds, meaning that the initial parameter \n", - "space sampling is extremely efficient leading to a significant speed up of the model-fit (not accounted for in\n", - "the run-time estimate below).\n", + "Checking a few positions is cheaper than evaluating the full image likelihood. Rejecting unsuitable mass models early\n", + "can therefore speed up the initial exploration of parameter space; the benefit depends on the model and dataset.\n", "\n", "__Search__\n", "\n", diff --git a/notebooks/chapter_2_lens_modeling/tutorial_7_results.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_7_results.ipynb index 52e0a4d..07e4f46 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_7_results.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_7_results.ipynb @@ -12,7 +12,7 @@ "\n", "__Contents__\n", "\n", - "- **Initial Setup:** Lets use the model-fit performed in tutorial 1 to get a `Result` object.\n", + "- **Initial Setup:** Run a separate fit to the Tutorial 1 dataset to obtain a `Result` object.\n", "- **Dataset Auto-Simulation:** Simulate the dataset via its simulator script if it is not on your hard-disk.\n", "- **Tracer & Fit:** In the previous tutorials, we saw that this result contains the maximum log likelihood fit, which.\n", "- **Samples:** The result contains a lot more information about the model-fit.\n", @@ -82,7 +82,9 @@ "source": [ "__Initial Setup__\n", "\n", - "Lets use the model-fit performed in tutorial 1 to get a `Result` object." + "We use the same dataset as Tutorial 1 and run a separate fit to obtain a `Result` object. Here, the source uses an\n", + "ordinary light profile, so its intensity is explored by the non-linear search. This setup does not reload the\n", + "Tutorial 1 result." ] }, { 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 c8f684a..f1afdf5 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 @@ -15,17 +15,17 @@ "resolution datasets this is somewhat unavoidable. However, it is worth us discussing what drives the long run-times of\n", "the lens modeling process and how we might speed it up.\n", "\n", - "We have carefully tracked the log likelihood evaluation times and therefore expected overall run-time of every\n", - "fit performed in this chapter. Lets quickly remind ourselves of the main factors that drive the run-time, and\n", - "how we might reduce it.\n", + "The preceding tutorials discussed the costs contributing to a fit's elapsed time. Lets remind ourselves of the main\n", + "factors that drive the run-time and how we might reduce it.\n", "\n", - "The overall run-time of a model-fit is, to a good approximation, a simple product of two numbers:\n", + "For sequential likelihood evaluations, the search's evaluation cost is approximately the product of two numbers:\n", "\n", " - The number of log likelihood evaluations the non-linear search performs before it converges.\n", "\n", " - The time each individual log likelihood evaluation takes.\n", "\n", - "Everything we discuss below reduces one (or both) of these numbers.\n", + "Batching evaluates several models together, so this product does not directly predict GPU elapsed time. Compilation\n", + "and saving output also add time. The approaches below address these costs or reduce the exploration needed.\n", "\n", "__Contents__\n", "\n", @@ -125,20 +125,17 @@ "\n", "__Run Time Estimation__\n", "\n", - "Because run-time is the product of the two numbers above, we can estimate it before committing to a fit:\n", + "Tutorial 2 explains how likelihood cost, the number of evaluations, compilation and output contribute to elapsed time.\n", + "It does not measure a likelihood evaluation time or predict a fixed duration for the fit.\n", "\n", - " - Time the log likelihood evaluation: perform a fit of the model to the data once (e.g. via a `FitImaging`) and\n", - " time it, remembering to discard the first call, which includes JIT compilation.\n", + "An estimate needs measurements from the actual likelihood calculation, using the intended model, dataset, hardware\n", + "and batch size. A standalone `FitImaging` calculation need not follow the same compiled and batched path as the search.\n", + "JAX measurements must wait for device calculations to finish, with compilation considered separately from repeated\n", + "evaluations.\n", "\n", - " - Estimate the number of evaluations: for `Nautilus` a reasonable rule of thumb is of order 10000 evaluations per\n", - " free parameter, with simpler parameter spaces (e.g. linear light profiles, chained searches with tight priors)\n", - " converging in fewer.\n", - "\n", - "Multiplying the two gives a ballpark overall run-time. In tutorial 2 we used exactly this arithmetic: a log\n", - "likelihood evaluation time below 0.01 seconds on CPU (below 0.001 seconds on GPU) and 50000-100000 evaluations gave\n", - "expected run-times of roughly 30 minutes on CPU and 10 minutes on GPU. If your own estimate comes out at days or\n", - "weeks, that is the moment to simplify the model, tighten the search settings, reach for search chaining or find\n", - "a GPU -- before starting the fit, not after.\n", + "The number of evaluations needed also depends on the parameter space and search settings. Compare the saved durations\n", + "of representative completed fits, as in Tutorial 3, before extrapolating to a larger analysis. If those runs suggest\n", + "that a fit will take days or weeks, consider simplifying the model, search chaining or different hardware.\n", "\n", "On a GPU, tutorial 2 also showed the other pre-flight check: `analysis.print_vram_use` estimates whether the fit\n", "will fit within the GPU's memory for your chosen batch size.\n", diff --git a/notebooks/chapter_3_pixelizations/tutorial_11_brightness_adaption.ipynb b/notebooks/chapter_3_pixelizations/tutorial_11_brightness_adaption.ipynb index e832b37..fe74db0 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_11_brightness_adaption.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_11_brightness_adaption.ipynb @@ -7,19 +7,21 @@ "Tutorial 11: Brightness Adaption\n", "================================\n", "\n", - "In the previous tutorial we motivated our need to adapt the pixelization to the source's morphology, such that source\n", - "pixels congregates in the source's brightest regions regardless of where the source is located in the source-plane.\n", + "In the previous tutorial we motivated our need to adapt the pixelization to the source's morphology, such that\n", + "source pixels congregates in the source's brightest regions regardless of where the source is located in the\n", + "source-plane.\n", "\n", - "This poses a challenge; how do we adapt our pixelization to the reconstructed source's light, before we've\n", - "actually reconstructed the source and therefore know what to adapt it too?\n", + "This poses a challenge; how do we adapt our pixelization to the reconstructed source's light, before we've actually\n", + "reconstructed the source and therefore know what to adapt it too?\n", "\n", - "To do this, we define 'adapt_images' of the lensed source galaxy, which are model images of the source computed using\n", - "a previous lens model that has been fit to the image (e.g. in the earlier search of a pipeline). This image tells\n", - "us where in the image our source is located, thus informing us of where we need to adapt our source pixelization!\n", + "To do this, we define 'adapt_images' of the lensed source galaxy, which are model images of the source computed\n", + "using a previous lens model that has been fit to the image (e.g. in the earlier search of a pipeline). This image\n", + "tells us where in the image our source is located, thus informing us of where we need to adapt our source\n", + "pixelization!\n", "\n", - "This tutorial goes into the details of how this works. We'll use the same compact source galaxy as the previous\n", - "tutorial and begin by fitting it with a magnification based pixelization. This will produce a model image which can\n", - "then be used an adapt image.\n", + "Tutorial 8's compactness experiment motivated adapting to the source's morphology. Here we use the standalone\n", + "`simple__no_lens_light` dataset, rather than one of those progressively compact simulated sources. We begin with a\n", + "magnification-based pixelization and use its model image as an adapt image.\n", "\n", "__Contents__\n", "\n", @@ -27,7 +29,8 @@ "- **Adapt Image:** We can use this fit to set up our adapt image.\n", "- **Adaption:** Now lets take a look at brightness based adaption in action.\n", "- **Hilbert:** So how does the `adapt_image` adapt the pixelization to the source's brightness?\n", - "- **Weight Map:** We now have a sense of how our `Hilbert` image-mesh is computed, so lets look at how we create the.\n", + "- **Weight Map:** We now have a sense of how our `Hilbert` image-mesh is computed, so lets look at how we create\n", + " the.\n", "- **Wrap Up:** Summary of the script and next steps." ] }, @@ -90,7 +93,8 @@ "\n", "from pathlib import Path\n", "import autolens as al\n", - "import autolens.plot as aplt" + "import autolens.plot as aplt\n", + "import autoarray.plot as aaplt" ], "outputs": [], "execution_count": null @@ -124,8 +128,8 @@ "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 does not already exist on your system, it will be created by running the corresponding simulator\n", + "script. This ensures that all example scripts can be run without manually simulating data first." ] }, { @@ -165,7 +169,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Next, we're going to fit the image using the RectangularBilinearAdaptDensity magnification based grid. \n", + "Next, we're going to fit the image using the RectangularBilinearAdaptDensity magnification based grid.\n", "\n", "The code below does all the usual steps required to do this." ] @@ -195,7 +199,8 @@ "\n", "tracer = al.Tracer(galaxies=[lens_galaxy, source_galaxy_magnification], fields=[field])\n", "\n", - "fit = al.FitImaging(dataset=dataset, tracer=tracer)" + "magnification_fit = al.FitImaging(dataset=dataset, tracer=tracer)\n", + "fit = magnification_fit" ], "outputs": [], "execution_count": null @@ -204,7 +209,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Lets have a quick look to make sure it has the same residuals we saw in the previous tutorial." + "Inspect the source reconstruction and residuals before using its model image to guide the next mesh." ] }, { @@ -226,10 +231,10 @@ "source": [ "__Adapt Image__\n", "\n", - "We can use this fit to set up our adapt image. \n", + "We can use this fit to set up our adapt image.\n", "\n", - "This adapt-image is not perfect, because there are residuals in the central regions of the reconstructed source. \n", - "However, it is good enough for us to adapt our pixelization to the lensed source." + "The adapt image is conditional on this first fit. Check its residuals: an inaccurate starting model can guide the\n", + "next mesh to the wrong parts of the image." ] }, { @@ -247,10 +252,11 @@ "source": [ "__Adaption__\n", "\n", - "Now lets take a look at brightness based adaption in action. \n", + "Now lets take a look at brightness based adaption in action.\n", "\n", - "Below, we define a source-galaxy using the `Hilbert` image-mesh (we discuss below how this adapts to the source light) \n", - "and `RectangularBilinearAdaptDensity` mesh and use this to fit the lens-data. " + "Below, we define a source galaxy using the `Hilbert` image-mesh and a `Delaunay` mesh. We discuss below how Hilbert\n", + "adapts to the source light. Unlike the density-adaptive rectangular mesh, Delaunay uses the supplied Hilbert points\n", + "as its source-mesh vertices after ray tracing." ] }, { @@ -264,8 +270,8 @@ ")\n", "\n", "pixelization = al.Pixelization(\n", - " mesh=al.mesh.RectangularBilinearAdaptDensity(shape=(24, 24)),\n", - " regularization=al.reg.Constant(coefficient=0.5),\n", + " mesh=al.mesh.Delaunay(pixels=image_plane_mesh_grid.shape[0]),\n", + " regularization=al.reg.Constant(coefficient=1.0),\n", ")\n", "\n", "galaxy_adapt = al.Galaxy(\n", @@ -303,8 +309,8 @@ "source": [ "We now fit using this adapt image and mesh using the normal API.\n", "\n", - "Note however that the `FitImaging` object receives the `adapt_images` as an input and they are used when\n", - "setting up the image-mesh and mesh." + "Note however that the `FitImaging` object receives the `adapt_images` as an input and they are used when setting up\n", + "the image-mesh and mesh." ] }, { @@ -313,8 +319,17 @@ "source": [ "tracer = al.Tracer(galaxies=[lens_galaxy, galaxy_adapt], fields=[field])\n", "\n", - "fit = al.FitImaging(dataset=dataset, tracer=tracer, adapt_images=adapt_images)\n", + "brightness_fit = al.FitImaging(dataset=dataset, tracer=tracer, adapt_images=adapt_images)\n", + "fit = brightness_fit\n", "\n", + "aplt.plot_array(\n", + " array=dataset.data, positions=image_plane_mesh_grid, title=\"Hilbert Image-Mesh Points\",\n", + ")\n", + "mapper = fit.inversion.cls_list_from(al.Mapper)[0]\n", + "aaplt.plot_mapper(\n", + " mapper=mapper, solution_vector=fit.inversion.reconstruction,\n", + " mesh_grid=mapper.source_plane_mesh_grid, title=\"Brightness-Adaptive Source Mesh\",\n", + ")\n", "aplt.subplot_fit_imaging(fit=fit)\n", "aplt.subplot_fit_imaging_of_planes(fit=fit)\n" ], @@ -325,19 +340,19 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Our reconstruction of the image no longer has residuals! \n", - "\n", - "By congregating more source pixels in the brightest regions of the source reconstruction we get a better fit. \n", - "Furthermore, we can check that this provides an increase in Bayesian log evidence, noting that the log evidence of the \n", - "compact source when using a `Overlay` image-mesh was 4216:" + "Compare the source mesh and residuals with the initial density-adaptive reconstruction. We can now compare measured\n", + "evidence values instead of carrying a number over from another simulation. This first comparison changes both mesh\n", + "family and regularization coefficient; it does not isolate brightness weighting alone." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(\"Evidence using magnification based pixelization. \", 4216)\n", - "print(\"Evidence using brightness based pixelization. \", fit.log_evidence)" + "print(\"Evidence using magnification based pixelization:\", magnification_fit.log_evidence)\n", + "print(\"Evidence using brightness based pixelization:\", brightness_fit.log_evidence)\n", + "print(\"Difference in log evidence:\", brightness_fit.log_evidence - magnification_fit.log_evidence)\n", + "print(\"Source mesh values:\", mapper.pixels)" ], "outputs": [], "execution_count": null @@ -346,21 +361,12 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "It increases by over 1000, which for a Bayesian evidence is pretty large! \n", - "\n", - "This pixelization is a huge success, we should have been adapting to the source's brightness all along! \n", - "\n", - "In doing so, we will *always* reconstruct the detailed structure of the source's brightest regions with a \n", - "sufficiently high resolution!\n", - "\n", - "We are now able to adapt the pixelization's mesh to the morphology of the lensed source galaxy. To my knowledge, this\n", - "is the *best* approach one can take in lens modeling. Its more tricky to implement and introduces additional non-linear \n", - "parameters. But the pay-off is worth it, as we fit our data better and use fewer source pixels to reconstruct\n", - "the source.\n", + "Brightness adaptation gives us another way to distribute source resolution. It does not guarantee an improved fit\n", + "or higher evidence for every dataset. Inspect both the calculated comparison and the residuals.\n", "\n", "__Hilbert__\n", "\n", - "So how does the `adapt_image` adapt the pixelization to the source's brightness? It uses a standard algorithm for \n", + "So how does the `adapt_image` adapt the pixelization to the source's brightness? It uses a standard algorithm for\n", "partitioning data in statistics called a Hilbert curve:\n", "\n", "https://en.wikipedia.org/wiki/Hilbert_curve\n", @@ -368,43 +374,46 @@ "In simple terms, this algorithm works as follows:\n", "\n", " 1) Input an image of weight values to the Hilbert algorithm which determines the \"hilbert space filling curve\" \n", - " (e.g. this `weight_map` is determined from the adapt-image). The Hilbert space-filling curve fills more space there\n", + " (e.g. this `weight_map` is determined from the adapt-image). The Hilbert space-filling curve fills more space\n", + " there\n", " the weight values are highest, and less space where they are lowest. It therefore closely traces the brightest\n", " regions of the image.\n", " \n", - " 2) Probabilistically draw N $(y,x)$ points from this Hilbert curve, where the majority of points will therefore be \n", + " 2) Probabilistically draw N $(y,x)$ points from this Hilbert curve, where the majority of points will therefore be\n", " drawn from high weighted regions. \n", " \n", " 3) These N $(y,x)$ are our source-pixel centres, albeit we have drawn them in the image-plane so we first map them\n", - " to the source-plane, via the mass model, in order to set up the source pixel centres of the mesh. Because points are\n", - " drawn from high weighted regions (e.g. the brightest image pixels in the lensed source adapt image), we will trace \n", + " to the source-plane, via the mass model, in order to set up the source pixel centres of the mesh. Because points\n", + " are\n", + " drawn from high weighted regions (e.g. the brightest image pixels in the lensed source adapt image), we will trace\n", " more source-pixels to the brightest regions of where the source is actually reconstructed.\n", " \n", "__Weight Map__\n", "\n", - "We now have a sense of how our `Hilbert` image-mesh is computed, so lets look at how we create the weighted data the \n", - "Hilbert space filling curve uses.\n", + "We now have a sense of how our `Hilbert` image-mesh is computed, so lets look at how we create the weighted data\n", + "the Hilbert space filling curve uses.\n", "\n", - "This image, called the `weight_map` is generated using the `weight_floor` and `weight_power` parameters of \n", - "the `Hilbert` object. The weight map is generated following 4 steps:\n", + "This image, called the `weight_map` is generated using the `weight_floor` and `weight_power` parameters of the\n", + "`Hilbert` object. The weight map is generated following 4 steps:\n", "\n", " 1) Take an absolute value of all pixels in the adapt image, because negative values break the Hilbert algorithm.\n", " \n", - " 2) Divide all values of this image by its maximum value, such that the adapt-image now only contains values between \n", + " 2) Divide all values of this image by its maximum value, such that the adapt-image now only contains values\n", + " between\n", " 0.0 and 1.0 (where the values of 1.0 are the maximum values of the adapt-image).\n", " \n", - " 3) Add the weight_floor to all values (a weight_floor of 0.0 therefore does not change the weight map).\n", - " \n", - " 4) Raise all values to the power of weight_power (a weight_power of 1.0 therefore does not change the\n", - " weight map, whereas a value of 0.0 means all values 1.0 and therefore weighted equally).\n", + " 3) Raise all values to the power of `weight_power`. A power of 1.0 leaves them unchanged; a power of 0.0\n", + " makes all weights equal to 1.0.\n", + "\n", + " 4) Set any value below `weight_floor` to that floor. This is a minimum weight, not a value added to every pixel.\n", " \n", - "The idea is that using high values of `weight_power` will make the highest weight values much higher than the lowest\n", - "values, such that the Hilbert curve will trace these values much more than the lower values. The weight_floor gives\n", - "the algorithm some balance, by introducing a floor to the weight map that prevents the lowest values from being\n", - "weighted to near zero.\n", + "The idea is that using high values of `weight_power` will make the highest weight values much higher than the\n", + "lowest values, such that the Hilbert curve will trace these values much more than the lower values. The\n", + "weight_floor gives the algorithm some balance, by introducing a floor to the weight map that prevents the lowest\n", + "values from being weighted to near zero.\n", "\n", - "Lets look at this in action. we'll inspect 3 weight_maps, using a weight_power of 0.0, 5.0 and 10.0 and\n", - "setting the `weight_floor` to 0.0 for now." + "Lets look at this in action. we'll inspect 3 weight_maps, using a weight_power of 0.0, 5.0 and 10.0 and setting the\n", + "`weight_floor` to 0.0 for now." ] }, { @@ -416,7 +425,7 @@ "weight_map = image_mesh.weight_map_from(adapt_data=adapt_image)\n", "weight_map = al.Array2D(values=weight_map, mask=mask)\n", "\n", - "aplt.plot_array(array=weight_map, title=\"\")\n", + "aplt.plot_array(array=weight_map, title=\"Hilbert Weight Power 0: Weight Map\")\n", "\n", "\n", "image_mesh = al.image_mesh.Hilbert(pixels=500, weight_floor=0.0, weight_power=5.0)\n", @@ -424,7 +433,7 @@ "weight_map = image_mesh.weight_map_from(adapt_data=adapt_image)\n", "weight_map = al.Array2D(values=weight_map, mask=mask)\n", "\n", - "aplt.plot_array(array=weight_map, title=\"\")\n", + "aplt.plot_array(array=weight_map, title=\"Hilbert Weight Power 5: Weight Map\")\n", "\n", "\n", "image_mesh = al.image_mesh.Hilbert(pixels=500, weight_floor=0.0, weight_power=10.0)\n", @@ -432,7 +441,7 @@ "weight_map = image_mesh.weight_map_from(adapt_data=adapt_image)\n", "weight_map = al.Array2D(values=weight_map, mask=mask)\n", "\n", - "aplt.plot_array(array=weight_map, title=\"\")" + "aplt.plot_array(array=weight_map, title=\"Hilbert Weight Power 10: Weight Map\")" ], "outputs": [], "execution_count": null @@ -441,46 +450,60 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "When we increase the weight-power the brightest regions of the adapt-image become weighted higher relative to the \n", - "fainter regions. \n", + "When we increase the weight-power the brightest regions of the adapt-image become weighted higher relative to the\n", + "fainter regions.\n", "\n", "This means that the Hilbert algorithm will adapt more pixels to the brightest regions of the source.\n", "\n", - "Lets use the method to perform a fit with a weight power of 10, showing that we now get a significantly higher\n", - "log_evidence." + "Let us compare powers 0, 5 and 10 using the same number of Hilbert points, Delaunay mesh and regularization\n", + "coefficient. We reuse the power-10 reconstruction above. Each new power changes the mesh points, so we must\n", + "reconstruct the source again before comparing evidence." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "image_mesh = al.image_mesh.Hilbert(pixels=500, weight_floor=0.0, weight_power=10.0)\n", - "\n", - "image_plane_mesh_grid = image_mesh.image_plane_mesh_grid_from(\n", - " mask=dataset.mask, adapt_data=adapt_image\n", - ")\n", - "\n", - "\n", - "pixelization = al.Pixelization(\n", - " mesh=al.mesh.RectangularBilinearAdaptDensity(shape=(24, 24)),\n", - " regularization=al.reg.Constant(coefficient=1.0),\n", - ")\n", - "\n", - "source_weight_power_10 = al.Galaxy(\n", - " redshift=1.0,\n", - " pixelization=pixelization,\n", - ")\n", - "\n", - "tracer = al.Tracer(galaxies=[lens_galaxy, source_weight_power_10], fields=[field])\n", - "\n", - "adapt_images = al.AdaptImages(\n", - " galaxy_image_dict={source_weight_power_10: adapt_image},\n", - " galaxy_image_plane_mesh_grid_dict={source_weight_power_10: image_plane_mesh_grid},\n", - ")\n", - "\n", - "fit = al.FitImaging(dataset=dataset, tracer=tracer, adapt_images=adapt_images)\n", + "fits_by_power = {10.0: brightness_fit}\n", + "\n", + "for weight_power in (0.0, 5.0, 10.0):\n", + " if weight_power not in fits_by_power:\n", + " image_mesh = al.image_mesh.Hilbert(\n", + " pixels=500, weight_floor=0.0, weight_power=weight_power,\n", + " )\n", + " image_plane_mesh_grid = image_mesh.image_plane_mesh_grid_from(\n", + " mask=dataset.mask, adapt_data=adapt_image,\n", + " )\n", + " source = al.Galaxy(\n", + " redshift=1.0,\n", + " pixelization=al.Pixelization(\n", + " mesh=al.mesh.Delaunay(pixels=image_plane_mesh_grid.shape[0]),\n", + " regularization=al.reg.Constant(coefficient=1.0),\n", + " ),\n", + " )\n", + " adapt_images = al.AdaptImages(\n", + " galaxy_image_dict={source: adapt_image},\n", + " galaxy_image_plane_mesh_grid_dict={source: image_plane_mesh_grid},\n", + " )\n", + " tracer = al.Tracer(galaxies=[lens_galaxy, source], fields=[field])\n", + " fits_by_power[weight_power] = al.FitImaging(\n", + " dataset=dataset, tracer=tracer, adapt_images=adapt_images,\n", + " )\n", + "\n", + " current_fit = fits_by_power[weight_power]\n", + " current_mapper = current_fit.inversion.cls_list_from(al.Mapper)[0]\n", + " aaplt.plot_mapper(\n", + " mapper=current_mapper, solution_vector=current_fit.inversion.reconstruction,\n", + " mesh_grid=current_mapper.source_plane_mesh_grid,\n", + " title=f\"Hilbert Weight Power {weight_power:g}\",\n", + " )\n", + " aplt.subplot_fit_imaging(fit=current_fit)\n", + " print(f\"Weight power {weight_power:g}: log evidence={float(current_fit.log_evidence):.3f}\")\n", "\n", - "aplt.plot_array(array=fit.model_images_of_planes_list[1], title=\"Plane 1 Image\")" + "print(\n", + " \"Log evidence difference, power 10 minus power 0:\",\n", + " fits_by_power[10.0].log_evidence - fits_by_power[0.0].log_evidence,\n", + ")" ], "outputs": [], "execution_count": null @@ -489,14 +512,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "So, what does the `weight_floor` do? Increasing the weight-power congregates pixels around the source. However, there \n", - "is a risk that by congregating too many source pixels in its brightest regions we lose resolution further out, where \n", - "the source is bright, but not its brightest!\n", + "So, what does the `weight_floor` do? Increasing the weight-power congregates pixels around the source. However,\n", + "there is a risk that by congregating too many source pixels in its brightest regions we lose resolution further\n", + "out, where the source is bright, but not its brightest!\n", "\n", - "The `weight_floor` allows these regions to maintain a higher weighting whilst the `weight_power` increases. This means \n", - "that the mesh can fully adapt to the source's brightest and faintest regions simultaneously.\n", + "The `weight_floor` allows these regions to maintain a higher weighting whilst the `weight_power` increases. This\n", + "means that the mesh can retain more coverage away from the brightest regions. Check whether this improves the fit.\n", "\n", - "Lets look at once example:" + "Let us compare a floor of 0.5 with the power-10, floor-zero fit, keeping the other settings fixed:" ] }, { @@ -511,18 +534,18 @@ "\n", "\n", "pixelization = al.Pixelization(\n", - " mesh=al.mesh.RectangularBilinearAdaptDensity(shape=(24, 24)),\n", + " mesh=al.mesh.Delaunay(pixels=image_plane_mesh_grid.shape[0]),\n", " regularization=al.reg.Constant(coefficient=1.0),\n", ")\n", "\n", "source_weight_floor = al.Galaxy(\n", - " redshift=1.0, pixelization=pixelization, adapt_galaxy_image=adapt_image\n", + " redshift=1.0, pixelization=pixelization\n", ")\n", "\n", "weight_map = image_mesh.weight_map_from(adapt_data=adapt_image)\n", "weight_map = al.Array2D(values=weight_map, mask=mask)\n", "\n", - "aplt.plot_array(array=weight_map, title=\"\")\n", + "aplt.plot_array(array=weight_map, title=\"Hilbert Weight Floor 0.5: Weight Map\")\n", "\n", "tracer = al.Tracer(galaxies=[lens_galaxy, source_weight_floor], fields=[field])\n", "\n", @@ -533,7 +556,16 @@ "\n", "fit = al.FitImaging(dataset=dataset, tracer=tracer, adapt_images=adapt_images)\n", "\n", - "aplt.plot_array(array=fit.model_images_of_planes_list[1], title=\"Plane 1 Image\")" + "floor_fit = fit\n", + "floor_mapper = fit.inversion.cls_list_from(al.Mapper)[0]\n", + "aaplt.plot_mapper(\n", + " mapper=floor_mapper, solution_vector=fit.inversion.reconstruction,\n", + " mesh_grid=floor_mapper.source_plane_mesh_grid, title=\"Hilbert Weight Floor 0.5\",\n", + ")\n", + "aplt.subplot_fit_imaging(fit=fit)\n", + "print(\"Evidence with weight floor 0.0:\", fits_by_power[10.0].log_evidence)\n", + "print(\"Evidence with weight floor 0.5:\", floor_fit.log_evidence)\n", + "print(\"Difference in log evidence:\", floor_fit.log_evidence - fits_by_power[10.0].log_evidence)" ], "outputs": [], "execution_count": null @@ -544,21 +576,16 @@ "source": [ "__Wrap Up__\n", "\n", - "To end, lets think about the Bayesian evidence, which we saw now goes to significantly higher values than for a\n", - "magnification-based grid. At this point, it might be worth reminding yourself how the Bayesian evidence works by\n", - "going back to tutorials 4 and 5 of this chapter.\n", - "\n", - "So, why do you think why adapting to the source's brightness increases the log evidence?\n", + "The measured evidence comparisons show how these choices affect this dataset. Revisit tutorial 2 for the\n", + "interpretation of evidence: image agreement and the source prior must be considered together.\n", "\n", - "It is because by adapting to the source's morphology we can now access solutions that fit the data really well \n", - "(e.g. to the Gaussian noise-limit) but use significantly fewer source-pixels than before. For instance, a typical \n", - "magnification based grid uses resolutions of 40 x 40, or 1600 pixels. In contrast, a morphology based pixelization \n", - "typically uses just 300-800 pixels (depending on the source itself). Clearly, the easiest way to make our source \n", - "solution simpler is to use fewer pixels overall!\n", + "Brightness weighting can concentrate mesh points where source light is expected. Excessive concentration can leave\n", + "faint regions poorly resolved, and a more detailed mesh does not establish that every reconstructed feature is\n", + "real. Inspect the mesh, source and residuals together before choosing settings.\n", "\n", - "This provides a second benefit. If the best solutions in our fit want to use the fewest source-pixels possible and \n", - "**PyAutoLens** can now access those solutions, this means that adapt-mode will run much faster than the magnification \n", - "based grid! Put simply, fewer source-pixels means lower computational overheads. YAY!\n", + "Here we held the coefficient fixed while comparing powers and floors. A full analysis would also explore\n", + "regularization, since its preferred strength depends on mesh geometry. Fewer source values can reduce the cost of\n", + "the inversion, but neither faster fits nor higher evidence are guaranteed by brightness adaptation alone.\n", "\n", "Tutorial 11 done, next up, adaptive regularization!" ] diff --git a/notebooks/chapter_3_pixelizations/tutorial_12_adaptive_regularization.ipynb b/notebooks/chapter_3_pixelizations/tutorial_12_adaptive_regularization.ipynb index 1f88f0d..c9bb1cb 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_12_adaptive_regularization.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_12_adaptive_regularization.ipynb @@ -11,14 +11,15 @@ "regularization, motivating a scheme which adapts to the reconstructed source's surface brightness.\n", "\n", "This raises the same question as before, how do we adapt our regularization scheme to the source before we've\n", - "reconstructed it? Just like in the last tutorial, we'll use a model image of a strongly lensed source from a previous\n", - "model that we've begun calling the `adapt-image`.\n", + "reconstructed it? Just like in the last tutorial, we'll use a model image of a strongly lensed source from a\n", + "previous model that we've begun calling the `adapt-image`.\n", "\n", "__Contents__\n", "\n", "- **Initial Setup:** we'll use the same strong lensing data as the previous tutorial, where.\n", "- **Convenience Function:** We are going to fit the image using a magnification based grid.\n", - "- **Adaptive Regularization:** Lets now look at adaptive regularization in action, by setting up a adapt-image and using the.\n", + "- **Adaptive Regularization:** Lets now look at adaptive regularization in action, by setting up a adapt-image and\n", + " using the.\n", "- **Wrap Up:** Summary of the script and next steps." ] }, @@ -71,7 +72,8 @@ "\n", "from pathlib import Path\n", "import autolens as al\n", - "import autolens.plot as aplt" + "import autolens.plot as aplt\n", + "import autoarray.plot as aaplt" ], "outputs": [], "execution_count": null @@ -82,7 +84,8 @@ "source": [ "__Initial Setup__\n", "\n", - "we'll use the same strong lensing data as the previous tutorial, where:\n", + "Tutorial 8's compactness experiment motivates the need for resolution and smoothing checks. As in tutorial 11, this\n", + "standalone example uses `simple__no_lens_light`, rather than the progressively compact simulations, where:\n", "\n", " - The lens galaxy's light is omitted.\n", " - The lens system uses an `Isothermal` galaxy mass profile and a separate `ExternalShear` field.\n", @@ -105,8 +108,8 @@ "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 does not already exist on your system, it will be created by running the corresponding simulator\n", + "script. This ensures that all example scripts can be run without manually simulating data first." ] }, { @@ -146,7 +149,7 @@ "source": [ "__Convenience Function__\n", "\n", - "We are going to fit the image using a magnification based grid. \n", + "We are going to fit the image using a magnification based grid.\n", "\n", "To perform the fits, we'll use a convenience function to fit the lens data we simulated above." ] @@ -195,7 +198,8 @@ "\n", "source_magnification = al.Galaxy(redshift=1.0, pixelization=pixelization)\n", "\n", - "fit = fit_via_source_galaxy_from(dataset=dataset, source_galaxy=source_magnification)\n", + "constant_fit = fit_via_source_galaxy_from(dataset=dataset, source_galaxy=source_magnification)\n", + "fit = constant_fit\n", "\n", "mapper = fit.inversion.cls_list_from(al.Mapper)[0]\n", "\n", @@ -210,19 +214,22 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The fit looks just like it did in the previous tutorials (residuals in the centre due to a lack of source pixels). \n", - "\n", - "Lets quickly remind ourselves that the effective regularization weight of each source pixel is our input coefficient \n", - "value of 3.3." + "Inspect the residuals before changing the prior. We can display the actual regularization weights on the source\n", + "mesh: Constant gives every source value the input coefficient of 3.3. These are weights, rather than source\n", + "brightnesses or an image-plane reconstruction." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "aplt.plot_array(\n", - " array=fit.inversion.mapped_reconstructed_operated_data, title=\"Inversion\"\n", - ")" + "constant_weights = mapper.regularization.regularization_weights_from(linear_obj=mapper)\n", + "aaplt.plot_mapper(\n", + " mapper=mapper, solution_vector=constant_weights,\n", + " mesh_grid=mapper.source_plane_mesh_grid, zoom_to_brightest=False,\n", + " vmin=0.0, vmax=4.0, title=\"Constant Regularization Weights\",\n", + ")\n", + "print(\"Constant weight range:\", float(min(constant_weights)), float(max(constant_weights)))" ], "outputs": [], "execution_count": null @@ -233,8 +240,8 @@ "source": [ "__Adaptive Regularization__\n", "\n", - "Lets now look at adaptive regularization in action, by setting up a adapt-image and using the `Adapt` \n", - "regularization scheme. \n", + "Lets now look at adaptive regularization in action, by setting up a adapt-image and using the `Adapt`\n", + "regularization scheme.\n", "\n", "This introduces additional parameters, that are explained below." ] @@ -255,7 +262,6 @@ "source_adapt_regularization = al.Galaxy(\n", " redshift=1.0,\n", " pixelization=pixelization,\n", - " adapt_galaxy_image=adapt_image,\n", ")\n", "\n", "adapt_images = al.AdaptImages(\n", @@ -268,10 +274,19 @@ " adapt_images=adapt_images,\n", ")\n", "\n", - "aplt.plot_array(\n", - " array=fit.inversion.mapped_reconstructed_operated_data,\n", - " title=\"Inversion Reconstruction\",\n", - ")" + "adaptive_fit = fit\n", + "mapper = fit.inversion.cls_list_from(al.Mapper)[0]\n", + "adaptive_weights = mapper.regularization.regularization_weights_from(linear_obj=mapper)\n", + "aaplt.plot_mapper(\n", + " mapper=mapper, solution_vector=adaptive_weights,\n", + " mesh_grid=mapper.source_plane_mesh_grid, zoom_to_brightest=False,\n", + " vmin=0.0, vmax=4.0, title=\"Adaptive Regularization Weights\",\n", + ")\n", + "aaplt.plot_mapper(\n", + " mapper=mapper, solution_vector=fit.inversion.reconstruction,\n", + " mesh_grid=mapper.source_plane_mesh_grid, title=\"Adaptively Regularized Source\",\n", + ")\n", + "print(\"Adaptive weight range:\", float(min(adaptive_weights)), float(max(adaptive_weights)))" ], "outputs": [], "execution_count": null @@ -280,39 +295,21 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "As expected, we now have a variable regularization scheme. \n", + "The weights now vary across the source mesh. Compare their locations with the reconstructed source, using the same\n", + "weight colour scale as the Constant example. These weights enter the regularization matrix; they are not\n", + "uncertainties on the reconstructed brightnesses.\n", "\n", - "The regularization of the source's brightest regions is much lower than that of its outer regions. As discussed \n", - "before, this is what we want. Lets quickly check that this does, indeed, increase the Bayesian log evidence:" + "Let us compare the evidence measured from these two fits:" ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(\"Evidence using constant regularization. \", 4216)\n", - "print(\"Evidence using adaptive regularization. \", fit.log_evidence)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Yes, it does! \n", + "print(\"Evidence using constant regularization:\", constant_fit.log_evidence)\n", + "print(\"Evidence using adaptive regularization:\", adaptive_fit.log_evidence)\n", + "print(\"Difference in log evidence:\", adaptive_fit.log_evidence - constant_fit.log_evidence)\n", "\n", - "Combining the adaptive mesh and regularization will only further benefit lens modeling!\n", - "\n", - "However, as shown below, we don't fit the source as well as the morphology based mesh did in the previous tutorial.\n", - "This is because although the adaptive regularization scheme improves the fit, the magnification based\n", - "mesh simply does not have sufficient resolution to resolve the source's cuspy central light." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ "aplt.subplot_fit_imaging(fit=fit)" ], "outputs": [], @@ -322,25 +319,31 @@ "cell_type": "markdown", "metadata": {}, "source": [ + "An evidence increase is something to measure, rather than assume. The mesh is unchanged here, so this comparison\n", + "examines the regularization choice. These hand-chosen settings are not optimized, and varying the smoothing cannot\n", + "supply resolution that the source mesh lacks. Inspect the source and residuals alongside the evidence.\n", + "\n", "__How does adaptive regularization work?__\n", "\n", - "For every source-pixel, we have a mapping between that pixel and a set of pixels in the adapt-image. Therefore, for \n", - "every source-pixel, if we sum the values of all adapt-image pixels that map to it we get an estimate of how much of \n", + "For every source-pixel, we have a mapping between that pixel and a set of pixels in the adapt-image. Therefore, for\n", + "every source-pixel, if we sum the values of all adapt-image pixels that map to it we get an estimate of how much of\n", "the lensed source's signal we expect will be reconstructed. We call this each pixel's `pixel signal`.\n", "\n", - "If a source-pixel has a higher pixel-signal, we anticipate that it`ll reconstruct more flux and we use this information \n", - "to regularize it less. Conversely, if the pixel-signal is close to zero, the source pixel will reconstruct near-zero \n", - "flux and regularization will smooth over these pixels by using a high regularization coefficient.\n", + "If a source-pixel has a higher pixel-signal, we anticipate that it`ll reconstruct more flux and we use this\n", + "information to regularize it less. Conversely, if the pixel-signal is close to zero, the source pixel will\n", + "reconstruct near-zero flux and regularization will smooth over these pixels by using a high regularization\n", + "coefficient.\n", "\n", "This works as follows:\n", "\n", " 1) For every source pixel, compute its pixel-signal, the summed flux of all corresponding image-pixels in the \n", " adapt-galaxy-image.\n", " \n", - " 2) Divide every pixel-signal by the number of image-pixels that map directly to that source-pixel. In doing so, all \n", + " 2) Divide every pixel-signal by the number of image-pixels that map directly to that source-pixel. In doing so,\n", + " all\n", " pixel-signals are 'relative'. This means that source-pixels which by chance map to more image-pixels than their \n", " neighbors will not have a higher pixel-signal, and visa versa. This ensures the specific pixelization\n", - " does impact the adaptive regularization pattern.\n", + " does not by itself determine the adaptive regularization pattern.\n", " \n", " 3) Divide the pixel-signals by the maximum pixel signal so that they range between 0.0 and 1.0.\n", " \n", @@ -352,22 +355,23 @@ " \n", " (inner_coefficient * pixel_signals + outer_coefficient * (1.0 - pixel_signals)) ** 2.0\n", " \n", - " This uses two regularization coefficient parameters, one which is applied to pixels with high pixel-signals and one to \n", + " This uses two regularization coefficient parameters, one which is applied to pixels with high pixel-signals and\n", + " one to\n", " pixels with low pixel-signals. Thus, pixels in the inner regions of the source may be given a lower level of \n", " regularization than pixels further away, as desired.\n", "\n", - "Thus, we now adapt our regularization scheme to the source's surface brightness. Where its brighter (and therefore \n", - "has a steeper flux gradient) we apply a lower level of regularization than further out. Furthermore, in the edges of \n", - "the source-plane where no source-flux is present we will assume a high regularization coefficient that smooths over \n", - "all of the source-pixels.\n", + "Thus, we now adapt our regularization scheme to the source's surface brightness. Where its brighter (and therefore\n", + "has a steeper flux gradient) we apply a lower level of regularization than further out. Furthermore, in the edges\n", + "of the source-plane where no source-flux is present we will assume a high regularization coefficient that smooths\n", + "over all of the source-pixels.\n", "\n", - "Try looking at a couple of extra solutions which use with different inner and outer regularization coefficients or \n", - "signal scales. I doubt you'll notice a lot change visually, but the log evidence certainly has a lot of room for \n", + "Try looking at a couple of extra solutions which use with different inner and outer regularization coefficients or\n", + "signal scales. I doubt you'll notice a lot change visually, but the log evidence certainly has a lot of room for\n", "manuveur with different values.\n", "\n", - "You may find solutions that raise an `InversionException`. These solutions mean that the matrix used during the \n", - "linear algebra calculation was ill-defined, and could not be inverted. These solutions are removed \n", - "during lens modeling." + "You may find solutions that raise an `InversionException`. These solutions mean that the matrix used during the\n", + "linear algebra calculation was ill-defined, and could not be inverted. These solutions are removed during lens\n", + "modeling." ] }, { @@ -384,7 +388,6 @@ "source_adapt_regularization = al.Galaxy(\n", " redshift=1.0,\n", " pixelization=pixelization,\n", - " adapt_galaxy_image=adapt_image,\n", ")\n", "\n", "adapt_images = al.AdaptImages(\n", @@ -407,7 +410,15 @@ " title=\"Inversion Reconstruction\",\n", ")\n", "\n", - "print(\"Evidence using adaptive regularization. \", fit.log_evidence)" + "alternative_weights = mapper.regularization.regularization_weights_from(linear_obj=mapper)\n", + "aaplt.plot_mapper(\n", + " mapper=mapper, solution_vector=alternative_weights,\n", + " mesh_grid=mapper.source_plane_mesh_grid, zoom_to_brightest=False,\n", + " vmin=0.0, vmax=4.0, title=\"Alternative Adaptive Regularization Weights\",\n", + ")\n", + "print(\"Evidence using alternative adaptive regularization:\", fit.log_evidence)\n", + "print(\"Difference from constant regularization:\", fit.log_evidence - constant_fit.log_evidence)\n", + "print(\"Difference from first adaptive example:\", fit.log_evidence - adaptive_fit.log_evidence)" ], "outputs": [], "execution_count": null @@ -418,28 +429,19 @@ "source": [ "__Wrap Up__\n", "\n", - "To end, lets consider what this adaptive regularization scheme means in the context of maximizing the Bayesian\n", - "evidence. In the previous tutorial, we noted that by using a brightness-based adaptive pixelization we increased\n", - "the Bayesian evidence by allowing for new solutions which fit the data using fewer source pixels; the key criteria\n", - "in making a source reconstruction 'more simple' and 'less complex'.\n", - "\n", - "As you might have guessed, adaptive regularization increases the Bayesian log evidence by making the source\n", - "reconstruction simpler:\n", - "\n", - " 1) Reducing regularization in the source's brightest regions produces a `simpler` solution in that we are not\n", - " over-smoothing our reconstruction of its brightest regions.\n", - "\n", - " 2) Increasing regularization in the outskirts produces a simpler solution by correlating more source-pixels,\n", - " effectively reducing the number of pixels used by the reconstruction.\n", + "Adaptive regularization lets bright and faint parts of the source receive different smoothing weights. Lower\n", + "weights can preserve sharp structure where the data support it; higher weights can correlate values in faint\n", + "regions that would otherwise fit noise. The adapt image guides that distinction and must itself be checked.\n", "\n", - "Together, brightness based pixelizations and regularization allow us to find the objectively `simplest` source\n", - "solution possible and therefore ensure that our Bayesian evidence has a well defined maximum value. This was not the\n", - "case for magnification based pixelizations and constant regularization schemes.\n", + "The evidence comparisons quantify the outcomes for our chosen settings. They do not guarantee an increase for every\n", + "dataset, a unique maximum, or recovery of arbitrary source detail. Mesh resolution, the adapt image and the lens\n", + "model still limit the reconstruction. In a scientific analysis, explore the regularization parameters and inspect\n", + "the source and residuals together.\n", "\n", - "That completes this chapter on pixelized source reconstruction. You can now reconstruct sources of arbitrary\n", - "complexity and adapt every part of the analysis to the data itself. In chapter 4, `Scaling Up Lensing`, we take these\n", - "tools to bigger systems: lenses with extra galaxies along the line of sight, multi-galaxy lenses, scaling relations,\n", - "group and cluster scale lenses and weak lensing." + "That completes this chapter on pixelized source reconstruction. You can now investigate flexible source\n", + "reconstructions while checking the assumptions that shape them. In chapter 4, `Scaling Up Lensing`, we take these\n", + "tools to bigger systems: lenses with extra galaxies along the line of sight, multi-galaxy lenses, scaling\n", + "relations, group and cluster scale lenses and weak lensing." ] } ], diff --git a/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb b/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb index 03b292f..9db8897 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb @@ -22,7 +22,60 @@ "- Turning the reconstructed source back into an image\n", "- Inspecting the reconstruction\n", "- Changing the source resolution\n", - "- Wrap up" + "- Wrap up\n", + "\n", + "__Opening \u2014 Pixelized source reconstruction__\n", + "\n", + "Look at a resolved lensed arc. Its broad shape may be smooth, but the light along it can contain bright knots,\n", + "faint extensions and irregular structure. A model might reproduce the overall arc while leaving compact, coherent\n", + "features in the residual image.\n", + "\n", + "In Chapter 2, we introduced linear light profiles and multi-Gaussian expansions (MGEs). By combining Gaussians of\n", + "different widths, an MGE can describe a much more flexible radial brightness distribution than a single S\u00e9rsic\n", + "profile. Gaussian groups with different ellipticities and orientations can also describe changes in flattening and\n", + "isophotal twists. Fixed widths and linearly solved intensities keep the number of non-linear parameters manageable.\n", + "\n", + "That flexibility makes MGE a useful modelling tool, but consider the geometry of our worked example. Within each\n", + "galaxy\u2019s Gaussian group, the components shared a common centre and elliptical shape. Adding more Gaussians gives us\n", + "finer control over how brightness changes around that centre. It does not give us separate centres for star-forming\n", + "knots, off-centre clumps or several distinct source components.\n", + "\n", + "We could add offset Gaussian groups. MGEs are not fundamentally restricted to one centre. The practical difficulty\n", + "is deciding how many groups to use, where to place them and how to fit their geometry as the source becomes more\n", + "complicated.\n", + "\n", + "This is where the image residuals become useful. If an MGE captures the broad light distribution but leaves compact\n", + "structure along the arcs, its source description may need more spatial freedom. Those residuals are not proof of\n", + "source clumpiness: errors in the mass model, foreground light subtraction, telescope blurring or other aspects of\n", + "the data treatment can also produce structure. We need to investigate their origin.\n", + "\n", + "In this chapter, we introduce pixelized source reconstruction. Instead of prescribing a light-profile centre and\n", + "shape for every feature, we describe the source brightness on a mesh. Different regions of that mesh can take\n", + "different brightness values, allowing the reconstruction to represent more complicated source structure.\n", + "\n", + "The connection to Chapter 2 is direct. There, we solved for Gaussian intensities linearly. Here, for a specified\n", + "mass model and mesh, we solve for source brightness values using the same underlying advantage: they enter the\n", + "predicted image linearly.\n", + "\n", + "This additional freedom also allows the reconstruction to fit noise. We therefore introduce regularization\u2014a prior\n", + "that controls how freely neighbouring source brightnesses can vary. Pixelization is not assumption-free: the mass\n", + "model, mesh geometry, resolution and regularization all affect the inferred source.\n", + "\n", + "MGE remains valuable, especially for foreground lens light and initial source fits. Pixelization is the next tool\n", + "when the source requires more spatial freedom. We will learn how to use these tools together, inspect their\n", + "reconstructions and recognise when their assumptions need revisiting.\n", + "\n", + "__A complex source__\n", + "\n", + "We will use a simulated source with several light components at different positions, giving it an asymmetric\n", + "appearance. The simulation provides both the lensed image and the original source, so we can see what the\n", + "reconstruction is trying to recover.\n", + "\n", + "The next figures show these two views. Look at the separate bright regions in the source and how lensing stretches\n", + "and repeats their structure in the image.\n", + "\n", + "For observed data, we would only have the lensed image. The source reconstruction would be an inference from that\n", + "image and our lens model, not an independent observation of the unlensed galaxy." ] }, { @@ -63,39 +116,6 @@ "_setup_colab.setup(\"howtolens\")" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Opening \u2014 Pixelized source reconstruction__\n", - "\n", - "Look at a resolved lensed arc. Its broad shape may be smooth, but the light along it can contain bright knots, faint extensions and irregular structure. A model might reproduce the overall arc while leaving compact, coherent features in the residual image.\n", - "\n", - "In Chapter 2, we introduced linear light profiles and multi-Gaussian expansions (MGEs). By combining Gaussians of different widths, an MGE can describe a much more flexible radial brightness distribution than a single S\u00e9rsic profile. Gaussian groups with different ellipticities and orientations can also describe changes in flattening and isophotal twists. Fixed widths and linearly solved intensities keep the number of non-linear parameters manageable.\n", - "\n", - "That flexibility makes MGE a useful modelling tool, but consider the geometry of our worked example. Within each galaxy\u2019s Gaussian group, the components shared a common centre and elliptical shape. Adding more Gaussians gives us finer control over how brightness changes around that centre. It does not give us separate centres for star-forming knots, off-centre clumps or several distinct source components.\n", - "\n", - "We could add offset Gaussian groups. MGEs are not fundamentally restricted to one centre. The practical difficulty is deciding how many groups to use, where to place them and how to fit their geometry as the source becomes more complicated.\n", - "\n", - "This is where the image residuals become useful. If an MGE captures the broad light distribution but leaves compact structure along the arcs, its source description may need more spatial freedom. Those residuals are not proof of source clumpiness: errors in the mass model, foreground light subtraction, telescope blurring or other aspects of the data treatment can also produce structure. We need to investigate their origin.\n", - "\n", - "In this chapter, we introduce pixelized source reconstruction. Instead of prescribing a light-profile centre and shape for every feature, we describe the source brightness on a mesh. Different regions of that mesh can take different brightness values, allowing the reconstruction to represent more complicated source structure.\n", - "\n", - "The connection to Chapter 2 is direct. There, we solved for Gaussian intensities linearly. Here, for a specified mass model and mesh, we solve for source brightness values using the same underlying advantage: they enter the predicted image linearly.\n", - "\n", - "This additional freedom also allows the reconstruction to fit noise. We therefore introduce regularization\u2014a prior that controls how freely neighbouring source brightnesses can vary. Pixelization is not assumption-free: the mass model, mesh geometry, resolution and regularization all affect the inferred source.\n", - "\n", - "MGE remains valuable, especially for foreground lens light and initial source fits. Pixelization is the next tool when the source requires more spatial freedom. We will learn how to use these tools together, inspect their reconstructions and recognise when their assumptions need revisiting.\n", - "\n", - "__A complex source__\n", - "\n", - "We will use a simulated source with several light components at different positions, giving it an asymmetric appearance. The simulation provides both the lensed image and the original source, so we can see what the reconstruction is trying to recover.\n", - "\n", - "The next figures show these two views. Look at the separate bright regions in the source and how lensing stretches and repeats their structure in the image.\n", - "\n", - "For observed data, we would only have the lensed image. The source reconstruction would be an inference from that image and our lens model, not an independent observation of the unlensed galaxy." - ] - }, { "cell_type": "code", "metadata": {}, @@ -167,13 +187,19 @@ "source": [ "__Why a simple source model falls short__\n", "\n", - "An MGE can describe flexible radial light distributions, as we saw in Chapter 2. Here we fix a Gaussian group to one common centre and elliptical shape to isolate the missing spatial freedom: adding widths at that centre cannot independently place all the bright regions in this source.\n", + "An MGE can describe flexible radial light distributions, as we saw in Chapter 2. Here we fix a Gaussian group to\n", + "one common centre and elliptical shape to isolate the missing spatial freedom: adding widths at that centre cannot\n", + "independently place all the bright regions in this source.\n", "\n", - "We will compare the simulated image with a model that uses one common-centre MGE group, keeping the lens mass fixed to the values used in the simulation. This is an illustrative fixed-geometry comparison, not an optimized MGE search. The fixed mass cannot compensate for missing source structure.\n", + "We will compare the simulated image with a model that uses one common-centre MGE group, keeping the lens mass fixed\n", + "to the values used in the simulation. This is an illustrative fixed-geometry comparison, not an optimized MGE\n", + "search. The fixed mass cannot compensate for missing source structure.\n", "\n", - "Inspect the residual map for coherent structure along the arcs. Such structure would show where this source model leaves light unexplained, rather than just the random differences expected from noise.\n", + "Inspect the residual map for coherent structure along the arcs. Such structure would show where this source model\n", + "leaves light unexplained, rather than just the random differences expected from noise.\n", "\n", - "**\ud83e\udd16 Ask AI:** If I allowed the lens mass parameters to vary while using this overly simple source model, how could the missing source structure affect the inferred mass distribution?" + "**\ud83e\udd16 Ask AI:** If I allowed the lens mass parameters to vary while using this overly simple source model, how could\n", + "the missing source structure affect the inferred mass distribution?" ] }, { @@ -200,26 +226,37 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Offset Gaussian groups could supply this spatial freedom too, at the cost of choosing and fitting their geometry. MGE remains useful for initial source fits and foreground light. Here we explore a mesh as the next tool for more complicated source structure.\n", + "Offset Gaussian groups could supply this spatial freedom too, at the cost of choosing and fitting their geometry.\n", + "MGE remains useful for initial source fits and foreground light. Here we explore a mesh as the next tool for more\n", + "complicated source structure.\n", "\n", "\n", "__A grid for the source light__\n", "\n", - "A pixelization describes the source using brightness values distributed across a mesh. We infer these values from the image instead of requiring the entire source to follow a small set of analytic profiles.\n", + "A pixelization describes the source using brightness values distributed across a mesh. We infer these values from\n", + "the image instead of requiring the entire source to follow a small set of analytic profiles.\n", "\n", - "We begin with `RectangularUniform`, which places mesh points at regular intervals in the source plane. Its `shape` specifies the number of points along each direction. The next plot shows where these points lie relative to the ray-traced image coordinates.\n", + "We begin with `RectangularUniform`, which places mesh points at regular intervals in the source plane. Its `shape`\n", + "specifies the number of points along each direction. The next plot shows where these points lie relative to the\n", + "ray-traced image coordinates.\n", "\n", - "The mesh also defines how brightness is interpolated between its points. We will examine this more closely in the next tutorial. For now, the important distinction is that the mesh specifies where we represent the source; it does not yet tell us how bright the source is.\n", + "The mesh also defines how brightness is interpolated between its points. We will examine this more closely in the\n", + "next tutorial. For now, the important distinction is that the mesh specifies where we represent the source; it does\n", + "not yet tell us how bright the source is.\n", "\n", "\n", "\n", "__Following the same image pixels into the source plane__\n", "\n", - "Every unmasked image pixel has an index and a position. Ray tracing changes its position, but preserves its index: image point 100 and traced source point 100 describe the same light path.\n", + "Every unmasked image pixel has an index and a position. Ray tracing changes its position, but preserves its index:\n", + "image point 100 and traced source point 100 describe the same light path.\n", "\n", - "We will highlight two small groups of image pixels and follow them into the source plane. Matching colours identify matching indexes in the two plots. The source-plane points here are ray-traced image coordinates; they are not the points of our source mesh.\n", + "We will highlight two small groups of image pixels and follow them into the source plane. Matching colours identify\n", + "matching indexes in the two plots. The source-plane points here are ray-traced image coordinates; they are not the\n", + "points of our source mesh.\n", "\n", - "For this demonstration, we use one sample at each image-pixel centre, making the correspondence easy to follow. More accurate image integration can use several samples within each pixel." + "For this demonstration, we use one sample at each image-pixel centre, making the correspondence easy to follow.\n", + "More accurate image integration can use several samples within each pixel." ] }, { @@ -285,17 +322,22 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Compare the separation and shape of each group before and after ray tracing. Their indexes remain unchanged even when the lens strongly changes their arrangement.\n", + "Compare the separation and shape of each group before and after ray tracing. Their indexes remain unchanged even\n", + "when the lens strongly changes their arrangement.\n", "\n", "\n", "\n", "__Where a traced image pixel meets the source mesh__\n", "\n", - "We now place a separate rectangular mesh in the source plane. Its indexes identify the brightness values we will reconstruct. An image-pixel index and a source-mesh index therefore refer to different things.\n", + "We now place a separate rectangular mesh in the source plane. Its indexes identify the brightness values we will\n", + "reconstruct. An image-pixel index and a source-mesh index therefore refer to different things.\n", "\n", - "A traced image coordinate generally falls between mesh points. With bilinear interpolation, its brightness is calculated from the four surrounding mesh values, weighted according to its position. Falling within one rectangular cell does not mean taking its brightness from just one source point.\n", + "A traced image coordinate generally falls between mesh points. With bilinear interpolation, its brightness is\n", + "calculated from the four surrounding mesh values, weighted according to its position. Falling within one\n", + "rectangular cell does not mean taking its brightness from just one source point.\n", "\n", - "The next cell selects one image pixel and highlights the source mesh points contributing to it. We print their indexes and weights to make this relationship explicit." + "The next cell selects one image pixel and highlights the source mesh points contributing to it. We print their\n", + "indexes and weights to make this relationship explicit." ] }, { @@ -342,17 +384,22 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The mapper stores these relationships for all image pixels. We do not need to construct or solve the mapping matrix by hand; inspecting one row simply exposes what the mapping means.\n", + "The mapper stores these relationships for all image pixels. We do not need to construct or solve the mapping matrix\n", + "by hand; inspecting one row simply exposes what the mapping means.\n", "\n", "\n", "\n", "__One source region, several image regions__\n", "\n", - "We can also follow the mapping in the opposite direction. Select a source mesh point and ask which image pixels receive a contribution from it.\n", + "We can also follow the mapping in the opposite direction. Select a source mesh point and ask which image pixels\n", + "receive a contribution from it.\n", "\n", - "The figure below uses the same colour for a selected source region and its associated image regions. A small source region can contribute to widely separated parts of the image: this is how multiple images constrain a shared source reconstruction.\n", + "The figure below uses the same colour for a selected source region and its associated image regions. A small source\n", + "region can contribute to widely separated parts of the image: this is how multiple images constrain a shared source\n", + "reconstruction.\n", "\n", - "The coloured image regions show interpolation support. They are not a strict statement that every traced coordinate falls inside the coloured source cell." + "The coloured image regions show interpolation support. They are not a strict statement that every traced coordinate\n", + "falls inside the coloured source cell." ] }, { @@ -413,27 +460,37 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Try changing `(0.3, 0.3)` to another source position and follow how its image regions change. The number of coloured patches is not necessarily the physical image multiplicity: masking and pixel sampling can split or hide regions.\n", + "Try changing `(0.3, 0.3)` to another source position and follow how its image regions change. The number of\n", + "coloured patches is not necessarily the physical image multiplicity: masking and pixel sampling can split or hide\n", + "regions.\n", "\n", "\n", "\n", "__Reconstructing the source__\n", "\n", - "We now have a mesh and a description of how its brightness values contribute to the observed image. The next step is to infer those values from the data. This is called an inversion.\n", + "We now have a mesh and a description of how its brightness values contribute to the observed image. The next step\n", + "is to infer those values from the data. This is called an inversion.\n", "\n", - "For a fixed lens mass model, the source brightnesses enter the predicted image linearly. PyAutoLens uses this property to solve for them together, rather than asking a non-linear search to explore each brightness value individually.\n", + "For a fixed lens mass model, the source brightnesses enter the predicted image linearly. PyAutoLens uses this\n", + "property to solve for them together, rather than asking a non-linear search to explore each brightness value\n", + "individually.\n", "\n", - "The next cell evaluates a `FitImaging` using a pixelized source. We keep the lens mass fixed to the simulation values, so this calculation reconstructs the source without searching for a new mass model.\n", + "The next cell evaluates a `FitImaging` using a pixelized source. We keep the lens mass fixed to the simulation\n", + "values, so this calculation reconstructs the source without searching for a new mass model.\n", "\n", "\n", "\n", "__A first look at regularization__\n", "\n", - "Giving the source many adjustable brightness values lets it represent complex structure, but also gives it freedom to fit noise. We therefore include regularization: a prior that favours smoother source reconstructions.\n", + "Giving the source many adjustable brightness values lets it represent complex structure, but also gives it freedom\n", + "to fit noise. We therefore include regularization: a prior that favours smoother source reconstructions.\n", "\n", - "For this first reconstruction, we use `Constant` regularization with a fixed coefficient. It discourages large differences between neighbouring mesh values. The data can still support structure, but adding structure comes with a penalty.\n", + "For this first reconstruction, we use `Constant` regularization with a fixed coefficient. It discourages large\n", + "differences between neighbouring mesh values. The data can still support structure, but adding structure comes with\n", + "a penalty.\n", "\n", - "We will keep this setting fixed for the rest of this tutorial. In tutorial 2, we will vary it and see how too little smoothing fits noise, while too much smoothing erases source detail." + "We will keep this setting fixed for the rest of this tutorial. In tutorial 2, we will vary it and see how too\n", + "little smoothing fits noise, while too much smoothing erases source detail." ] }, { @@ -461,11 +518,14 @@ "source": [ "__From source indexes to reconstructed brightnesses__\n", "\n", - "So far, the mapper tells us how source brightness would contribute to the image, but we have not determined those brightnesses.\n", + "So far, the mapper tells us how source brightness would contribute to the image, but we have not determined those\n", + "brightnesses.\n", "\n", - "The inversion combines these mappings with the observed image, its noise and telescope blurring. It solves for the source brightness values together, including the smoothness prior supplied by regularization.\n", + "The inversion combines these mappings with the observed image, its noise and telescope blurring. It solves for the\n", + "source brightness values together, including the smoothness prior supplied by regularization.\n", "\n", - "In this example there is one mapper. Entry `j` of its reconstruction therefore gives the brightness associated with source mesh index `j`. We can print selected values and show their locations on the reconstructed source." + "In this example there is one mapper. Entry `j` of its reconstruction therefore gives the brightness associated with\n", + "source mesh index `j`. We can print selected values and show their locations on the reconstructed source." ] }, { @@ -503,15 +563,19 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "These brightnesses are inferred jointly. We do not independently fit each coloured image region: shared source values must explain their contributions across the image, while regularization connects neighbouring source values.\n", + "These brightnesses are inferred jointly. We do not independently fit each coloured image region: shared source\n", + "values must explain their contributions across the image, while regularization connects neighbouring source values.\n", "\n", "\n", "\n", "__Turning the reconstructed source back into an image__\n", "\n", - "The source reconstruction and the reconstructed image are different objects. The source lives on our source-plane mesh. Mapping its brightness values through the lens produces an image-plane prediction.\n", + "The source reconstruction and the reconstructed image are different objects. The source lives on our source-plane\n", + "mesh. Mapping its brightness values through the lens produces an image-plane prediction.\n", "\n", - "The telescope then blurs that prediction. This blurred image is what we compare with the observed data. The inversion already accounts for that blurring when solving for the source; it is not an extra correction applied after an otherwise completed fit.\n", + "The telescope then blurs that prediction. This blurred image is what we compare with the observed data. The\n", + "inversion already accounts for that blurring when solving for the source; it is not an extra correction applied\n", + "after an otherwise completed fit.\n", "\n", "The following plots separate these stages." ] @@ -551,21 +615,29 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Compare the source reconstruction with these image-plane plots. A feature in the source can appear in several places in the lensed image, and telescope blurring can make those image features less distinct.\n", + "Compare the source reconstruction with these image-plane plots. A feature in the source can appear in several\n", + "places in the lensed image, and telescope blurring can make those image features less distinct.\n", "\n", - "Inspect the residuals for coherent unexplained structure. A plausible-looking source alone does not establish that the model explains the data.\n", + "Inspect the residuals for coherent unexplained structure. A plausible-looking source alone does not establish that\n", + "the model explains the data.\n", "\n", - "**\ud83e\udd16 Ask AI:** Why must the same reconstructed source brightnesses explain all of their associated image regions, rather than allowing each arc to have an independent source reconstruction?\n", + "**\ud83e\udd16 Ask AI:** Why must the same reconstructed source brightnesses explain all of their associated image regions,\n", + "rather than allowing each arc to have an independent source reconstruction?\n", "\n", "__Inspecting the reconstruction__\n", "\n", "We will plot the inferred source alongside the model image and residuals. These answer different questions.\n", "\n", - "The source reconstruction shows the brightness distribution inferred under our chosen lens model, mesh and regularization. The model image shows how that reconstruction appears after lensing and telescope blurring. The residuals show what remains unexplained in the observed image.\n", + "The source reconstruction shows the brightness distribution inferred under our chosen lens model, mesh and\n", + "regularization. The model image shows how that reconstruction appears after lensing and telescope blurring. The\n", + "residuals show what remains unexplained in the observed image.\n", "\n", - "Compare these residuals with those from the simple source model earlier in the tutorial. Look particularly at the image regions associated with the source\u2019s separate bright components. The comparison will show whether the extra source freedom helps explain those features.\n", + "Compare these residuals with those from the simple source model earlier in the tutorial. Look particularly at the\n", + "image regions associated with the source\u2019s separate bright components. The comparison will show whether the extra\n", + "source freedom helps explain those features.\n", "\n", - "Because this is a simulation, we can also compare the reconstruction with the input source. We should not expect an exact copy: finite resolution, noise and regularization limit the detail we can recover." + "Because this is a simulation, we can also compare the reconstruction with the input source. We should not expect an\n", + "exact copy: finite resolution, noise and regularization limit the detail we can recover." ] }, { @@ -586,13 +658,19 @@ "source": [ "__Changing the source resolution__\n", "\n", - "The mesh resolution controls how finely we can represent the source. A coarse mesh may merge distinct features, while a finer mesh gives the reconstruction more freedom.\n", + "The mesh resolution controls how finely we can represent the source. A coarse mesh may merge distinct features,\n", + "while a finer mesh gives the reconstruction more freedom.\n", "\n", - "Repeat the reconstruction with mesh shapes of `(15, 15)`, `(25, 25)` and `(35, 35)`, keeping the lens mass and regularization coefficient fixed. Compare the source structure and image residuals in each case, then restore the starting shape of `(25, 25)`.\n", + "Repeat the reconstruction with mesh shapes of `(15, 15)`, `(25, 25)` and `(35, 35)`, keeping the lens mass and\n", + "regularization coefficient fixed. Compare the source structure and image residuals in each case, then restore the\n", + "starting shape of `(25, 25)`.\n", "\n", - "More mesh points do not necessarily reveal more reliable detail. The data must constrain that detail, and changing the mesh also changes how the regularization acts. This experiment explores the effect of resolution; choosing an appropriate reconstruction requires considering resolution and smoothing together.\n", + "More mesh points do not necessarily reveal more reliable detail. The data must constrain that detail, and changing\n", + "the mesh also changes how the regularization acts. This experiment explores the effect of resolution; choosing an\n", + "appropriate reconstruction requires considering resolution and smoothing together.\n", "\n", - "**\ud83e\udd16 Ask AI:** When I increase the source mesh resolution, how can I distinguish newly resolved source structure from extra freedom being used to fit noise?" + "**\ud83e\udd16 Ask AI:** When I increase the source mesh resolution, how can I distinguish newly resolved source structure\n", + "from extra freedom being used to fit noise?" ] }, { @@ -623,13 +701,18 @@ "source": [ "__Wrap up__\n", "\n", - "We have reconstructed a complex source without prescribing the positions and shapes of its individual light components.\n", + "We have reconstructed a complex source without prescribing the positions and shapes of its individual light\n", + "components.\n", "\n", - "The mesh specifies where we represent the source. The mapper connects its brightness values to the observed image through the lens model. The inversion solves for those values, with regularization controlling the freedom to introduce structure.\n", + "The mesh specifies where we represent the source. The mapper connects its brightness values to the observed image\n", + "through the lens model. The inversion solves for those values, with regularization controlling the freedom to\n", + "introduce structure.\n", "\n", - "Throughout this tutorial, the lens mass was fixed. Later in the chapter, we will vary the mass model and reconstruct the source for each proposed model, allowing the image to constrain both.\n", + "Throughout this tutorial, the lens mass was fixed. Later in the chapter, we will vary the mass model and\n", + "reconstruct the source for each proposed model, allowing the image to constrain both.\n", "\n", - "First, we need to understand how interpolation and regularization shape the reconstruction. Tutorial 2 explores these choices and introduces the Bayesian evidence used to compare different levels of smoothing." + "First, we need to understand how interpolation and regularization shape the reconstruction. Tutorial 2 explores\n", + "these choices and introduces the Bayesian evidence used to compare different levels of smoothing." ] } ], diff --git a/notebooks/chapter_3_pixelizations/tutorial_2_bayesian_regularization.ipynb b/notebooks/chapter_3_pixelizations/tutorial_2_bayesian_regularization.ipynb index c22c51b..994c6f7 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_2_bayesian_regularization.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_2_bayesian_regularization.ipynb @@ -18,7 +18,29 @@ "- Inspecting the preferred reconstruction\n", "- What is linear, and what requires a search?\n", "- Mesh resolution and regularization belong together\n", - "- What we have learned, and what comes next" + "- What we have learned, and what comes next\n", + "\n", + "__Interpolation and Bayesian regularization__\n", + "\n", + "So far, we have:\n", + "\n", + "- Used pixelizations and mappers to connect source mesh points to image pixels.\n", + "- Used an inversion to reconstruct the source\u2019s brightness.\n", + "- Mapped that reconstruction back into the image, including telescope blurring, to compare it with the data.\n", + "\n", + "Our explanation of how an inversion works has deliberately left some things unexplained. In particular, you will\n", + "have noticed the regularization input that we passed when creating our pixelization. We used a coefficient of\n", + "`1.0`, but have not established why that value should give an appropriate reconstruction.\n", + "\n", + "This tutorial explores what regularization does and why we need it. We will change its strength, inspect the\n", + "resulting source reconstructions, and see why obtaining a close fit to the image is not enough on its own.\n", + "\n", + "First, we will revisit interpolation. It is easy to confuse interpolation with smoothing, because both affect the\n", + "appearance of the reconstructed source. Understanding the distinction will help us interpret the experiments that\n", + "follow.\n", + "\n", + "We use the same complex source as tutorial 1. The lens mass remains fixed to the simulation values, so changes in\n", + "the reconstruction come from our source modelling choices." ] }, { @@ -59,27 +81,6 @@ "_setup_colab.setup(\"howtolens\")" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Interpolation and Bayesian regularization__\n", - "\n", - "So far, we have:\n", - "\n", - "- Used pixelizations and mappers to connect source mesh points to image pixels.\n", - "- Used an inversion to reconstruct the source\u2019s brightness.\n", - "- Mapped that reconstruction back into the image, including telescope blurring, to compare it with the data.\n", - "\n", - "Our explanation of how an inversion works has deliberately left some things unexplained. In particular, you will have noticed the regularization input that we passed when creating our pixelization. We used a coefficient of `1.0`, but have not established why that value should give an appropriate reconstruction.\n", - "\n", - "This tutorial explores what regularization does and why we need it. We will change its strength, inspect the resulting source reconstructions, and see why obtaining a close fit to the image is not enough on its own.\n", - "\n", - "First, we will revisit interpolation. It is easy to confuse interpolation with smoothing, because both affect the appearance of the reconstructed source. Understanding the distinction will help us interpret the experiments that follow.\n", - "\n", - "We use the same complex source as tutorial 1. The lens mass remains fixed to the simulation values, so changes in the reconstruction come from our source modelling choices." - ] - }, { "cell_type": "code", "metadata": {}, @@ -139,19 +140,26 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The single sample per image pixel keeps the indexed mapping example straightforward. For scientific modelling, we would also check that our image sampling is sufficiently accurate.\n", + "The single sample per image pixel keeps the indexed mapping example straightforward. For scientific modelling, we\n", + "would also check that our image sampling is sufficiently accurate.\n", "\n", "__Interpolation and our starting reconstruction__\n", "\n", "Let\u2019s look at our reconstruction from the previous tutorial in more detail.\n", "\n", - "The `RectangularUniform` mesh describes the source using brightness values at regularly spaced points. A ray-traced image coordinate generally falls between these points. Its predicted brightness is obtained by combining the four surrounding values, with weights determined by its position. This is bilinear interpolation.\n", + "The `RectangularUniform` mesh describes the source using brightness values at regularly spaced points. A ray-traced\n", + "image coordinate generally falls between these points. Its predicted brightness is obtained by combining the four\n", + "surrounding values, with weights determined by its position. This is bilinear interpolation.\n", "\n", - "Interpolation tells us how to calculate brightness between mesh points, but it does not tell us what those mesh values should be. Four neighbouring values could be similar, or one could be much brighter than the others. Both can be interpolated. In the second case, however, the brightness changes much more sharply across the source.\n", + "Interpolation tells us how to calculate brightness between mesh points, but it does not tell us what those mesh\n", + "values should be. Four neighbouring values could be similar, or one could be much brighter than the others. Both\n", + "can be interpolated. In the second case, however, the brightness changes much more sharply across the source.\n", "\n", - "Regularization influences the brightness values we infer, discouraging variations that are not sufficiently supported by the data. Interpolation then determines how those values contribute between mesh points.\n", + "Regularization influences the brightness values we infer, discouraging variations that are not sufficiently\n", + "supported by the data. Interpolation then determines how those values contribute between mesh points.\n", "\n", - "We are going to evaluate several reconstructions, so the function below keeps their common setup in one place. Only the regularization coefficient changes." + "We are going to evaluate several reconstructions, so the function below keeps their common setup in one place. Only\n", + "the regularization coefficient changes." ] }, { @@ -190,7 +198,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Here is the interpolation calculation for one image pixel. As in tutorial 1, the mapper supplies the contributing source indexes and their weights. This time, we also have reconstructed brightness values, so we can see how the contributions combine." + "Here is the interpolation calculation for one image pixel. As in tutorial 1, the mapper supplies the contributing\n", + "source indexes and their weights. This time, we also have reconstructed brightness values, so we can see how the\n", + "contributions combine." ] }, { @@ -233,13 +243,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "This is the image prediction before the PSF redistributes light between image pixels. We are inspecting a small part of the calculation, not replacing the inversion\u2019s treatment of telescope blurring.\n", + "This is the image prediction before the PSF redistributes light between image pixels. We are inspecting a small\n", + "part of the calculation, not replacing the inversion\u2019s treatment of telescope blurring.\n", "\n", "__Reducing regularization__\n", "\n", - "Our starting reconstruction uses a regularization coefficient of `1.0`. Let\u2019s reduce it substantially and examine what changes.\n", + "Our starting reconstruction uses a regularization coefficient of `1.0`. Let\u2019s reduce it substantially and examine\n", + "what changes.\n", "\n", - "We use `0.01` rather than exactly zero, retaining a small smoothness penalty. Keep the lens model, mesh and data unchanged: we want to isolate the effect of weakening regularization." + "We use `0.01` rather than exactly zero, retaining a small smoothness penalty. Keep the lens model, mesh and data\n", + "unchanged: we want to isolate the effect of weakening regularization." ] }, { @@ -261,19 +274,30 @@ "source": [ "To understand this comparison, we need to look more closely at what regularization actually does.\n", "\n", - "When the inversion reconstructs the source, it does not only seek brightness values that reproduce the image. With `Constant` regularization, it also compares neighbouring brightness values on the rectangular source mesh. Interior mesh points have four immediate neighbours. Large differences between their brightnesses contribute a larger penalty.\n", + "When the inversion reconstructs the source, it does not only seek brightness values that reproduce the image. With\n", + "`Constant` regularization, it also compares neighbouring brightness values on the rectangular source mesh. Interior\n", + "mesh points have four immediate neighbours. Large differences between their brightnesses contribute a larger\n", + "penalty.\n", "\n", - "You can think of this as applying a **smoothness prior** to the reconstructed source. It expresses a preference for neighbouring regions to have similar brightness, unless the image provides enough evidence for them to differ.\n", + "You can think of this as applying a **smoothness prior** to the reconstructed source. It expresses a preference for\n", + "neighbouring regions to have similar brightness, unless the image provides enough evidence for them to differ.\n", "\n", - "The penalty depends on squared differences, so positive and negative differences cannot cancel. The coefficient controls its strength. Reducing that coefficient makes a given amount of variation less costly; increasing it makes the same variation more costly.\n", + "The penalty depends on squared differences, so positive and negative differences cannot cancel. The coefficient\n", + "controls its strength. Reducing that coefficient makes a given amount of variation less costly; increasing it makes\n", + "the same variation more costly.\n", "\n", - "In the language of linear algebra, this prior contributes a regularization matrix to the system the inversion solves. We do not need to construct that matrix ourselves to understand its effect.\n", + "In the language of linear algebra, this prior contributes a regularization matrix to the system the inversion\n", + "solves. We do not need to construct that matrix ourselves to understand its effect.\n", "\n", - "Without sufficient regularization, the inversion has greater freedom to fit fluctuations in the observed image, including noise. Some of those fluctuations can be explained by adding irregular structure to the source. The image fit may improve even though the inferred source becomes less faithful to the galaxy that produced the data.\n", + "Without sufficient regularization, the inversion has greater freedom to fit fluctuations in the observed image,\n", + "including noise. Some of those fluctuations can be explained by adding irregular structure to the source. The image\n", + "fit may improve even though the inferred source becomes less faithful to the galaxy that produced the data.\n", "\n", - "Inspect the weakly regularized reconstruction for isolated bright values or rapid changes between neighbouring points. Also look at its faint regions, where the image provides less information about the source.\n", + "Inspect the weakly regularized reconstruction for isolated bright values or rapid changes between neighbouring\n", + "points. Also look at its faint regions, where the image provides less information about the source.\n", "\n", - "A few extreme values can dominate the colour scale. We can compare both reconstructions using the starting reconstruction\u2019s brightness range to see the remaining structure more clearly." + "A few extreme values can dominate the colour scale. We can compare both reconstructions using the starting\n", + "reconstruction\u2019s brightness range to see the remaining structure more clearly." ] }, { @@ -305,17 +329,24 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Values above this plotting limit share the highest colour, so use these figures alongside the original plots rather than treating them as the full brightness range.\n", + "Values above this plotting limit share the highest colour, so use these figures alongside the original plots rather\n", + "than treating them as the full brightness range.\n", "\n", - "The important point is that recovering recognizable source structure does not mean every reconstructed feature is reliable. Genuine structure and noise-fitting can appear in the same reconstruction.\n", + "The important point is that recovering recognizable source structure does not mean every reconstructed feature is\n", + "reliable. Genuine structure and noise-fitting can appear in the same reconstruction.\n", "\n", "__Increasing regularization__\n", "\n", "Now let\u2019s move in the other direction and use a much larger coefficient.\n", "\n", - "With stronger regularization, the inversion pays a greater penalty for differences between neighbouring brightnesses. This discourages the sharp variations that can fit noise. However, the real source also contains brightness variations: compact components, bright centres and the changes between those regions and their surroundings.\n", + "With stronger regularization, the inversion pays a greater penalty for differences between neighbouring\n", + "brightnesses. This discourages the sharp variations that can fit noise. However, the real source also contains\n", + "brightness variations: compact components, bright centres and the changes between those regions and their\n", + "surroundings.\n", "\n", - "Regularization cannot identify which variations are genuine simply by examining the source. The image fit and the prior must work together. If we make the smoothness preference too strong, the reconstruction can lose genuine structure because reproducing it carries too large a penalty." + "Regularization cannot identify which variations are genuine simply by examining the source. The image fit and the\n", + "prior must work together. If we make the smoothness preference too strong, the reconstruction can lose genuine\n", + "structure because reproducing it carries too large a penalty." ] }, { @@ -345,9 +376,12 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Compare the bright components with the starting reconstruction. Look for features becoming flatter or merging together, then inspect the corresponding regions of the image residuals.\n", + "Compare the bright components with the starting reconstruction. Look for features becoming flatter or merging\n", + "together, then inspect the corresponding regions of the image residuals.\n", "\n", - "This illustrates the difficulty in choosing a coefficient. Too little smoothing can introduce structure that explains noise. Too much can remove structure needed to explain the galaxy. Neither the smoothest source nor the closest possible image fit is automatically the reconstruction we want.\n", + "This illustrates the difficulty in choosing a coefficient. Too little smoothing can introduce structure that\n", + "explains noise. Too much can remove structure needed to explain the galaxy. Neither the smoothest source nor the\n", + "closest possible image fit is automatically the reconstruction we want.\n", "\n", "We can quantify image agreement using chi-squared: the sum of squared residuals divided by their noise variances." ] @@ -378,25 +412,38 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "A lower chi-squared means closer agreement with the image under the assumed noise map. It does not distinguish fitting genuine structure from fitting noise. This is why choosing the coefficient solely by image agreement would favour giving the source too much freedom.\n", + "A lower chi-squared means closer agreement with the image under the assumed noise map. It does not distinguish\n", + "fitting genuine structure from fitting noise. This is why choosing the coefficient solely by image agreement would\n", + "favour giving the source too much freedom.\n", "\n", - "**\ud83e\udd16 Ask AI:** Why might a weakly regularized reconstruction have a lower chi-squared but a less trustworthy source than a more strongly regularized reconstruction?\n", + "**\ud83e\udd16 Ask AI:** Why might a weakly regularized reconstruction have a lower chi-squared but a less trustworthy source\n", + "than a more strongly regularized reconstruction?\n", "\n", "__Bayesian evidence__\n", "\n", "For inversions, we therefore need more than image agreement to choose an appropriate level of regularization.\n", "\n", - "We use the **Bayesian evidence**, which accounts for both the fit to the image and the source prior. It helps us compare reconstructions that have different amounts of freedom, rather than simply choosing whichever one follows the observed pixel values most closely.\n", + "We use the **Bayesian evidence**, which accounts for both the fit to the image and the source prior. It helps us\n", + "compare reconstructions that have different amounts of freedom, rather than simply choosing whichever one follows\n", + "the observed pixel values most closely.\n", "\n", "There are two useful parts to this intuition.\n", "\n", - "First, the reconstruction must explain the image. If strong regularization prevents it from reproducing genuine source structure, the resulting residuals count against that choice. Preferring a smooth source is not useful if that source cannot explain the observed arcs.\n", + "First, the reconstruction must explain the image. If strong regularization prevents it from reproducing genuine\n", + "source structure, the resulting residuals count against that choice. Preferring a smooth source is not useful if\n", + "that source cannot explain the observed arcs.\n", "\n", - "Second, allowing a more flexible source comes at a cost. Weak regularization permits many more patterns of brightness across neighbouring mesh points. Some of that extra freedom may be needed to describe the galaxy, but some may only help reproduce the particular noise fluctuations in this image.\n", + "Second, allowing a more flexible source comes at a cost. Weak regularization permits many more patterns of\n", + "brightness across neighbouring mesh points. Some of that extra freedom may be needed to describe the galaxy, but\n", + "some may only help reproduce the particular noise fluctuations in this image.\n", "\n", - "Evidence weighs the improvement in fit against the freedom allowed by the prior. An improvement must be sufficient to justify that additional flexibility.\n", + "Evidence weighs the improvement in fit against the freedom allowed by the prior. An improvement must be sufficient\n", + "to justify that additional flexibility.\n", "\n", - "This is also why complexity is not simply the number of source mesh points. Our three examples have exactly the same mesh. Stronger regularization ties neighbouring brightnesses together more closely, reducing their freedom to vary independently. We can therefore change the effective flexibility of the reconstruction without changing the number of mesh points.\n", + "This is also why complexity is not simply the number of source mesh points. Our three examples have exactly the\n", + "same mesh. Stronger regularization ties neighbouring brightnesses together more closely, reducing their freedom to\n", + "vary independently. We can therefore change the effective flexibility of the reconstruction without changing the\n", + "number of mesh points.\n", "\n", "Let\u2019s compare the evidence values returned by `FitImaging`." ] @@ -432,21 +479,30 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Compare this ranking with the source plots and the chi-squared values. The highest evidence need not belong to the reconstruction with the lowest chi-squared, because image agreement is only part of the comparison.\n", + "Compare this ranking with the source plots and the chi-squared values. The highest evidence need not belong to the\n", + "reconstruction with the lowest chi-squared, because image agreement is only part of the comparison.\n", "\n", - "We still need to inspect the residuals ourselves. Evidence does not explicitly examine their spatial pattern or guarantee that a preferred model is correct. Structured residuals can reveal shortcomings in the source, lens mass, PSF or other assumptions that this three-coefficient comparison does not address.\n", + "We still need to inspect the residuals ourselves. Evidence does not explicitly examine their spatial pattern or\n", + "guarantee that a preferred model is correct. Structured residuals can reveal shortcomings in the source, lens mass,\n", + "PSF or other assumptions that this three-coefficient comparison does not address.\n", "\n", - "For now, we have compared only three choices. The starting value of `1.0` has no special status, and the best of these three is not necessarily the best coefficient overall. Next, we will explore a broader range and see how this choice fits into the wider modelling process.\n", + "For now, we have compared only three choices. The starting value of `1.0` has no special status, and the best of\n", + "these three is not necessarily the best coefficient overall. Next, we will explore a broader range and see how this\n", + "choice fits into the wider modelling process.\n", "\n", "__Exploring the regularization coefficient__\n", "\n", - "We have compared weak, moderate and strong regularization, but those three values were chosen to illustrate different behaviours. They do not tell us where the evidence reaches its highest value.\n", + "We have compared weak, moderate and strong regularization, but those three values were chosen to illustrate\n", + "different behaviours. They do not tell us where the evidence reaches its highest value.\n", "\n", - "Let\u2019s explore the coefficient more systematically. We will keep the lens mass, mesh resolution, mask and noise map fixed, and reconstruct the source for a sequence of coefficients.\n", + "Let\u2019s explore the coefficient more systematically. We will keep the lens mass, mesh resolution, mask and noise map\n", + "fixed, and reconstruct the source for a sequence of coefficients.\n", "\n", - "Regularization coefficients can span several orders of magnitude, so we use logarithmically spaced values. This gives us comparable coverage between `0.01` and `0.1`, between `0.1` and `1.0`, and so on.\n", + "Regularization coefficients can span several orders of magnitude, so we use logarithmically spaced values. This\n", + "gives us comparable coverage between `0.01` and `0.1`, between `0.1` and `1.0`, and so on.\n", "\n", - "Every point in this experiment requires a new source reconstruction. We are not taking one reconstructed source and smoothing it by different amounts afterwards. The coefficient changes the problem that the inversion solves." + "Every point in this experiment requires a new source reconstruction. We are not taking one reconstructed source and\n", + "smoothing it by different amounts afterwards. The coefficient changes the problem that the inversion solves." ] }, { @@ -502,19 +558,26 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Look for the part of the curve where the evidence is highest. Moving towards weaker regularization gives the source more freedom; moving towards stronger regularization increasingly restricts its variations.\n", + "Look for the part of the curve where the evidence is highest. Moving towards weaker regularization gives the source\n", + "more freedom; moving towards stronger regularization increasingly restricts its variations.\n", "\n", - "We may find a clear peak, a broad region with similar evidence, or a highest value at one end of the range. These outcomes mean different things. A boundary maximum tells us that this experiment has not bracketed the preferred coefficient\u2014we should extend the range before claiming to have located it.\n", + "We may find a clear peak, a broad region with similar evidence, or a highest value at one end of the range. These\n", + "outcomes mean different things. A boundary maximum tells us that this experiment has not bracketed the preferred\n", + "coefficient\u2014we should extend the range before claiming to have located it.\n", "\n", - "The plotted points are also discrete samples. Even an interior maximum only identifies the best coefficient we have tried so far.\n", + "The plotted points are also discrete samples. Even an interior maximum only identifies the best coefficient we have\n", + "tried so far.\n", "\n", "__Inspecting the preferred reconstruction__\n", "\n", "Let\u2019s inspect the reconstruction with the highest evidence in our sampled range.\n", "\n", - "It is tempting to treat the highest number as the end of the analysis. However, we should connect that number back to the source and image. We want to understand what this choice preserves, what it smooths away, and what the resulting model still fails to explain.\n", + "It is tempting to treat the highest number as the end of the analysis. However, we should connect that number back\n", + "to the source and image. We want to understand what this choice preserves, what it smooths away, and what the\n", + "resulting model still fails to explain.\n", "\n", - "Compare it with the weakly and strongly regularized examples. In particular, examine the distinct bright source components and the faint regions between them. Then look at the image residuals where those components are lensed." + "Compare it with the weakly and strongly regularized examples. In particular, examine the distinct bright source\n", + "components and the faint regions between them. Then look at the image residuals where those components are lensed." ] }, { @@ -559,21 +622,31 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "A preferred coefficient does not establish that every visible feature in the source is real. The reconstruction remains conditional on the lens model, source mesh, noise map and telescope blurring.\n", + "A preferred coefficient does not establish that every visible feature in the source is real. The reconstruction\n", + "remains conditional on the lens model, source mesh, noise map and telescope blurring.\n", "\n", - "Nor does a good-looking source excuse coherent residuals in the image. The source and residual plots provide complementary information: one shows what we inferred, while the other shows what that inference leaves unexplained.\n", + "Nor does a good-looking source excuse coherent residuals in the image. The source and residual plots provide\n", + "complementary information: one shows what we inferred, while the other shows what that inference leaves\n", + "unexplained.\n", "\n", - "**\ud83e\udd16 Ask AI:** If the evidence prefers a particular regularization coefficient but the residuals still follow the shape of an arc, what modelling assumptions should I investigate next?\n", + "**\ud83e\udd16 Ask AI:** If the evidence prefers a particular regularization coefficient but the residuals still follow the\n", + "shape of an arc, what modelling assumptions should I investigate next?\n", "\n", "__What is linear, and what requires a search?__\n", "\n", "Before going further, let\u2019s separate two parts of the calculation that are easy to confuse.\n", "\n", - "For each coefficient we supplied, the inversion solved for the source brightnesses. We did not give a non-linear search hundreds of independent source brightness parameters and ask it to explore their possible combinations. Instead, the source enters the predicted image linearly, allowing these brightnesses to be solved together using linear algebra.\n", + "For each coefficient we supplied, the inversion solved for the source brightnesses. We did not give a non-linear\n", + "search hundreds of independent source brightness parameters and ask it to explore their possible combinations.\n", + "Instead, the source enters the predicted image linearly, allowing these brightnesses to be solved together using\n", + "linear algebra.\n", "\n", - "Regularization is included in that solve. The source is not first reconstructed without a prior and then smoothed afterwards. The inferred brightnesses already reflect the balance between fitting the image and satisfying the smoothness prior.\n", + "Regularization is included in that solve. The source is not first reconstructed without a prior and then smoothed\n", + "afterwards. The inferred brightnesses already reflect the balance between fitting the image and satisfying the\n", + "smoothness prior.\n", "\n", - "Choosing the regularization coefficient is a different problem. We supplied several coefficients, performed an inversion for each, and compared their evidence values. Our loop is a simple grid search over one quantity.\n", + "Choosing the regularization coefficient is a different problem. We supplied several coefficients, performed an\n", + "inversion for each, and compared their evidence values. Our loop is a simple grid search over one quantity.\n", "\n", "We can see the difference in scale directly:" ] @@ -598,9 +671,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The reconstruction contains an entry for each source mesh point in this single-mapper example. Some values may be constrained to zero at the mesh boundary, and regularization couples neighbouring values, so the number of entries is not the number of independently constrained source features.\n", + "The reconstruction contains an entry for each source mesh point in this single-mapper example. Some values may be\n", + "constrained to zero at the mesh boundary, and regularization couples neighbouring values, so the number of entries\n", + "is not the number of independently constrained source features.\n", "\n", - "During lens modelling, the search also changes the mass parameters. Each proposed mass model changes the ray tracing and therefore the mappings between source and image. The source must be reconstructed again for that proposal.\n", + "During lens modelling, the search also changes the mass parameters. Each proposed mass model changes the ray\n", + "tracing and therefore the mappings between source and image. The source must be reconstructed again for that\n", + "proposal.\n", "\n", "The sequence is therefore:\n", "\n", @@ -609,17 +686,23 @@ "3. Solve for the source brightnesses.\n", "4. Evaluate how well that model explains the data, accounting for the source prior.\n", "\n", - "This is what makes pixelized sources practical: the search explores the non-linear model choices, while the inversion handles the many source brightness values.\n", + "This is what makes pixelized sources practical: the search explores the non-linear model choices, while the\n", + "inversion handles the many source brightness values.\n", "\n", "__Mesh resolution and regularization belong together__\n", "\n", "We have held the source mesh at `(25, 25)`. The preferred coefficient we found belongs to that choice of mesh.\n", "\n", - "Changing the mesh changes the locations and number of source brightness values, their neighbours, and how they contribute to the image. The same numerical coefficient therefore need not give an equivalent amount of smoothing on another mesh.\n", + "Changing the mesh changes the locations and number of source brightness values, their neighbours, and how they\n", + "contribute to the image. The same numerical coefficient therefore need not give an equivalent amount of smoothing\n", + "on another mesh.\n", "\n", - "This matters when testing resolution. If we increase the number of source points but keep the coefficient fixed, any change in the reconstruction reflects both the new resolution and its interaction with the prior. We cannot assume that we have made a fair comparison of the best reconstructions available at each resolution.\n", + "This matters when testing resolution. If we increase the number of source points but keep the coefficient fixed,\n", + "any change in the reconstruction reflects both the new resolution and its interaction with the prior. We cannot\n", + "assume that we have made a fair comparison of the best reconstructions available at each resolution.\n", "\n", - "Let\u2019s repeat the coefficient experiment for `(15, 15)` and `(35, 35)`, alongside our existing `(25, 25)` results. We extend our helper so the mesh shape is an explicit input." + "Let\u2019s repeat the coefficient experiment for `(15, 15)` and `(35, 35)`, alongside our existing `(25, 25)` results.\n", + "We extend our helper so the mesh shape is an explicit input." ] }, { @@ -693,21 +776,30 @@ "source": [ "This experiment performs 26 additional reconstructions, so it takes longer than our earlier three-way comparison.\n", "\n", - "Look at both the locations and heights of the curves\u2019 maxima. The preferred coefficient may shift as the mesh changes. A finer mesh may help describe source structure, but adding points does not guarantee a higher evidence.\n", + "Look at both the locations and heights of the curves\u2019 maxima. The preferred coefficient may shift as the mesh\n", + "changes. A finer mesh may help describe source structure, but adding points does not guarantee a higher evidence.\n", "\n", - "All three curves use the same image pixels and noise model. We also subtract one common reference evidence, preserving differences between the meshes. Subtracting each curve\u2019s own maximum would hide those differences.\n", + "All three curves use the same image pixels and noise model. We also subtract one common reference evidence,\n", + "preserving differences between the meshes. Subtracting each curve\u2019s own maximum would hide those differences.\n", "\n", - "As before, a boundary maximum means that the coefficient range needs extending. These are controlled resolution checks, not a demonstration that mesh dimensions should become free parameters in every lens-model search.\n", + "As before, a boundary maximum means that the coefficient range needs extending. These are controlled resolution\n", + "checks, not a demonstration that mesh dimensions should become free parameters in every lens-model search.\n", "\n", "__Wrap Up__\n", "\n", "We can now give the regularization input a more meaningful interpretation.\n", "\n", - "The source mesh supplies brightness values that can vary to explain the image. Interpolation defines the brightness between those values. Regularization places a prior on their variation, discouraging unnecessary differences between neighbours.\n", + "The source mesh supplies brightness values that can vary to explain the image. Interpolation defines the brightness\n", + "between those values. Regularization places a prior on their variation, discouraging unnecessary differences\n", + "between neighbours.\n", "\n", - "Too little regularization can allow the reconstruction to explain noise through spurious source structure. Too much can suppress real structure and leave it visible in the image residuals. Evidence helps compare these choices by accounting for both image agreement and the freedom allowed by the source prior.\n", + "Too little regularization can allow the reconstruction to explain noise through spurious source structure. Too much\n", + "can suppress real structure and leave it visible in the image residuals. Evidence helps compare these choices by\n", + "accounting for both image agreement and the freedom allowed by the source prior.\n", "\n", - "We also saw that the coefficient is not a universal setting. Its appropriate value depends on the dataset, lens model, mesh and regularization scheme. A value that works for one reconstruction should not simply be carried into another analysis without checking it.\n", + "We also saw that the coefficient is not a universal setting. Its appropriate value depends on the dataset, lens\n", + "model, mesh and regularization scheme. A value that works for one reconstruction should not simply be carried into\n", + "another analysis without checking it.\n", "\n", "For a final comparison, print the preferred sampled coefficient for each mesh:" ] @@ -738,11 +830,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Throughout this tutorial, we fixed the lens mass to the simulation values. We have selected source-reconstruction settings under that assumption; we have not inferred the mass or its uncertainty.\n", + "Throughout this tutorial, we fixed the lens mass to the simulation values. We have selected source-reconstruction\n", + "settings under that assumption; we have not inferred the mass or its uncertainty.\n", "\n", - "Later, these source reconstructions will sit inside a lens-model search. Before that, the next tutorial examines another practical issue: how the source mesh covers the ray-traced image coordinates, and why a small number of extreme coordinates can affect the resolution available to reconstruct the source.\n", + "Later, these source reconstructions will sit inside a lens-model search. Before that, the next tutorial examines\n", + "another practical issue: how the source mesh covers the ray-traced image coordinates, and why a small number of\n", + "extreme coordinates can affect the resolution available to reconstruct the source.\n", "\n", - "For readers who want the underlying equations, the workspace\u2019s [pixelization likelihood guide](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/likelihood_function.py) follows the mapping, blurring, regularization and evidence calculations step by step. That derivation complements the experiments here; it is not required to continue using pixelizations." + "For readers who want the underlying equations, the workspace\u2019s [pixelization likelihood\n", + "guide](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/likelihood_function.py)\n", + "follows the mapping, blurring, regularization and evidence calculations step by step. That derivation complements\n", + "the experiments here; it is not required to continue using pixelizations." ] } ], diff --git a/notebooks/chapter_3_pixelizations/tutorial_3_borders.ipynb b/notebooks/chapter_3_pixelizations/tutorial_3_borders.ipynb index f7fd667..cc1c183 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_3_borders.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_3_borders.ipynb @@ -18,7 +18,23 @@ "- Switching border relocation on\n", "- What relocation changes\u2014and what it does not\n", "- The mask still needs to cover the lensed source\n", - "- Wrap up" + "- Wrap up\n", + "\n", + "__Why the extent of the source mesh matters__\n", + "\n", + "In the previous tutorials, we chose how many points our rectangular source mesh contained. However, the number of\n", + "points is only part of what determines its resolution. We also need to consider how much of the source plane those\n", + "points cover.\n", + "\n", + "A `(25, 25)` mesh spread across a small source region can describe finer structure than the same mesh spread across\n", + "a much larger region. If a few ray-traced coordinates extend far beyond the source, the mesh can expand to\n", + "accommodate them, leaving fewer points where we actually need to reconstruct the galaxy.\n", + "\n", + "This tutorial examines how that happens and introduces the border relocator, which provides a practical way to\n", + "control these extreme coordinates.\n", + "\n", + "We return to a simpler simulated source so that its morphology does not distract from the geometry. The image\n", + "contains lensed source light but no foreground lens light." ] }, { @@ -59,21 +75,6 @@ "_setup_colab.setup(\"howtolens\")" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Why the extent of the source mesh matters__\n", - "\n", - "In the previous tutorials, we chose how many points our rectangular source mesh contained. However, the number of points is only part of what determines its resolution. We also need to consider how much of the source plane those points cover.\n", - "\n", - "A `(25, 25)` mesh spread across a small source region can describe finer structure than the same mesh spread across a much larger region. If a few ray-traced coordinates extend far beyond the source, the mesh can expand to accommodate them, leaving fewer points where we actually need to reconstruct the galaxy.\n", - "\n", - "This tutorial examines how that happens and introduces the border relocator, which provides a practical way to control these extreme coordinates.\n", - "\n", - "We return to a simpler simulated source so that its morphology does not distract from the geometry. The image contains lensed source light but no foreground lens light." - ] - }, { "cell_type": "code", "metadata": {}, @@ -118,13 +119,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We will compare two masks with the same outer radius. One includes the centre of the image; the other excludes it. This lets us see what happens when the central image pixels enter the reconstruction.\n", + "We will compare two masks with the same outer radius. One includes the centre of the image; the other excludes it.\n", + "This lets us see what happens when the central image pixels enter the reconstruction.\n", "\n", "__What we mean by a border__\n", "\n", "The border is the outermost boundary of the unmasked image region.\n", "\n", - "For a circular mask, this is straightforward: the border follows the outside of the circle. An annular mask has an inner and an outer edge, but the border used here follows the outer edge. The hole in the middle does not become a second outer border.\n", + "For a circular mask, this is straightforward: the border follows the outside of the circle. An annular mask has an\n", + "inner and an outer edge, but the border used here follows the outer edge. The hole in the middle does not become a\n", + "second outer border.\n", "\n", "Let\u2019s plot both masks and mark their border coordinates." ] @@ -169,15 +173,20 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The outer borders should coincide because the masks share the same outer radius. The difference is inside: the circular mask includes image pixels near the lens centre that the annular mask removes.\n", + "The outer borders should coincide because the masks share the same outer radius. The difference is inside: the\n", + "circular mask includes image pixels near the lens centre that the annular mask removes.\n", "\n", - "We will keep the masks fixed while comparing the source-plane grids. Choosing the mask and relocating a border are different operations: the mask selects which image pixels enter the fit, while relocation changes how certain coordinates are treated when constructing the source reconstruction.\n", + "We will keep the masks fixed while comparing the source-plane grids. Choosing the mask and relocating a border are\n", + "different operations: the mask selects which image pixels enter the fit, while relocation changes how certain\n", + "coordinates are treated when constructing the source reconstruction.\n", "\n", "__Starting without border relocation__\n", "\n", "First, let\u2019s reconstruct the source using the annular mask with border relocation explicitly switched off.\n", "\n", - "We use the mass model that generated the simulation and a uniform rectangular source mesh. The helper below lets us change the mask and relocation setting while keeping the lens model, mesh shape and regularization coefficient unchanged." + "We use the mass model that generated the simulation and a uniform rectangular source mesh. The helper below lets us\n", + "change the mask and relocation setting while keeping the lens model, mesh shape and regularization coefficient\n", + "unchanged." ] }, { @@ -263,15 +272,18 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The first plot shows where the image coordinates land after ray tracing. The second shows the source mesh and the brightnesses inferred on it.\n", + "The first plot shows where the image coordinates land after ray tracing. The second shows the source mesh and the\n", + "brightnesses inferred on it.\n", "\n", - "Look at the coordinate ranges as well as the source itself. These tell us how much source-plane area the mesh is covering. We will use this reconstruction as a reference when we add the central image pixels.\n", + "Look at the coordinate ranges as well as the source itself. These tell us how much source-plane area the mesh is\n", + "covering. We will use this reconstruction as a reference when we add the central image pixels.\n", "\n", "__Including the central image pixels__\n", "\n", "Now repeat the calculation with the circular mask, still without border relocation.\n", "\n", - "The outer image boundary is unchanged. We are adding the pixels within the central hole of the annulus, rather than extending the image to larger radii." + "The outer image boundary is unchanged. We are adding the pixels within the central hole of the annulus, rather than\n", + "extending the image to larger radii." ] }, { @@ -318,19 +330,24 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Compare the source-plane extent with the annular case. The added image pixels can trace outside the compact region occupied by the other coordinates, causing the rectangular mesh to cover a larger area.\n", + "Compare the source-plane extent with the annular case. The added image pixels can trace outside the compact region\n", + "occupied by the other coordinates, causing the rectangular mesh to cover a larger area.\n", "\n", - "Both reconstructions still use the same number of mesh points. If the mesh expands, their spacing increases, reducing the resolution available to describe the central source.\n", + "Both reconstructions still use the same number of mesh points. If the mesh expands, their spacing increases,\n", + "reducing the resolution available to describe the central source.\n", "\n", - "This illustrates why increasing the number of image pixels does not automatically improve a reconstruction with a fixed mesh. We must also consider how those pixels affect the source-plane coverage.\n", + "This illustrates why increasing the number of image pixels does not automatically improve a reconstruction with a\n", + "fixed mesh. We must also consider how those pixels affect the source-plane coverage.\n", "\n", - "The two masks contain different data, so this is a geometric comparison\u2014not a direct evidence comparison between otherwise identical fits.\n", + "The two masks contain different data, so this is a geometric comparison\u2014not a direct evidence comparison between\n", + "otherwise identical fits.\n", "\n", "__Following the central pixels into the source plane__\n", "\n", "Let\u2019s confirm where the extra source-plane coordinates come from.\n", "\n", - "We select two small groups of image pixels: one close to the lens centre and another near the lensed arc. As in tutorial 1, we use the same index groups in both planes, so matching colours identify the same light paths." + "We select two small groups of image pixels: one close to the lens centre and another near the lensed arc. As in\n", + "tutorial 1, we use the same index groups in both planes, so matching colours identify the same light paths." ] }, { @@ -381,25 +398,38 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The central image coordinates need not map close to the source-plane origin. Their source positions depend on the difference between their image positions and the lens deflections.\n", + "The central image coordinates need not map close to the source-plane origin. Their source positions depend on the\n", + "difference between their image positions and the lens deflections.\n", "\n", - "Near the centre of a cuspy mass distribution, a small image region can correspond to a much larger source region. This is demagnification: the image occupies less area than the corresponding source region. It does not require the deflection angle itself to become arbitrarily large.\n", + "Near the centre of a cuspy mass distribution, a small image region can correspond to a much larger source region.\n", + "This is demagnification: the image occupies less area than the corresponding source region. It does not require the\n", + "deflection angle itself to become arbitrarily large.\n", "\n", - "For our reconstruction, the practical consequence is that central image pixels can map well outside the region traced by the arcs. The mesh then spends some of its resolution covering those distant positions.\n", + "For our reconstruction, the practical consequence is that central image pixels can map well outside the region\n", + "traced by the arcs. The mesh then spends some of its resolution covering those distant positions.\n", "\n", - "There is another concern. Source structure reconstructed at those positions may predict other images outside our chosen mask, where we are not comparing the model with the data. The reconstruction is then missing some of the observational constraints that would otherwise act on that structure.\n", + "There is another concern. Source structure reconstructed at those positions may predict other images outside our\n", + "chosen mask, where we are not comparing the model with the data. The reconstruction is then missing some of the\n", + "observational constraints that would otherwise act on that structure.\n", "\n", - "In the next blocks, we will trace the outer border into the source plane and examine how border relocation handles coordinates beyond it. We will compare the same circularly masked dataset with relocation switched off and on, so that the effect of relocation is isolated.\n", + "In the next blocks, we will trace the outer border into the source plane and examine how border relocation handles\n", + "coordinates beyond it. We will compare the same circularly masked dataset with relocation switched off and on, so\n", + "that the effect of relocation is isolated.\n", "\n", - "**\ud83e\udd16 Ask AI:** Why can a small group of central image pixels change the resolution of a rectangular source mesh, even when most of the observed source light lies in the arcs?\n", + "**\ud83e\udd16 Ask AI:** Why can a small group of central image pixels change the resolution of a rectangular source mesh,\n", + "even when most of the observed source light lies in the arcs?\n", "\n", "__Tracing the outer border__\n", "\n", - "We have seen that some central image pixels trace beyond the compact source region. To decide how to handle those coordinates, we first need a reference boundary in the source plane.\n", + "We have seen that some central image pixels trace beyond the compact source region. To decide how to handle those\n", + "coordinates, we first need a reference boundary in the source plane.\n", "\n", - "We obtain this from the outer border of the image mask. These are ordinary image coordinates, so we can ray-trace them through the same lens model as every other pixel. Their traced positions describe where the edge of our fitted image region maps into the source plane.\n", + "We obtain this from the outer border of the image mask. These are ordinary image coordinates, so we can ray-trace\n", + "them through the same lens model as every other pixel. Their traced positions describe where the edge of our fitted\n", + "image region maps into the source plane.\n", "\n", - "Let\u2019s highlight the border pixels in the image and follow the same indexes into the source plane. Border relocation is still switched off here, so we are looking at the original ray-traced coordinates." + "Let\u2019s highlight the border pixels in the image and follow the same indexes into the source plane. Border relocation\n", + "is still switched off here, so we are looking at the original ray-traced coordinates." ] }, { @@ -428,17 +458,22 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Compare the highlighted border with the central image pixels traced in the previous block. Some image coordinates that were well inside the image mask can land beyond the traced outer border in the source plane.\n", + "Compare the highlighted border with the central image pixels traced in the previous block. Some image coordinates\n", + "that were well inside the image mask can land beyond the traced outer border in the source plane.\n", "\n", - "This is the important geometric distinction: being inside the image-plane border does not guarantee that a coordinate remains inside its traced counterpart.\n", + "This is the important geometric distinction: being inside the image-plane border does not guarantee that a\n", + "coordinate remains inside its traced counterpart.\n", "\n", - "The border relocator uses the traced outer-border coordinates to estimate a source-plane boundary. In the current implementation, this is an ellipse. Coordinates beyond that boundary are moved inward for the source reconstruction, preventing them from extending its coverage unchecked.\n", + "The border relocator uses the traced outer-border coordinates to estimate a source-plane boundary. In the current\n", + "implementation, this is an ellipse. Coordinates beyond that boundary are moved inward for the source\n", + "reconstruction, preventing them from extending its coverage unchecked.\n", "\n", "__Switching border relocation on__\n", "\n", "Let\u2019s repeat the circular-mask fit with border relocation enabled.\n", "\n", - "The data, mask, lens mass, mesh shape and regularization coefficient all remain unchanged. This time, the source mesh is constructed using the relocated coordinates." + "The data, mask, lens mass, mesh shape and regularization coefficient all remain unchanged. This time, the source\n", + "mesh is constructed using the relocated coordinates." ] }, { @@ -478,9 +513,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Follow the same coloured coordinate groups through the two plots. Coordinates outside the estimated boundary are relocated towards it; those inside remain unchanged.\n", + "Follow the same coloured coordinate groups through the two plots. Coordinates outside the estimated boundary are\n", + "relocated towards it; those inside remain unchanged.\n", "\n", - "If relocation reduces the mesh extent, the same number of source points now covers a smaller area. This can restore resolution in the region where the source is being reconstructed, without increasing the mesh dimensions.\n", + "If relocation reduces the mesh extent, the same number of source points now covers a smaller area. This can restore\n", + "resolution in the region where the source is being reconstructed, without increasing the mesh dimensions.\n", "\n", "We can also identify which coordinates moved and display their positions before and after relocation." ] @@ -525,13 +562,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "These are still the same image pixels with the same measured brightnesses. Relocation changes their source-plane mapping coordinates; it does not remove them from the fit or move their positions in the observed image.\n", + "These are still the same image pixels with the same measured brightnesses. Relocation changes their source-plane\n", + "mapping coordinates; it does not remove them from the fit or move their positions in the observed image.\n", "\n", "__What relocation changes\u2014and what it does not__\n", "\n", - "Border relocation is a numerical treatment of the source reconstruction. It does not change the lens mass profile or the physical deflection calculation.\n", + "Border relocation is a numerical treatment of the source reconstruction. It does not change the lens mass profile\n", + "or the physical deflection calculation.\n", "\n", - "That distinction matters. If we ray-trace the image grid directly through the tracer, we recover the original source coordinates. The mapper used by the relocated inversion instead contains the coordinates after the border treatment.\n", + "That distinction matters. If we ray-trace the image grid directly through the tracer, we recover the original\n", + "source coordinates. The mapper used by the relocated inversion instead contains the coordinates after the border\n", + "treatment.\n", "\n", "Let\u2019s compare these explicitly." ] @@ -572,9 +613,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We should therefore understand relocation as a practical boundary treatment, not an alternative physical lens equation. It controls how extreme coordinates participate in a reconstruction whose image coverage is finite.\n", + "We should therefore understand relocation as a practical boundary treatment, not an alternative physical lens\n", + "equation. It controls how extreme coordinates participate in a reconstruction whose image coverage is finite.\n", "\n", - "The next step is to inspect its effect on the inferred source and the model image. We use a common source colour scale so that changes in brightness are not hidden by separately scaled figures." + "The next step is to inspect its effect on the inferred source and the model image. We use a common source colour\n", + "scale so that changes in brightness are not hidden by separately scaled figures." ] }, { @@ -617,19 +660,25 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Look for changes in the mesh coverage, the source structure and the residuals. A more compact mesh alone does not prove that the model is accurate, and relocation does not guarantee freedom from systematic errors.\n", + "Look for changes in the mesh coverage, the source structure and the residuals. A more compact mesh alone does not\n", + "prove that the model is accurate, and relocation does not guarantee freedom from systematic errors.\n", "\n", - "We have also kept the regularization coefficient fixed to isolate the change in configuration. As tutorial 2 showed, changing mesh geometry can alter how regularization acts, so this is a diagnostic comparison rather than a complete optimization of both reconstructions.\n", + "We have also kept the regularization coefficient fixed to isolate the change in configuration. As tutorial 2\n", + "showed, changing mesh geometry can alter how regularization acts, so this is a diagnostic comparison rather than a\n", + "complete optimization of both reconstructions.\n", "\n", "__The mask still needs to cover the lensed source__\n", "\n", "Border relocation does not replace choosing an appropriate image mask.\n", "\n", - "If the mask excludes part of an arc or another image of the source, those pixels do not constrain the reconstruction. Relocating source coordinates cannot recover information that we have excluded from the fit.\n", + "If the mask excludes part of an arc or another image of the source, those pixels do not constrain the\n", + "reconstruction. Relocating source coordinates cannot recover information that we have excluded from the fit.\n", "\n", - "The mask also determines the border from which the source-plane boundary is estimated. Changing its size therefore changes both the image pixels being fitted and the boundary treatment.\n", + "The mask also determines the border from which the source-plane boundary is estimated. Changing its size therefore\n", + "changes both the image pixels being fitted and the boundary treatment.\n", "\n", - "Let\u2019s inspect several circular masks before fitting them. We plot their borders on the full image so that any source light outside the selected region remains visible." + "Let\u2019s inspect several circular masks before fitting them. We plot their borders on the full image so that any\n", + "source light outside the selected region remains visible." ] }, { @@ -661,7 +710,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Check whether each border encloses the visible lensed emission with some surrounding background. A mask that follows only the brightest parts can exclude faint extensions that still matter to the reconstruction.\n", + "Check whether each border encloses the visible lensed emission with some surrounding background. A mask that\n", + "follows only the brightest parts can exclude faint extensions that still matter to the reconstruction.\n", "\n", "Now compare the resulting fits with relocation enabled." ] @@ -699,21 +749,32 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Compare the source structure and residuals, especially where a smaller mask approaches the arcs. If the reconstruction changes substantially as clearly relevant source light enters the mask, the smaller-mask result deserves closer inspection.\n", + "Compare the source structure and residuals, especially where a smaller mask approaches the arcs. If the\n", + "reconstruction changes substantially as clearly relevant source light enters the mask, the smaller-mask result\n", + "deserves closer inspection.\n", "\n", - "Do not rank these masks by their raw evidence values: they contain different sets of image pixels. The purpose here is to examine coverage and stability, not to select whichever mask produces the largest number.\n", + "Do not rank these masks by their raw evidence values: they contain different sets of image pixels. The purpose here\n", + "is to examine coverage and stability, not to select whichever mask produces the largest number.\n", "\n", - "**\ud83e\udd16 Ask AI:** Why can a reconstruction appear satisfactory inside a small mask while failing to explain other visible parts of the same lensed source?\n", + "**\ud83e\udd16 Ask AI:** Why can a reconstruction appear satisfactory inside a small mask while failing to explain other\n", + "visible parts of the same lensed source?\n", "\n", "__Wrap up__\n", "\n", - "We began with a rectangular source mesh whose resolution depended on both its number of points and the area they covered. A small number of extreme ray-traced coordinates could expand that area and reduce the resolution available for the source.\n", + "We began with a rectangular source mesh whose resolution depended on both its number of points and the area they\n", + "covered. A small number of extreme ray-traced coordinates could expand that area and reduce the resolution\n", + "available for the source.\n", "\n", - "The border relocator uses the traced outer image border to estimate a source-plane boundary, then moves coordinates beyond that boundary inward for the reconstruction. The observed image pixels remain in the fit, and the physical lens model is unchanged.\n", + "The border relocator uses the traced outer image border to estimate a source-plane boundary, then moves coordinates\n", + "beyond that boundary inward for the reconstruction. The observed image pixels remain in the fit, and the physical\n", + "lens model is unchanged.\n", "\n", - "In routine modelling, we normally leave this treatment enabled. Knowing what it does is useful when a source mesh extends unexpectedly far from the reconstructed galaxy, or when a reconstruction changes strongly with the mask.\n", + "In routine modelling, we normally leave this treatment enabled. Knowing what it does is useful when a source mesh\n", + "extends unexpectedly far from the reconstructed galaxy, or when a reconstruction changes strongly with the mask.\n", "\n", - "These issues can also occur in systems with several lens galaxies. Extreme coordinates need not originate only near the centre of the image; they can be associated with other mass concentrations. The same diagnostic applies: follow the image coordinates into the source plane and inspect the boundary and mesh coverage.\n", + "These issues can also occur in systems with several lens galaxies. Extreme coordinates need not originate only near\n", + "the centre of the image; they can be associated with other mass concentrations. The same diagnostic applies: follow\n", + "the image coordinates into the source plane and inspect the boundary and mesh coverage.\n", "\n", "For subsequent inspection, return to our circular mask with radius `2.5` arcsec and relocation enabled." ] @@ -744,9 +805,12 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We have now examined the source mesh, interpolation, regularization and border treatment while holding the lens mass fixed.\n", + "We have now examined the source mesh, interpolation, regularization and border treatment while holding the lens\n", + "mass fixed.\n", "\n", - "In the next tutorial, we let the mass model vary. We will see how a pixelized source participates in lens modelling, why its flexibility can admit misleading solutions, and how a sensible starting model helps the search find the relevant region of parameter space." + "In the next tutorial, we let the mass model vary. We will see how a pixelized source participates in lens\n", + "modelling, why its flexibility can admit misleading solutions, and how a sensible starting model helps the search\n", + "find the relevant region of parameter space." ] } ], diff --git a/notebooks/chapter_3_pixelizations/tutorial_4_lens_modeling.ipynb b/notebooks/chapter_3_pixelizations/tutorial_4_lens_modeling.ipynb index 70cd985..1c3bb74 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_4_lens_modeling.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_4_lens_modeling.ipynb @@ -20,7 +20,37 @@ "- Replacing the analytic source with a pixelization\n", "- Running the pixelized-source search\n", "- Establishing the foreground light model\n", - "- Using that result in the pixelized-source fit" + "- Using that result in the pixelized-source fit\n", + "\n", + "__Lens modelling with a pixelized source__\n", + "\n", + "So far, we have reconstructed sources while keeping the lens mass fixed. We could therefore concentrate on the\n", + "mesh, mappings and regularization without worrying about whether the lens model itself was correct.\n", + "\n", + "In a scientific analysis, the mass distribution is usually one of the things we want to measure. Changing it\n", + "changes the ray tracing, which changes how the source must be reconstructed to explain the image.\n", + "\n", + "Pixelizations are powerful here because they can describe complicated source structure without requiring us to\n", + "specify a separate analytic profile for every bright component. The non-linear search explores the lens parameters\n", + "and regularization settings, while the inversion solves for the source brightnesses.\n", + "\n", + "However, this flexibility comes with a difficulty. An incorrect mass model can sometimes be compensated for by an\n", + "unusual source reconstruction. A close fit to the image does not, by itself, establish that we have found the right\n", + "mass distribution.\n", + "\n", + "We will investigate this using the familiar simulated lens with no foreground light. Its true Einstein radius is\n", + "`1.6` arcsec, giving us a reference against which to compare deliberately incorrect models.\n", + "\n", + "The published example below makes this ambiguity visible before we explore it in code. Compare the reconstructed\n", + "source structures with their corresponding image fits: a model can describe much of the observed image while\n", + "assigning it a very different source morphology.\n", + "\n", + "![Demagnified source solutions, Figure 1 of Maresca et\n", + "al.](https://raw.githubusercontent.com/PyAutoLabs/HowToLens/main/scripts/chapter_3_pixelizations/images/maresca_fig1.png)\n", + "\n", + "Figure 1 from [Maresca et al. (2021)](https://arxiv.org/abs/2012.04665), also discussed in the [PyAutoLens\n", + "demagnified-solutions guide](https://pyautolens.readthedocs.io/en/latest/general/demagnified_solutions.html). We\n", + "reproduce this figure to illustrate the ambiguity; the experiments below use our own simulated dataset." ] }, { @@ -61,29 +91,6 @@ "_setup_colab.setup(\"howtolens\")" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Lens modelling with a pixelized source__\n", - "\n", - "So far, we have reconstructed sources while keeping the lens mass fixed. We could therefore concentrate on the mesh, mappings and regularization without worrying about whether the lens model itself was correct.\n", - "\n", - "In a scientific analysis, the mass distribution is usually one of the things we want to measure. Changing it changes the ray tracing, which changes how the source must be reconstructed to explain the image.\n", - "\n", - "Pixelizations are powerful here because they can describe complicated source structure without requiring us to specify a separate analytic profile for every bright component. The non-linear search explores the lens parameters and regularization settings, while the inversion solves for the source brightnesses.\n", - "\n", - "However, this flexibility comes with a difficulty. An incorrect mass model can sometimes be compensated for by an unusual source reconstruction. A close fit to the image does not, by itself, establish that we have found the right mass distribution.\n", - "\n", - "We will investigate this using the familiar simulated lens with no foreground light. Its true Einstein radius is `1.6` arcsec, giving us a reference against which to compare deliberately incorrect models.\n", - "\n", - "The published example below makes this ambiguity visible before we explore it in code. Compare the reconstructed source structures with their corresponding image fits: a model can describe much of the observed image while assigning it a very different source morphology.\n", - "\n", - "![Demagnified source solutions, Figure 1 of Maresca et al.](https://raw.githubusercontent.com/PyAutoLabs/HowToLens/main/scripts/chapter_3_pixelizations/images/maresca_fig1.png)\n", - "\n", - "Figure 1 from [Maresca et al. (2021)](https://arxiv.org/abs/2012.04665), also discussed in the [PyAutoLens demagnified-solutions guide](https://pyautolens.readthedocs.io/en/latest/general/demagnified_solutions.html). We reproduce this figure to illustrate the ambiguity; the experiments below use our own simulated dataset." - ] - }, { "cell_type": "code", "metadata": {}, @@ -134,15 +141,19 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We retain one sample per image pixel for the indexed mapping demonstration below. As before, the sampling accuracy would need checking before interpreting a scientific fit.\n", + "We retain one sample per image pixel for the indexed mapping demonstration below. As before, the sampling accuracy\n", + "would need checking before interpreting a scientific fit.\n", "\n", "__Giving the inversion an incorrect mass model__\n", "\n", "Let\u2019s begin with a mass model whose Einstein radius is `0.8` arcsec\u2014half the value used in the simulation.\n", "\n", - "Everything else remains fixed, including the mass ellipticity, external shear, mesh dimensions and regularization coefficient. We then ask the inversion to reconstruct whatever source best satisfies this model\u2019s mappings and smoothness prior.\n", + "Everything else remains fixed, including the mass ellipticity, external shear, mesh dimensions and regularization\n", + "coefficient. We then ask the inversion to reconstruct whatever source best satisfies this model\u2019s mappings and\n", + "smoothness prior.\n", "\n", - "This is the kind of incorrect mass model that a non-linear search could encounter while exploring a broad parameter range." + "This is the kind of incorrect mass model that a non-linear search could encounter while exploring a broad parameter\n", + "range." ] }, { @@ -206,11 +217,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Inspect both the image residuals and the reconstructed source. The experiment is designed to show how an inversion can explain some of the observed structure even when the lens mass is substantially wrong.\n", + "Inspect both the image residuals and the reconstructed source. The experiment is designed to show how an inversion\n", + "can explain some of the observed structure even when the lens mass is substantially wrong.\n", "\n", - "Under insufficient deflection, parts of the observed arcs can remain separated in the source plane. Instead of reconstructing one compact galaxy whose light produces multiple images, the inversion can assign brightness to those separate source regions. The source may begin to resemble a less strongly lensed version of the observed image.\n", + "Under insufficient deflection, parts of the observed arcs can remain separated in the source plane. Instead of\n", + "reconstructing one compact galaxy whose light produces multiple images, the inversion can assign brightness to\n", + "those separate source regions. The source may begin to resemble a less strongly lensed version of the observed\n", + "image.\n", "\n", - "Such solutions are often called **demagnified solutions**. This is a different issue from the demagnified central image coordinates discussed in the borders tutorial: here, the problem concerns an alternative mass-and-source interpretation of the image.\n", + "Such solutions are often called **demagnified solutions**. This is a different issue from the demagnified central\n", + "image coordinates discussed in the borders tutorial: here, the problem concerns an alternative mass-and-source\n", + "interpretation of the image.\n", "\n", "Border relocation does not remove this modelling ambiguity.\n", "\n", @@ -218,7 +235,8 @@ "\n", "Now repeat the reconstruction with the Einstein radius restored to `1.6` arcsec.\n", "\n", - "The inversion still has the same mesh dimensions and regularization coefficient. Only the Einstein radius changes. This gives us a controlled comparison of how the mass model affects the source required to explain the image." + "The inversion still has the same mesh dimensions and regularization coefficient. Only the Einstein radius changes.\n", + "This gives us a controlled comparison of how the mass model affects the source required to explain the image." ] }, { @@ -261,9 +279,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Compare the source morphology and its coordinate extent. With the correct mass model, the different images of the source should be brought into a mutually consistent source reconstruction. With an incorrect mass model, the inversion may need more extended or fragmented structure to account for them.\n", + "Compare the source morphology and its coordinate extent. With the correct mass model, the different images of the\n", + "source should be brought into a mutually consistent source reconstruction. With an incorrect mass model, the\n", + "inversion may need more extended or fragmented structure to account for them.\n", "\n", - "This is where regularization and evidence become important. The inversion\u2019s flexibility does not mean that all source reconstructions are equally preferred. A reconstruction requiring large variations between neighbouring brightnesses is treated differently from one that explains the data with a smoother source.\n", + "This is where regularization and evidence become important. The inversion\u2019s flexibility does not mean that all\n", + "source reconstructions are equally preferred. A reconstruction requiring large variations between neighbouring\n", + "brightnesses is treated differently from one that explains the data with a smoother source.\n", "\n", "Let\u2019s compare image agreement and evidence directly." ] @@ -292,17 +314,22 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The expected lesson is that image agreement and source plausibility must be considered together. We should inspect the calculated evidence values rather than assume that the correct model wins by a particular amount.\n", + "The expected lesson is that image agreement and source plausibility must be considered together. We should inspect\n", + "the calculated evidence values rather than assume that the correct model wins by a particular amount.\n", "\n", - "We have also held the coefficient fixed. A full model search would allow regularization to change, so these two evaluations do not establish the final relative preference after all model parameters have been explored.\n", + "We have also held the coefficient fixed. A full model search would allow regularization to change, so these two\n", + "evaluations do not establish the final relative preference after all model parameters have been explored.\n", "\n", "__Seeing how the mass model changes the mappings__\n", "\n", "The source plots show the outcome, but the mappings help explain why it happens.\n", "\n", - "Let\u2019s select two small image regions on opposite sides of the lens and follow them into the source plane under each mass model. The image indexes stay the same: we are examining the same measured pixels through two different ray-tracing calculations.\n", + "Let\u2019s select two small image regions on opposite sides of the lens and follow them into the source plane under each\n", + "mass model. The image indexes stay the same: we are examining the same measured pixels through two different\n", + "ray-tracing calculations.\n", "\n", - "To isolate the physical ray tracing, we use the tracer directly. These plots show the coordinates before border relocation." + "To isolate the physical ray tracing, we use the tracer directly. These plots show the coordinates before border\n", + "relocation." ] }, { @@ -350,21 +377,30 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Look at the relative positions of the coloured groups. Changing the mass model changes whether image regions can be explained by nearby parts of the source or require brightness in more widely separated regions.\n", + "Look at the relative positions of the coloured groups. Changing the mass model changes whether image regions can be\n", + "explained by nearby parts of the source or require brightness in more widely separated regions.\n", "\n", - "These groups were chosen to illustrate the geometry, not identified as exact images of the same source feature. We should therefore not expect their traced coordinates to coincide perfectly, even for the correct model.\n", + "These groups were chosen to illustrate the geometry, not identified as exact images of the same source feature. We\n", + "should therefore not expect their traced coordinates to coincide perfectly, even for the correct model.\n", "\n", - "For a stronger constraint, we can identify image positions that genuinely correspond to the same source feature and require them to trace close together. We will introduce that idea when preparing the model search.\n", + "For a stronger constraint, we can identify image positions that genuinely correspond to the same source feature and\n", + "require them to trace close together. We will introduce that idea when preparing the model search.\n", "\n", - "**\ud83e\udd16 Ask AI:** How can an incorrect mass model still fit an arc if the source reconstruction is allowed to place light in several separate source regions?\n", + "**\ud83e\udd16 Ask AI:** How can an incorrect mass model still fit an arc if the source reconstruction is allowed to place\n", + "light in several separate source regions?\n", "\n", "__Why evidence does not remove the search difficulty__\n", "\n", - "Even if the correct mass model has higher evidence than our deliberately incorrect example, the non-linear search still has to find it.\n", + "Even if the correct mass model has higher evidence than our deliberately incorrect example, the non-linear search\n", + "still has to find it.\n", "\n", - "A pixelized source can provide tolerable image fits across a broad range of incorrect mass models. This can create competing regions of parameter space that require substantial exploration. Solving the source brightnesses efficiently does not make the remaining non-linear problem trivial or guarantee that a search finds the relevant solution.\n", + "A pixelized source can provide tolerable image fits across a broad range of incorrect mass models. This can create\n", + "competing regions of parameter space that require substantial exploration. Solving the source brightnesses\n", + "efficiently does not make the remaining non-linear problem trivial or guarantee that a search finds the relevant\n", + "solution.\n", "\n", - "Let\u2019s examine a simple slice through this problem by changing only the Einstein radius. At every value, we reconstruct a new source and calculate its evidence." + "Let\u2019s examine a simple slice through this problem by changing only the Einstein radius. At every value, we\n", + "reconstruct a new source and calculate its evidence." ] }, { @@ -427,25 +463,42 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "This scan shows how the evidence behaves along one restricted direction. It is not a posterior distribution or an uncertainty measurement: the other mass parameters and regularization coefficient remain fixed, and we have sampled only a few radii.\n", + "This scan shows how the evidence behaves along one restricted direction. It is not a posterior distribution or an\n", + "uncertainty measurement: the other mass parameters and regularization coefficient remain fixed, and we have sampled\n", + "only a few radii.\n", "\n", - "In a full search, those other parameters can vary together. An incorrect Einstein radius may be partly compensated for by changes in ellipticity, shear or source regularization, creating possibilities that this one-dimensional experiment cannot show.\n", + "In a full search, those other parameters can vary together. An incorrect Einstein radius may be partly compensated\n", + "for by changes in ellipticity, shear or source regularization, creating possibilities that this one-dimensional\n", + "experiment cannot show.\n", "\n", - "A useful strategy is therefore **search chaining**. We begin with a simpler source model to find a plausible region of lens parameter space, then introduce the pixelized source so that the detailed source structure can be reconstructed.\n", + "A useful strategy is therefore **search chaining**. We begin with a simpler source model to find a plausible region\n", + "of lens parameter space, then introduce the pixelized source so that the detailed source structure can be\n", + "reconstructed.\n", "\n", - "The initial analytic source is a starting point, not the final description of the galaxy. Its purpose is to help establish the lensing geometry without giving the source enough freedom to reproduce almost any image arrangement.\n", + "The initial analytic source is a starting point, not the final description of the galaxy. Its purpose is to help\n", + "establish the lensing geometry without giving the source enough freedom to reproduce almost any image arrangement.\n", "\n", - "In the next blocks, we will turn that idea into a model-search setup and explain how corresponding image positions can help reject misleading solutions. We will also introduce foreground lens light, which must be modelled alongside the pixelized source.\n", + "In the next blocks, we will turn that idea into a model-search setup and explain how corresponding image positions\n", + "can help reject misleading solutions. We will also introduce foreground lens light, which must be modelled\n", + "alongside the pixelized source.\n", "\n", "__Starting with a simpler source model__\n", "\n", - "The misleading reconstructions we have just examined arise because a pixelized source has enough freedom to compensate for some incorrect mass models.\n", + "The misleading reconstructions we have just examined arise because a pixelized source has enough freedom to\n", + "compensate for some incorrect mass models.\n", "\n", - "A useful starting point is therefore a source model with less freedom. We first fit an analytic light profile, using it to establish a plausible lensing geometry. Once that fit has identified a useful region of parameter space, we replace the analytic source with a pixelization.\n", + "A useful starting point is therefore a source model with less freedom. We first fit an analytic light profile,\n", + "using it to establish a plausible lensing geometry. Once that fit has identified a useful region of parameter\n", + "space, we replace the analytic source with a pixelization.\n", "\n", - "This is search chaining, introduced in chapter 2. Here, the reason for chaining is particularly important: we want the pixelized reconstruction to improve the description of the source without beginning its search among a wide range of unrelated mass-and-source configurations.\n", + "This is search chaining, introduced in chapter 2. Here, the reason for chaining is particularly important: we want\n", + "the pixelized reconstruction to improve the description of the source without beginning its search among a wide\n", + "range of unrelated mass-and-source configurations.\n", "\n", - "We use the multi-Gaussian expansion (MGE) from Chapter 2 as our baseline analytic source. Its fixed Gaussian widths and linearly solved intensities provide radial flexibility while a common centre and elliptical shape keep the geometry manageable. For a more complex galaxy, this first model may leave source structure unexplained. We would inspect those residuals and the inferred geometry before using it to initialize the next search." + "We use the multi-Gaussian expansion (MGE) from Chapter 2 as our baseline analytic source. Its fixed Gaussian widths\n", + "and linearly solved intensities provide radial flexibility while a common centre and elliptical shape keep the\n", + "geometry manageable. For a more complex galaxy, this first model may leave source structure unexplained. We would\n", + "inspect those residuals and the inferred geometry before using it to initialize the next search." ] }, { @@ -501,15 +554,20 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Unlike our earlier experiments, the Einstein radius, mass ellipticity and external shear are now free. The MGE group\u2019s common centre and elliptical shape are also free. Its Gaussian widths are fixed, and all Gaussian intensities are solved linearly.\n", + "Unlike our earlier experiments, the Einstein radius, mass ellipticity and external shear are now free. The MGE\n", + "group\u2019s common centre and elliptical shape are also free. Its Gaussian widths are fixed, and all Gaussian\n", + "intensities are solved linearly.\n", "\n", - "Inspect `model_1.info` to see the complete set of free parameters and their priors. The known simulation values provide a check on the result; they are not supplied as the answer to the search.\n", + "Inspect `model_1.info` to see the complete set of free parameters and their priors. The known simulation values\n", + "provide a check on the result; they are not supplied as the answer to the search.\n", "\n", "__Running and inspecting the initial search__\n", "\n", - "We now perform a model fit. For each proposal, the search changes the non-linear parameters, predicts the image and evaluates its agreement with the data.\n", + "We now perform a model fit. For each proposal, the search changes the non-linear parameters, predicts the image and\n", + "evaluates its agreement with the data.\n", "\n", - "This is different from calling `FitImaging` with specified parameter values. The search explores alternatives and produces samples that describe the inferred parameter distribution." + "This is different from calling `FitImaging` with specified parameter values. The search explores alternatives and\n", + "produces samples that describe the inferred parameter distribution." ] }, { @@ -545,23 +603,34 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Before continuing, inspect the model image, residuals and source. The purpose of this first fit is to establish a credible starting geometry, so a poor or clearly misleading solution should not simply be passed to the next search.\n", + "Before continuing, inspect the model image, residuals and source. The purpose of this first fit is to establish a\n", + "credible starting geometry, so a poor or clearly misleading solution should not simply be passed to the next\n", + "search.\n", "\n", - "For this simulated example, we can also compare the recovered Einstein radius with the input value of `1.6` arcsec. In an observed system, that answer would not be available; we would rely on the fit diagnostics, image configuration and parameter constraints.\n", + "For this simulated example, we can also compare the recovered Einstein radius with the input value of `1.6` arcsec.\n", + "In an observed system, that answer would not be available; we would rely on the fit diagnostics, image\n", + "configuration and parameter constraints.\n", "\n", - "The maximum-likelihood fit is useful for visualization, but it is only one model. The result summary and samples are needed to assess uncertainty and whether the search adequately explored the parameters.\n", + "The maximum-likelihood fit is useful for visualization, but it is only one model. The result summary and samples\n", + "are needed to assess uncertainty and whether the search adequately explored the parameters.\n", "\n", "__Requiring corresponding images to trace together__\n", "\n", "Search chaining gives us a useful starting point, but we can also impose a simple geometric check.\n", "\n", - "If several image positions represent the same source feature, a plausible mass model should trace them close together in the source plane. An incorrect model that reconstructs them as unrelated pieces of source light fails this check.\n", + "If several image positions represent the same source feature, a plausible mass model should trace them close\n", + "together in the source plane. An incorrect model that reconstructs them as unrelated pieces of source light fails\n", + "this check.\n", "\n", - "The `PositionsLH` object applies a penalty when the traced positions are separated by more than a chosen threshold. Models that bring them within the threshold receive no positions penalty.\n", + "The `PositionsLH` object applies a penalty when the traced positions are separated by more than a chosen threshold.\n", + "Models that bring them within the threshold receive no positions penalty.\n", "\n", - "`PositionsLH` penalizes demagnified solutions whose corresponding image positions fail to trace sufficiently close together.\n", + "`PositionsLH` penalizes demagnified solutions whose corresponding image positions fail to trace sufficiently close\n", + "together.\n", "\n", - "We can identify corresponding positions manually, but our initial fit also provides a way to estimate them. The following method uses the fitted source centre and mass model to predict its multiple-image positions and constructs a positions constraint for the next search." + "We can identify corresponding positions manually, but our initial fit also provides a way to estimate them. The\n", + "following method uses the fitted source centre and mass model to predict its multiple-image positions and\n", + "constructs a positions constraint for the next search." ] }, { @@ -606,19 +675,27 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "These positions are predictions from the initial model, not independent measurements. Check that they correspond sensibly to the observed image configuration before using them.\n", + "These positions are predictions from the initial model, not independent measurements. Check that they correspond\n", + "sensibly to the observed image configuration before using them.\n", "\n", - "The threshold should be loose enough to allow the mass model to improve. We are trying to reject grossly inconsistent mappings, not force every subsequent model to reproduce the initial solution exactly. Here, `factor` enlarges the separation estimated from the initial result, while `minimum_threshold` prevents the returned threshold from becoming smaller than `0.2` arcsec.\n", + "The threshold should be loose enough to allow the mass model to improve. We are trying to reject grossly\n", + "inconsistent mappings, not force every subsequent model to reproduce the initial solution exactly. Here, `factor`\n", + "enlarges the separation estimated from the initial result, while `minimum_threshold` prevents the returned\n", + "threshold from becoming smaller than `0.2` arcsec.\n", "\n", - "This positions penalty is a modelling aid rather than a replacement for the image likelihood. It does not by itself establish that the mass model is correct, and an inappropriate set of positions or an overly restrictive threshold can exclude useful solutions.\n", + "This positions penalty is a modelling aid rather than a replacement for the image likelihood. It does not by itself\n", + "establish that the mass model is correct, and an inappropriate set of positions or an overly restrictive threshold\n", + "can exclude useful solutions.\n", "\n", "__Replacing the analytic source with a pixelization__\n", "\n", "We are ready to construct the second model.\n", "\n", - "The lens mass and shear remain free, but their priors are initialized from the first result using the prior-passing machinery introduced in chapter 2. The source profile is replaced by a rectangular mesh and a regularization model.\n", + "The lens mass and shear remain free, but their priors are initialized from the first result using the prior-passing\n", + "machinery introduced in chapter 2. The source profile is replaced by a rectangular mesh and a regularization model.\n", "\n", - "The distinction between `result_1.model` and `result_1.instance` matters here. Using the model carries free parameters into the next search. Using the instance would instead fix those components to particular fitted values." + "The distinction between `result_1.model` and `result_1.instance` matters here. Using the model carries free\n", + "parameters into the next search. Using the instance would instead fix those components to particular fitted values." ] }, { @@ -661,17 +738,23 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Inspect the resulting priors rather than assuming that they are suitable simply because they came from an earlier fit. In particular, a restrictive analytic source can bias an initial mass estimate; its result should guide the next search without preventing the mass model from changing.\n", + "Inspect the resulting priors rather than assuming that they are suitable simply because they came from an earlier\n", + "fit. In particular, a restrictive analytic source can bias an initial mass estimate; its result should guide the\n", + "next search without preventing the mass model from changing.\n", "\n", - "The mesh shape stays fixed. The regularization coefficient is now a non-linear parameter, explored alongside the mass and shear parameters.\n", + "The mesh shape stays fixed. The regularization coefficient is now a non-linear parameter, explored alongside the\n", + "mass and shear parameters.\n", "\n", - "The hundreds of source brightnesses do not appear as hundreds of additional search parameters. For each proposal, the inversion reconstructs those values using the proposed mass model and coefficient.\n", + "The hundreds of source brightnesses do not appear as hundreds of additional search parameters. For each proposal,\n", + "the inversion reconstructs those values using the proposed mass model and coefficient.\n", "\n", "__Running the pixelized-source search__\n", "\n", "The second search combines the pixelized model with the positions constraint.\n", "\n", - "For each proposed mass model, the analysis checks the positions condition and evaluates the source reconstruction as appropriate. The search can adjust the lens parameters and regularization coefficient, while each inversion solves for the source brightnesses." + "For each proposed mass model, the analysis checks the positions condition and evaluates the source reconstruction\n", + "as appropriate. The search can adjust the lens parameters and regularization coefficient, while each inversion\n", + "solves for the source brightnesses." ] }, { @@ -711,9 +794,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Compare this result with the analytic-source fit. Inspect the source structure and image residuals, then examine how the inferred mass parameters and their uncertainties have changed.\n", + "Compare this result with the analytic-source fit. Inspect the source structure and image residuals, then examine\n", + "how the inferred mass parameters and their uncertainties have changed.\n", "\n", - "For this simple simulated source, an MGE can already describe its smooth light distribution, so a pixelization need not produce a dramatic improvement. Its value becomes clearer for irregular sources that cannot be described adequately by the initial profile. This example teaches the modelling procedure without requiring that extra complication.\n", + "For this simple simulated source, an MGE can already describe its smooth light distribution, so a pixelization need\n", + "not produce a dramatic improvement. Its value becomes clearer for irregular sources that cannot be described\n", + "adequately by the initial profile. This example teaches the modelling procedure without requiring that extra\n", + "complication.\n", "\n", "We can also check whether the displayed pixelized model satisfies the positions threshold." ] @@ -756,19 +843,28 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Passing this check means the selected positions trace sufficiently close together under this model. It does not replace inspecting the residuals, uncertainties or search behaviour.\n", + "Passing this check means the selected positions trace sufficiently close together under this model. It does not\n", + "replace inspecting the residuals, uncertainties or search behaviour.\n", "\n", - "We have now performed a chained fit with a pixelized source and a free mass model. The next blocks introduce foreground lens light, explaining how its analytic profiles are fitted alongside the source reconstruction and why errors in that light model can affect the inferred source.\n", + "We have now performed a chained fit with a pixelized source and a free mass model. The next blocks introduce\n", + "foreground lens light, explaining how its analytic profiles are fitted alongside the source reconstruction and why\n", + "errors in that light model can affect the inferred source.\n", "\n", "__Establishing the foreground light model__\n", "\n", - "We can model the foreground lens galaxy\u2019s light and reconstruct a pixelized background source within the same fit. The foreground light profile and the lensed source contribute together to the predicted image.\n", + "We can model the foreground lens galaxy\u2019s light and reconstruct a pixelized background source within the same fit.\n", + "The foreground light profile and the lensed source contribute together to the predicted image.\n", "\n", - "However, fitting everything from the outset gives the search several problems to solve at once. It must establish the mass distribution, separate foreground light from source light, and choose an appropriate source reconstruction.\n", + "However, fitting everything from the outset gives the search several problems to solve at once. It must establish\n", + "the mass distribution, separate foreground light from source light, and choose an appropriate source\n", + "reconstruction.\n", "\n", - "Search chaining helps us approach these problems in stages. We begin with MGE light models for both galaxies, following Chapter 2. This simpler source description provides a useful starting lens geometry and lets us establish the foreground light model before introducing a pixelization.\n", + "Search chaining helps us approach these problems in stages. We begin with MGE light models for both galaxies,\n", + "following Chapter 2. This simpler source description provides a useful starting lens geometry and lets us establish\n", + "the foreground light model before introducing a pixelization.\n", "\n", - "Let\u2019s perform that initial fit using a simulated dataset containing foreground lens light. This is a new dataset, so we run a new search rather than reuse the result from our earlier no-lens-light example." + "Let\u2019s perform that initial fit using a simulated dataset containing foreground lens light. This is a new dataset,\n", + "so we run a new search rather than reuse the result from our earlier no-lens-light example." ] }, { @@ -892,9 +988,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We fix the foreground light and mass centres for this introductory example, while allowing their other parameters to vary. The foreground MGE uses two Gaussian groups, which can have different elliptical shapes; the source uses one. Their Gaussian widths are fixed and all Gaussian intensities are solved linearly.\n", + "We fix the foreground light and mass centres for this introductory example, while allowing their other parameters\n", + "to vary. The foreground MGE uses two Gaussian groups, which can have different elliptical shapes; the source uses\n", + "one. Their Gaussian widths are fixed and all Gaussian intensities are solved linearly.\n", "\n", - "Before continuing, inspect the foreground model and residuals. We want a satisfactory description of the lens light and a plausible source geometry. For an irregular source, the analytic profile may leave structure unexplained, but obvious foreground residuals should not simply be passed into the next stage.\n", + "Before continuing, inspect the foreground model and residuals. We want a satisfactory description of the lens light\n", + "and a plausible source geometry. For an irregular source, the analytic profile may leave structure unexplained, but\n", + "obvious foreground residuals should not simply be passed into the next stage.\n", "\n", "This is a genuine non-linear search, so it will take longer than evaluating a single `FitImaging`.\n", "\n", @@ -902,11 +1002,17 @@ "\n", "We now replace the analytic source with a pixelization and carry the foreground model into the second search.\n", "\n", - "The distinction between `.model` and `.instance` is useful here. We use `.instance` to hold the foreground profile\u2019s fitted shape fixed, reducing the number of non-linear parameters the next search must explore. We use `.model` for the mass and shear so that they remain free, with priors passed from the first result.\n", + "The distinction between `.model` and `.instance` is useful here. We use `.instance` to hold the foreground\n", + "profile\u2019s fitted shape fixed, reducing the number of non-linear parameters the next search must explore. We use\n", + "`.model` for the mass and shear so that they remain free, with priors passed from the first result.\n", "\n", - "Because the foreground MGE uses linear Gaussian profiles, fixing its geometry does **not** fix its intensities. The second fit solves all Gaussian intensities alongside the pixelized source brightnesses. The foreground subtraction can therefore adjust without reopening the non-linear Gaussian geometry.\n", + "Because the foreground MGE uses linear Gaussian profiles, fixing its geometry does **not** fix its intensities. The\n", + "second fit solves all Gaussian intensities alongside the pixelized source brightnesses. The foreground subtraction\n", + "can therefore adjust without reopening the non-linear Gaussian geometry.\n", "\n", - "Search chaining also supplies the initial geometry from which we construct the positions constraint. **`PositionsLH` penalizes demagnified solutions whose corresponding image positions fail to trace sufficiently close together.**" + "Search chaining also supplies the initial geometry from which we construct the positions constraint.\n", + "**`PositionsLH` penalizes demagnified solutions whose corresponding image positions fail to trace sufficiently\n", + "close together.**" ] }, { @@ -991,15 +1097,22 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Inspect the predicted positions before running the second search, as we did earlier. They come from the initial model and should sensibly represent the multiple-image configuration.\n", + "Inspect the predicted positions before running the second search, as we did earlier. They come from the initial\n", + "model and should sensibly represent the multiple-image configuration.\n", "\n", - "The second search now starts with an established foreground light shape and lens geometry. It can refine the mass and regularization while reconstructing the source, rather than solving the entire problem from broad initial priors.\n", + "The second search now starts with an established foreground light shape and lens geometry. It can refine the mass\n", + "and regularization while reconstructing the source, rather than solving the entire problem from broad initial\n", + "priors.\n", "\n", - "Compare the two results, paying attention to the foreground subtraction, source reconstruction and residuals. If the fixed foreground shape leaves significant residuals, a later chained search can free its parameters again. Fixing it is a useful intermediate step, not a requirement that the initial light model must remain unchanged throughout the analysis.\n", + "Compare the two results, paying attention to the foreground subtraction, source reconstruction and residuals. If\n", + "the fixed foreground shape leaves significant residuals, a later chained search can free its parameters again.\n", + "Fixing it is a useful intermediate step, not a requirement that the initial light model must remain unchanged\n", + "throughout the analysis.\n", "\n", "__Wrap Up__\n", "\n", - "This completes the practical chain: fit MGE lens and source light, carry forward the foreground geometry and mass priors, then fit a pixelized source with the positions constraint." + "This completes the practical chain: fit MGE lens and source light, carry forward the foreground geometry and mass\n", + "priors, then fit a pixelized source with the positions constraint." ] } ], diff --git a/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb b/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb index 26ef768..9aa24bd 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.ipynb @@ -10,7 +10,7 @@ "In this tutorial we will introduce a new `Pixelization` object, which uses an `Overlay` image-mesh and a `Delaunay`\n", "mesh.\n", "\n", - "This pixelization does not use a uniform grid of rectangular pixels, but instead uses a `Delaunay` triangulation.\n", + "This pixelization does not use a rectangular mesh, but instead uses a `Delaunay` triangulation.\n", "\n", "So, why would we want to do that? Lets take another quick look at the rectangular grid.\n", "\n", @@ -19,7 +19,8 @@ "- **Initial Setup:** We'll use the same strong lensing data as the previous tutorial, where.\n", "- **Advantages and Disadvantages:** Lets think about the rectangular pixelization.\n", "- **Image Mesh:** The Delaunay mesh is an irregular grid of pixels (or triangles) in the source-plane.\n", - "- **Regularization:** On the rectangular grid, we regularized each source pixel with its 4 neighbors.\n", + "- **Regularization:** Penalize differences between neighbouring reconstructed values.\n", + "- **Source Compactness:** Reconstruct three sources with the same lens, mesh and noise.\n", "- **Wrap Up:** Summary of the script and next steps." ] }, @@ -81,6 +82,7 @@ "from autolens import setup_notebook; setup_notebook()\n", "\n", "from pathlib import Path\n", + "import numpy as np\n", "import autolens as al\n", "import autolens.plot as aplt" ], @@ -116,8 +118,8 @@ "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 does not already exist on your system, it will be created by running the corresponding simulator\n", + "script. This ensures that all example scripts can be run without manually simulating data first." ] }, { @@ -155,8 +157,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The lines of code below do everything we're used to, that is, setup an image, mask it, trace it via a tracer, \n", - "setup the rectangular mapper, etc." + "The lines of code below do everything we're used to, that is, setup an image, mask it, trace it via a tracer, setup\n", + "the rectangular mapper, etc." ] }, { @@ -204,13 +206,9 @@ "source": [ "__Advantages and Disadvantages__\n", "\n", - "Lets think about the rectangular pixelization. Is this the optimal way to reconstruct our source? Are there features\n", - "in the source-plane that aren't ideal? How do you think we could do a better job?\n", - "\n", - "There are a number of reasons the rectangular pixelization is not optimal, and it is in fact a pretty poor method to\n", - "model strong lenses!\n", - "\n", - "So what is wrong with the grid? Well, lets think about the source reconstruction." + "The rectangular mesh is a useful baseline, but its finite resolution can limit a reconstruction.\n", + "`RectangularBilinearAdaptDensity` adjusts rectangular sampling to the traced data density; it is not simply a\n", + "uniform source-plane grid. Inspect where its mesh points lie relative to the bright source." ] }, { @@ -218,8 +216,8 @@ "metadata": {}, "source": [ "mapper = fit.inversion.cls_list_from(al.Mapper)[0]\n", - "\n", - "\n", + "rectangular_pixels = mapper.pixels\n", + "print(f\"Rectangular source pixels: {rectangular_pixels}\")\n", "aplt.subplot_fit_imaging_of_planes(fit=fit)" ], "outputs": [], @@ -229,29 +227,18 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "There is one clear problem, we are using only a small number of the total source pixels to reconstruct the source. The\n", - "majority of source pixels are located away from the source. By my estimate, we are using just 16 pixels (the central\n", - "4x4 grid) out of the 784 pixels to actually fit the data! The remaining ~750 pixels are doing nothing but fitting\n", - "noise.\n", - "\n", - "This means that regularization is sub-optimal. In tutorial 2, we discussed how the Bayesian evidence of the\n", - "regularization favours the simplest source solution. That is, the solution which fits the data using the fewest source \n", - "pixels. If we are dedicating a large number of source pixels to fitting *nothing*, the source reconstruction is \n", - "unnecessarily complex (and therefore is lower `log_evidence` solution).\n", - "\n", - "If our pixelization could 'focus' its pixels where we actually have more data, e.g. the highly magnified regions of \n", - "the source-plane, we could reconstruct the source using fewer pixels. This would significantly increase the Bayesian\n", - "evidence. It'd also be beneficial computationally, as using fewer source pixels means faster run times.\n", - "\n", - "This is what the Delaunay mesh enables.\n", + "A mesh point in a faint region is not necessarily wasted: those measurements can constrain the source's extent. The\n", + "evidence balances fit quality, regularization and complexity, rather than simply rewarding fewer pixels. An\n", + "image-plane overlay offers another allocation: ray-tracing its points concentrates source-plane sampling according\n", + "to lens magnification. Whether this improves a fit must be checked for the data and regularization used.\n", "\n", "__Image Mesh__\n", "\n", - "The Delaunay mesh is an irregular grid of pixels (or triangles) in the source-plane. We must first therefore determine\n", - "a set of (y,x) source-plane coordinates defining this grid, specifically where each triangle vertex is located.\n", + "The Delaunay mesh is an irregular triangulation in the source-plane. First determine a set of (y,x) source-plane\n", + "coordinates defining this grid, specifically where each triangle vertex is located.\n", "\n", - "We do this using an `image_mesh`, which defines a method to determine a set of coordinates in the image-plane \n", - "which are ray-traced to the source-plane. These traced coordinates are the triangle vertexes of our source-pixel mesh. \n", + "We do this using an `image_mesh`, which defines a method to determine a set of coordinates in the image-plane which\n", + "are ray-traced to the source-plane. These traced coordinates are the vertices of our source-pixel mesh.\n", "\n", "Below, we use the `Overlay` image-mesh to do this, which overlays a grid of (y,x) coordinates over the image-plane\n", "mask and retains all (Y,x) coordinates which fall within this mask." @@ -282,7 +269,9 @@ "metadata": {}, "source": [ "\n", - "aplt.plot_array(array=dataset.data, title=\"Data\")" + "aplt.plot_array(\n", + " array=dataset.data, grid=image_plane_mesh_grid, title=\"Image-plane mesh overlay\"\n", + ")" ], "outputs": [], "execution_count": null @@ -291,8 +280,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "By passing a `Tracer` a source galaxy with the image-mesh and a `Delaunay` mesh object, contained in \n", - "a `Pixelization` object, it automatically computes this source-plane Delaunay mesh." + "Give the source galaxy a `Pixelization` containing a `Delaunay` mesh. The fit receives the image-plane mesh\n", + "coordinates separately through `AdaptImages` below, and ray-traces them to construct the source-plane mesh." ] }, { @@ -342,16 +331,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "A closer inspection of the pixelization shows the improvement. \n", - "\n", - "We are using fewer pixels than the rectangular grid (400, instead of 784) and reconstructing the source in far\n", - "greater detail!" + "Compare the residuals and reconstructed source with the rectangular example. The overlay retains only points inside\n", + "the mask, so its actual number of source pixels is smaller than the full 20 by 20 overlay. The two fits also use\n", + "different regularization coefficients; this is not a controlled ranking of mesh quality." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "print(f\"Delaunay source pixels: {mapper.pixels}; rectangular: {rectangular_pixels}\")\n", "aplt.subplot_fit_imaging_of_planes(fit=fit)" ], "outputs": [], @@ -363,23 +352,114 @@ "source": [ "__Regularization__\n", "\n", - "On the rectangular grid, we regularized each source pixel with its 4 neighbors. We compared their fluxes, summed \n", - "the differences, and penalized solutions where the differences were large. \n", + "Constant regularization penalizes differences between neighbouring reconstructed source values. Rectangular meshes\n", + "use their grid connectivity; Delaunay meshes use the connected vertices of the triangulation. A vertex need not\n", + "have exactly three neighbours. One coefficient controls the strength of smoothing across the mesh.\n", "\n", - "For a Delaunay grid, we do a similar calculation, instead comparing each source-pixel with the 3 Delaunay triangles \n", - "it shares a direct vertex with.\n", + "__Source Compactness__\n", "\n", - "__Wrap Up__\n", + "Magnification depends on the lens and source position, not on the brightness distribution we place there. Keep this\n", + "lens, image-plane overlay and regularization fixed while making three source profiles progressively more compact.\n", + "This restores a direct test of a limitation of magnification-based sampling.\n", + "\n", + "Use identical PSF, mask, Gaussian noise map and noise realization for each simulated image. The profiles retain the\n", + "same intensity at their effective radius, so their total fluxes and signal-to-noise ratios also differ; this is a\n", + "diagnostic experiment, not an isolated measurement of the effect of radius. The coefficient of 1.0 is an explicit\n", + "illustrative choice, not an evidence optimum for any of these datasets." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "simulation_grid = al.Grid2D.uniform(\n", + " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales\n", + ")\n", + "simulation_grid = simulation_grid.apply_over_sampling(over_sample_size=8)\n", + "simulator = al.SimulatorImaging(\n", + " exposure_time=300.0,\n", + " psf=dataset.psf,\n", + " background_sky_level=0.1,\n", + " add_poisson_noise_to_data=False,\n", + ")\n", + "noise_sigma = 0.05\n", + "noise_values = np.random.default_rng(1).normal(\n", + " loc=0.0, scale=noise_sigma, size=simulation_grid.shape_native\n", + ")\n", + "common_noise_map = al.Array2D.no_mask(\n", + " values=np.full(simulation_grid.shape_native, noise_sigma),\n", + " pixel_scales=dataset.pixel_scales,\n", + ")\n", "\n", - "The `Overlay` image-mesh and `Delaunay` mesh is still far from optimal. There are lots of source-pixels effectively\n", - "fitting just noise. We could achieve even better solutions if the central regions of the source were reconstructed\n", - "using more pixels, and fewer source pixels were used in the outskirts of the source plane.\n", + "compactness_fits = {}\n", + "for label, effective_radius, sersic_index in [\n", + " (\"Extended\", 0.5, 1.0),\n", + " (\"Compact\", 0.2, 2.5),\n", + " (\"Very compact\", 0.1, 4.0),\n", + "]:\n", + " true_source = al.Galaxy(\n", + " redshift=1.0,\n", + " bulge=al.lp.Sersic(\n", + " centre=(0.0, 0.0),\n", + " ell_comps=(0.0, 0.15),\n", + " intensity=0.2,\n", + " effective_radius=effective_radius,\n", + " sersic_index=sersic_index,\n", + " ),\n", + " )\n", + " true_tracer = al.Tracer(galaxies=[lens_galaxy, true_source], fields=[field])\n", + " noiseless = simulator.via_tracer_from(tracer=true_tracer, grid=simulation_grid)\n", + " simulated_dataset = al.Imaging(\n", + " data=al.Array2D.no_mask(\n", + " values=np.asarray(noiseless.data.native) + noise_values,\n", + " pixel_scales=dataset.pixel_scales,\n", + " ),\n", + " noise_map=common_noise_map,\n", + " psf=dataset.psf,\n", + " )\n", + " simulated_dataset = simulated_dataset.apply_mask(mask=mask)\n", + " simulated_dataset = simulated_dataset.apply_sparse_operator()\n", + " compactness_fit = al.FitImaging(\n", + " dataset=simulated_dataset, tracer=tracer, adapt_images=adapt_images\n", + " )\n", + " compactness_fits[label] = compactness_fit\n", + " compactness_mapper = compactness_fit.inversion.cls_list_from(al.Mapper)[0]\n", + " mesh_radii = np.sqrt(\n", + " np.sum(np.asarray(compactness_mapper.source_plane_mesh_grid) ** 2, axis=1)\n", + " )\n", + " vertices_within_radius = np.count_nonzero(mesh_radii <= effective_radius)\n", + " print(\n", + " f\"{label}: radius={effective_radius:.2f}, index={sersic_index:.1f}, \"\n", + " f\"coefficient=1.0, mesh pixels={compactness_mapper.pixels}, \"\n", + " f\"vertices within circular effective-radius aperture={vertices_within_radius}, \"\n", + " f\"chi_squared / data pixels={compactness_fit.chi_squared / simulated_dataset.data.shape[0]:.3f}, \"\n", + " f\"max |normalized residual|={np.max(np.abs(compactness_fit.normalized_residual_map)):.3f}\"\n", + " )\n", + " aplt.subplot_fit_imaging(fit=compactness_fit)\n", + " aplt.subplot_fit_imaging_of_planes(fit=compactness_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The printed aperture counts measure available mesh vertices, not the number of independently constrained source\n", + "values. Inspect the source reconstructions alongside the residual maps: can the same mesh resolve each bright\n", + "centre without coherent residuals? Changing the coefficient may trade smoothing of the centre against noise in the\n", + "outskirts, but cannot add mesh vertices. We have not searched for an optimal coefficient, and these separate\n", + "simulated datasets must not be ranked against one another using their absolute evidences.\n", + "\n", + "__Wrap Up__\n", "\n", - "Tutorials 11 and 12 show even more advanced and adaptive pixelizations which do just this, by adapting to the\n", - "source galaxy's morphology rather than the mass model magnification.\n", + "The overlay responds to magnification rather than source morphology. The compactness experiment lets us inspect\n", + "where that distinction matters; neither fewer pixels nor a more adaptive mesh guarantees a better reconstruction.\n", + "Tutorials 11 and 12 explore adapting the mesh and regularization to a fitted brightness distribution. They test\n", + "those choices on the same data so that changes in fit quality and evidence can be assessed meaningfully.\n", "\n", - "In the mean time, you may wish to experiment with using both rectangular and Delaunay meshes to fit\n", - "lenses, which is easily achieved by changing the input pixelization given to a pipeline." + "You can also experiment with rectangular and Delaunay meshes by changing the pixelization in a pipeline." ] } ], 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 0dbcd6d..f896481 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 @@ -35,9 +35,7 @@ - **Other Searches:** Find the optional optimisation and MCMC examples. - **Wrap Up:** Review the lesson and its connection to the next topic. -""" -""" __Overview__ This tutorial introduces the main pieces of an automated model fit: @@ -49,9 +47,7 @@ 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__ Imagine varying just two properties of a lens model: the lens’s Einstein radius and the source’s effective radius. Each @@ -71,9 +67,7 @@ **🤖 Ask AI:** In strong-lens modeling, why might changing the lens mass and the source size together produce similar images, and how could this appear on a likelihood surface? -""" -""" __Automated Exploration__ A non-linear search automates the exploration you performed manually in Chapter 1. @@ -84,9 +78,7 @@ 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 explanations here introduce what the search does and how to interpret its results. You do not need to understand @@ -354,9 +346,7 @@ 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. -""" -""" __Search Settings__ One of Nautilus’s main settings is `n_live`, the number of “live points”. Each live point represents a set of model @@ -444,9 +434,7 @@ 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__ You have now fitted a lens model automatically, using the same image prediction and likelihood calculation that you diff --git a/scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py b/scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py index 54166b7..2644371 100755 --- a/scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py +++ b/scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py @@ -38,9 +38,7 @@ - **Further Results:** Find the workspace guides for more detailed result analysis. - **Wrap Up:** Review the lesson and its connection to the next topic. -""" -""" __Dataset__ Our new simulated image contains a bright foreground lens galaxy as well as the lensed source. @@ -123,9 +121,7 @@ We use the model construction from the previous tutorial, adding the lens-light profile and placing external shear in a separate `fields` component. -""" -""" 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. @@ -227,9 +223,7 @@ 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. -""" -""" __Output Updates__ While the search runs, PyAutoLens can save updated figures showing the best-fitting model found so far. These let you @@ -246,9 +240,7 @@ 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 @@ -297,9 +289,7 @@ 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. -""" -""" __Notebooks and Scripts__ In a notebook, the cell containing `search.fit` remains busy until the search finishes. You can inspect files already @@ -319,9 +309,7 @@ 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**. -""" -""" __Model Fit__ We now pass the model and analysis to Nautilus and begin the fit. @@ -396,9 +384,7 @@ |-- dataset_identity.json # Record of the input dataset `-- search_internal/ # Search checkpoints, when retained ``` -""" -""" __Unique Identifier__ The identifier looks like a random string, but it is calculated from the model, the identifying search settings and the @@ -416,9 +402,7 @@ 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 @@ -433,9 +417,7 @@ 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__ Begin with `image/fit.png`. Inspect whether the predicted image reproduces the lens and source light, and whether @@ -452,9 +434,7 @@ 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. -""" -""" __Parameter Uncertainties__ A corner plot shows the parameter uncertainties inferred by the search and the relationships between them. @@ -511,9 +491,7 @@ 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. -""" -""" __Further Results__ You now know how to inspect a fit, read its parameter estimates and find its saved output. That is enough to continue @@ -527,9 +505,7 @@ 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__ We have fitted a model containing lens light, lens mass, external shear and source light, while retaining the same diff --git a/scripts/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.py b/scripts/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.py index f74b7c3..60fe77c 100644 --- a/scripts/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.py +++ b/scripts/chapter_2_lens_modeling/tutorial_3_why_modeling_is_hard.py @@ -51,9 +51,7 @@ - **Model Mismatch:** Distinguish insufficient exploration from an inadequate model. - **Wrap Up:** Review the lesson and its connection to the next topic. -""" -""" __Overview__ We will first run a less thorough search and inspect its result. It may find a satisfactory solution, or it may miss a @@ -61,9 +59,7 @@ 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 @@ -251,9 +247,7 @@ 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: @@ -270,9 +264,7 @@ **🤖 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 @@ -290,9 +282,7 @@ 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 @@ -540,9 +530,7 @@ 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 @@ -556,9 +544,7 @@ 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 @@ -669,9 +655,7 @@ 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 @@ -685,9 +669,7 @@ 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 @@ -808,9 +790,7 @@ 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 @@ -827,8 +807,25 @@ 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. + +The following values come from each search's saved timer, so loading a completed result reports its recorded duration +rather than the time spent loading it. A resumed search includes the time since its original start, including any +interruption. Runs without recorded timing information are labelled accordingly. """ +for label, fit_result in [ + ("Less thorough", result), + ("Practicalities", result_reference), + ("Prior tuning", result_custom_priors), + ("Reduced complexity", result_linked), + ("More thorough", result_thorough), +]: + elapsed_seconds = fit_result.samples.time + if elapsed_seconds is None: + print(f"{label}: elapsed time not recorded") + else: + print(f"{label}: recorded elapsed time = {float(elapsed_seconds):.1f} seconds") + """ __Model Mismatch__ @@ -848,9 +845,7 @@ 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 diff --git a/scripts/chapter_2_lens_modeling/tutorial_4_linear_profiles.py b/scripts/chapter_2_lens_modeling/tutorial_4_linear_profiles.py index 1c7619b..8e91348 100644 --- a/scripts/chapter_2_lens_modeling/tutorial_4_linear_profiles.py +++ b/scripts/chapter_2_lens_modeling/tutorial_4_linear_profiles.py @@ -42,9 +42,7 @@ - **Other Basis Functions:** Find other ways to expand a galaxy’s light distribution. - **Wrap Up:** Review the lesson and its connection to the next topic. -""" -""" __Overview__ We first replace the ordinary lens and source light profiles with their linear equivalents. We will inspect the model, @@ -55,9 +53,7 @@ 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 @@ -123,9 +119,7 @@ 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 @@ -144,9 +138,7 @@ 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`. @@ -317,9 +309,7 @@ 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 @@ -417,9 +407,7 @@ 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. @@ -619,9 +607,7 @@ 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 @@ -636,9 +622,7 @@ 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 @@ -653,9 +637,7 @@ 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**, @@ -670,9 +652,7 @@ 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 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 56fcba1..fca23db 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 @@ -209,11 +209,10 @@ ) """ -To check the image-positions are accurate we can plot them using the `lines=`/`positions=` overlays object (they are the magenta dots on -the image). +To check that the image positions are accurate, we plot them as marked points on the image using `positions=`. """ -aplt.subplot_imaging_dataset(dataset=dataset) +aplt.subplot_imaging_dataset(dataset=dataset, positions=positions) """ For the positions to be used in a model-fit, we create a `PositionsLH` object which we pass to @@ -243,9 +242,8 @@ """ __Run Time__ -The likelihood evaluation time of the position threshold is below 0.001 seconds, meaning that the initial parameter -space sampling is extremely efficient leading to a significant speed up of the model-fit (not accounted for in -the run-time estimate below). +Checking a few positions is cheaper than evaluating the full image likelihood. Rejecting unsuitable mass models early +can therefore speed up the initial exploration of parameter space; the benefit depends on the model and dataset. __Search__ diff --git a/scripts/chapter_2_lens_modeling/tutorial_7_results.py b/scripts/chapter_2_lens_modeling/tutorial_7_results.py index 450eeca..0b08b2a 100644 --- a/scripts/chapter_2_lens_modeling/tutorial_7_results.py +++ b/scripts/chapter_2_lens_modeling/tutorial_7_results.py @@ -7,7 +7,7 @@ __Contents__ -- **Initial Setup:** Lets use the model-fit performed in tutorial 1 to get a `Result` object. +- **Initial Setup:** Run a separate fit to the Tutorial 1 dataset to obtain a `Result` object. - **Dataset Auto-Simulation:** Simulate the dataset via its simulator script if it is not on your hard-disk. - **Tracer & Fit:** In the previous tutorials, we saw that this result contains the maximum log likelihood fit, which. - **Samples:** The result contains a lot more information about the model-fit. @@ -29,7 +29,9 @@ """ __Initial Setup__ -Lets use the model-fit performed in tutorial 1 to get a `Result` object. +We use the same dataset as Tutorial 1 and run a separate fit to obtain a `Result` object. Here, the source uses an +ordinary light profile, so its intensity is explored by the non-linear search. This setup does not reload the +Tutorial 1 result. """ dataset_name = "simple__no_lens_light__mass_sis" dataset_path = Path("dataset") / "imaging" / dataset_name 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 a5e799c..776d51f 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 @@ -10,17 +10,17 @@ resolution datasets this is somewhat unavoidable. However, it is worth us discussing what drives the long run-times of the lens modeling process and how we might speed it up. -We have carefully tracked the log likelihood evaluation times and therefore expected overall run-time of every -fit performed in this chapter. Lets quickly remind ourselves of the main factors that drive the run-time, and -how we might reduce it. +The preceding tutorials discussed the costs contributing to a fit's elapsed time. Lets remind ourselves of the main +factors that drive the run-time and how we might reduce it. -The overall run-time of a model-fit is, to a good approximation, a simple product of two numbers: +For sequential likelihood evaluations, the search's evaluation cost is approximately the product of two numbers: - The number of log likelihood evaluations the non-linear search performs before it converges. - The time each individual log likelihood evaluation takes. -Everything we discuss below reduces one (or both) of these numbers. +Batching evaluates several models together, so this product does not directly predict GPU elapsed time. Compilation +and saving output also add time. The approaches below address these costs or reduce the exploration needed. __Contents__ @@ -120,20 +120,17 @@ __Run Time Estimation__ -Because run-time is the product of the two numbers above, we can estimate it before committing to a fit: +Tutorial 2 explains how likelihood cost, the number of evaluations, compilation and output contribute to elapsed time. +It does not measure a likelihood evaluation time or predict a fixed duration for the fit. - - Time the log likelihood evaluation: perform a fit of the model to the data once (e.g. via a `FitImaging`) and - time it, remembering to discard the first call, which includes JIT compilation. +An estimate needs measurements from the actual likelihood calculation, using the intended model, dataset, hardware +and batch size. A standalone `FitImaging` calculation need not follow the same compiled and batched path as the search. +JAX measurements must wait for device calculations to finish, with compilation considered separately from repeated +evaluations. - - Estimate the number of evaluations: for `Nautilus` a reasonable rule of thumb is of order 10000 evaluations per - free parameter, with simpler parameter spaces (e.g. linear light profiles, chained searches with tight priors) - converging in fewer. - -Multiplying the two gives a ballpark overall run-time. In tutorial 2 we used exactly this arithmetic: a log -likelihood evaluation time below 0.01 seconds on CPU (below 0.001 seconds on GPU) and 50000-100000 evaluations gave -expected run-times of roughly 30 minutes on CPU and 10 minutes on GPU. If your own estimate comes out at days or -weeks, that is the moment to simplify the model, tighten the search settings, reach for search chaining or find -a GPU -- before starting the fit, not after. +The number of evaluations needed also depends on the parameter space and search settings. Compare the saved durations +of representative completed fits, as in Tutorial 3, before extrapolating to a larger analysis. If those runs suggest +that a fit will take days or weeks, consider simplifying the model, search chaining or different hardware. On a GPU, tutorial 2 also showed the other pre-flight check: `analysis.print_vram_use` estimates whether the fit will fit within the GPU's memory for your chosen batch size. diff --git a/scripts/chapter_3_pixelizations/tutorial_11_brightness_adaption.py b/scripts/chapter_3_pixelizations/tutorial_11_brightness_adaption.py index d0b6edf..7988db6 100644 --- a/scripts/chapter_3_pixelizations/tutorial_11_brightness_adaption.py +++ b/scripts/chapter_3_pixelizations/tutorial_11_brightness_adaption.py @@ -2,19 +2,21 @@ Tutorial 11: Brightness Adaption ================================ -In the previous tutorial we motivated our need to adapt the pixelization to the source's morphology, such that source -pixels congregates in the source's brightest regions regardless of where the source is located in the source-plane. +In the previous tutorial we motivated our need to adapt the pixelization to the source's morphology, such that +source pixels congregates in the source's brightest regions regardless of where the source is located in the +source-plane. -This poses a challenge; how do we adapt our pixelization to the reconstructed source's light, before we've -actually reconstructed the source and therefore know what to adapt it too? +This poses a challenge; how do we adapt our pixelization to the reconstructed source's light, before we've actually +reconstructed the source and therefore know what to adapt it too? -To do this, we define 'adapt_images' of the lensed source galaxy, which are model images of the source computed using -a previous lens model that has been fit to the image (e.g. in the earlier search of a pipeline). This image tells -us where in the image our source is located, thus informing us of where we need to adapt our source pixelization! +To do this, we define 'adapt_images' of the lensed source galaxy, which are model images of the source computed +using a previous lens model that has been fit to the image (e.g. in the earlier search of a pipeline). This image +tells us where in the image our source is located, thus informing us of where we need to adapt our source +pixelization! -This tutorial goes into the details of how this works. We'll use the same compact source galaxy as the previous -tutorial and begin by fitting it with a magnification based pixelization. This will produce a model image which can -then be used an adapt image. +Tutorial 8's compactness experiment motivated adapting to the source's morphology. Here we use the standalone +`simple__no_lens_light` dataset, rather than one of those progressively compact simulated sources. We begin with a +magnification-based pixelization and use its model image as an adapt image. __Contents__ @@ -22,7 +24,8 @@ - **Adapt Image:** We can use this fit to set up our adapt image. - **Adaption:** Now lets take a look at brightness based adaption in action. - **Hilbert:** So how does the `adapt_image` adapt the pixelization to the source's brightness? -- **Weight Map:** We now have a sense of how our `Hilbert` image-mesh is computed, so lets look at how we create the. +- **Weight Map:** We now have a sense of how our `Hilbert` image-mesh is computed, so lets look at how we create + the. - **Wrap Up:** Summary of the script and next steps. """ @@ -44,6 +47,7 @@ from pathlib import Path import autolens as al import autolens.plot as aplt +import autoarray.plot as aaplt """ __Initial Setup__ @@ -60,8 +64,8 @@ """ __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 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 @@ -90,7 +94,7 @@ dataset = dataset.apply_sparse_operator() """ -Next, we're going to fit the image using the RectangularBilinearAdaptDensity magnification based grid. +Next, we're going to fit the image using the RectangularBilinearAdaptDensity magnification based grid. The code below does all the usual steps required to do this. """ @@ -115,10 +119,11 @@ tracer = al.Tracer(galaxies=[lens_galaxy, source_galaxy_magnification], fields=[field]) -fit = al.FitImaging(dataset=dataset, tracer=tracer) +magnification_fit = al.FitImaging(dataset=dataset, tracer=tracer) +fit = magnification_fit """ -Lets have a quick look to make sure it has the same residuals we saw in the previous tutorial. +Inspect the source reconstruction and residuals before using its model image to guide the next mesh. """ mapper = fit.inversion.cls_list_from(al.Mapper)[0] @@ -129,20 +134,21 @@ """ __Adapt Image__ -We can use this fit to set up our adapt image. +We can use this fit to set up our adapt image. -This adapt-image is not perfect, because there are residuals in the central regions of the reconstructed source. -However, it is good enough for us to adapt our pixelization to the lensed source. +The adapt image is conditional on this first fit. Check its residuals: an inaccurate starting model can guide the +next mesh to the wrong parts of the image. """ adapt_image = fit.model_data.slim """ __Adaption__ -Now lets take a look at brightness based adaption in action. +Now lets take a look at brightness based adaption in action. -Below, we define a source-galaxy using the `Hilbert` image-mesh (we discuss below how this adapts to the source light) -and `RectangularBilinearAdaptDensity` mesh and use this to fit the lens-data. +Below, we define a source galaxy using the `Hilbert` image-mesh and a `Delaunay` mesh. We discuss below how Hilbert +adapts to the source light. Unlike the density-adaptive rectangular mesh, Delaunay uses the supplied Hilbert points +as its source-mesh vertices after ray tracing. """ image_mesh = al.image_mesh.Hilbert(pixels=500, weight_floor=0.0, weight_power=10.0) @@ -151,8 +157,8 @@ ) pixelization = al.Pixelization( - mesh=al.mesh.RectangularBilinearAdaptDensity(shape=(24, 24)), - regularization=al.reg.Constant(coefficient=0.5), + mesh=al.mesh.Delaunay(pixels=image_plane_mesh_grid.shape[0]), + regularization=al.reg.Constant(coefficient=1.0), ) galaxy_adapt = al.Galaxy( @@ -173,43 +179,43 @@ """ We now fit using this adapt image and mesh using the normal API. -Note however that the `FitImaging` object receives the `adapt_images` as an input and they are used when -setting up the image-mesh and mesh. +Note however that the `FitImaging` object receives the `adapt_images` as an input and they are used when setting up +the image-mesh and mesh. """ tracer = al.Tracer(galaxies=[lens_galaxy, galaxy_adapt], fields=[field]) -fit = al.FitImaging(dataset=dataset, tracer=tracer, adapt_images=adapt_images) +brightness_fit = al.FitImaging(dataset=dataset, tracer=tracer, adapt_images=adapt_images) +fit = brightness_fit +aplt.plot_array( + array=dataset.data, positions=image_plane_mesh_grid, title="Hilbert Image-Mesh Points", +) +mapper = fit.inversion.cls_list_from(al.Mapper)[0] +aaplt.plot_mapper( + mapper=mapper, solution_vector=fit.inversion.reconstruction, + mesh_grid=mapper.source_plane_mesh_grid, title="Brightness-Adaptive Source Mesh", +) aplt.subplot_fit_imaging(fit=fit) aplt.subplot_fit_imaging_of_planes(fit=fit) """ -Our reconstruction of the image no longer has residuals! - -By congregating more source pixels in the brightest regions of the source reconstruction we get a better fit. -Furthermore, we can check that this provides an increase in Bayesian log evidence, noting that the log evidence of the -compact source when using a `Overlay` image-mesh was 4216: +Compare the source mesh and residuals with the initial density-adaptive reconstruction. We can now compare measured +evidence values instead of carrying a number over from another simulation. This first comparison changes both mesh +family and regularization coefficient; it does not isolate brightness weighting alone. """ -print("Evidence using magnification based pixelization. ", 4216) -print("Evidence using brightness based pixelization. ", fit.log_evidence) +print("Evidence using magnification based pixelization:", magnification_fit.log_evidence) +print("Evidence using brightness based pixelization:", brightness_fit.log_evidence) +print("Difference in log evidence:", brightness_fit.log_evidence - magnification_fit.log_evidence) +print("Source mesh values:", mapper.pixels) """ -It increases by over 1000, which for a Bayesian evidence is pretty large! - -This pixelization is a huge success, we should have been adapting to the source's brightness all along! - -In doing so, we will *always* reconstruct the detailed structure of the source's brightest regions with a -sufficiently high resolution! - -We are now able to adapt the pixelization's mesh to the morphology of the lensed source galaxy. To my knowledge, this -is the *best* approach one can take in lens modeling. Its more tricky to implement and introduces additional non-linear -parameters. But the pay-off is worth it, as we fit our data better and use fewer source pixels to reconstruct -the source. +Brightness adaptation gives us another way to distribute source resolution. It does not guarantee an improved fit +or higher evidence for every dataset. Inspect both the calculated comparison and the residuals. __Hilbert__ -So how does the `adapt_image` adapt the pixelization to the source's brightness? It uses a standard algorithm for +So how does the `adapt_image` adapt the pixelization to the source's brightness? It uses a standard algorithm for partitioning data in statistics called a Hilbert curve: https://en.wikipedia.org/wiki/Hilbert_curve @@ -217,50 +223,53 @@ In simple terms, this algorithm works as follows: 1) Input an image of weight values to the Hilbert algorithm which determines the "hilbert space filling curve" - (e.g. this `weight_map` is determined from the adapt-image). The Hilbert space-filling curve fills more space there + (e.g. this `weight_map` is determined from the adapt-image). The Hilbert space-filling curve fills more space + there the weight values are highest, and less space where they are lowest. It therefore closely traces the brightest regions of the image. - 2) Probabilistically draw N $(y,x)$ points from this Hilbert curve, where the majority of points will therefore be + 2) Probabilistically draw N $(y,x)$ points from this Hilbert curve, where the majority of points will therefore be drawn from high weighted regions. 3) These N $(y,x)$ are our source-pixel centres, albeit we have drawn them in the image-plane so we first map them - to the source-plane, via the mass model, in order to set up the source pixel centres of the mesh. Because points are - drawn from high weighted regions (e.g. the brightest image pixels in the lensed source adapt image), we will trace + to the source-plane, via the mass model, in order to set up the source pixel centres of the mesh. Because points + are + drawn from high weighted regions (e.g. the brightest image pixels in the lensed source adapt image), we will trace more source-pixels to the brightest regions of where the source is actually reconstructed. __Weight Map__ -We now have a sense of how our `Hilbert` image-mesh is computed, so lets look at how we create the weighted data the -Hilbert space filling curve uses. +We now have a sense of how our `Hilbert` image-mesh is computed, so lets look at how we create the weighted data +the Hilbert space filling curve uses. -This image, called the `weight_map` is generated using the `weight_floor` and `weight_power` parameters of -the `Hilbert` object. The weight map is generated following 4 steps: +This image, called the `weight_map` is generated using the `weight_floor` and `weight_power` parameters of the +`Hilbert` object. The weight map is generated following 4 steps: 1) Take an absolute value of all pixels in the adapt image, because negative values break the Hilbert algorithm. - 2) Divide all values of this image by its maximum value, such that the adapt-image now only contains values between + 2) Divide all values of this image by its maximum value, such that the adapt-image now only contains values + between 0.0 and 1.0 (where the values of 1.0 are the maximum values of the adapt-image). - 3) Add the weight_floor to all values (a weight_floor of 0.0 therefore does not change the weight map). - - 4) Raise all values to the power of weight_power (a weight_power of 1.0 therefore does not change the - weight map, whereas a value of 0.0 means all values 1.0 and therefore weighted equally). + 3) Raise all values to the power of `weight_power`. A power of 1.0 leaves them unchanged; a power of 0.0 + makes all weights equal to 1.0. + + 4) Set any value below `weight_floor` to that floor. This is a minimum weight, not a value added to every pixel. -The idea is that using high values of `weight_power` will make the highest weight values much higher than the lowest -values, such that the Hilbert curve will trace these values much more than the lower values. The weight_floor gives -the algorithm some balance, by introducing a floor to the weight map that prevents the lowest values from being -weighted to near zero. +The idea is that using high values of `weight_power` will make the highest weight values much higher than the +lowest values, such that the Hilbert curve will trace these values much more than the lower values. The +weight_floor gives the algorithm some balance, by introducing a floor to the weight map that prevents the lowest +values from being weighted to near zero. -Lets look at this in action. we'll inspect 3 weight_maps, using a weight_power of 0.0, 5.0 and 10.0 and -setting the `weight_floor` to 0.0 for now. +Lets look at this in action. we'll inspect 3 weight_maps, using a weight_power of 0.0, 5.0 and 10.0 and setting the +`weight_floor` to 0.0 for now. """ image_mesh = al.image_mesh.Hilbert(pixels=500, weight_floor=0.0, weight_power=0.0) weight_map = image_mesh.weight_map_from(adapt_data=adapt_image) weight_map = al.Array2D(values=weight_map, mask=mask) -aplt.plot_array(array=weight_map, title="") +aplt.plot_array(array=weight_map, title="Hilbert Weight Power 0: Weight Map") image_mesh = al.image_mesh.Hilbert(pixels=500, weight_floor=0.0, weight_power=5.0) @@ -268,7 +277,7 @@ weight_map = image_mesh.weight_map_from(adapt_data=adapt_image) weight_map = al.Array2D(values=weight_map, mask=mask) -aplt.plot_array(array=weight_map, title="") +aplt.plot_array(array=weight_map, title="Hilbert Weight Power 5: Weight Map") image_mesh = al.image_mesh.Hilbert(pixels=500, weight_floor=0.0, weight_power=10.0) @@ -276,54 +285,68 @@ weight_map = image_mesh.weight_map_from(adapt_data=adapt_image) weight_map = al.Array2D(values=weight_map, mask=mask) -aplt.plot_array(array=weight_map, title="") +aplt.plot_array(array=weight_map, title="Hilbert Weight Power 10: Weight Map") """ -When we increase the weight-power the brightest regions of the adapt-image become weighted higher relative to the -fainter regions. +When we increase the weight-power the brightest regions of the adapt-image become weighted higher relative to the +fainter regions. This means that the Hilbert algorithm will adapt more pixels to the brightest regions of the source. -Lets use the method to perform a fit with a weight power of 10, showing that we now get a significantly higher -log_evidence. +Let us compare powers 0, 5 and 10 using the same number of Hilbert points, Delaunay mesh and regularization +coefficient. We reuse the power-10 reconstruction above. Each new power changes the mesh points, so we must +reconstruct the source again before comparing evidence. """ -image_mesh = al.image_mesh.Hilbert(pixels=500, weight_floor=0.0, weight_power=10.0) - -image_plane_mesh_grid = image_mesh.image_plane_mesh_grid_from( - mask=dataset.mask, adapt_data=adapt_image -) - - -pixelization = al.Pixelization( - mesh=al.mesh.RectangularBilinearAdaptDensity(shape=(24, 24)), - regularization=al.reg.Constant(coefficient=1.0), -) - -source_weight_power_10 = al.Galaxy( - redshift=1.0, - pixelization=pixelization, -) - -tracer = al.Tracer(galaxies=[lens_galaxy, source_weight_power_10], fields=[field]) +fits_by_power = {10.0: brightness_fit} + +for weight_power in (0.0, 5.0, 10.0): + if weight_power not in fits_by_power: + image_mesh = al.image_mesh.Hilbert( + pixels=500, weight_floor=0.0, weight_power=weight_power, + ) + image_plane_mesh_grid = image_mesh.image_plane_mesh_grid_from( + mask=dataset.mask, adapt_data=adapt_image, + ) + source = al.Galaxy( + redshift=1.0, + pixelization=al.Pixelization( + mesh=al.mesh.Delaunay(pixels=image_plane_mesh_grid.shape[0]), + regularization=al.reg.Constant(coefficient=1.0), + ), + ) + adapt_images = al.AdaptImages( + galaxy_image_dict={source: adapt_image}, + galaxy_image_plane_mesh_grid_dict={source: image_plane_mesh_grid}, + ) + tracer = al.Tracer(galaxies=[lens_galaxy, source], fields=[field]) + fits_by_power[weight_power] = al.FitImaging( + dataset=dataset, tracer=tracer, adapt_images=adapt_images, + ) + + current_fit = fits_by_power[weight_power] + current_mapper = current_fit.inversion.cls_list_from(al.Mapper)[0] + aaplt.plot_mapper( + mapper=current_mapper, solution_vector=current_fit.inversion.reconstruction, + mesh_grid=current_mapper.source_plane_mesh_grid, + title=f"Hilbert Weight Power {weight_power:g}", + ) + aplt.subplot_fit_imaging(fit=current_fit) + print(f"Weight power {weight_power:g}: log evidence={float(current_fit.log_evidence):.3f}") -adapt_images = al.AdaptImages( - galaxy_image_dict={source_weight_power_10: adapt_image}, - galaxy_image_plane_mesh_grid_dict={source_weight_power_10: image_plane_mesh_grid}, +print( + "Log evidence difference, power 10 minus power 0:", + fits_by_power[10.0].log_evidence - fits_by_power[0.0].log_evidence, ) -fit = al.FitImaging(dataset=dataset, tracer=tracer, adapt_images=adapt_images) - -aplt.plot_array(array=fit.model_images_of_planes_list[1], title="Plane 1 Image") - """ -So, what does the `weight_floor` do? Increasing the weight-power congregates pixels around the source. However, there -is a risk that by congregating too many source pixels in its brightest regions we lose resolution further out, where -the source is bright, but not its brightest! +So, what does the `weight_floor` do? Increasing the weight-power congregates pixels around the source. However, +there is a risk that by congregating too many source pixels in its brightest regions we lose resolution further +out, where the source is bright, but not its brightest! -The `weight_floor` allows these regions to maintain a higher weighting whilst the `weight_power` increases. This means -that the mesh can fully adapt to the source's brightest and faintest regions simultaneously. +The `weight_floor` allows these regions to maintain a higher weighting whilst the `weight_power` increases. This +means that the mesh can retain more coverage away from the brightest regions. Check whether this improves the fit. -Lets look at once example: +Let us compare a floor of 0.5 with the power-10, floor-zero fit, keeping the other settings fixed: """ image_mesh = al.image_mesh.Hilbert(pixels=500, weight_floor=0.5, weight_power=10.0) @@ -333,18 +356,18 @@ pixelization = al.Pixelization( - mesh=al.mesh.RectangularBilinearAdaptDensity(shape=(24, 24)), + mesh=al.mesh.Delaunay(pixels=image_plane_mesh_grid.shape[0]), regularization=al.reg.Constant(coefficient=1.0), ) source_weight_floor = al.Galaxy( - redshift=1.0, pixelization=pixelization, adapt_galaxy_image=adapt_image + redshift=1.0, pixelization=pixelization ) weight_map = image_mesh.weight_map_from(adapt_data=adapt_image) weight_map = al.Array2D(values=weight_map, mask=mask) -aplt.plot_array(array=weight_map, title="") +aplt.plot_array(array=weight_map, title="Hilbert Weight Floor 0.5: Weight Map") tracer = al.Tracer(galaxies=[lens_galaxy, source_weight_floor], fields=[field]) @@ -355,26 +378,30 @@ fit = al.FitImaging(dataset=dataset, tracer=tracer, adapt_images=adapt_images) -aplt.plot_array(array=fit.model_images_of_planes_list[1], title="Plane 1 Image") +floor_fit = fit +floor_mapper = fit.inversion.cls_list_from(al.Mapper)[0] +aaplt.plot_mapper( + mapper=floor_mapper, solution_vector=fit.inversion.reconstruction, + mesh_grid=floor_mapper.source_plane_mesh_grid, title="Hilbert Weight Floor 0.5", +) +aplt.subplot_fit_imaging(fit=fit) +print("Evidence with weight floor 0.0:", fits_by_power[10.0].log_evidence) +print("Evidence with weight floor 0.5:", floor_fit.log_evidence) +print("Difference in log evidence:", floor_fit.log_evidence - fits_by_power[10.0].log_evidence) """ __Wrap Up__ -To end, lets think about the Bayesian evidence, which we saw now goes to significantly higher values than for a -magnification-based grid. At this point, it might be worth reminding yourself how the Bayesian evidence works by -going back to tutorials 4 and 5 of this chapter. - -So, why do you think why adapting to the source's brightness increases the log evidence? +The measured evidence comparisons show how these choices affect this dataset. Revisit tutorial 2 for the +interpretation of evidence: image agreement and the source prior must be considered together. -It is because by adapting to the source's morphology we can now access solutions that fit the data really well -(e.g. to the Gaussian noise-limit) but use significantly fewer source-pixels than before. For instance, a typical -magnification based grid uses resolutions of 40 x 40, or 1600 pixels. In contrast, a morphology based pixelization -typically uses just 300-800 pixels (depending on the source itself). Clearly, the easiest way to make our source -solution simpler is to use fewer pixels overall! +Brightness weighting can concentrate mesh points where source light is expected. Excessive concentration can leave +faint regions poorly resolved, and a more detailed mesh does not establish that every reconstructed feature is +real. Inspect the mesh, source and residuals together before choosing settings. -This provides a second benefit. If the best solutions in our fit want to use the fewest source-pixels possible and -**PyAutoLens** can now access those solutions, this means that adapt-mode will run much faster than the magnification -based grid! Put simply, fewer source-pixels means lower computational overheads. YAY! +Here we held the coefficient fixed while comparing powers and floors. A full analysis would also explore +regularization, since its preferred strength depends on mesh geometry. Fewer source values can reduce the cost of +the inversion, but neither faster fits nor higher evidence are guaranteed by brightness adaptation alone. Tutorial 11 done, next up, adaptive regularization! """ diff --git a/scripts/chapter_3_pixelizations/tutorial_12_adaptive_regularization.py b/scripts/chapter_3_pixelizations/tutorial_12_adaptive_regularization.py index 304ec95..4a9bc07 100644 --- a/scripts/chapter_3_pixelizations/tutorial_12_adaptive_regularization.py +++ b/scripts/chapter_3_pixelizations/tutorial_12_adaptive_regularization.py @@ -6,14 +6,15 @@ regularization, motivating a scheme which adapts to the reconstructed source's surface brightness. This raises the same question as before, how do we adapt our regularization scheme to the source before we've -reconstructed it? Just like in the last tutorial, we'll use a model image of a strongly lensed source from a previous -model that we've begun calling the `adapt-image`. +reconstructed it? Just like in the last tutorial, we'll use a model image of a strongly lensed source from a +previous model that we've begun calling the `adapt-image`. __Contents__ - **Initial Setup:** we'll use the same strong lensing data as the previous tutorial, where. - **Convenience Function:** We are going to fit the image using a magnification based grid. -- **Adaptive Regularization:** Lets now look at adaptive regularization in action, by setting up a adapt-image and using the. +- **Adaptive Regularization:** Lets now look at adaptive regularization in action, by setting up a adapt-image and + using the. - **Wrap Up:** Summary of the script and next steps. """ @@ -25,11 +26,13 @@ from pathlib import Path import autolens as al import autolens.plot as aplt +import autoarray.plot as aaplt """ __Initial Setup__ -we'll use the same strong lensing data as the previous tutorial, where: +Tutorial 8's compactness experiment motivates the need for resolution and smoothing checks. As in tutorial 11, this +standalone example uses `simple__no_lens_light`, rather than the progressively compact simulations, where: - The lens galaxy's light is omitted. - The lens system uses an `Isothermal` galaxy mass profile and a separate `ExternalShear` field. @@ -41,8 +44,8 @@ """ __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 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 @@ -71,7 +74,7 @@ """ __Convenience Function__ -We are going to fit the image using a magnification based grid. +We are going to fit the image using a magnification based grid. To perform the fits, we'll use a convenience function to fit the lens data we simulated above. """ @@ -105,7 +108,8 @@ def fit_via_source_galaxy_from(dataset, source_galaxy, adapt_images=None): source_magnification = al.Galaxy(redshift=1.0, pixelization=pixelization) -fit = fit_via_source_galaxy_from(dataset=dataset, source_galaxy=source_magnification) +constant_fit = fit_via_source_galaxy_from(dataset=dataset, source_galaxy=source_magnification) +fit = constant_fit mapper = fit.inversion.cls_list_from(al.Mapper)[0] @@ -114,20 +118,23 @@ def fit_via_source_galaxy_from(dataset, source_galaxy, adapt_images=None): aplt.plot_array(array=fit.model_data, title="Plane 1 Image") """ -The fit looks just like it did in the previous tutorials (residuals in the centre due to a lack of source pixels). - -Lets quickly remind ourselves that the effective regularization weight of each source pixel is our input coefficient -value of 3.3. +Inspect the residuals before changing the prior. We can display the actual regularization weights on the source +mesh: Constant gives every source value the input coefficient of 3.3. These are weights, rather than source +brightnesses or an image-plane reconstruction. """ -aplt.plot_array( - array=fit.inversion.mapped_reconstructed_operated_data, title="Inversion" +constant_weights = mapper.regularization.regularization_weights_from(linear_obj=mapper) +aaplt.plot_mapper( + mapper=mapper, solution_vector=constant_weights, + mesh_grid=mapper.source_plane_mesh_grid, zoom_to_brightest=False, + vmin=0.0, vmax=4.0, title="Constant Regularization Weights", ) +print("Constant weight range:", float(min(constant_weights)), float(max(constant_weights))) """ __Adaptive Regularization__ -Lets now look at adaptive regularization in action, by setting up a adapt-image and using the `Adapt` -regularization scheme. +Lets now look at adaptive regularization in action, by setting up a adapt-image and using the `Adapt` +regularization scheme. This introduces additional parameters, that are explained below. """ @@ -143,7 +150,6 @@ def fit_via_source_galaxy_from(dataset, source_galaxy, adapt_images=None): source_adapt_regularization = al.Galaxy( redshift=1.0, pixelization=pixelization, - adapt_galaxy_image=adapt_image, ) adapt_images = al.AdaptImages( @@ -156,51 +162,59 @@ def fit_via_source_galaxy_from(dataset, source_galaxy, adapt_images=None): adapt_images=adapt_images, ) -aplt.plot_array( - array=fit.inversion.mapped_reconstructed_operated_data, - title="Inversion Reconstruction", +adaptive_fit = fit +mapper = fit.inversion.cls_list_from(al.Mapper)[0] +adaptive_weights = mapper.regularization.regularization_weights_from(linear_obj=mapper) +aaplt.plot_mapper( + mapper=mapper, solution_vector=adaptive_weights, + mesh_grid=mapper.source_plane_mesh_grid, zoom_to_brightest=False, + vmin=0.0, vmax=4.0, title="Adaptive Regularization Weights", ) +aaplt.plot_mapper( + mapper=mapper, solution_vector=fit.inversion.reconstruction, + mesh_grid=mapper.source_plane_mesh_grid, title="Adaptively Regularized Source", +) +print("Adaptive weight range:", float(min(adaptive_weights)), float(max(adaptive_weights))) """ -As expected, we now have a variable regularization scheme. - -The regularization of the source's brightest regions is much lower than that of its outer regions. As discussed -before, this is what we want. Lets quickly check that this does, indeed, increase the Bayesian log evidence: -""" -print("Evidence using constant regularization. ", 4216) -print("Evidence using adaptive regularization. ", fit.log_evidence) +The weights now vary across the source mesh. Compare their locations with the reconstructed source, using the same +weight colour scale as the Constant example. These weights enter the regularization matrix; they are not +uncertainties on the reconstructed brightnesses. +Let us compare the evidence measured from these two fits: """ -Yes, it does! - -Combining the adaptive mesh and regularization will only further benefit lens modeling! +print("Evidence using constant regularization:", constant_fit.log_evidence) +print("Evidence using adaptive regularization:", adaptive_fit.log_evidence) +print("Difference in log evidence:", adaptive_fit.log_evidence - constant_fit.log_evidence) -However, as shown below, we don't fit the source as well as the morphology based mesh did in the previous tutorial. -This is because although the adaptive regularization scheme improves the fit, the magnification based -mesh simply does not have sufficient resolution to resolve the source's cuspy central light. -""" aplt.subplot_fit_imaging(fit=fit) """ +An evidence increase is something to measure, rather than assume. The mesh is unchanged here, so this comparison +examines the regularization choice. These hand-chosen settings are not optimized, and varying the smoothing cannot +supply resolution that the source mesh lacks. Inspect the source and residuals alongside the evidence. + __How does adaptive regularization work?__ -For every source-pixel, we have a mapping between that pixel and a set of pixels in the adapt-image. Therefore, for -every source-pixel, if we sum the values of all adapt-image pixels that map to it we get an estimate of how much of +For every source-pixel, we have a mapping between that pixel and a set of pixels in the adapt-image. Therefore, for +every source-pixel, if we sum the values of all adapt-image pixels that map to it we get an estimate of how much of the lensed source's signal we expect will be reconstructed. We call this each pixel's `pixel signal`. -If a source-pixel has a higher pixel-signal, we anticipate that it`ll reconstruct more flux and we use this information -to regularize it less. Conversely, if the pixel-signal is close to zero, the source pixel will reconstruct near-zero -flux and regularization will smooth over these pixels by using a high regularization coefficient. +If a source-pixel has a higher pixel-signal, we anticipate that it`ll reconstruct more flux and we use this +information to regularize it less. Conversely, if the pixel-signal is close to zero, the source pixel will +reconstruct near-zero flux and regularization will smooth over these pixels by using a high regularization +coefficient. This works as follows: 1) For every source pixel, compute its pixel-signal, the summed flux of all corresponding image-pixels in the adapt-galaxy-image. - 2) Divide every pixel-signal by the number of image-pixels that map directly to that source-pixel. In doing so, all + 2) Divide every pixel-signal by the number of image-pixels that map directly to that source-pixel. In doing so, + all pixel-signals are 'relative'. This means that source-pixels which by chance map to more image-pixels than their neighbors will not have a higher pixel-signal, and visa versa. This ensures the specific pixelization - does impact the adaptive regularization pattern. + does not by itself determine the adaptive regularization pattern. 3) Divide the pixel-signals by the maximum pixel signal so that they range between 0.0 and 1.0. @@ -212,22 +226,23 @@ def fit_via_source_galaxy_from(dataset, source_galaxy, adapt_images=None): (inner_coefficient * pixel_signals + outer_coefficient * (1.0 - pixel_signals)) ** 2.0 - This uses two regularization coefficient parameters, one which is applied to pixels with high pixel-signals and one to + This uses two regularization coefficient parameters, one which is applied to pixels with high pixel-signals and + one to pixels with low pixel-signals. Thus, pixels in the inner regions of the source may be given a lower level of regularization than pixels further away, as desired. -Thus, we now adapt our regularization scheme to the source's surface brightness. Where its brighter (and therefore -has a steeper flux gradient) we apply a lower level of regularization than further out. Furthermore, in the edges of -the source-plane where no source-flux is present we will assume a high regularization coefficient that smooths over -all of the source-pixels. +Thus, we now adapt our regularization scheme to the source's surface brightness. Where its brighter (and therefore +has a steeper flux gradient) we apply a lower level of regularization than further out. Furthermore, in the edges +of the source-plane where no source-flux is present we will assume a high regularization coefficient that smooths +over all of the source-pixels. -Try looking at a couple of extra solutions which use with different inner and outer regularization coefficients or -signal scales. I doubt you'll notice a lot change visually, but the log evidence certainly has a lot of room for +Try looking at a couple of extra solutions which use with different inner and outer regularization coefficients or +signal scales. I doubt you'll notice a lot change visually, but the log evidence certainly has a lot of room for manuveur with different values. -You may find solutions that raise an `InversionException`. These solutions mean that the matrix used during the -linear algebra calculation was ill-defined, and could not be inverted. These solutions are removed -during lens modeling. +You may find solutions that raise an `InversionException`. These solutions mean that the matrix used during the +linear algebra calculation was ill-defined, and could not be inverted. These solutions are removed during lens +modeling. """ pixelization = al.Pixelization( mesh=al.mesh.RectangularBilinearAdaptDensity(shape=(24, 24)), @@ -239,7 +254,6 @@ def fit_via_source_galaxy_from(dataset, source_galaxy, adapt_images=None): source_adapt_regularization = al.Galaxy( redshift=1.0, pixelization=pixelization, - adapt_galaxy_image=adapt_image, ) adapt_images = al.AdaptImages( @@ -262,31 +276,30 @@ def fit_via_source_galaxy_from(dataset, source_galaxy, adapt_images=None): title="Inversion Reconstruction", ) -print("Evidence using adaptive regularization. ", fit.log_evidence) +alternative_weights = mapper.regularization.regularization_weights_from(linear_obj=mapper) +aaplt.plot_mapper( + mapper=mapper, solution_vector=alternative_weights, + mesh_grid=mapper.source_plane_mesh_grid, zoom_to_brightest=False, + vmin=0.0, vmax=4.0, title="Alternative Adaptive Regularization Weights", +) +print("Evidence using alternative adaptive regularization:", fit.log_evidence) +print("Difference from constant regularization:", fit.log_evidence - constant_fit.log_evidence) +print("Difference from first adaptive example:", fit.log_evidence - adaptive_fit.log_evidence) """ __Wrap Up__ -To end, lets consider what this adaptive regularization scheme means in the context of maximizing the Bayesian -evidence. In the previous tutorial, we noted that by using a brightness-based adaptive pixelization we increased -the Bayesian evidence by allowing for new solutions which fit the data using fewer source pixels; the key criteria -in making a source reconstruction 'more simple' and 'less complex'. - -As you might have guessed, adaptive regularization increases the Bayesian log evidence by making the source -reconstruction simpler: - - 1) Reducing regularization in the source's brightest regions produces a `simpler` solution in that we are not - over-smoothing our reconstruction of its brightest regions. - - 2) Increasing regularization in the outskirts produces a simpler solution by correlating more source-pixels, - effectively reducing the number of pixels used by the reconstruction. +Adaptive regularization lets bright and faint parts of the source receive different smoothing weights. Lower +weights can preserve sharp structure where the data support it; higher weights can correlate values in faint +regions that would otherwise fit noise. The adapt image guides that distinction and must itself be checked. -Together, brightness based pixelizations and regularization allow us to find the objectively `simplest` source -solution possible and therefore ensure that our Bayesian evidence has a well defined maximum value. This was not the -case for magnification based pixelizations and constant regularization schemes. +The evidence comparisons quantify the outcomes for our chosen settings. They do not guarantee an increase for every +dataset, a unique maximum, or recovery of arbitrary source detail. Mesh resolution, the adapt image and the lens +model still limit the reconstruction. In a scientific analysis, explore the regularization parameters and inspect +the source and residuals together. -That completes this chapter on pixelized source reconstruction. You can now reconstruct sources of arbitrary -complexity and adapt every part of the analysis to the data itself. In chapter 4, `Scaling Up Lensing`, we take these -tools to bigger systems: lenses with extra galaxies along the line of sight, multi-galaxy lenses, scaling relations, -group and cluster scale lenses and weak lensing. +That completes this chapter on pixelized source reconstruction. You can now investigate flexible source +reconstructions while checking the assumptions that shape them. In chapter 4, `Scaling Up Lensing`, we take these +tools to bigger systems: lenses with extra galaxies along the line of sight, multi-galaxy lenses, scaling +relations, group and cluster scale lenses and weak lensing. """ diff --git a/scripts/chapter_3_pixelizations/tutorial_1_pixelizations.py b/scripts/chapter_3_pixelizations/tutorial_1_pixelizations.py index 22fa938..b59d537 100644 --- a/scripts/chapter_3_pixelizations/tutorial_1_pixelizations.py +++ b/scripts/chapter_3_pixelizations/tutorial_1_pixelizations.py @@ -18,36 +18,59 @@ - Inspecting the reconstruction - Changing the source resolution - Wrap up -""" -""" __Opening — Pixelized source reconstruction__ -Look at a resolved lensed arc. Its broad shape may be smooth, but the light along it can contain bright knots, faint extensions and irregular structure. A model might reproduce the overall arc while leaving compact, coherent features in the residual image. +Look at a resolved lensed arc. Its broad shape may be smooth, but the light along it can contain bright knots, +faint extensions and irregular structure. A model might reproduce the overall arc while leaving compact, coherent +features in the residual image. -In Chapter 2, we introduced linear light profiles and multi-Gaussian expansions (MGEs). By combining Gaussians of different widths, an MGE can describe a much more flexible radial brightness distribution than a single Sérsic profile. Gaussian groups with different ellipticities and orientations can also describe changes in flattening and isophotal twists. Fixed widths and linearly solved intensities keep the number of non-linear parameters manageable. +In Chapter 2, we introduced linear light profiles and multi-Gaussian expansions (MGEs). By combining Gaussians of +different widths, an MGE can describe a much more flexible radial brightness distribution than a single Sérsic +profile. Gaussian groups with different ellipticities and orientations can also describe changes in flattening and +isophotal twists. Fixed widths and linearly solved intensities keep the number of non-linear parameters manageable. -That flexibility makes MGE a useful modelling tool, but consider the geometry of our worked example. Within each galaxy’s Gaussian group, the components shared a common centre and elliptical shape. Adding more Gaussians gives us finer control over how brightness changes around that centre. It does not give us separate centres for star-forming knots, off-centre clumps or several distinct source components. +That flexibility makes MGE a useful modelling tool, but consider the geometry of our worked example. Within each +galaxy’s Gaussian group, the components shared a common centre and elliptical shape. Adding more Gaussians gives us +finer control over how brightness changes around that centre. It does not give us separate centres for star-forming +knots, off-centre clumps or several distinct source components. -We could add offset Gaussian groups. MGEs are not fundamentally restricted to one centre. The practical difficulty is deciding how many groups to use, where to place them and how to fit their geometry as the source becomes more complicated. +We could add offset Gaussian groups. MGEs are not fundamentally restricted to one centre. The practical difficulty +is deciding how many groups to use, where to place them and how to fit their geometry as the source becomes more +complicated. -This is where the image residuals become useful. If an MGE captures the broad light distribution but leaves compact structure along the arcs, its source description may need more spatial freedom. Those residuals are not proof of source clumpiness: errors in the mass model, foreground light subtraction, telescope blurring or other aspects of the data treatment can also produce structure. We need to investigate their origin. +This is where the image residuals become useful. If an MGE captures the broad light distribution but leaves compact +structure along the arcs, its source description may need more spatial freedom. Those residuals are not proof of +source clumpiness: errors in the mass model, foreground light subtraction, telescope blurring or other aspects of +the data treatment can also produce structure. We need to investigate their origin. -In this chapter, we introduce pixelized source reconstruction. Instead of prescribing a light-profile centre and shape for every feature, we describe the source brightness on a mesh. Different regions of that mesh can take different brightness values, allowing the reconstruction to represent more complicated source structure. +In this chapter, we introduce pixelized source reconstruction. Instead of prescribing a light-profile centre and +shape for every feature, we describe the source brightness on a mesh. Different regions of that mesh can take +different brightness values, allowing the reconstruction to represent more complicated source structure. -The connection to Chapter 2 is direct. There, we solved for Gaussian intensities linearly. Here, for a specified mass model and mesh, we solve for source brightness values using the same underlying advantage: they enter the predicted image linearly. +The connection to Chapter 2 is direct. There, we solved for Gaussian intensities linearly. Here, for a specified +mass model and mesh, we solve for source brightness values using the same underlying advantage: they enter the +predicted image linearly. -This additional freedom also allows the reconstruction to fit noise. We therefore introduce regularization—a prior that controls how freely neighbouring source brightnesses can vary. Pixelization is not assumption-free: the mass model, mesh geometry, resolution and regularization all affect the inferred source. +This additional freedom also allows the reconstruction to fit noise. We therefore introduce regularization—a prior +that controls how freely neighbouring source brightnesses can vary. Pixelization is not assumption-free: the mass +model, mesh geometry, resolution and regularization all affect the inferred source. -MGE remains valuable, especially for foreground lens light and initial source fits. Pixelization is the next tool when the source requires more spatial freedom. We will learn how to use these tools together, inspect their reconstructions and recognise when their assumptions need revisiting. +MGE remains valuable, especially for foreground lens light and initial source fits. Pixelization is the next tool +when the source requires more spatial freedom. We will learn how to use these tools together, inspect their +reconstructions and recognise when their assumptions need revisiting. __A complex source__ -We will use a simulated source with several light components at different positions, giving it an asymmetric appearance. The simulation provides both the lensed image and the original source, so we can see what the reconstruction is trying to recover. +We will use a simulated source with several light components at different positions, giving it an asymmetric +appearance. The simulation provides both the lensed image and the original source, so we can see what the +reconstruction is trying to recover. -The next figures show these two views. Look at the separate bright regions in the source and how lensing stretches and repeats their structure in the image. +The next figures show these two views. Look at the separate bright regions in the source and how lensing stretches +and repeats their structure in the image. -For observed data, we would only have the lensed image. The source reconstruction would be an inference from that image and our lens model, not an independent observation of the unlensed galaxy. +For observed data, we would only have the lensed image. The source reconstruction would be an inference from that +image and our lens model, not an independent observation of the unlensed galaxy. """ from autolens import jax_wrapper @@ -110,13 +133,19 @@ """ __Why a simple source model falls short__ -An MGE can describe flexible radial light distributions, as we saw in Chapter 2. Here we fix a Gaussian group to one common centre and elliptical shape to isolate the missing spatial freedom: adding widths at that centre cannot independently place all the bright regions in this source. +An MGE can describe flexible radial light distributions, as we saw in Chapter 2. Here we fix a Gaussian group to +one common centre and elliptical shape to isolate the missing spatial freedom: adding widths at that centre cannot +independently place all the bright regions in this source. -We will compare the simulated image with a model that uses one common-centre MGE group, keeping the lens mass fixed to the values used in the simulation. This is an illustrative fixed-geometry comparison, not an optimized MGE search. The fixed mass cannot compensate for missing source structure. +We will compare the simulated image with a model that uses one common-centre MGE group, keeping the lens mass fixed +to the values used in the simulation. This is an illustrative fixed-geometry comparison, not an optimized MGE +search. The fixed mass cannot compensate for missing source structure. -Inspect the residual map for coherent structure along the arcs. Such structure would show where this source model leaves light unexplained, rather than just the random differences expected from noise. +Inspect the residual map for coherent structure along the arcs. Such structure would show where this source model +leaves light unexplained, rather than just the random differences expected from noise. -**🤖 Ask AI:** If I allowed the lens mass parameters to vary while using this overly simple source model, how could the missing source structure affect the inferred mass distribution? +**🤖 Ask AI:** If I allowed the lens mass parameters to vary while using this overly simple source model, how could +the missing source structure affect the inferred mass distribution? """ gaussians = [ @@ -132,26 +161,37 @@ aplt.subplot_fit_imaging(fit=analytic_fit) """ -Offset Gaussian groups could supply this spatial freedom too, at the cost of choosing and fitting their geometry. MGE remains useful for initial source fits and foreground light. Here we explore a mesh as the next tool for more complicated source structure. +Offset Gaussian groups could supply this spatial freedom too, at the cost of choosing and fitting their geometry. +MGE remains useful for initial source fits and foreground light. Here we explore a mesh as the next tool for more +complicated source structure. __A grid for the source light__ -A pixelization describes the source using brightness values distributed across a mesh. We infer these values from the image instead of requiring the entire source to follow a small set of analytic profiles. +A pixelization describes the source using brightness values distributed across a mesh. We infer these values from +the image instead of requiring the entire source to follow a small set of analytic profiles. -We begin with `RectangularUniform`, which places mesh points at regular intervals in the source plane. Its `shape` specifies the number of points along each direction. The next plot shows where these points lie relative to the ray-traced image coordinates. +We begin with `RectangularUniform`, which places mesh points at regular intervals in the source plane. Its `shape` +specifies the number of points along each direction. The next plot shows where these points lie relative to the +ray-traced image coordinates. -The mesh also defines how brightness is interpolated between its points. We will examine this more closely in the next tutorial. For now, the important distinction is that the mesh specifies where we represent the source; it does not yet tell us how bright the source is. +The mesh also defines how brightness is interpolated between its points. We will examine this more closely in the +next tutorial. For now, the important distinction is that the mesh specifies where we represent the source; it does +not yet tell us how bright the source is. __Following the same image pixels into the source plane__ -Every unmasked image pixel has an index and a position. Ray tracing changes its position, but preserves its index: image point 100 and traced source point 100 describe the same light path. +Every unmasked image pixel has an index and a position. Ray tracing changes its position, but preserves its index: +image point 100 and traced source point 100 describe the same light path. -We will highlight two small groups of image pixels and follow them into the source plane. Matching colours identify matching indexes in the two plots. The source-plane points here are ray-traced image coordinates; they are not the points of our source mesh. +We will highlight two small groups of image pixels and follow them into the source plane. Matching colours identify +matching indexes in the two plots. The source-plane points here are ray-traced image coordinates; they are not the +points of our source mesh. -For this demonstration, we use one sample at each image-pixel centre, making the correspondence easy to follow. More accurate image integration can use several samples within each pixel. +For this demonstration, we use one sample at each image-pixel centre, making the correspondence easy to follow. +More accurate image integration can use several samples within each pixel. """ import numpy as np @@ -206,17 +246,22 @@ ) """ -Compare the separation and shape of each group before and after ray tracing. Their indexes remain unchanged even when the lens strongly changes their arrangement. +Compare the separation and shape of each group before and after ray tracing. Their indexes remain unchanged even +when the lens strongly changes their arrangement. __Where a traced image pixel meets the source mesh__ -We now place a separate rectangular mesh in the source plane. Its indexes identify the brightness values we will reconstruct. An image-pixel index and a source-mesh index therefore refer to different things. +We now place a separate rectangular mesh in the source plane. Its indexes identify the brightness values we will +reconstruct. An image-pixel index and a source-mesh index therefore refer to different things. -A traced image coordinate generally falls between mesh points. With bilinear interpolation, its brightness is calculated from the four surrounding mesh values, weighted according to its position. Falling within one rectangular cell does not mean taking its brightness from just one source point. +A traced image coordinate generally falls between mesh points. With bilinear interpolation, its brightness is +calculated from the four surrounding mesh values, weighted according to its position. Falling within one +rectangular cell does not mean taking its brightness from just one source point. -The next cell selects one image pixel and highlights the source mesh points contributing to it. We print their indexes and weights to make this relationship explicit. +The next cell selects one image pixel and highlights the source mesh points contributing to it. We print their +indexes and weights to make this relationship explicit. """ mesh = al.mesh.RectangularUniform(shape=mesh_shape) @@ -252,17 +297,22 @@ ) """ -The mapper stores these relationships for all image pixels. We do not need to construct or solve the mapping matrix by hand; inspecting one row simply exposes what the mapping means. +The mapper stores these relationships for all image pixels. We do not need to construct or solve the mapping matrix +by hand; inspecting one row simply exposes what the mapping means. __One source region, several image regions__ -We can also follow the mapping in the opposite direction. Select a source mesh point and ask which image pixels receive a contribution from it. +We can also follow the mapping in the opposite direction. Select a source mesh point and ask which image pixels +receive a contribution from it. -The figure below uses the same colour for a selected source region and its associated image regions. A small source region can contribute to widely separated parts of the image: this is how multiple images constrain a shared source reconstruction. +The figure below uses the same colour for a selected source region and its associated image regions. A small source +region can contribute to widely separated parts of the image: this is how multiple images constrain a shared source +reconstruction. -The coloured image regions show interpolation support. They are not a strict statement that every traced coordinate falls inside the coloured source cell. +The coloured image regions show interpolation support. They are not a strict statement that every traced coordinate +falls inside the coloured source cell. """ source_coordinates = np.asarray(mapper.source_plane_mesh_grid) @@ -312,27 +362,37 @@ ) """ -Try changing `(0.3, 0.3)` to another source position and follow how its image regions change. The number of coloured patches is not necessarily the physical image multiplicity: masking and pixel sampling can split or hide regions. +Try changing `(0.3, 0.3)` to another source position and follow how its image regions change. The number of +coloured patches is not necessarily the physical image multiplicity: masking and pixel sampling can split or hide +regions. __Reconstructing the source__ -We now have a mesh and a description of how its brightness values contribute to the observed image. The next step is to infer those values from the data. This is called an inversion. +We now have a mesh and a description of how its brightness values contribute to the observed image. The next step +is to infer those values from the data. This is called an inversion. -For a fixed lens mass model, the source brightnesses enter the predicted image linearly. PyAutoLens uses this property to solve for them together, rather than asking a non-linear search to explore each brightness value individually. +For a fixed lens mass model, the source brightnesses enter the predicted image linearly. PyAutoLens uses this +property to solve for them together, rather than asking a non-linear search to explore each brightness value +individually. -The next cell evaluates a `FitImaging` using a pixelized source. We keep the lens mass fixed to the simulation values, so this calculation reconstructs the source without searching for a new mass model. +The next cell evaluates a `FitImaging` using a pixelized source. We keep the lens mass fixed to the simulation +values, so this calculation reconstructs the source without searching for a new mass model. __A first look at regularization__ -Giving the source many adjustable brightness values lets it represent complex structure, but also gives it freedom to fit noise. We therefore include regularization: a prior that favours smoother source reconstructions. +Giving the source many adjustable brightness values lets it represent complex structure, but also gives it freedom +to fit noise. We therefore include regularization: a prior that favours smoother source reconstructions. -For this first reconstruction, we use `Constant` regularization with a fixed coefficient. It discourages large differences between neighbouring mesh values. The data can still support structure, but adding structure comes with a penalty. +For this first reconstruction, we use `Constant` regularization with a fixed coefficient. It discourages large +differences between neighbouring mesh values. The data can still support structure, but adding structure comes with +a penalty. -We will keep this setting fixed for the rest of this tutorial. In tutorial 2, we will vary it and see how too little smoothing fits noise, while too much smoothing erases source detail. +We will keep this setting fixed for the rest of this tutorial. In tutorial 2, we will vary it and see how too +little smoothing fits noise, while too much smoothing erases source detail. """ pixelization = al.Pixelization( @@ -349,11 +409,14 @@ """ __From source indexes to reconstructed brightnesses__ -So far, the mapper tells us how source brightness would contribute to the image, but we have not determined those brightnesses. +So far, the mapper tells us how source brightness would contribute to the image, but we have not determined those +brightnesses. -The inversion combines these mappings with the observed image, its noise and telescope blurring. It solves for the source brightness values together, including the smoothness prior supplied by regularization. +The inversion combines these mappings with the observed image, its noise and telescope blurring. It solves for the +source brightness values together, including the smoothness prior supplied by regularization. -In this example there is one mapper. Entry `j` of its reconstruction therefore gives the brightness associated with source mesh index `j`. We can print selected values and show their locations on the reconstructed source. +In this example there is one mapper. Entry `j` of its reconstruction therefore gives the brightness associated with +source mesh index `j`. We can print selected values and show their locations on the reconstructed source. """ inversion = al.Inversion( @@ -380,15 +443,19 @@ ) """ -These brightnesses are inferred jointly. We do not independently fit each coloured image region: shared source values must explain their contributions across the image, while regularization connects neighbouring source values. +These brightnesses are inferred jointly. We do not independently fit each coloured image region: shared source +values must explain their contributions across the image, while regularization connects neighbouring source values. __Turning the reconstructed source back into an image__ -The source reconstruction and the reconstructed image are different objects. The source lives on our source-plane mesh. Mapping its brightness values through the lens produces an image-plane prediction. +The source reconstruction and the reconstructed image are different objects. The source lives on our source-plane +mesh. Mapping its brightness values through the lens produces an image-plane prediction. -The telescope then blurs that prediction. This blurred image is what we compare with the observed data. The inversion already accounts for that blurring when solving for the source; it is not an extra correction applied after an otherwise completed fit. +The telescope then blurs that prediction. This blurred image is what we compare with the observed data. The +inversion already accounts for that blurring when solving for the source; it is not an extra correction applied +after an otherwise completed fit. The following plots separate these stages. """ @@ -417,21 +484,29 @@ ) """ -Compare the source reconstruction with these image-plane plots. A feature in the source can appear in several places in the lensed image, and telescope blurring can make those image features less distinct. +Compare the source reconstruction with these image-plane plots. A feature in the source can appear in several +places in the lensed image, and telescope blurring can make those image features less distinct. -Inspect the residuals for coherent unexplained structure. A plausible-looking source alone does not establish that the model explains the data. +Inspect the residuals for coherent unexplained structure. A plausible-looking source alone does not establish that +the model explains the data. -**🤖 Ask AI:** Why must the same reconstructed source brightnesses explain all of their associated image regions, rather than allowing each arc to have an independent source reconstruction? +**🤖 Ask AI:** Why must the same reconstructed source brightnesses explain all of their associated image regions, +rather than allowing each arc to have an independent source reconstruction? __Inspecting the reconstruction__ We will plot the inferred source alongside the model image and residuals. These answer different questions. -The source reconstruction shows the brightness distribution inferred under our chosen lens model, mesh and regularization. The model image shows how that reconstruction appears after lensing and telescope blurring. The residuals show what remains unexplained in the observed image. +The source reconstruction shows the brightness distribution inferred under our chosen lens model, mesh and +regularization. The model image shows how that reconstruction appears after lensing and telescope blurring. The +residuals show what remains unexplained in the observed image. -Compare these residuals with those from the simple source model earlier in the tutorial. Look particularly at the image regions associated with the source’s separate bright components. The comparison will show whether the extra source freedom helps explain those features. +Compare these residuals with those from the simple source model earlier in the tutorial. Look particularly at the +image regions associated with the source’s separate bright components. The comparison will show whether the extra +source freedom helps explain those features. -Because this is a simulation, we can also compare the reconstruction with the input source. We should not expect an exact copy: finite resolution, noise and regularization limit the detail we can recover. +Because this is a simulation, we can also compare the reconstruction with the input source. We should not expect an +exact copy: finite resolution, noise and regularization limit the detail we can recover. """ aplt.subplot_fit_imaging(fit=analytic_fit) @@ -441,13 +516,19 @@ """ __Changing the source resolution__ -The mesh resolution controls how finely we can represent the source. A coarse mesh may merge distinct features, while a finer mesh gives the reconstruction more freedom. +The mesh resolution controls how finely we can represent the source. A coarse mesh may merge distinct features, +while a finer mesh gives the reconstruction more freedom. -Repeat the reconstruction with mesh shapes of `(15, 15)`, `(25, 25)` and `(35, 35)`, keeping the lens mass and regularization coefficient fixed. Compare the source structure and image residuals in each case, then restore the starting shape of `(25, 25)`. +Repeat the reconstruction with mesh shapes of `(15, 15)`, `(25, 25)` and `(35, 35)`, keeping the lens mass and +regularization coefficient fixed. Compare the source structure and image residuals in each case, then restore the +starting shape of `(25, 25)`. -More mesh points do not necessarily reveal more reliable detail. The data must constrain that detail, and changing the mesh also changes how the regularization acts. This experiment explores the effect of resolution; choosing an appropriate reconstruction requires considering resolution and smoothing together. +More mesh points do not necessarily reveal more reliable detail. The data must constrain that detail, and changing +the mesh also changes how the regularization acts. This experiment explores the effect of resolution; choosing an +appropriate reconstruction requires considering resolution and smoothing together. -**🤖 Ask AI:** When I increase the source mesh resolution, how can I distinguish newly resolved source structure from extra freedom being used to fit noise? +**🤖 Ask AI:** When I increase the source mesh resolution, how can I distinguish newly resolved source structure +from extra freedom being used to fit noise? """ for shape in ([(6, 6), (8, 8), (10, 10)] if mesh_shape == (8, 8) else [(15, 15), (25, 25), (35, 35)]): @@ -467,11 +548,16 @@ """ __Wrap up__ -We have reconstructed a complex source without prescribing the positions and shapes of its individual light components. +We have reconstructed a complex source without prescribing the positions and shapes of its individual light +components. -The mesh specifies where we represent the source. The mapper connects its brightness values to the observed image through the lens model. The inversion solves for those values, with regularization controlling the freedom to introduce structure. +The mesh specifies where we represent the source. The mapper connects its brightness values to the observed image +through the lens model. The inversion solves for those values, with regularization controlling the freedom to +introduce structure. -Throughout this tutorial, the lens mass was fixed. Later in the chapter, we will vary the mass model and reconstruct the source for each proposed model, allowing the image to constrain both. +Throughout this tutorial, the lens mass was fixed. Later in the chapter, we will vary the mass model and +reconstruct the source for each proposed model, allowing the image to constrain both. -First, we need to understand how interpolation and regularization shape the reconstruction. Tutorial 2 explores these choices and introduces the Bayesian evidence used to compare different levels of smoothing. +First, we need to understand how interpolation and regularization shape the reconstruction. Tutorial 2 explores +these choices and introduces the Bayesian evidence used to compare different levels of smoothing. """ diff --git a/scripts/chapter_3_pixelizations/tutorial_2_bayesian_regularization.py b/scripts/chapter_3_pixelizations/tutorial_2_bayesian_regularization.py index aec3022..51acc01 100644 --- a/scripts/chapter_3_pixelizations/tutorial_2_bayesian_regularization.py +++ b/scripts/chapter_3_pixelizations/tutorial_2_bayesian_regularization.py @@ -14,9 +14,7 @@ - What is linear, and what requires a search? - Mesh resolution and regularization belong together - What we have learned, and what comes next -""" -""" __Interpolation and Bayesian regularization__ So far, we have: @@ -25,13 +23,19 @@ - Used an inversion to reconstruct the source’s brightness. - Mapped that reconstruction back into the image, including telescope blurring, to compare it with the data. -Our explanation of how an inversion works has deliberately left some things unexplained. In particular, you will have noticed the regularization input that we passed when creating our pixelization. We used a coefficient of `1.0`, but have not established why that value should give an appropriate reconstruction. +Our explanation of how an inversion works has deliberately left some things unexplained. In particular, you will +have noticed the regularization input that we passed when creating our pixelization. We used a coefficient of +`1.0`, but have not established why that value should give an appropriate reconstruction. -This tutorial explores what regularization does and why we need it. We will change its strength, inspect the resulting source reconstructions, and see why obtaining a close fit to the image is not enough on its own. +This tutorial explores what regularization does and why we need it. We will change its strength, inspect the +resulting source reconstructions, and see why obtaining a close fit to the image is not enough on its own. -First, we will revisit interpolation. It is easy to confuse interpolation with smoothing, because both affect the appearance of the reconstructed source. Understanding the distinction will help us interpret the experiments that follow. +First, we will revisit interpolation. It is easy to confuse interpolation with smoothing, because both affect the +appearance of the reconstructed source. Understanding the distinction will help us interpret the experiments that +follow. -We use the same complex source as tutorial 1. The lens mass remains fixed to the simulation values, so changes in the reconstruction come from our source modelling choices. +We use the same complex source as tutorial 1. The lens mass remains fixed to the simulation values, so changes in +the reconstruction come from our source modelling choices. """ from autolens import jax_wrapper @@ -82,19 +86,26 @@ aplt.subplot_imaging_dataset(dataset=dataset) """ -The single sample per image pixel keeps the indexed mapping example straightforward. For scientific modelling, we would also check that our image sampling is sufficiently accurate. +The single sample per image pixel keeps the indexed mapping example straightforward. For scientific modelling, we +would also check that our image sampling is sufficiently accurate. __Interpolation and our starting reconstruction__ Let’s look at our reconstruction from the previous tutorial in more detail. -The `RectangularUniform` mesh describes the source using brightness values at regularly spaced points. A ray-traced image coordinate generally falls between these points. Its predicted brightness is obtained by combining the four surrounding values, with weights determined by its position. This is bilinear interpolation. +The `RectangularUniform` mesh describes the source using brightness values at regularly spaced points. A ray-traced +image coordinate generally falls between these points. Its predicted brightness is obtained by combining the four +surrounding values, with weights determined by its position. This is bilinear interpolation. -Interpolation tells us how to calculate brightness between mesh points, but it does not tell us what those mesh values should be. Four neighbouring values could be similar, or one could be much brighter than the others. Both can be interpolated. In the second case, however, the brightness changes much more sharply across the source. +Interpolation tells us how to calculate brightness between mesh points, but it does not tell us what those mesh +values should be. Four neighbouring values could be similar, or one could be much brighter than the others. Both +can be interpolated. In the second case, however, the brightness changes much more sharply across the source. -Regularization influences the brightness values we infer, discouraging variations that are not sufficiently supported by the data. Interpolation then determines how those values contribute between mesh points. +Regularization influences the brightness values we infer, discouraging variations that are not sufficiently +supported by the data. Interpolation then determines how those values contribute between mesh points. -We are going to evaluate several reconstructions, so the function below keeps their common setup in one place. Only the regularization coefficient changes. +We are going to evaluate several reconstructions, so the function below keeps their common setup in one place. Only +the regularization coefficient changes. """ mesh_shape = (8, 8) if dataset.shape_native == al.util.dataset.SMALL_DATASETS_SHAPE_NATIVE else (25, 25) @@ -122,7 +133,9 @@ def fit_with_coefficient(coefficient): aplt.subplot_fit_imaging_of_planes(fit=fit) """ -Here is the interpolation calculation for one image pixel. As in tutorial 1, the mapper supplies the contributing source indexes and their weights. This time, we also have reconstructed brightness values, so we can see how the contributions combine. +Here is the interpolation calculation for one image pixel. As in tutorial 1, the mapper supplies the contributing +source indexes and their weights. This time, we also have reconstructed brightness values, so we can see how the +contributions combine. """ mapper = fit.inversion.cls_list_from(al.Mapper)[0] @@ -154,13 +167,16 @@ def fit_with_coefficient(coefficient): ) """ -This is the image prediction before the PSF redistributes light between image pixels. We are inspecting a small part of the calculation, not replacing the inversion’s treatment of telescope blurring. +This is the image prediction before the PSF redistributes light between image pixels. We are inspecting a small +part of the calculation, not replacing the inversion’s treatment of telescope blurring. __Reducing regularization__ -Our starting reconstruction uses a regularization coefficient of `1.0`. Let’s reduce it substantially and examine what changes. +Our starting reconstruction uses a regularization coefficient of `1.0`. Let’s reduce it substantially and examine +what changes. -We use `0.01` rather than exactly zero, retaining a small smoothness penalty. Keep the lens model, mesh and data unchanged: we want to isolate the effect of weakening regularization. +We use `0.01` rather than exactly zero, retaining a small smoothness penalty. Keep the lens model, mesh and data +unchanged: we want to isolate the effect of weakening regularization. """ weak_regularization_fit = fit_with_coefficient(coefficient=0.01) @@ -171,19 +187,30 @@ def fit_with_coefficient(coefficient): """ To understand this comparison, we need to look more closely at what regularization actually does. -When the inversion reconstructs the source, it does not only seek brightness values that reproduce the image. With `Constant` regularization, it also compares neighbouring brightness values on the rectangular source mesh. Interior mesh points have four immediate neighbours. Large differences between their brightnesses contribute a larger penalty. +When the inversion reconstructs the source, it does not only seek brightness values that reproduce the image. With +`Constant` regularization, it also compares neighbouring brightness values on the rectangular source mesh. Interior +mesh points have four immediate neighbours. Large differences between their brightnesses contribute a larger +penalty. -You can think of this as applying a **smoothness prior** to the reconstructed source. It expresses a preference for neighbouring regions to have similar brightness, unless the image provides enough evidence for them to differ. +You can think of this as applying a **smoothness prior** to the reconstructed source. It expresses a preference for +neighbouring regions to have similar brightness, unless the image provides enough evidence for them to differ. -The penalty depends on squared differences, so positive and negative differences cannot cancel. The coefficient controls its strength. Reducing that coefficient makes a given amount of variation less costly; increasing it makes the same variation more costly. +The penalty depends on squared differences, so positive and negative differences cannot cancel. The coefficient +controls its strength. Reducing that coefficient makes a given amount of variation less costly; increasing it makes +the same variation more costly. -In the language of linear algebra, this prior contributes a regularization matrix to the system the inversion solves. We do not need to construct that matrix ourselves to understand its effect. +In the language of linear algebra, this prior contributes a regularization matrix to the system the inversion +solves. We do not need to construct that matrix ourselves to understand its effect. -Without sufficient regularization, the inversion has greater freedom to fit fluctuations in the observed image, including noise. Some of those fluctuations can be explained by adding irregular structure to the source. The image fit may improve even though the inferred source becomes less faithful to the galaxy that produced the data. +Without sufficient regularization, the inversion has greater freedom to fit fluctuations in the observed image, +including noise. Some of those fluctuations can be explained by adding irregular structure to the source. The image +fit may improve even though the inferred source becomes less faithful to the galaxy that produced the data. -Inspect the weakly regularized reconstruction for isolated bright values or rapid changes between neighbouring points. Also look at its faint regions, where the image provides less information about the source. +Inspect the weakly regularized reconstruction for isolated bright values or rapid changes between neighbouring +points. Also look at its faint regions, where the image provides less information about the source. -A few extreme values can dominate the colour scale. We can compare both reconstructions using the starting reconstruction’s brightness range to see the remaining structure more clearly. +A few extreme values can dominate the colour scale. We can compare both reconstructions using the starting +reconstruction’s brightness range to see the remaining structure more clearly. """ source_vmax = float(np.max(np.asarray(fit.inversion.reconstruction))) @@ -204,17 +231,24 @@ def fit_with_coefficient(coefficient): ) """ -Values above this plotting limit share the highest colour, so use these figures alongside the original plots rather than treating them as the full brightness range. +Values above this plotting limit share the highest colour, so use these figures alongside the original plots rather +than treating them as the full brightness range. -The important point is that recovering recognizable source structure does not mean every reconstructed feature is reliable. Genuine structure and noise-fitting can appear in the same reconstruction. +The important point is that recovering recognizable source structure does not mean every reconstructed feature is +reliable. Genuine structure and noise-fitting can appear in the same reconstruction. __Increasing regularization__ Now let’s move in the other direction and use a much larger coefficient. -With stronger regularization, the inversion pays a greater penalty for differences between neighbouring brightnesses. This discourages the sharp variations that can fit noise. However, the real source also contains brightness variations: compact components, bright centres and the changes between those regions and their surroundings. +With stronger regularization, the inversion pays a greater penalty for differences between neighbouring +brightnesses. This discourages the sharp variations that can fit noise. However, the real source also contains +brightness variations: compact components, bright centres and the changes between those regions and their +surroundings. -Regularization cannot identify which variations are genuine simply by examining the source. The image fit and the prior must work together. If we make the smoothness preference too strong, the reconstruction can lose genuine structure because reproducing it carries too large a penalty. +Regularization cannot identify which variations are genuine simply by examining the source. The image fit and the +prior must work together. If we make the smoothness preference too strong, the reconstruction can lose genuine +structure because reproducing it carries too large a penalty. """ strong_regularization_fit = fit_with_coefficient(coefficient=100.0) @@ -233,9 +267,12 @@ def fit_with_coefficient(coefficient): aplt.subplot_fit_imaging(fit=strong_regularization_fit) """ -Compare the bright components with the starting reconstruction. Look for features becoming flatter or merging together, then inspect the corresponding regions of the image residuals. +Compare the bright components with the starting reconstruction. Look for features becoming flatter or merging +together, then inspect the corresponding regions of the image residuals. -This illustrates the difficulty in choosing a coefficient. Too little smoothing can introduce structure that explains noise. Too much can remove structure needed to explain the galaxy. Neither the smoothest source nor the closest possible image fit is automatically the reconstruction we want. +This illustrates the difficulty in choosing a coefficient. Too little smoothing can introduce structure that +explains noise. Too much can remove structure needed to explain the galaxy. Neither the smoothest source nor the +closest possible image fit is automatically the reconstruction we want. We can quantify image agreement using chi-squared: the sum of squared residuals divided by their noise variances. """ @@ -255,25 +292,38 @@ def fit_with_coefficient(coefficient): print(f"{label}: coefficient={coefficient:g}, chi-squared={chi_squared:.3f}") """ -A lower chi-squared means closer agreement with the image under the assumed noise map. It does not distinguish fitting genuine structure from fitting noise. This is why choosing the coefficient solely by image agreement would favour giving the source too much freedom. +A lower chi-squared means closer agreement with the image under the assumed noise map. It does not distinguish +fitting genuine structure from fitting noise. This is why choosing the coefficient solely by image agreement would +favour giving the source too much freedom. -**🤖 Ask AI:** Why might a weakly regularized reconstruction have a lower chi-squared but a less trustworthy source than a more strongly regularized reconstruction? +**🤖 Ask AI:** Why might a weakly regularized reconstruction have a lower chi-squared but a less trustworthy source +than a more strongly regularized reconstruction? __Bayesian evidence__ For inversions, we therefore need more than image agreement to choose an appropriate level of regularization. -We use the **Bayesian evidence**, which accounts for both the fit to the image and the source prior. It helps us compare reconstructions that have different amounts of freedom, rather than simply choosing whichever one follows the observed pixel values most closely. +We use the **Bayesian evidence**, which accounts for both the fit to the image and the source prior. It helps us +compare reconstructions that have different amounts of freedom, rather than simply choosing whichever one follows +the observed pixel values most closely. There are two useful parts to this intuition. -First, the reconstruction must explain the image. If strong regularization prevents it from reproducing genuine source structure, the resulting residuals count against that choice. Preferring a smooth source is not useful if that source cannot explain the observed arcs. +First, the reconstruction must explain the image. If strong regularization prevents it from reproducing genuine +source structure, the resulting residuals count against that choice. Preferring a smooth source is not useful if +that source cannot explain the observed arcs. -Second, allowing a more flexible source comes at a cost. Weak regularization permits many more patterns of brightness across neighbouring mesh points. Some of that extra freedom may be needed to describe the galaxy, but some may only help reproduce the particular noise fluctuations in this image. +Second, allowing a more flexible source comes at a cost. Weak regularization permits many more patterns of +brightness across neighbouring mesh points. Some of that extra freedom may be needed to describe the galaxy, but +some may only help reproduce the particular noise fluctuations in this image. -Evidence weighs the improvement in fit against the freedom allowed by the prior. An improvement must be sufficient to justify that additional flexibility. +Evidence weighs the improvement in fit against the freedom allowed by the prior. An improvement must be sufficient +to justify that additional flexibility. -This is also why complexity is not simply the number of source mesh points. Our three examples have exactly the same mesh. Stronger regularization ties neighbouring brightnesses together more closely, reducing their freedom to vary independently. We can therefore change the effective flexibility of the reconstruction without changing the number of mesh points. +This is also why complexity is not simply the number of source mesh points. Our three examples have exactly the +same mesh. Stronger regularization ties neighbouring brightnesses together more closely, reducing their freedom to +vary independently. We can therefore change the effective flexibility of the reconstruction without changing the +number of mesh points. Let’s compare the evidence values returned by `FitImaging`. """ @@ -298,21 +348,30 @@ def fit_with_coefficient(coefficient): ) """ -Compare this ranking with the source plots and the chi-squared values. The highest evidence need not belong to the reconstruction with the lowest chi-squared, because image agreement is only part of the comparison. +Compare this ranking with the source plots and the chi-squared values. The highest evidence need not belong to the +reconstruction with the lowest chi-squared, because image agreement is only part of the comparison. -We still need to inspect the residuals ourselves. Evidence does not explicitly examine their spatial pattern or guarantee that a preferred model is correct. Structured residuals can reveal shortcomings in the source, lens mass, PSF or other assumptions that this three-coefficient comparison does not address. +We still need to inspect the residuals ourselves. Evidence does not explicitly examine their spatial pattern or +guarantee that a preferred model is correct. Structured residuals can reveal shortcomings in the source, lens mass, +PSF or other assumptions that this three-coefficient comparison does not address. -For now, we have compared only three choices. The starting value of `1.0` has no special status, and the best of these three is not necessarily the best coefficient overall. Next, we will explore a broader range and see how this choice fits into the wider modelling process. +For now, we have compared only three choices. The starting value of `1.0` has no special status, and the best of +these three is not necessarily the best coefficient overall. Next, we will explore a broader range and see how this +choice fits into the wider modelling process. __Exploring the regularization coefficient__ -We have compared weak, moderate and strong regularization, but those three values were chosen to illustrate different behaviours. They do not tell us where the evidence reaches its highest value. +We have compared weak, moderate and strong regularization, but those three values were chosen to illustrate +different behaviours. They do not tell us where the evidence reaches its highest value. -Let’s explore the coefficient more systematically. We will keep the lens mass, mesh resolution, mask and noise map fixed, and reconstruct the source for a sequence of coefficients. +Let’s explore the coefficient more systematically. We will keep the lens mass, mesh resolution, mask and noise map +fixed, and reconstruct the source for a sequence of coefficients. -Regularization coefficients can span several orders of magnitude, so we use logarithmically spaced values. This gives us comparable coverage between `0.01` and `0.1`, between `0.1` and `1.0`, and so on. +Regularization coefficients can span several orders of magnitude, so we use logarithmically spaced values. This +gives us comparable coverage between `0.01` and `0.1`, between `0.1` and `1.0`, and so on. -Every point in this experiment requires a new source reconstruction. We are not taking one reconstructed source and smoothing it by different amounts afterwards. The coefficient changes the problem that the inversion solves. +Every point in this experiment requires a new source reconstruction. We are not taking one reconstructed source and +smoothing it by different amounts afterwards. The coefficient changes the problem that the inversion solves. """ import matplotlib.pyplot as plt @@ -357,19 +416,26 @@ def fit_with_coefficient(coefficient): plt.show() """ -Look for the part of the curve where the evidence is highest. Moving towards weaker regularization gives the source more freedom; moving towards stronger regularization increasingly restricts its variations. +Look for the part of the curve where the evidence is highest. Moving towards weaker regularization gives the source +more freedom; moving towards stronger regularization increasingly restricts its variations. -We may find a clear peak, a broad region with similar evidence, or a highest value at one end of the range. These outcomes mean different things. A boundary maximum tells us that this experiment has not bracketed the preferred coefficient—we should extend the range before claiming to have located it. +We may find a clear peak, a broad region with similar evidence, or a highest value at one end of the range. These +outcomes mean different things. A boundary maximum tells us that this experiment has not bracketed the preferred +coefficient—we should extend the range before claiming to have located it. -The plotted points are also discrete samples. Even an interior maximum only identifies the best coefficient we have tried so far. +The plotted points are also discrete samples. Even an interior maximum only identifies the best coefficient we have +tried so far. __Inspecting the preferred reconstruction__ Let’s inspect the reconstruction with the highest evidence in our sampled range. -It is tempting to treat the highest number as the end of the analysis. However, we should connect that number back to the source and image. We want to understand what this choice preserves, what it smooths away, and what the resulting model still fails to explain. +It is tempting to treat the highest number as the end of the analysis. However, we should connect that number back +to the source and image. We want to understand what this choice preserves, what it smooths away, and what the +resulting model still fails to explain. -Compare it with the weakly and strongly regularized examples. In particular, examine the distinct bright source components and the faint regions between them. Then look at the image residuals where those components are lensed. +Compare it with the weakly and strongly regularized examples. In particular, examine the distinct bright source +components and the faint regions between them. Then look at the image residuals where those components are lensed. """ best_index = int(np.argmax(evidence_grid)) @@ -403,21 +469,31 @@ def fit_with_coefficient(coefficient): aplt.subplot_fit_imaging_of_planes(fit=preferred_fit) """ -A preferred coefficient does not establish that every visible feature in the source is real. The reconstruction remains conditional on the lens model, source mesh, noise map and telescope blurring. +A preferred coefficient does not establish that every visible feature in the source is real. The reconstruction +remains conditional on the lens model, source mesh, noise map and telescope blurring. -Nor does a good-looking source excuse coherent residuals in the image. The source and residual plots provide complementary information: one shows what we inferred, while the other shows what that inference leaves unexplained. +Nor does a good-looking source excuse coherent residuals in the image. The source and residual plots provide +complementary information: one shows what we inferred, while the other shows what that inference leaves +unexplained. -**🤖 Ask AI:** If the evidence prefers a particular regularization coefficient but the residuals still follow the shape of an arc, what modelling assumptions should I investigate next? +**🤖 Ask AI:** If the evidence prefers a particular regularization coefficient but the residuals still follow the +shape of an arc, what modelling assumptions should I investigate next? __What is linear, and what requires a search?__ Before going further, let’s separate two parts of the calculation that are easy to confuse. -For each coefficient we supplied, the inversion solved for the source brightnesses. We did not give a non-linear search hundreds of independent source brightness parameters and ask it to explore their possible combinations. Instead, the source enters the predicted image linearly, allowing these brightnesses to be solved together using linear algebra. +For each coefficient we supplied, the inversion solved for the source brightnesses. We did not give a non-linear +search hundreds of independent source brightness parameters and ask it to explore their possible combinations. +Instead, the source enters the predicted image linearly, allowing these brightnesses to be solved together using +linear algebra. -Regularization is included in that solve. The source is not first reconstructed without a prior and then smoothed afterwards. The inferred brightnesses already reflect the balance between fitting the image and satisfying the smoothness prior. +Regularization is included in that solve. The source is not first reconstructed without a prior and then smoothed +afterwards. The inferred brightnesses already reflect the balance between fitting the image and satisfying the +smoothness prior. -Choosing the regularization coefficient is a different problem. We supplied several coefficients, performed an inversion for each, and compared their evidence values. Our loop is a simple grid search over one quantity. +Choosing the regularization coefficient is a different problem. We supplied several coefficients, performed an +inversion for each, and compared their evidence values. Our loop is a simple grid search over one quantity. We can see the difference in scale directly: """ @@ -431,9 +507,13 @@ def fit_with_coefficient(coefficient): print("Number of coefficients evaluated:", coefficient_grid.size) """ -The reconstruction contains an entry for each source mesh point in this single-mapper example. Some values may be constrained to zero at the mesh boundary, and regularization couples neighbouring values, so the number of entries is not the number of independently constrained source features. +The reconstruction contains an entry for each source mesh point in this single-mapper example. Some values may be +constrained to zero at the mesh boundary, and regularization couples neighbouring values, so the number of entries +is not the number of independently constrained source features. -During lens modelling, the search also changes the mass parameters. Each proposed mass model changes the ray tracing and therefore the mappings between source and image. The source must be reconstructed again for that proposal. +During lens modelling, the search also changes the mass parameters. Each proposed mass model changes the ray +tracing and therefore the mappings between source and image. The source must be reconstructed again for that +proposal. The sequence is therefore: @@ -442,17 +522,23 @@ def fit_with_coefficient(coefficient): 3. Solve for the source brightnesses. 4. Evaluate how well that model explains the data, accounting for the source prior. -This is what makes pixelized sources practical: the search explores the non-linear model choices, while the inversion handles the many source brightness values. +This is what makes pixelized sources practical: the search explores the non-linear model choices, while the +inversion handles the many source brightness values. __Mesh resolution and regularization belong together__ We have held the source mesh at `(25, 25)`. The preferred coefficient we found belongs to that choice of mesh. -Changing the mesh changes the locations and number of source brightness values, their neighbours, and how they contribute to the image. The same numerical coefficient therefore need not give an equivalent amount of smoothing on another mesh. +Changing the mesh changes the locations and number of source brightness values, their neighbours, and how they +contribute to the image. The same numerical coefficient therefore need not give an equivalent amount of smoothing +on another mesh. -This matters when testing resolution. If we increase the number of source points but keep the coefficient fixed, any change in the reconstruction reflects both the new resolution and its interaction with the prior. We cannot assume that we have made a fair comparison of the best reconstructions available at each resolution. +This matters when testing resolution. If we increase the number of source points but keep the coefficient fixed, +any change in the reconstruction reflects both the new resolution and its interaction with the prior. We cannot +assume that we have made a fair comparison of the best reconstructions available at each resolution. -Let’s repeat the coefficient experiment for `(15, 15)` and `(35, 35)`, alongside our existing `(25, 25)` results. We extend our helper so the mesh shape is an explicit input. +Let’s repeat the coefficient experiment for `(15, 15)` and `(35, 35)`, alongside our existing `(25, 25)` results. +We extend our helper so the mesh shape is an explicit input. """ def fit_with_coefficient(coefficient, mesh_shape=mesh_shape): @@ -515,21 +601,30 @@ def fit_with_coefficient(coefficient, mesh_shape=mesh_shape): """ This experiment performs 26 additional reconstructions, so it takes longer than our earlier three-way comparison. -Look at both the locations and heights of the curves’ maxima. The preferred coefficient may shift as the mesh changes. A finer mesh may help describe source structure, but adding points does not guarantee a higher evidence. +Look at both the locations and heights of the curves’ maxima. The preferred coefficient may shift as the mesh +changes. A finer mesh may help describe source structure, but adding points does not guarantee a higher evidence. -All three curves use the same image pixels and noise model. We also subtract one common reference evidence, preserving differences between the meshes. Subtracting each curve’s own maximum would hide those differences. +All three curves use the same image pixels and noise model. We also subtract one common reference evidence, +preserving differences between the meshes. Subtracting each curve’s own maximum would hide those differences. -As before, a boundary maximum means that the coefficient range needs extending. These are controlled resolution checks, not a demonstration that mesh dimensions should become free parameters in every lens-model search. +As before, a boundary maximum means that the coefficient range needs extending. These are controlled resolution +checks, not a demonstration that mesh dimensions should become free parameters in every lens-model search. __Wrap Up__ We can now give the regularization input a more meaningful interpretation. -The source mesh supplies brightness values that can vary to explain the image. Interpolation defines the brightness between those values. Regularization places a prior on their variation, discouraging unnecessary differences between neighbours. +The source mesh supplies brightness values that can vary to explain the image. Interpolation defines the brightness +between those values. Regularization places a prior on their variation, discouraging unnecessary differences +between neighbours. -Too little regularization can allow the reconstruction to explain noise through spurious source structure. Too much can suppress real structure and leave it visible in the image residuals. Evidence helps compare these choices by accounting for both image agreement and the freedom allowed by the source prior. +Too little regularization can allow the reconstruction to explain noise through spurious source structure. Too much +can suppress real structure and leave it visible in the image residuals. Evidence helps compare these choices by +accounting for both image agreement and the freedom allowed by the source prior. -We also saw that the coefficient is not a universal setting. Its appropriate value depends on the dataset, lens model, mesh and regularization scheme. A value that works for one reconstruction should not simply be carried into another analysis without checking it. +We also saw that the coefficient is not a universal setting. Its appropriate value depends on the dataset, lens +model, mesh and regularization scheme. A value that works for one reconstruction should not simply be carried into +another analysis without checking it. For a final comparison, print the preferred sampled coefficient for each mesh: """ @@ -549,9 +644,15 @@ def fit_with_coefficient(coefficient, mesh_shape=mesh_shape): fit = preferred_fit """ -Throughout this tutorial, we fixed the lens mass to the simulation values. We have selected source-reconstruction settings under that assumption; we have not inferred the mass or its uncertainty. +Throughout this tutorial, we fixed the lens mass to the simulation values. We have selected source-reconstruction +settings under that assumption; we have not inferred the mass or its uncertainty. -Later, these source reconstructions will sit inside a lens-model search. Before that, the next tutorial examines another practical issue: how the source mesh covers the ray-traced image coordinates, and why a small number of extreme coordinates can affect the resolution available to reconstruct the source. +Later, these source reconstructions will sit inside a lens-model search. Before that, the next tutorial examines +another practical issue: how the source mesh covers the ray-traced image coordinates, and why a small number of +extreme coordinates can affect the resolution available to reconstruct the source. -For readers who want the underlying equations, the workspace’s [pixelization likelihood guide](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/likelihood_function.py) follows the mapping, blurring, regularization and evidence calculations step by step. That derivation complements the experiments here; it is not required to continue using pixelizations. +For readers who want the underlying equations, the workspace’s [pixelization likelihood +guide](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/features/pixelization/likelihood_function.py) +follows the mapping, blurring, regularization and evidence calculations step by step. That derivation complements +the experiments here; it is not required to continue using pixelizations. """ diff --git a/scripts/chapter_3_pixelizations/tutorial_3_borders.py b/scripts/chapter_3_pixelizations/tutorial_3_borders.py index ef684c2..b831bc9 100644 --- a/scripts/chapter_3_pixelizations/tutorial_3_borders.py +++ b/scripts/chapter_3_pixelizations/tutorial_3_borders.py @@ -14,18 +14,22 @@ - What relocation changes—and what it does not - The mask still needs to cover the lensed source - Wrap up -""" -""" __Why the extent of the source mesh matters__ -In the previous tutorials, we chose how many points our rectangular source mesh contained. However, the number of points is only part of what determines its resolution. We also need to consider how much of the source plane those points cover. +In the previous tutorials, we chose how many points our rectangular source mesh contained. However, the number of +points is only part of what determines its resolution. We also need to consider how much of the source plane those +points cover. -A `(25, 25)` mesh spread across a small source region can describe finer structure than the same mesh spread across a much larger region. If a few ray-traced coordinates extend far beyond the source, the mesh can expand to accommodate them, leaving fewer points where we actually need to reconstruct the galaxy. +A `(25, 25)` mesh spread across a small source region can describe finer structure than the same mesh spread across +a much larger region. If a few ray-traced coordinates extend far beyond the source, the mesh can expand to +accommodate them, leaving fewer points where we actually need to reconstruct the galaxy. -This tutorial examines how that happens and introduces the border relocator, which provides a practical way to control these extreme coordinates. +This tutorial examines how that happens and introduces the border relocator, which provides a practical way to +control these extreme coordinates. -We return to a simpler simulated source so that its morphology does not distract from the geometry. The image contains lensed source light but no foreground lens light. +We return to a simpler simulated source so that its morphology does not distract from the geometry. The image +contains lensed source light but no foreground lens light. """ from autolens import jax_wrapper @@ -61,13 +65,16 @@ aplt.subplot_imaging_dataset(dataset=dataset_unmasked) """ -We will compare two masks with the same outer radius. One includes the centre of the image; the other excludes it. This lets us see what happens when the central image pixels enter the reconstruction. +We will compare two masks with the same outer radius. One includes the centre of the image; the other excludes it. +This lets us see what happens when the central image pixels enter the reconstruction. __What we mean by a border__ The border is the outermost boundary of the unmasked image region. -For a circular mask, this is straightforward: the border follows the outside of the circle. An annular mask has an inner and an outer edge, but the border used here follows the outer edge. The hole in the middle does not become a second outer border. +For a circular mask, this is straightforward: the border follows the outside of the circle. An annular mask has an +inner and an outer edge, but the border used here follows the outer edge. The hole in the middle does not become a +second outer border. Let’s plot both masks and mark their border coordinates. """ @@ -101,15 +108,20 @@ ) """ -The outer borders should coincide because the masks share the same outer radius. The difference is inside: the circular mask includes image pixels near the lens centre that the annular mask removes. +The outer borders should coincide because the masks share the same outer radius. The difference is inside: the +circular mask includes image pixels near the lens centre that the annular mask removes. -We will keep the masks fixed while comparing the source-plane grids. Choosing the mask and relocating a border are different operations: the mask selects which image pixels enter the fit, while relocation changes how certain coordinates are treated when constructing the source reconstruction. +We will keep the masks fixed while comparing the source-plane grids. Choosing the mask and relocating a border are +different operations: the mask selects which image pixels enter the fit, while relocation changes how certain +coordinates are treated when constructing the source reconstruction. __Starting without border relocation__ First, let’s reconstruct the source using the annular mask with border relocation explicitly switched off. -We use the mass model that generated the simulation and a uniform rectangular source mesh. The helper below lets us change the mask and relocation setting while keeping the lens model, mesh shape and regularization coefficient unchanged. +We use the mass model that generated the simulation and a uniform rectangular source mesh. The helper below lets us +change the mask and relocation setting while keeping the lens model, mesh shape and regularization coefficient +unchanged. """ # Match mesh size to capped smoke data; normal tutorial runs retain 25 x 25. @@ -184,15 +196,18 @@ def fit_with_mask_and_border(mask, use_border_relocator): ) """ -The first plot shows where the image coordinates land after ray tracing. The second shows the source mesh and the brightnesses inferred on it. +The first plot shows where the image coordinates land after ray tracing. The second shows the source mesh and the +brightnesses inferred on it. -Look at the coordinate ranges as well as the source itself. These tell us how much source-plane area the mesh is covering. We will use this reconstruction as a reference when we add the central image pixels. +Look at the coordinate ranges as well as the source itself. These tell us how much source-plane area the mesh is +covering. We will use this reconstruction as a reference when we add the central image pixels. __Including the central image pixels__ Now repeat the calculation with the circular mask, still without border relocation. -The outer image boundary is unchanged. We are adding the pixels within the central hole of the annulus, rather than extending the image to larger radii. +The outer image boundary is unchanged. We are adding the pixels within the central hole of the annulus, rather than +extending the image to larger radii. """ fit_circular = fit_with_mask_and_border( @@ -228,19 +243,24 @@ def fit_with_mask_and_border(mask, use_border_relocator): ) """ -Compare the source-plane extent with the annular case. The added image pixels can trace outside the compact region occupied by the other coordinates, causing the rectangular mesh to cover a larger area. +Compare the source-plane extent with the annular case. The added image pixels can trace outside the compact region +occupied by the other coordinates, causing the rectangular mesh to cover a larger area. -Both reconstructions still use the same number of mesh points. If the mesh expands, their spacing increases, reducing the resolution available to describe the central source. +Both reconstructions still use the same number of mesh points. If the mesh expands, their spacing increases, +reducing the resolution available to describe the central source. -This illustrates why increasing the number of image pixels does not automatically improve a reconstruction with a fixed mesh. We must also consider how those pixels affect the source-plane coverage. +This illustrates why increasing the number of image pixels does not automatically improve a reconstruction with a +fixed mesh. We must also consider how those pixels affect the source-plane coverage. -The two masks contain different data, so this is a geometric comparison—not a direct evidence comparison between otherwise identical fits. +The two masks contain different data, so this is a geometric comparison—not a direct evidence comparison between +otherwise identical fits. __Following the central pixels into the source plane__ Let’s confirm where the extra source-plane coordinates come from. -We select two small groups of image pixels: one close to the lens centre and another near the lensed arc. As in tutorial 1, we use the same index groups in both planes, so matching colours identify the same light paths. +We select two small groups of image pixels: one close to the lens centre and another near the lensed arc. As in +tutorial 1, we use the same index groups in both planes, so matching colours identify the same light paths. """ image_coordinates = np.asarray( @@ -280,25 +300,38 @@ def fit_with_mask_and_border(mask, use_border_relocator): ) """ -The central image coordinates need not map close to the source-plane origin. Their source positions depend on the difference between their image positions and the lens deflections. +The central image coordinates need not map close to the source-plane origin. Their source positions depend on the +difference between their image positions and the lens deflections. -Near the centre of a cuspy mass distribution, a small image region can correspond to a much larger source region. This is demagnification: the image occupies less area than the corresponding source region. It does not require the deflection angle itself to become arbitrarily large. +Near the centre of a cuspy mass distribution, a small image region can correspond to a much larger source region. +This is demagnification: the image occupies less area than the corresponding source region. It does not require the +deflection angle itself to become arbitrarily large. -For our reconstruction, the practical consequence is that central image pixels can map well outside the region traced by the arcs. The mesh then spends some of its resolution covering those distant positions. +For our reconstruction, the practical consequence is that central image pixels can map well outside the region +traced by the arcs. The mesh then spends some of its resolution covering those distant positions. -There is another concern. Source structure reconstructed at those positions may predict other images outside our chosen mask, where we are not comparing the model with the data. The reconstruction is then missing some of the observational constraints that would otherwise act on that structure. +There is another concern. Source structure reconstructed at those positions may predict other images outside our +chosen mask, where we are not comparing the model with the data. The reconstruction is then missing some of the +observational constraints that would otherwise act on that structure. -In the next blocks, we will trace the outer border into the source plane and examine how border relocation handles coordinates beyond it. We will compare the same circularly masked dataset with relocation switched off and on, so that the effect of relocation is isolated. +In the next blocks, we will trace the outer border into the source plane and examine how border relocation handles +coordinates beyond it. We will compare the same circularly masked dataset with relocation switched off and on, so +that the effect of relocation is isolated. -**🤖 Ask AI:** Why can a small group of central image pixels change the resolution of a rectangular source mesh, even when most of the observed source light lies in the arcs? +**🤖 Ask AI:** Why can a small group of central image pixels change the resolution of a rectangular source mesh, +even when most of the observed source light lies in the arcs? __Tracing the outer border__ -We have seen that some central image pixels trace beyond the compact source region. To decide how to handle those coordinates, we first need a reference boundary in the source plane. +We have seen that some central image pixels trace beyond the compact source region. To decide how to handle those +coordinates, we first need a reference boundary in the source plane. -We obtain this from the outer border of the image mask. These are ordinary image coordinates, so we can ray-trace them through the same lens model as every other pixel. Their traced positions describe where the edge of our fitted image region maps into the source plane. +We obtain this from the outer border of the image mask. These are ordinary image coordinates, so we can ray-trace +them through the same lens model as every other pixel. Their traced positions describe where the edge of our fitted +image region maps into the source plane. -Let’s highlight the border pixels in the image and follow the same indexes into the source plane. Border relocation is still switched off here, so we are looking at the original ray-traced coordinates. +Let’s highlight the border pixels in the image and follow the same indexes into the source plane. Border relocation +is still switched off here, so we are looking at the original ray-traced coordinates. """ border_indexes = mask_circular.derive_indexes.border_slim.tolist() @@ -316,17 +349,22 @@ def fit_with_mask_and_border(mask, use_border_relocator): ) """ -Compare the highlighted border with the central image pixels traced in the previous block. Some image coordinates that were well inside the image mask can land beyond the traced outer border in the source plane. +Compare the highlighted border with the central image pixels traced in the previous block. Some image coordinates +that were well inside the image mask can land beyond the traced outer border in the source plane. -This is the important geometric distinction: being inside the image-plane border does not guarantee that a coordinate remains inside its traced counterpart. +This is the important geometric distinction: being inside the image-plane border does not guarantee that a +coordinate remains inside its traced counterpart. -The border relocator uses the traced outer-border coordinates to estimate a source-plane boundary. In the current implementation, this is an ellipse. Coordinates beyond that boundary are moved inward for the source reconstruction, preventing them from extending its coverage unchecked. +The border relocator uses the traced outer-border coordinates to estimate a source-plane boundary. In the current +implementation, this is an ellipse. Coordinates beyond that boundary are moved inward for the source +reconstruction, preventing them from extending its coverage unchecked. __Switching border relocation on__ Let’s repeat the circular-mask fit with border relocation enabled. -The data, mask, lens mass, mesh shape and regularization coefficient all remain unchanged. This time, the source mesh is constructed using the relocated coordinates. +The data, mask, lens mass, mesh shape and regularization coefficient all remain unchanged. This time, the source +mesh is constructed using the relocated coordinates. """ fit_relocated = fit_with_mask_and_border( @@ -355,9 +393,11 @@ def fit_with_mask_and_border(mask, use_border_relocator): ) """ -Follow the same coloured coordinate groups through the two plots. Coordinates outside the estimated boundary are relocated towards it; those inside remain unchanged. +Follow the same coloured coordinate groups through the two plots. Coordinates outside the estimated boundary are +relocated towards it; those inside remain unchanged. -If relocation reduces the mesh extent, the same number of source points now covers a smaller area. This can restore resolution in the region where the source is being reconstructed, without increasing the mesh dimensions. +If relocation reduces the mesh extent, the same number of source points now covers a smaller area. This can restore +resolution in the region where the source is being reconstructed, without increasing the mesh dimensions. We can also identify which coordinates moved and display their positions before and after relocation. """ @@ -391,13 +431,17 @@ def fit_with_mask_and_border(mask, use_border_relocator): ) """ -These are still the same image pixels with the same measured brightnesses. Relocation changes their source-plane mapping coordinates; it does not remove them from the fit or move their positions in the observed image. +These are still the same image pixels with the same measured brightnesses. Relocation changes their source-plane +mapping coordinates; it does not remove them from the fit or move their positions in the observed image. __What relocation changes—and what it does not__ -Border relocation is a numerical treatment of the source reconstruction. It does not change the lens mass profile or the physical deflection calculation. +Border relocation is a numerical treatment of the source reconstruction. It does not change the lens mass profile +or the physical deflection calculation. -That distinction matters. If we ray-trace the image grid directly through the tracer, we recover the original source coordinates. The mapper used by the relocated inversion instead contains the coordinates after the border treatment. +That distinction matters. If we ray-trace the image grid directly through the tracer, we recover the original +source coordinates. The mapper used by the relocated inversion instead contains the coordinates after the border +treatment. Let’s compare these explicitly. """ @@ -427,9 +471,11 @@ def fit_with_mask_and_border(mask, use_border_relocator): print("Position used after relocation:", coordinates_after[index]) """ -We should therefore understand relocation as a practical boundary treatment, not an alternative physical lens equation. It controls how extreme coordinates participate in a reconstruction whose image coverage is finite. +We should therefore understand relocation as a practical boundary treatment, not an alternative physical lens +equation. It controls how extreme coordinates participate in a reconstruction whose image coverage is finite. -The next step is to inspect its effect on the inferred source and the model image. We use a common source colour scale so that changes in brightness are not hidden by separately scaled figures. +The next step is to inspect its effect on the inferred source and the model image. We use a common source colour +scale so that changes in brightness are not hidden by separately scaled figures. """ source_vmax = max( @@ -461,19 +507,25 @@ def fit_with_mask_and_border(mask, use_border_relocator): ) """ -Look for changes in the mesh coverage, the source structure and the residuals. A more compact mesh alone does not prove that the model is accurate, and relocation does not guarantee freedom from systematic errors. +Look for changes in the mesh coverage, the source structure and the residuals. A more compact mesh alone does not +prove that the model is accurate, and relocation does not guarantee freedom from systematic errors. -We have also kept the regularization coefficient fixed to isolate the change in configuration. As tutorial 2 showed, changing mesh geometry can alter how regularization acts, so this is a diagnostic comparison rather than a complete optimization of both reconstructions. +We have also kept the regularization coefficient fixed to isolate the change in configuration. As tutorial 2 +showed, changing mesh geometry can alter how regularization acts, so this is a diagnostic comparison rather than a +complete optimization of both reconstructions. __The mask still needs to cover the lensed source__ Border relocation does not replace choosing an appropriate image mask. -If the mask excludes part of an arc or another image of the source, those pixels do not constrain the reconstruction. Relocating source coordinates cannot recover information that we have excluded from the fit. +If the mask excludes part of an arc or another image of the source, those pixels do not constrain the +reconstruction. Relocating source coordinates cannot recover information that we have excluded from the fit. -The mask also determines the border from which the source-plane boundary is estimated. Changing its size therefore changes both the image pixels being fitted and the boundary treatment. +The mask also determines the border from which the source-plane boundary is estimated. Changing its size therefore +changes both the image pixels being fitted and the boundary treatment. -Let’s inspect several circular masks before fitting them. We plot their borders on the full image so that any source light outside the selected region remains visible. +Let’s inspect several circular masks before fitting them. We plot their borders on the full image so that any +source light outside the selected region remains visible. """ mask_radii = [2.0, 2.5, 3.0] @@ -494,7 +546,8 @@ def fit_with_mask_and_border(mask, use_border_relocator): ) """ -Check whether each border encloses the visible lensed emission with some surrounding background. A mask that follows only the brightest parts can exclude faint extensions that still matter to the reconstruction. +Check whether each border encloses the visible lensed emission with some surrounding background. A mask that +follows only the brightest parts can exclude faint extensions that still matter to the reconstruction. Now compare the resulting fits with relocation enabled. """ @@ -521,21 +574,32 @@ def fit_with_mask_and_border(mask, use_border_relocator): aplt.subplot_fit_imaging(fit=current_fit) """ -Compare the source structure and residuals, especially where a smaller mask approaches the arcs. If the reconstruction changes substantially as clearly relevant source light enters the mask, the smaller-mask result deserves closer inspection. +Compare the source structure and residuals, especially where a smaller mask approaches the arcs. If the +reconstruction changes substantially as clearly relevant source light enters the mask, the smaller-mask result +deserves closer inspection. -Do not rank these masks by their raw evidence values: they contain different sets of image pixels. The purpose here is to examine coverage and stability, not to select whichever mask produces the largest number. +Do not rank these masks by their raw evidence values: they contain different sets of image pixels. The purpose here +is to examine coverage and stability, not to select whichever mask produces the largest number. -**🤖 Ask AI:** Why can a reconstruction appear satisfactory inside a small mask while failing to explain other visible parts of the same lensed source? +**🤖 Ask AI:** Why can a reconstruction appear satisfactory inside a small mask while failing to explain other +visible parts of the same lensed source? __Wrap up__ -We began with a rectangular source mesh whose resolution depended on both its number of points and the area they covered. A small number of extreme ray-traced coordinates could expand that area and reduce the resolution available for the source. +We began with a rectangular source mesh whose resolution depended on both its number of points and the area they +covered. A small number of extreme ray-traced coordinates could expand that area and reduce the resolution +available for the source. -The border relocator uses the traced outer image border to estimate a source-plane boundary, then moves coordinates beyond that boundary inward for the reconstruction. The observed image pixels remain in the fit, and the physical lens model is unchanged. +The border relocator uses the traced outer image border to estimate a source-plane boundary, then moves coordinates +beyond that boundary inward for the reconstruction. The observed image pixels remain in the fit, and the physical +lens model is unchanged. -In routine modelling, we normally leave this treatment enabled. Knowing what it does is useful when a source mesh extends unexpectedly far from the reconstructed galaxy, or when a reconstruction changes strongly with the mask. +In routine modelling, we normally leave this treatment enabled. Knowing what it does is useful when a source mesh +extends unexpectedly far from the reconstructed galaxy, or when a reconstruction changes strongly with the mask. -These issues can also occur in systems with several lens galaxies. Extreme coordinates need not originate only near the centre of the image; they can be associated with other mass concentrations. The same diagnostic applies: follow the image coordinates into the source plane and inspect the boundary and mesh coverage. +These issues can also occur in systems with several lens galaxies. Extreme coordinates need not originate only near +the centre of the image; they can be associated with other mass concentrations. The same diagnostic applies: follow +the image coordinates into the source plane and inspect the boundary and mesh coverage. For subsequent inspection, return to our circular mask with radius `2.5` arcsec and relocation enabled. """ @@ -555,7 +619,10 @@ def fit_with_mask_and_border(mask, use_border_relocator): ) """ -We have now examined the source mesh, interpolation, regularization and border treatment while holding the lens mass fixed. +We have now examined the source mesh, interpolation, regularization and border treatment while holding the lens +mass fixed. -In the next tutorial, we let the mass model vary. We will see how a pixelized source participates in lens modelling, why its flexibility can admit misleading solutions, and how a sensible starting model helps the search find the relevant region of parameter space. +In the next tutorial, we let the mass model vary. We will see how a pixelized source participates in lens +modelling, why its flexibility can admit misleading solutions, and how a sensible starting model helps the search +find the relevant region of parameter space. """ diff --git a/scripts/chapter_3_pixelizations/tutorial_4_lens_modeling.py b/scripts/chapter_3_pixelizations/tutorial_4_lens_modeling.py index ac675a1..8d416f3 100644 --- a/scripts/chapter_3_pixelizations/tutorial_4_lens_modeling.py +++ b/scripts/chapter_3_pixelizations/tutorial_4_lens_modeling.py @@ -16,26 +16,36 @@ - Running the pixelized-source search - Establishing the foreground light model - Using that result in the pixelized-source fit -""" -""" __Lens modelling with a pixelized source__ -So far, we have reconstructed sources while keeping the lens mass fixed. We could therefore concentrate on the mesh, mappings and regularization without worrying about whether the lens model itself was correct. +So far, we have reconstructed sources while keeping the lens mass fixed. We could therefore concentrate on the +mesh, mappings and regularization without worrying about whether the lens model itself was correct. -In a scientific analysis, the mass distribution is usually one of the things we want to measure. Changing it changes the ray tracing, which changes how the source must be reconstructed to explain the image. +In a scientific analysis, the mass distribution is usually one of the things we want to measure. Changing it +changes the ray tracing, which changes how the source must be reconstructed to explain the image. -Pixelizations are powerful here because they can describe complicated source structure without requiring us to specify a separate analytic profile for every bright component. The non-linear search explores the lens parameters and regularization settings, while the inversion solves for the source brightnesses. +Pixelizations are powerful here because they can describe complicated source structure without requiring us to +specify a separate analytic profile for every bright component. The non-linear search explores the lens parameters +and regularization settings, while the inversion solves for the source brightnesses. -However, this flexibility comes with a difficulty. An incorrect mass model can sometimes be compensated for by an unusual source reconstruction. A close fit to the image does not, by itself, establish that we have found the right mass distribution. +However, this flexibility comes with a difficulty. An incorrect mass model can sometimes be compensated for by an +unusual source reconstruction. A close fit to the image does not, by itself, establish that we have found the right +mass distribution. -We will investigate this using the familiar simulated lens with no foreground light. Its true Einstein radius is `1.6` arcsec, giving us a reference against which to compare deliberately incorrect models. +We will investigate this using the familiar simulated lens with no foreground light. Its true Einstein radius is +`1.6` arcsec, giving us a reference against which to compare deliberately incorrect models. -The published example below makes this ambiguity visible before we explore it in code. Compare the reconstructed source structures with their corresponding image fits: a model can describe much of the observed image while assigning it a very different source morphology. +The published example below makes this ambiguity visible before we explore it in code. Compare the reconstructed +source structures with their corresponding image fits: a model can describe much of the observed image while +assigning it a very different source morphology. -![Demagnified source solutions, Figure 1 of Maresca et al.](https://raw.githubusercontent.com/PyAutoLabs/HowToLens/main/scripts/chapter_3_pixelizations/images/maresca_fig1.png) +![Demagnified source solutions, Figure 1 of Maresca et +al.](https://raw.githubusercontent.com/PyAutoLabs/HowToLens/main/scripts/chapter_3_pixelizations/images/maresca_fig1.png) -Figure 1 from [Maresca et al. (2021)](https://arxiv.org/abs/2012.04665), also discussed in the [PyAutoLens demagnified-solutions guide](https://pyautolens.readthedocs.io/en/latest/general/demagnified_solutions.html). We reproduce this figure to illustrate the ambiguity; the experiments below use our own simulated dataset. +Figure 1 from [Maresca et al. (2021)](https://arxiv.org/abs/2012.04665), also discussed in the [PyAutoLens +demagnified-solutions guide](https://pyautolens.readthedocs.io/en/latest/general/demagnified_solutions.html). We +reproduce this figure to illustrate the ambiguity; the experiments below use our own simulated dataset. """ from autolens import jax_wrapper @@ -77,15 +87,19 @@ aplt.subplot_imaging_dataset(dataset=dataset) """ -We retain one sample per image pixel for the indexed mapping demonstration below. As before, the sampling accuracy would need checking before interpreting a scientific fit. +We retain one sample per image pixel for the indexed mapping demonstration below. As before, the sampling accuracy +would need checking before interpreting a scientific fit. __Giving the inversion an incorrect mass model__ Let’s begin with a mass model whose Einstein radius is `0.8` arcsec—half the value used in the simulation. -Everything else remains fixed, including the mass ellipticity, external shear, mesh dimensions and regularization coefficient. We then ask the inversion to reconstruct whatever source best satisfies this model’s mappings and smoothness prior. +Everything else remains fixed, including the mass ellipticity, external shear, mesh dimensions and regularization +coefficient. We then ask the inversion to reconstruct whatever source best satisfies this model’s mappings and +smoothness prior. -This is the kind of incorrect mass model that a non-linear search could encounter while exploring a broad parameter range. +This is the kind of incorrect mass model that a non-linear search could encounter while exploring a broad parameter +range. """ # Match mesh size to capped smoke data; normal tutorial runs retain 25 x 25. @@ -138,11 +152,17 @@ def fit_at_einstein_radius(einstein_radius, coefficient=1.0): aplt.subplot_fit_imaging_of_planes(fit=incorrect_fit) """ -Inspect both the image residuals and the reconstructed source. The experiment is designed to show how an inversion can explain some of the observed structure even when the lens mass is substantially wrong. +Inspect both the image residuals and the reconstructed source. The experiment is designed to show how an inversion +can explain some of the observed structure even when the lens mass is substantially wrong. -Under insufficient deflection, parts of the observed arcs can remain separated in the source plane. Instead of reconstructing one compact galaxy whose light produces multiple images, the inversion can assign brightness to those separate source regions. The source may begin to resemble a less strongly lensed version of the observed image. +Under insufficient deflection, parts of the observed arcs can remain separated in the source plane. Instead of +reconstructing one compact galaxy whose light produces multiple images, the inversion can assign brightness to +those separate source regions. The source may begin to resemble a less strongly lensed version of the observed +image. -Such solutions are often called **demagnified solutions**. This is a different issue from the demagnified central image coordinates discussed in the borders tutorial: here, the problem concerns an alternative mass-and-source interpretation of the image. +Such solutions are often called **demagnified solutions**. This is a different issue from the demagnified central +image coordinates discussed in the borders tutorial: here, the problem concerns an alternative mass-and-source +interpretation of the image. Border relocation does not remove this modelling ambiguity. @@ -150,7 +170,8 @@ def fit_at_einstein_radius(einstein_radius, coefficient=1.0): Now repeat the reconstruction with the Einstein radius restored to `1.6` arcsec. -The inversion still has the same mesh dimensions and regularization coefficient. Only the Einstein radius changes. This gives us a controlled comparison of how the mass model affects the source required to explain the image. +The inversion still has the same mesh dimensions and regularization coefficient. Only the Einstein radius changes. +This gives us a controlled comparison of how the mass model affects the source required to explain the image. """ correct_fit = fit_at_einstein_radius(einstein_radius=1.6) @@ -182,9 +203,13 @@ def fit_at_einstein_radius(einstein_radius, coefficient=1.0): ) """ -Compare the source morphology and its coordinate extent. With the correct mass model, the different images of the source should be brought into a mutually consistent source reconstruction. With an incorrect mass model, the inversion may need more extended or fragmented structure to account for them. +Compare the source morphology and its coordinate extent. With the correct mass model, the different images of the +source should be brought into a mutually consistent source reconstruction. With an incorrect mass model, the +inversion may need more extended or fragmented structure to account for them. -This is where regularization and evidence become important. The inversion’s flexibility does not mean that all source reconstructions are equally preferred. A reconstruction requiring large variations between neighbouring brightnesses is treated differently from one that explains the data with a smoother source. +This is where regularization and evidence become important. The inversion’s flexibility does not mean that all +source reconstructions are equally preferred. A reconstruction requiring large variations between neighbouring +brightnesses is treated differently from one that explains the data with a smoother source. Let’s compare image agreement and evidence directly. """ @@ -202,17 +227,22 @@ def fit_at_einstein_radius(einstein_radius, coefficient=1.0): print(" Log evidence:", float(current_fit.log_evidence)) """ -The expected lesson is that image agreement and source plausibility must be considered together. We should inspect the calculated evidence values rather than assume that the correct model wins by a particular amount. +The expected lesson is that image agreement and source plausibility must be considered together. We should inspect +the calculated evidence values rather than assume that the correct model wins by a particular amount. -We have also held the coefficient fixed. A full model search would allow regularization to change, so these two evaluations do not establish the final relative preference after all model parameters have been explored. +We have also held the coefficient fixed. A full model search would allow regularization to change, so these two +evaluations do not establish the final relative preference after all model parameters have been explored. __Seeing how the mass model changes the mappings__ The source plots show the outcome, but the mappings help explain why it happens. -Let’s select two small image regions on opposite sides of the lens and follow them into the source plane under each mass model. The image indexes stay the same: we are examining the same measured pixels through two different ray-tracing calculations. +Let’s select two small image regions on opposite sides of the lens and follow them into the source plane under each +mass model. The image indexes stay the same: we are examining the same measured pixels through two different +ray-tracing calculations. -To isolate the physical ray tracing, we use the tracer directly. These plots show the coordinates before border relocation. +To isolate the physical ray tracing, we use the tracer directly. These plots show the coordinates before border +relocation. """ image_grid = dataset.grids.pixelization @@ -249,21 +279,30 @@ def fit_at_einstein_radius(einstein_radius, coefficient=1.0): ) """ -Look at the relative positions of the coloured groups. Changing the mass model changes whether image regions can be explained by nearby parts of the source or require brightness in more widely separated regions. +Look at the relative positions of the coloured groups. Changing the mass model changes whether image regions can be +explained by nearby parts of the source or require brightness in more widely separated regions. -These groups were chosen to illustrate the geometry, not identified as exact images of the same source feature. We should therefore not expect their traced coordinates to coincide perfectly, even for the correct model. +These groups were chosen to illustrate the geometry, not identified as exact images of the same source feature. We +should therefore not expect their traced coordinates to coincide perfectly, even for the correct model. -For a stronger constraint, we can identify image positions that genuinely correspond to the same source feature and require them to trace close together. We will introduce that idea when preparing the model search. +For a stronger constraint, we can identify image positions that genuinely correspond to the same source feature and +require them to trace close together. We will introduce that idea when preparing the model search. -**🤖 Ask AI:** How can an incorrect mass model still fit an arc if the source reconstruction is allowed to place light in several separate source regions? +**🤖 Ask AI:** How can an incorrect mass model still fit an arc if the source reconstruction is allowed to place +light in several separate source regions? __Why evidence does not remove the search difficulty__ -Even if the correct mass model has higher evidence than our deliberately incorrect example, the non-linear search still has to find it. +Even if the correct mass model has higher evidence than our deliberately incorrect example, the non-linear search +still has to find it. -A pixelized source can provide tolerable image fits across a broad range of incorrect mass models. This can create competing regions of parameter space that require substantial exploration. Solving the source brightnesses efficiently does not make the remaining non-linear problem trivial or guarantee that a search finds the relevant solution. +A pixelized source can provide tolerable image fits across a broad range of incorrect mass models. This can create +competing regions of parameter space that require substantial exploration. Solving the source brightnesses +efficiently does not make the remaining non-linear problem trivial or guarantee that a search finds the relevant +solution. -Let’s examine a simple slice through this problem by changing only the Einstein radius. At every value, we reconstruct a new source and calculate its evidence. +Let’s examine a simple slice through this problem by changing only the Einstein radius. At every value, we +reconstruct a new source and calculate its evidence. """ einstein_radii = np.array( @@ -315,25 +354,42 @@ def fit_at_einstein_radius(einstein_radius, coefficient=1.0): plt.show() """ -This scan shows how the evidence behaves along one restricted direction. It is not a posterior distribution or an uncertainty measurement: the other mass parameters and regularization coefficient remain fixed, and we have sampled only a few radii. +This scan shows how the evidence behaves along one restricted direction. It is not a posterior distribution or an +uncertainty measurement: the other mass parameters and regularization coefficient remain fixed, and we have sampled +only a few radii. -In a full search, those other parameters can vary together. An incorrect Einstein radius may be partly compensated for by changes in ellipticity, shear or source regularization, creating possibilities that this one-dimensional experiment cannot show. +In a full search, those other parameters can vary together. An incorrect Einstein radius may be partly compensated +for by changes in ellipticity, shear or source regularization, creating possibilities that this one-dimensional +experiment cannot show. -A useful strategy is therefore **search chaining**. We begin with a simpler source model to find a plausible region of lens parameter space, then introduce the pixelized source so that the detailed source structure can be reconstructed. +A useful strategy is therefore **search chaining**. We begin with a simpler source model to find a plausible region +of lens parameter space, then introduce the pixelized source so that the detailed source structure can be +reconstructed. -The initial analytic source is a starting point, not the final description of the galaxy. Its purpose is to help establish the lensing geometry without giving the source enough freedom to reproduce almost any image arrangement. +The initial analytic source is a starting point, not the final description of the galaxy. Its purpose is to help +establish the lensing geometry without giving the source enough freedom to reproduce almost any image arrangement. -In the next blocks, we will turn that idea into a model-search setup and explain how corresponding image positions can help reject misleading solutions. We will also introduce foreground lens light, which must be modelled alongside the pixelized source. +In the next blocks, we will turn that idea into a model-search setup and explain how corresponding image positions +can help reject misleading solutions. We will also introduce foreground lens light, which must be modelled +alongside the pixelized source. __Starting with a simpler source model__ -The misleading reconstructions we have just examined arise because a pixelized source has enough freedom to compensate for some incorrect mass models. +The misleading reconstructions we have just examined arise because a pixelized source has enough freedom to +compensate for some incorrect mass models. -A useful starting point is therefore a source model with less freedom. We first fit an analytic light profile, using it to establish a plausible lensing geometry. Once that fit has identified a useful region of parameter space, we replace the analytic source with a pixelization. +A useful starting point is therefore a source model with less freedom. We first fit an analytic light profile, +using it to establish a plausible lensing geometry. Once that fit has identified a useful region of parameter +space, we replace the analytic source with a pixelization. -This is search chaining, introduced in chapter 2. Here, the reason for chaining is particularly important: we want the pixelized reconstruction to improve the description of the source without beginning its search among a wide range of unrelated mass-and-source configurations. +This is search chaining, introduced in chapter 2. Here, the reason for chaining is particularly important: we want +the pixelized reconstruction to improve the description of the source without beginning its search among a wide +range of unrelated mass-and-source configurations. -We use the multi-Gaussian expansion (MGE) from Chapter 2 as our baseline analytic source. Its fixed Gaussian widths and linearly solved intensities provide radial flexibility while a common centre and elliptical shape keep the geometry manageable. For a more complex galaxy, this first model may leave source structure unexplained. We would inspect those residuals and the inferred geometry before using it to initialize the next search. +We use the multi-Gaussian expansion (MGE) from Chapter 2 as our baseline analytic source. Its fixed Gaussian widths +and linearly solved intensities provide radial flexibility while a common centre and elliptical shape keep the +geometry manageable. For a more complex galaxy, this first model may leave source structure unexplained. We would +inspect those residuals and the inferred geometry before using it to initialize the next search. """ import autofit as af @@ -378,15 +434,20 @@ def fit_at_einstein_radius(einstein_radius, coefficient=1.0): print(model_1.info) """ -Unlike our earlier experiments, the Einstein radius, mass ellipticity and external shear are now free. The MGE group’s common centre and elliptical shape are also free. Its Gaussian widths are fixed, and all Gaussian intensities are solved linearly. +Unlike our earlier experiments, the Einstein radius, mass ellipticity and external shear are now free. The MGE +group’s common centre and elliptical shape are also free. Its Gaussian widths are fixed, and all Gaussian +intensities are solved linearly. -Inspect `model_1.info` to see the complete set of free parameters and their priors. The known simulation values provide a check on the result; they are not supplied as the answer to the search. +Inspect `model_1.info` to see the complete set of free parameters and their priors. The known simulation values +provide a check on the result; they are not supplied as the answer to the search. __Running and inspecting the initial search__ -We now perform a model fit. For each proposal, the search changes the non-linear parameters, predicts the image and evaluates its agreement with the data. +We now perform a model fit. For each proposal, the search changes the non-linear parameters, predicts the image and +evaluates its agreement with the data. -This is different from calling `FitImaging` with specified parameter values. The search explores alternatives and produces samples that describe the inferred parameter distribution. +This is different from calling `FitImaging` with specified parameter values. The search explores alternatives and +produces samples that describe the inferred parameter distribution. """ search_1 = af.Nautilus( @@ -411,23 +472,34 @@ def fit_at_einstein_radius(einstein_radius, coefficient=1.0): aplt.subplot_fit_imaging_of_planes(fit=initial_fit) """ -Before continuing, inspect the model image, residuals and source. The purpose of this first fit is to establish a credible starting geometry, so a poor or clearly misleading solution should not simply be passed to the next search. +Before continuing, inspect the model image, residuals and source. The purpose of this first fit is to establish a +credible starting geometry, so a poor or clearly misleading solution should not simply be passed to the next +search. -For this simulated example, we can also compare the recovered Einstein radius with the input value of `1.6` arcsec. In an observed system, that answer would not be available; we would rely on the fit diagnostics, image configuration and parameter constraints. +For this simulated example, we can also compare the recovered Einstein radius with the input value of `1.6` arcsec. +In an observed system, that answer would not be available; we would rely on the fit diagnostics, image +configuration and parameter constraints. -The maximum-likelihood fit is useful for visualization, but it is only one model. The result summary and samples are needed to assess uncertainty and whether the search adequately explored the parameters. +The maximum-likelihood fit is useful for visualization, but it is only one model. The result summary and samples +are needed to assess uncertainty and whether the search adequately explored the parameters. __Requiring corresponding images to trace together__ Search chaining gives us a useful starting point, but we can also impose a simple geometric check. -If several image positions represent the same source feature, a plausible mass model should trace them close together in the source plane. An incorrect model that reconstructs them as unrelated pieces of source light fails this check. +If several image positions represent the same source feature, a plausible mass model should trace them close +together in the source plane. An incorrect model that reconstructs them as unrelated pieces of source light fails +this check. -The `PositionsLH` object applies a penalty when the traced positions are separated by more than a chosen threshold. Models that bring them within the threshold receive no positions penalty. +The `PositionsLH` object applies a penalty when the traced positions are separated by more than a chosen threshold. +Models that bring them within the threshold receive no positions penalty. -`PositionsLH` penalizes demagnified solutions whose corresponding image positions fail to trace sufficiently close together. +`PositionsLH` penalizes demagnified solutions whose corresponding image positions fail to trace sufficiently close +together. -We can identify corresponding positions manually, but our initial fit also provides a way to estimate them. The following method uses the fitted source centre and mass model to predict its multiple-image positions and constructs a positions constraint for the next search. +We can identify corresponding positions manually, but our initial fit also provides a way to estimate them. The +following method uses the fitted source centre and mass model to predict its multiple-image positions and +constructs a positions constraint for the next search. """ positions_likelihood = result_1.positions_likelihood_from( @@ -461,19 +533,27 @@ def fit_at_einstein_radius(einstein_radius, coefficient=1.0): ) """ -These positions are predictions from the initial model, not independent measurements. Check that they correspond sensibly to the observed image configuration before using them. +These positions are predictions from the initial model, not independent measurements. Check that they correspond +sensibly to the observed image configuration before using them. -The threshold should be loose enough to allow the mass model to improve. We are trying to reject grossly inconsistent mappings, not force every subsequent model to reproduce the initial solution exactly. Here, `factor` enlarges the separation estimated from the initial result, while `minimum_threshold` prevents the returned threshold from becoming smaller than `0.2` arcsec. +The threshold should be loose enough to allow the mass model to improve. We are trying to reject grossly +inconsistent mappings, not force every subsequent model to reproduce the initial solution exactly. Here, `factor` +enlarges the separation estimated from the initial result, while `minimum_threshold` prevents the returned +threshold from becoming smaller than `0.2` arcsec. -This positions penalty is a modelling aid rather than a replacement for the image likelihood. It does not by itself establish that the mass model is correct, and an inappropriate set of positions or an overly restrictive threshold can exclude useful solutions. +This positions penalty is a modelling aid rather than a replacement for the image likelihood. It does not by itself +establish that the mass model is correct, and an inappropriate set of positions or an overly restrictive threshold +can exclude useful solutions. __Replacing the analytic source with a pixelization__ We are ready to construct the second model. -The lens mass and shear remain free, but their priors are initialized from the first result using the prior-passing machinery introduced in chapter 2. The source profile is replaced by a rectangular mesh and a regularization model. +The lens mass and shear remain free, but their priors are initialized from the first result using the prior-passing +machinery introduced in chapter 2. The source profile is replaced by a rectangular mesh and a regularization model. -The distinction between `result_1.model` and `result_1.instance` matters here. Using the model carries free parameters into the next search. Using the instance would instead fix those components to particular fitted values. +The distinction between `result_1.model` and `result_1.instance` matters here. Using the model carries free +parameters into the next search. Using the instance would instead fix those components to particular fitted values. """ regularization = af.Model(al.reg.Constant) @@ -505,17 +585,23 @@ def fit_at_einstein_radius(einstein_radius, coefficient=1.0): print(model_2.info) """ -Inspect the resulting priors rather than assuming that they are suitable simply because they came from an earlier fit. In particular, a restrictive analytic source can bias an initial mass estimate; its result should guide the next search without preventing the mass model from changing. +Inspect the resulting priors rather than assuming that they are suitable simply because they came from an earlier +fit. In particular, a restrictive analytic source can bias an initial mass estimate; its result should guide the +next search without preventing the mass model from changing. -The mesh shape stays fixed. The regularization coefficient is now a non-linear parameter, explored alongside the mass and shear parameters. +The mesh shape stays fixed. The regularization coefficient is now a non-linear parameter, explored alongside the +mass and shear parameters. -The hundreds of source brightnesses do not appear as hundreds of additional search parameters. For each proposal, the inversion reconstructs those values using the proposed mass model and coefficient. +The hundreds of source brightnesses do not appear as hundreds of additional search parameters. For each proposal, +the inversion reconstructs those values using the proposed mass model and coefficient. __Running the pixelized-source search__ The second search combines the pixelized model with the positions constraint. -For each proposed mass model, the analysis checks the positions condition and evaluates the source reconstruction as appropriate. The search can adjust the lens parameters and regularization coefficient, while each inversion solves for the source brightnesses. +For each proposed mass model, the analysis checks the positions condition and evaluates the source reconstruction +as appropriate. The search can adjust the lens parameters and regularization coefficient, while each inversion +solves for the source brightnesses. """ analysis_2 = al.AnalysisImaging( @@ -544,9 +630,13 @@ def fit_at_einstein_radius(einstein_radius, coefficient=1.0): aplt.subplot_fit_imaging_of_planes(fit=pixelized_fit) """ -Compare this result with the analytic-source fit. Inspect the source structure and image residuals, then examine how the inferred mass parameters and their uncertainties have changed. +Compare this result with the analytic-source fit. Inspect the source structure and image residuals, then examine +how the inferred mass parameters and their uncertainties have changed. -For this simple simulated source, an MGE can already describe its smooth light distribution, so a pixelization need not produce a dramatic improvement. Its value becomes clearer for irregular sources that cannot be described adequately by the initial profile. This example teaches the modelling procedure without requiring that extra complication. +For this simple simulated source, an MGE can already describe its smooth light distribution, so a pixelization need +not produce a dramatic improvement. Its value becomes clearer for irregular sources that cannot be described +adequately by the initial profile. This example teaches the modelling procedure without requiring that extra +complication. We can also check whether the displayed pixelized model satisfies the positions threshold. """ @@ -578,19 +668,28 @@ def fit_at_einstein_radius(einstein_radius, coefficient=1.0): ) """ -Passing this check means the selected positions trace sufficiently close together under this model. It does not replace inspecting the residuals, uncertainties or search behaviour. +Passing this check means the selected positions trace sufficiently close together under this model. It does not +replace inspecting the residuals, uncertainties or search behaviour. -We have now performed a chained fit with a pixelized source and a free mass model. The next blocks introduce foreground lens light, explaining how its analytic profiles are fitted alongside the source reconstruction and why errors in that light model can affect the inferred source. +We have now performed a chained fit with a pixelized source and a free mass model. The next blocks introduce +foreground lens light, explaining how its analytic profiles are fitted alongside the source reconstruction and why +errors in that light model can affect the inferred source. __Establishing the foreground light model__ -We can model the foreground lens galaxy’s light and reconstruct a pixelized background source within the same fit. The foreground light profile and the lensed source contribute together to the predicted image. +We can model the foreground lens galaxy’s light and reconstruct a pixelized background source within the same fit. +The foreground light profile and the lensed source contribute together to the predicted image. -However, fitting everything from the outset gives the search several problems to solve at once. It must establish the mass distribution, separate foreground light from source light, and choose an appropriate source reconstruction. +However, fitting everything from the outset gives the search several problems to solve at once. It must establish +the mass distribution, separate foreground light from source light, and choose an appropriate source +reconstruction. -Search chaining helps us approach these problems in stages. We begin with MGE light models for both galaxies, following Chapter 2. This simpler source description provides a useful starting lens geometry and lets us establish the foreground light model before introducing a pixelization. +Search chaining helps us approach these problems in stages. We begin with MGE light models for both galaxies, +following Chapter 2. This simpler source description provides a useful starting lens geometry and lets us establish +the foreground light model before introducing a pixelization. -Let’s perform that initial fit using a simulated dataset containing foreground lens light. This is a new dataset, so we run a new search rather than reuse the result from our earlier no-lens-light example. +Let’s perform that initial fit using a simulated dataset containing foreground lens light. This is a new dataset, +so we run a new search rather than reuse the result from our earlier no-lens-light example. """ from pathlib import Path @@ -703,9 +802,13 @@ def fit_at_einstein_radius(einstein_radius, coefficient=1.0): ) """ -We fix the foreground light and mass centres for this introductory example, while allowing their other parameters to vary. The foreground MGE uses two Gaussian groups, which can have different elliptical shapes; the source uses one. Their Gaussian widths are fixed and all Gaussian intensities are solved linearly. +We fix the foreground light and mass centres for this introductory example, while allowing their other parameters +to vary. The foreground MGE uses two Gaussian groups, which can have different elliptical shapes; the source uses +one. Their Gaussian widths are fixed and all Gaussian intensities are solved linearly. -Before continuing, inspect the foreground model and residuals. We want a satisfactory description of the lens light and a plausible source geometry. For an irregular source, the analytic profile may leave structure unexplained, but obvious foreground residuals should not simply be passed into the next stage. +Before continuing, inspect the foreground model and residuals. We want a satisfactory description of the lens light +and a plausible source geometry. For an irregular source, the analytic profile may leave structure unexplained, but +obvious foreground residuals should not simply be passed into the next stage. This is a genuine non-linear search, so it will take longer than evaluating a single `FitImaging`. @@ -713,11 +816,17 @@ def fit_at_einstein_radius(einstein_radius, coefficient=1.0): We now replace the analytic source with a pixelization and carry the foreground model into the second search. -The distinction between `.model` and `.instance` is useful here. We use `.instance` to hold the foreground profile’s fitted shape fixed, reducing the number of non-linear parameters the next search must explore. We use `.model` for the mass and shear so that they remain free, with priors passed from the first result. +The distinction between `.model` and `.instance` is useful here. We use `.instance` to hold the foreground +profile’s fitted shape fixed, reducing the number of non-linear parameters the next search must explore. We use +`.model` for the mass and shear so that they remain free, with priors passed from the first result. -Because the foreground MGE uses linear Gaussian profiles, fixing its geometry does **not** fix its intensities. The second fit solves all Gaussian intensities alongside the pixelized source brightnesses. The foreground subtraction can therefore adjust without reopening the non-linear Gaussian geometry. +Because the foreground MGE uses linear Gaussian profiles, fixing its geometry does **not** fix its intensities. The +second fit solves all Gaussian intensities alongside the pixelized source brightnesses. The foreground subtraction +can therefore adjust without reopening the non-linear Gaussian geometry. -Search chaining also supplies the initial geometry from which we construct the positions constraint. **`PositionsLH` penalizes demagnified solutions whose corresponding image positions fail to trace sufficiently close together.** +Search chaining also supplies the initial geometry from which we construct the positions constraint. +**`PositionsLH` penalizes demagnified solutions whose corresponding image positions fail to trace sufficiently +close together.** """ lens = af.Model( @@ -791,13 +900,20 @@ def fit_at_einstein_radius(einstein_radius, coefficient=1.0): ) """ -Inspect the predicted positions before running the second search, as we did earlier. They come from the initial model and should sensibly represent the multiple-image configuration. +Inspect the predicted positions before running the second search, as we did earlier. They come from the initial +model and should sensibly represent the multiple-image configuration. -The second search now starts with an established foreground light shape and lens geometry. It can refine the mass and regularization while reconstructing the source, rather than solving the entire problem from broad initial priors. +The second search now starts with an established foreground light shape and lens geometry. It can refine the mass +and regularization while reconstructing the source, rather than solving the entire problem from broad initial +priors. -Compare the two results, paying attention to the foreground subtraction, source reconstruction and residuals. If the fixed foreground shape leaves significant residuals, a later chained search can free its parameters again. Fixing it is a useful intermediate step, not a requirement that the initial light model must remain unchanged throughout the analysis. +Compare the two results, paying attention to the foreground subtraction, source reconstruction and residuals. If +the fixed foreground shape leaves significant residuals, a later chained search can free its parameters again. +Fixing it is a useful intermediate step, not a requirement that the initial light model must remain unchanged +throughout the analysis. __Wrap Up__ -This completes the practical chain: fit MGE lens and source light, carry forward the foreground geometry and mass priors, then fit a pixelized source with the positions constraint. +This completes the practical chain: fit MGE lens and source light, carry forward the foreground geometry and mass +priors, then fit a pixelized source with the positions constraint. """ diff --git a/scripts/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.py b/scripts/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.py index 0c8a5dd..a2401af 100644 --- a/scripts/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.py +++ b/scripts/chapter_3_pixelizations/tutorial_8_adaptive_pixelization.py @@ -5,7 +5,7 @@ In this tutorial we will introduce a new `Pixelization` object, which uses an `Overlay` image-mesh and a `Delaunay` mesh. -This pixelization does not use a uniform grid of rectangular pixels, but instead uses a `Delaunay` triangulation. +This pixelization does not use a rectangular mesh, but instead uses a `Delaunay` triangulation. So, why would we want to do that? Lets take another quick look at the rectangular grid. @@ -14,7 +14,8 @@ - **Initial Setup:** We'll use the same strong lensing data as the previous tutorial, where. - **Advantages and Disadvantages:** Lets think about the rectangular pixelization. - **Image Mesh:** The Delaunay mesh is an irregular grid of pixels (or triangles) in the source-plane. -- **Regularization:** On the rectangular grid, we regularized each source pixel with its 4 neighbors. +- **Regularization:** Penalize differences between neighbouring reconstructed values. +- **Source Compactness:** Reconstruct three sources with the same lens, mesh and noise. - **Wrap Up:** Summary of the script and next steps. """ @@ -34,6 +35,7 @@ # from autolens import setup_notebook; setup_notebook() from pathlib import Path +import numpy as np import autolens as al import autolens.plot as aplt @@ -52,8 +54,8 @@ """ __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 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 @@ -80,8 +82,8 @@ aplt.subplot_imaging_dataset(dataset=dataset) """ -The lines of code below do everything we're used to, that is, setup an image, mask it, trace it via a tracer, -setup the rectangular mapper, etc. +The lines of code below do everything we're used to, that is, setup an image, mask it, trace it via a tracer, setup +the rectangular mapper, etc. """ lens_galaxy = al.Galaxy( redshift=0.5, @@ -118,43 +120,28 @@ """ __Advantages and Disadvantages__ -Lets think about the rectangular pixelization. Is this the optimal way to reconstruct our source? Are there features -in the source-plane that aren't ideal? How do you think we could do a better job? - -There are a number of reasons the rectangular pixelization is not optimal, and it is in fact a pretty poor method to -model strong lenses! - -So what is wrong with the grid? Well, lets think about the source reconstruction. +The rectangular mesh is a useful baseline, but its finite resolution can limit a reconstruction. +`RectangularBilinearAdaptDensity` adjusts rectangular sampling to the traced data density; it is not simply a +uniform source-plane grid. Inspect where its mesh points lie relative to the bright source. """ mapper = fit.inversion.cls_list_from(al.Mapper)[0] - - +rectangular_pixels = mapper.pixels +print(f"Rectangular source pixels: {rectangular_pixels}") aplt.subplot_fit_imaging_of_planes(fit=fit) """ -There is one clear problem, we are using only a small number of the total source pixels to reconstruct the source. The -majority of source pixels are located away from the source. By my estimate, we are using just 16 pixels (the central -4x4 grid) out of the 784 pixels to actually fit the data! The remaining ~750 pixels are doing nothing but fitting -noise. - -This means that regularization is sub-optimal. In tutorial 2, we discussed how the Bayesian evidence of the -regularization favours the simplest source solution. That is, the solution which fits the data using the fewest source -pixels. If we are dedicating a large number of source pixels to fitting *nothing*, the source reconstruction is -unnecessarily complex (and therefore is lower `log_evidence` solution). - -If our pixelization could 'focus' its pixels where we actually have more data, e.g. the highly magnified regions of -the source-plane, we could reconstruct the source using fewer pixels. This would significantly increase the Bayesian -evidence. It'd also be beneficial computationally, as using fewer source pixels means faster run times. - -This is what the Delaunay mesh enables. +A mesh point in a faint region is not necessarily wasted: those measurements can constrain the source's extent. The +evidence balances fit quality, regularization and complexity, rather than simply rewarding fewer pixels. An +image-plane overlay offers another allocation: ray-tracing its points concentrates source-plane sampling according +to lens magnification. Whether this improves a fit must be checked for the data and regularization used. __Image Mesh__ -The Delaunay mesh is an irregular grid of pixels (or triangles) in the source-plane. We must first therefore determine -a set of (y,x) source-plane coordinates defining this grid, specifically where each triangle vertex is located. +The Delaunay mesh is an irregular triangulation in the source-plane. First determine a set of (y,x) source-plane +coordinates defining this grid, specifically where each triangle vertex is located. -We do this using an `image_mesh`, which defines a method to determine a set of coordinates in the image-plane -which are ray-traced to the source-plane. These traced coordinates are the triangle vertexes of our source-pixel mesh. +We do this using an `image_mesh`, which defines a method to determine a set of coordinates in the image-plane which +are ray-traced to the source-plane. These traced coordinates are the vertices of our source-pixel mesh. Below, we use the `Overlay` image-mesh to do this, which overlays a grid of (y,x) coordinates over the image-plane mask and retains all (Y,x) coordinates which fall within this mask. @@ -169,11 +156,13 @@ We can plot this grid over the image, to see that it is a coarse grid of (y,x) coordinates laid over the image. """ -aplt.plot_array(array=dataset.data, title="Data") +aplt.plot_array( + array=dataset.data, grid=image_plane_mesh_grid, title="Image-plane mesh overlay" +) """ -By passing a `Tracer` a source galaxy with the image-mesh and a `Delaunay` mesh object, contained in -a `Pixelization` object, it automatically computes this source-plane Delaunay mesh. +Give the source galaxy a `Pixelization` containing a `Delaunay` mesh. The fit receives the image-plane mesh +coordinates separately through `AdaptImages` below, and ray-traces them to construct the source-plane mesh. """ pixelization = al.Pixelization( mesh=al.mesh.Delaunay( @@ -201,31 +190,111 @@ aplt.subplot_fit_imaging(fit=fit) """ -A closer inspection of the pixelization shows the improvement. - -We are using fewer pixels than the rectangular grid (400, instead of 784) and reconstructing the source in far -greater detail! +Compare the residuals and reconstructed source with the rectangular example. The overlay retains only points inside +the mask, so its actual number of source pixels is smaller than the full 20 by 20 overlay. The two fits also use +different regularization coefficients; this is not a controlled ranking of mesh quality. """ +print(f"Delaunay source pixels: {mapper.pixels}; rectangular: {rectangular_pixels}") aplt.subplot_fit_imaging_of_planes(fit=fit) """ __Regularization__ -On the rectangular grid, we regularized each source pixel with its 4 neighbors. We compared their fluxes, summed -the differences, and penalized solutions where the differences were large. +Constant regularization penalizes differences between neighbouring reconstructed source values. Rectangular meshes +use their grid connectivity; Delaunay meshes use the connected vertices of the triangulation. A vertex need not +have exactly three neighbours. One coefficient controls the strength of smoothing across the mesh. -For a Delaunay grid, we do a similar calculation, instead comparing each source-pixel with the 3 Delaunay triangles -it shares a direct vertex with. +__Source Compactness__ -__Wrap Up__ +Magnification depends on the lens and source position, not on the brightness distribution we place there. Keep this +lens, image-plane overlay and regularization fixed while making three source profiles progressively more compact. +This restores a direct test of a limitation of magnification-based sampling. + +Use identical PSF, mask, Gaussian noise map and noise realization for each simulated image. The profiles retain the +same intensity at their effective radius, so their total fluxes and signal-to-noise ratios also differ; this is a +diagnostic experiment, not an isolated measurement of the effect of radius. The coefficient of 1.0 is an explicit +illustrative choice, not an evidence optimum for any of these datasets. +""" + +simulation_grid = al.Grid2D.uniform( + shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales +) +simulation_grid = simulation_grid.apply_over_sampling(over_sample_size=8) +simulator = al.SimulatorImaging( + exposure_time=300.0, + psf=dataset.psf, + background_sky_level=0.1, + add_poisson_noise_to_data=False, +) +noise_sigma = 0.05 +noise_values = np.random.default_rng(1).normal( + loc=0.0, scale=noise_sigma, size=simulation_grid.shape_native +) +common_noise_map = al.Array2D.no_mask( + values=np.full(simulation_grid.shape_native, noise_sigma), + pixel_scales=dataset.pixel_scales, +) + +compactness_fits = {} +for label, effective_radius, sersic_index in [ + ("Extended", 0.5, 1.0), + ("Compact", 0.2, 2.5), + ("Very compact", 0.1, 4.0), +]: + true_source = al.Galaxy( + redshift=1.0, + bulge=al.lp.Sersic( + centre=(0.0, 0.0), + ell_comps=(0.0, 0.15), + intensity=0.2, + effective_radius=effective_radius, + sersic_index=sersic_index, + ), + ) + true_tracer = al.Tracer(galaxies=[lens_galaxy, true_source], fields=[field]) + noiseless = simulator.via_tracer_from(tracer=true_tracer, grid=simulation_grid) + simulated_dataset = al.Imaging( + data=al.Array2D.no_mask( + values=np.asarray(noiseless.data.native) + noise_values, + pixel_scales=dataset.pixel_scales, + ), + noise_map=common_noise_map, + psf=dataset.psf, + ) + simulated_dataset = simulated_dataset.apply_mask(mask=mask) + simulated_dataset = simulated_dataset.apply_sparse_operator() + compactness_fit = al.FitImaging( + dataset=simulated_dataset, tracer=tracer, adapt_images=adapt_images + ) + compactness_fits[label] = compactness_fit + compactness_mapper = compactness_fit.inversion.cls_list_from(al.Mapper)[0] + mesh_radii = np.sqrt( + np.sum(np.asarray(compactness_mapper.source_plane_mesh_grid) ** 2, axis=1) + ) + vertices_within_radius = np.count_nonzero(mesh_radii <= effective_radius) + print( + f"{label}: radius={effective_radius:.2f}, index={sersic_index:.1f}, " + f"coefficient=1.0, mesh pixels={compactness_mapper.pixels}, " + f"vertices within circular effective-radius aperture={vertices_within_radius}, " + f"chi_squared / data pixels={compactness_fit.chi_squared / simulated_dataset.data.shape[0]:.3f}, " + f"max |normalized residual|={np.max(np.abs(compactness_fit.normalized_residual_map)):.3f}" + ) + aplt.subplot_fit_imaging(fit=compactness_fit) + aplt.subplot_fit_imaging_of_planes(fit=compactness_fit) -The `Overlay` image-mesh and `Delaunay` mesh is still far from optimal. There are lots of source-pixels effectively -fitting just noise. We could achieve even better solutions if the central regions of the source were reconstructed -using more pixels, and fewer source pixels were used in the outskirts of the source plane. +""" +The printed aperture counts measure available mesh vertices, not the number of independently constrained source +values. Inspect the source reconstructions alongside the residual maps: can the same mesh resolve each bright +centre without coherent residuals? Changing the coefficient may trade smoothing of the centre against noise in the +outskirts, but cannot add mesh vertices. We have not searched for an optimal coefficient, and these separate +simulated datasets must not be ranked against one another using their absolute evidences. + +__Wrap Up__ -Tutorials 11 and 12 show even more advanced and adaptive pixelizations which do just this, by adapting to the -source galaxy's morphology rather than the mass model magnification. +The overlay responds to magnification rather than source morphology. The compactness experiment lets us inspect +where that distinction matters; neither fewer pixels nor a more adaptive mesh guarantees a better reconstruction. +Tutorials 11 and 12 explore adapting the mesh and regularization to a fitted brightness distribution. They test +those choices on the same data so that changes in fit quality and evidence can be assessed meaningfully. -In the mean time, you may wish to experiment with using both rectangular and Delaunay meshes to fit -lenses, which is easily achieved by changing the input pixelization given to a pipeline. +You can also experiment with rectangular and Delaunay meshes by changing the pixelization in a pipeline. """ diff --git a/workspace_index.json b/workspace_index.json index c6c567a..58c60c9 100644 --- a/workspace_index.json +++ b/workspace_index.json @@ -532,6 +532,7 @@ "Advantages and Disadvantages", "Image Mesh", "Regularization", + "Source Compactness", "Wrap Up" ], "cross_refs": [],