diff --git a/README.md b/README.md index 69972d8..557a06d 100644 --- a/README.md +++ b/README.md @@ -82,13 +82,12 @@ for the chapter 1 tutorials listed with a `markdown` link below; every other tut - **[Chapter 1: Introduction](scripts/chapter_1_introduction/README.md)** — Grids, light and mass profiles, galaxies, ray-tracing, point sources, the lensing formalism, data, and fitting. - Tutorial 0: Visualization — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_0_visualization.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_0_visualization.md)) - Tutorial 1: Grids and Galaxies — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_1_grids_and_galaxies.md)) - - Tutorial 2: Ray Tracing — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_2_ray_tracing.md)) - - Tutorial 3: More Ray Tracing — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_3_more_ray_tracing.md)) + - Tutorial 2: Ray Tracing — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_2_ray_tracing.md)) + - Tutorial 3: More Ray Tracing — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_3_more_ray_tracing.md)) - Tutorial 4: Point Sources — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_4_point_sources.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_4_point_sources.md)) - - Tutorial 5: Lensing Formalism — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_5_lensing_formalism.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_5_lensing_formalism.md)) - - Tutorial 6: Data — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_6_data.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_6_data.md)) - - Tutorial 7: Fitting — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_7_fitting.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_7_fitting.md)) - - Tutorial 8: Summary — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_8_summary.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_8_summary.md)) + - Tutorial 5: Data — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_5_data.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_5_data.md)) + - Tutorial 6: Fitting — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_6_fitting.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_6_fitting.md)) + - Tutorial 7: Summary — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_7_summary.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_7_summary.md)) - **[Chapter 2: Lens Modeling](scripts/chapter_2_lens_modeling/README.md)** — Bayesian inference, non-linear searches, lens modeling, search chaining, prior passing, and SLaM pipelines. - Tutorial 1: Non-linear Search — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb)) - Tutorial 2: Practicalities — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_2_lens_modeling/tutorial_2_practicalities.ipynb)) diff --git a/config/build/markdown_examples.yaml b/config/build/markdown_examples.yaml index fe8d232..10a4f49 100644 --- a/config/build/markdown_examples.yaml +++ b/config/build/markdown_examples.yaml @@ -11,11 +11,9 @@ max_minutes: 30 - script: scripts/chapter_1_introduction/tutorial_4_point_sources.py max_minutes: 30 -- script: scripts/chapter_1_introduction/tutorial_5_lensing_formalism.py +- script: scripts/chapter_1_introduction/tutorial_5_data.py max_minutes: 30 -- script: scripts/chapter_1_introduction/tutorial_6_data.py +- script: scripts/chapter_1_introduction/tutorial_6_fitting.py max_minutes: 30 -- script: scripts/chapter_1_introduction/tutorial_7_fitting.py - max_minutes: 30 -- script: scripts/chapter_1_introduction/tutorial_8_summary.py +- script: scripts/chapter_1_introduction/tutorial_7_summary.py max_minutes: 30 diff --git a/llms-full.txt b/llms-full.txt index 1fa8efd..77a9a2e 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -14,18 +14,16 @@ AUTO-GENERATED by PyAutoHands — do not edit by hand; regenerate with generate. - [HowToLens: Introduction](scripts/chapter_1_introduction/tutorial_1_grids_and_galaxies.py): A distant galaxy can appear as multiple images, stretched arcs or a ring when its light passes a sufficiently well-aligned foreground galaxy. The foreground galaxy’s gravity deflects the light, allowing it to reach us along different paths. This is strong gravitational lensing. - Contents: Grids, Geometry, Light Profiles, One Dimension Projection, Galaxies, Units, Wrap Up, Advanced Topics, Other Unit Conversion, Over Sampling - [Tutorial 2: Ray Tracing](scripts/chapter_1_introduction/tutorial_2_ray_tracing.py): Strong gravitational lensing occurs when the mass of a foreground galaxy curves space-time, bending the paths of light rays from a background source galaxy. The source can then appear as arcs, a ring or multiple images. - - Contents: Grid, Mass Profiles, Ray Tracing Grids, Mappings, Ray Tracing Images, Galaxies, Tracer, Wrap Up, Env -- [Tutorial 3: More Ray Tracing](scripts/chapter_1_introduction/tutorial_3_more_ray_tracing.py): We'll now reinforce the ideas that we learnt about ray-tracing in the previous tutorial and introduce the following new concepts: - - Contents: Initial Setup, Concise Code, Critical Curves, Caustics, Units, More Complexity, Multi Galaxy Ray Tracing, Wrap Up + - Contents: Grid, Mass Profiles, Ray Tracing Grids, Mappings, Ray Tracing Images, Galaxies, Tracer, Units, More Complexity, Multi Galaxy Ray Tracing, Wrap Up, Env +- [Tutorial 3: More Ray Tracing](scripts/chapter_1_introduction/tutorial_3_more_ray_tracing.py): In tutorial 2, we used the lens equation to trace coordinates from the image plane to the source plane and build an image of a strong lens. + - Contents: Initial Setup, Concise Code, Cosmological Distances, Convergence, Deflection Angles, The Lensing Potential, Shear and Magnification, Critical Curves and Caustics, Einstein Radius, Time Delays, Wrap Up, Env - [Tutorial 4: Point Sources](scripts/chapter_1_introduction/tutorial_4_point_sources.py): In the previous tutorials, the background sources we lensed were galaxies: extended objects whose light spreads over many thousands of light years. When lensed, their light is warped into the arcs and Einstein rings we produced with the `Tracer`, spread across many pixels of the image. - Contents: Initial Setup, Point Sources, Point Source Tracer, The Lens Equation, Point Solver, Multiple Images and Critical Curves, Magnifications, Time Delays, Extended Versus Point Computations, Wrap Up -- [Tutorial 5: Lensing Formalism](scripts/chapter_1_introduction/tutorial_5_lensing_formalism.py): This tutorial is the equations lecture of **HowToLens**. - - Contents: Initial Setup, Cosmological Distances, The Lens Equation, Convergence, Deflection Angles, The Lensing Potential, Shear and Magnification, Critical Curves and Caustics, Einstein Radius, Time Delays, Wrap Up -- [Tutorial 6: Data](scripts/chapter_1_introduction/tutorial_6_data.py): In the last tutorials, we use tracers to create images of strong lenses. However, those images don't accurately represent what we would observe through a telescope. +- [Tutorial 5: Data](scripts/chapter_1_introduction/tutorial_5_data.py): In the last tutorials, we use tracers to create images of strong lenses. However, those images don't accurately represent what we would observe through a telescope. - Contents: Initial Setup, Optics Blurring, Poisson Noise, Background Sky, Simulator, Output, Interferometer Data, Weak Lensing Data, Wrap Up -- [Tutorial 7: Fitting](scripts/chapter_1_introduction/tutorial_7_fitting.py): In previous tutorials, we used light profiles to create simulated images of a tracer and visualized how these images would appear when captured by a CCD detector on a telescope like the Hubble Space Telescope. +- [Tutorial 6: Fitting](scripts/chapter_1_introduction/tutorial_6_fitting.py): In previous tutorials, we used light profiles to create simulated images of a tracer and visualized how these images would appear when captured by a CCD detector on a telescope like the Hubble Space Telescope. - Contents: Dataset, Dataset Auto-Simulation, Mask, Masked Grid, Fitting, Incorrect Fit, Model Fitting, Wrap Up -- [Tutorial 8: Summary](scripts/chapter_1_introduction/tutorial_8_summary.py): In this chapter, we have learnt that: +- [Tutorial 7: Summary](scripts/chapter_1_introduction/tutorial_7_summary.py): In this chapter, we have learnt that: - Contents: Start, Object Composition, Visualization, Code Design, Source Code, Wrap Up ## chapter_2_lens_modeling diff --git a/llms.txt b/llms.txt index 5b97710..bafe3fa 100644 --- a/llms.txt +++ b/llms.txt @@ -32,8 +32,8 @@ analysis?" below). ## I want to understand… - **What is a strong lens / how does ray tracing work?** → [scripts/chapter_1_introduction/tutorial_2_ray_tracing.py](scripts/chapter_1_introduction/tutorial_2_ray_tracing.py): Mass profiles deflecting light; image-plane vs source-plane. -- **How does a telescope image (and noise/PSF) get simulated?** → [scripts/chapter_1_introduction/tutorial_6_data.py](scripts/chapter_1_introduction/tutorial_6_data.py): Optics blurring, Poisson noise, background sky, the simulator API. -- **What does "fitting" a lens actually mean?** → [scripts/chapter_1_introduction/tutorial_7_fitting.py](scripts/chapter_1_introduction/tutorial_7_fitting.py): Masking, model images, residuals and the log likelihood. +- **How does a telescope image (and noise/PSF) get simulated?** → [scripts/chapter_1_introduction/tutorial_5_data.py](scripts/chapter_1_introduction/tutorial_5_data.py): Optics blurring, Poisson noise, background sky, the simulator API. +- **What does "fitting" a lens actually mean?** → [scripts/chapter_1_introduction/tutorial_6_fitting.py](scripts/chapter_1_introduction/tutorial_6_fitting.py): Masking, model images, residuals and the log likelihood. - **How does a non-linear search find a model?** → [scripts/chapter_2_lens_modeling/tutorial_1_non_linear_search.py](scripts/chapter_2_lens_modeling/tutorial_1_non_linear_search.py): Parameter space, priors, nested sampling with Nautilus. - **My fit found a wrong (local-maxima) solution — what do I do?** → [scripts/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.py](scripts/chapter_2_lens_modeling/tutorial_4_dealing_with_failure.py): Prior tuning, simplifying the model, and other escapes from local maxima. - **What are linear light profiles / MGE?** → [scripts/chapter_2_lens_modeling/tutorial_5_linear_profiles.py](scripts/chapter_2_lens_modeling/tutorial_5_linear_profiles.py): Solving intensities linearly; the Multi-Gaussian Expansion basis. diff --git a/markdown/README.md b/markdown/README.md index 214f310..4d79a2b 100644 --- a/markdown/README.md +++ b/markdown/README.md @@ -7,9 +7,8 @@ Every page below is the corresponding example script **fully executed**, rendere - [Tutorial 2: Ray Tracing](chapter_1_introduction/tutorial_2_ray_tracing.md) — from `scripts/chapter_1_introduction/tutorial_2_ray_tracing.py` - [Tutorial 3: More Ray Tracing](chapter_1_introduction/tutorial_3_more_ray_tracing.md) — from `scripts/chapter_1_introduction/tutorial_3_more_ray_tracing.py` - [Tutorial 4: Point Sources](chapter_1_introduction/tutorial_4_point_sources.md) — from `scripts/chapter_1_introduction/tutorial_4_point_sources.py` -- [Tutorial 5: Lensing Formalism](chapter_1_introduction/tutorial_5_lensing_formalism.md) — from `scripts/chapter_1_introduction/tutorial_5_lensing_formalism.py` -- [Tutorial 6: Data](chapter_1_introduction/tutorial_6_data.md) — from `scripts/chapter_1_introduction/tutorial_6_data.py` -- [Tutorial 7: Fitting](chapter_1_introduction/tutorial_7_fitting.md) — from `scripts/chapter_1_introduction/tutorial_7_fitting.py` -- [Tutorial 8: Summary](chapter_1_introduction/tutorial_8_summary.md) — from `scripts/chapter_1_introduction/tutorial_8_summary.py` +- [Tutorial 5: Data](chapter_1_introduction/tutorial_5_data.md) — from `scripts/chapter_1_introduction/tutorial_5_data.py` +- [Tutorial 6: Fitting](chapter_1_introduction/tutorial_6_fitting.md) — from `scripts/chapter_1_introduction/tutorial_6_fitting.py` +- [Tutorial 7: Summary](chapter_1_introduction/tutorial_7_summary.md) — from `scripts/chapter_1_introduction/tutorial_7_summary.py` These pages are regenerated manually by PyAutoHands's `generate_markdown.py` when a curated script changes. diff --git a/markdown/chapter_1_introduction/tutorial_2_ray_tracing.md b/markdown/chapter_1_introduction/tutorial_2_ray_tracing.md index 342ad9d..4740b72 100644 --- a/markdown/chapter_1_introduction/tutorial_2_ray_tracing.md +++ b/markdown/chapter_1_introduction/tutorial_2_ray_tracing.md @@ -3,72 +3,79 @@ > Run it yourself via the [Python script](../../scripts/chapter_1_introduction/tutorial_2_ray_tracing.py) or the [Jupyter notebook](../../notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb). Tutorial 2: Ray Tracing -======================= +====================== -Strong gravitational lensing occurs when the mass of a foreground galaxy (or galaxies) curves space-time around it, -causing light rays from a background source to appear deflected. +Strong gravitational lensing occurs when the mass of a foreground galaxy curves +space-time, bending the paths of light rays from a background source galaxy. +The source can then appear as arcs, a ring or multiple images. -The process of ray tracing calculates how much the path of each light ray is bent by the mass of the foreground galaxy. -It then traces the paths of these light rays back to the observer, allowing us to determine how the source appears -distorted. As a result, the images of the source may appear as arcs, multiple images, or other complex patterns. +In the previous tutorial, we used light profiles to describe how a galaxy's +brightness varies across an image. We now introduce **mass profiles**, which +describe how its mass is distributed. From a mass profile, we can calculate +the **deflection angles** that tell us how the galaxy bends light. -In the previous tutorial, we introduced **light profiles**, which are analytic functions that describe the distribution -of light from a galaxy. In this tutorial, we will focus on **mass profiles**, which are analytic functions that -describe the mass distribution within a galaxy. A key quantity derived from these profiles is the **deflection angle**, -which quantifies how light is deflected by the mass of the galaxy at any point in space. +These two ingredients let us construct a lensed image. The mass profile tells +us where each light ray came from in the source galaxy, and the source's light +profile tells us how bright that location is. -Grids were crucial in the previous tutorial, as they enabled us to compute the light profile of a galaxy at every -coordinate point. In ray tracing, grids are equally important because they are used to calculate the deflection -angles of light rays caused by a mass profile and to map the source's light rays back to the observer. +Let's revisit both views of strong lensing from the previous tutorial. The +schematic shows the geometry from the side: light travels from the source, +past the lens and towards the observer. It is not drawn to scale. -Let’s revisit the schematic of strong lensing: +![Side-on illustration of light from a source galaxy passing a lens galaxy and reaching JWST](https://raw.githubusercontent.com/PyAutoLabs/autolens_assistant/main/docs/images/strong_lens_schematic.png) -![Schematic of Gravitational Lensing](https://i.imgur.com/zB6tIdI.jpg) +The JWST image of the COSMOS-Web Ring shows the view on the sky. The bright +central galaxy is the lens, and the surrounding ring is light from the more +distant source galaxy. -As observers, we do not see the true appearance of the source (e.g., a round blob of light). Instead, we only -perceive its light after it has been deflected and lensed by the foreground galaxies. This resulting image is known -as the **observed image** or **image-plane image**, which we will produce through the ray-tracing process. +![The COSMOS-Web Ring, labelled with the lens galaxy, lensed source galaxy and extra galaxy](https://raw.githubusercontent.com/PyAutoLabs/autolens_assistant/main/docs/images/cosmos_web_ring_rgb_labelled.png) -The schematic above uses the terms "image-plane" and "source-plane." In the context of gravitational lensing, a "plane" -refers to a collection of galaxies located at the same redshift, meaning they are physically aligned parallel to one -another. +The extra galaxy labelled in both figures is distinct from the main lens and +lensed source. We begin with one lens and one source, then add more galaxies +at the end of this tutorial. -In this tutorial, we will create a strong lensing system consisting of planes similar to the one depicted above. While -a plane can contain multiple galaxies, we will focus on a simple scenario with just one lens galaxy and one source -galaxy. +These figures are also used in the [COSMOS-Web Ring guided example](https://github.com/PyAutoLabs/autolens_assistant/blob/main/docs/colab/cosmos_web_ring_colab.py). -Here is an overview of what we'll cover in this tutorial: +In our calculation, we follow the light paths backwards: we start with +positions in the image seen by the observer and trace rays back to positions +at the source. -- **Grid**: How the 2D grids that were important for evaluating light profiles are equally important - for ray-tracing calculations. +This process is called **ray tracing**. It allows us to work out what the +source's light looks like after gravitational lensing. -- **Mass Profiles**: Introduce mass profiles, which describe the mass distribution of galaxies and are used to - calculate deflection angles. +We describe the positions using two coordinate planes: -- **Ray Tracing Grids**: How to map the light rays from the image-plane to the source-plane using the - deflection angles and **lens equation**. +- The **image plane** contains the angular positions at which we see light + on the sky. +- The **source plane** contains the angular positions of the source before + its light is distorted by the lens. -- **Ray Tracing Images**: How to evaluate the lensed image of a source galaxy after it has been - gravitationally lensed. +For the lensing calculation, we also represent the foreground galaxy's mass +on a **lens plane**. The lens and source planes are imagined sheets +perpendicular to our line of sight, at the respective distances of the lens +and source. They do not describe the orientations of the galaxies themselves. -- **Galaxies**: How to include both light and mass profiles in a single `Galaxy` object, and therefore -construct realistic lens and source galaxies. +We will first trace the rays ourselves using grids, then use a `Tracer` +to perform the same calculation for us. Finally, we will extend the tracer +to include two lens galaxies and two source galaxies. -- **Tracer**: Introduce the `Tracer` object, which automates the ray-tracing process and allows us to compute - images of the entire lens system. - -- **Mappings**: Visualize how coordinates in the image-plane map to the source-plane by plotting the ray-traced grids. +The resulting **lensed image** shows how the foreground galaxy's gravity +distorts the appearance of the source. __Contents__ -- **Grid:** In the previous tutorial, we created 2D grids of (y,x) coordinates and showed how shifting and. -- **Mass Profiles:** To perform lensing calculations, we use mass profiles available in the `mass_profile` module. -- **Ray Tracing Grids:** The lens equation uses deflection angles to map image-plane coordinates to the source-plane. -- **Ray Tracing Images:** Evaluating a source's light on the ray-traced grid produces its lensed image. -- **Galaxies:** A `Galaxy` can contain both light and mass profiles, forming realistic lens and source galaxies. -- **Tracer:** The `Tracer` object automates ray-tracing for a system of galaxies at different redshifts. -- **Mappings:** Every image-plane coordinate maps to a source-plane coordinate via the lens equation. -- **Wrap Up:** Summary of the script and next steps. +- **Grid:** Set up the image-plane coordinates where we will calculate the light. +- **Mass Profiles:** Describe the lens galaxy's mass and calculate its deflection angles. +- **Ray Tracing Grids:** Use the lens equation to map image-plane coordinates to the source plane. +- **Mappings:** Visualise how image-plane positions map to source-plane positions. +- **Ray Tracing Images:** Evaluate the source's light profile on the ray-traced grid. +- **Galaxies:** Combine light and mass profiles into lens and source galaxies. +- **Tracer:** Perform the ray-tracing calculation using a `Tracer`. +- **Units:** Convert angular sizes into physical sizes using redshifts and a cosmology. +- **More Complexity:** Add lens light, elliptical mass, external shear and additional galaxies. +- **Multi Galaxy Ray Tracing:** Combine two lens galaxies and two sources in one tracer. +- **Wrap Up:** Review what we have learned and the next steps. +- **Env:** Preserve the grid used by the mapping example. ```python @@ -80,68 +87,72 @@ from autolens import setup_notebook; setup_notebook() import matplotlib.pyplot as plt import autolens as al import autoarray as aa +import autoarray.plot as aaplt import autolens.plot as aplt ``` - .../PyAutoNerves/autonerves/workspace.py:206: UserWarning: Cannot verify the workspace at HowToLens/scripts/chapter_1_introduction is compatible with the installed library version (2026.7.23.1): no `version.minimum_library_version` or `version.workspace_version` key in config/general.yaml and no version.txt at the workspace root. - - If you cloned the workspace from `main` rather than a release tag, set `version.workspace_version_check: False` in config/general.yaml to silence this warning. The `main` branch updates more frequently than library releases, so version mismatches are expected and not actionable for `main`-branch users. - - You can also set the environment variable PYAUTO_SKIP_WORKSPACE_VERSION_CHECK=1 to disable temporarily. - warnings.warn(_missing_version_warning(root, library_version)) - .../PyAutoNerves/autonerves/workspace.py:206: UserWarning: Cannot verify the workspace at HowToLens/scripts/chapter_1_introduction is compatible with the installed library version (2026.7.23.1): no `version.minimum_library_version` or `version.workspace_version` key in config/general.yaml and no version.txt at the workspace root. - - If you cloned the workspace from `main` rather than a release tag, set `version.workspace_version_check: False` in config/general.yaml to silence this warning. The `main` branch updates more frequently than library releases, so version mismatches are expected and not actionable for `main`-branch users. - - You can also set the environment variable PYAUTO_SKIP_WORKSPACE_VERSION_CHECK=1 to disable temporarily. - warnings.warn(_missing_version_warning(root, library_version)) Working Directory has been set to `HowToLens` - .../PyAutoNerves/autonerves/workspace.py:206: UserWarning: Cannot verify the workspace at HowToLens/scripts/chapter_1_introduction is compatible with the installed library version (2026.7.23.1): no `version.minimum_library_version` or `version.workspace_version` key in config/general.yaml and no version.txt at the workspace root. - - If you cloned the workspace from `main` rather than a release tag, set `version.workspace_version_check: False` in config/general.yaml to silence this warning. The `main` branch updates more frequently than library releases, so version mismatches are expected and not actionable for `main`-branch users. - - You can also set the environment variable PYAUTO_SKIP_WORKSPACE_VERSION_CHECK=1 to disable temporarily. - warnings.warn(_missing_version_warning(root, library_version)) __Grid__ -In the previous tutorial, we created 2D grids of (y,x) coordinates and showed how shifting and rotating these grids -is crucial for evaluating the light profiles of galaxies. +In the previous tutorial, we evaluated light profiles on grids of (y,x) +coordinates. Each coordinate specified a position at which to calculate +the brightness. + +We begin in the same way here, creating a uniform grid called +`image_plane_grid`. Its coordinates represent positions on the sky where +we want to calculate the lensed image. -Grids are also essential for performing ray-tracing calculations. The coordinates in the grid are deflected by the -lens galaxy, and these deflected coordinates are used in ray-tracing calculations. +The grid has 101 rows and 101 columns, with adjacent pixel centres separated +by 0.1 arcseconds. As before, coordinates are measured relative to the centre +of the grid. -Now, let’s create the grid for this tutorial, which we’ll call the `image_plane_grid`. It represents the grid of -coordinates in the image plane, before the light is deflected by the lens galaxy. This grid is uniform, meaning -every coordinate is evenly spaced. However, this uniformity will change after ray-tracing, as the light rays are -mapped to the source plane. +Ray tracing will map each of these image-plane coordinates to a position +in the source plane. Although our starting grid is uniform, the mapped +source-plane coordinates will generally not be evenly spaced. ```python -image_plane_grid = al.Grid2D.uniform(shape_native=(101, 101), pixel_scales=0.1) + +image_plane_grid = al.Grid2D.uniform( + shape_native=(101, 101), pixel_scales=0.1 +) ``` __Mass Profiles__ -To perform lensing calculations, we use mass profiles available in the `mass_profile` module (accessible via `al.mp`). +A mass profile is a mathematical description of how mass is distributed +within a galaxy. Just as a light profile lets us calculate brightness, +a mass profile lets us calculate how the galaxy deflects light. + +Mass profiles are available through `al.mp`. We will begin with +`IsothermalSph`, a spherical isothermal mass profile. This is a simple +model commonly used to illustrate galaxy-scale lensing. -A mass profile is an analytic function that describes the mass distribution within a galaxy. It is used to calculate -deflection angles and other quantities like surface density and gravitational potential. +For this profile, we specify two parameters: -In gravitational lensing, deflection angles describe how a mass bends light by curving space-time. +- `centre`: The (y,x) position of the mass profile's centre, in arcseconds. + We place it at (0.0, 0.0), the centre of our grid. +- `einstein_radius`: The angular scale of the lensing deflection, in + arcseconds. For this spherical profile, a point source exactly behind + the lens centre would form a ring at this radius. -We will start with a simple mass profile, `IsothermalSph`, which represents a spherically symmetric isothermal -mass distribution. This profile has two main properties: its center (the origin of the coordinate system) and its -Einstein radius (which indicates the galaxy's mass and how much it bends light rays). +We set the Einstein radius to 1.6 arcseconds. For fixed lens and source +distances, a larger Einstein radius corresponds to a more massive lens +within that radius. + +Printing the profile shows the parameters we have supplied. ```python + sis_mass_profile = al.mp.IsothermalSph( - centre=(0.0, 0.0), # The (y,x) arc-second coordinates of the profile's center. - einstein_radius=1.6, # The Einstein radius of the profile in arc-seconds. + centre=(0.0, 0.0), # The profile centre in (y,x) arcseconds. + einstein_radius=1.6, # The Einstein radius in arcseconds. ) + print(sis_mass_profile) ``` @@ -153,255 +164,515 @@ print(sis_mass_profile) core_radius: 0.0 -In the previous tutorial, we used the `image_2d_from` method to compute the image of a light profile by evaluating -its intensity at each (y,x) coordinate on the grid. +In the previous tutorial, we called `image_2d_from` to evaluate a light +profile's intensity at every coordinate on a grid. + +For a mass profile, we call `deflections_yx_2d_from` to calculate the +deflection angles at those coordinates. -Mass profiles have a similar method called `deflections_yx_2d_from`, which calculates the deflection angles at -every (y,x) coordinate on the grid in units of arc-seconds. +Each position has two deflection components, ordered as (y,x), both +measured in arcseconds. Together, they describe the angular displacement +we will use to map that image-plane position to the source plane. + +The following calculation gives us one deflection vector for every +coordinate in `image_plane_grid`. ```python -deflections = sis_mass_profile.deflections_yx_2d_from(grid=image_plane_grid) + +deflections = sis_mass_profile.deflections_yx_2d_from( + grid=image_plane_grid +) ``` -Like grids and arrays, the deflection angles can be accessed using the `native` and `slim` attributes. These are -structured similarly to a `Grid2D` object: +As with the grids in the previous tutorial, we can access the deflections +using `native` and `slim`. + +- `native` preserves the image layout. Its shape is + (101, 101, 2): one pair of (y,x) deflection components for each pixel. +- `slim` lists the same pairs in pixel order. Its shape is + (10201, 2): one row per pixel, with two components in each row. -- **native**: A 2D array with shape \([total_y_pixels, total_x_pixels, 2]\), where the last dimension represents the - (y,x) deflection components. - -- **slim**: A 1D array with shape \([total_y_pixels * total_x_pixels, 2]\), where the coordinates are flattened - into a single list. +The final dimension has length 2 because a deflection has both a y +component and an x component. + +Below, we print the deflection at the first pixel using both representations. +The two outputs should be identical. We then print the deflection at the +next pixel using `slim`. ```python -print("Deflection angles of pixel 0:") + +print("Deflection at the first pixel, using native:") print(deflections.native[0, 0]) -print("Deflection angles of pixel 1:") + +print("Deflection at the first pixel, using slim:") +print(deflections.slim[0]) + +print("Deflection at the next pixel, using slim:") print(deflections.slim[1]) ``` - Deflection angles of pixel 0: + Deflection at the first pixel, using native: [ 1.13137085 -1.13137085] - Deflection angles of pixel 1: + Deflection at the first pixel, using slim: + [ 1.13137085 -1.13137085] + Deflection at the next pixel, using slim: [ 1.14274054 -1.11988573] -There is an important difference between a grid and deflection angles. A `Grid2D` is a set of coordinates, while -deflection angles are 2D vectors. This means that each deflection angle is defined at a specific (y,x) coordinate -but has two components: a y and an x value, which vary across the grid. +A grid tells us where we are evaluating the lensing calculation. A deflection +vector tells us the angular displacement associated with each of those +positions. -This is why the method is called `deflections_yx_2d_from`—the `yx` signifies that these are 2D vectors with both -y and x components. +Both use pairs of numbers, but the pairs have different meanings: a grid +stores (y,x) positions, whereas the deflections store (y,x) components of +a displacement. -The deflection angles are stored in a `VectorYX2D` data structure: +PyAutoLens stores these deflections in a `VectorYX2D` object. This keeps +the vectors together with the grid of positions where they were calculated. ```python + print(type(deflections)) ``` -This structure includes a `grid`, which represents the `Grid2D` of coordinates where the deflection angles are -calculated (in this case, the `image_plane_grid` we defined earlier). It also has vector-specific methods, -such as `magnitude`, which calculates the magnitude of each deflection vector using \((x^2 + y^2)^{0.5}\). +The `grid` attribute gives us the positions where the deflections were +calculated. Here, these are the coordinates of `image_plane_grid`. + +The `magnitudes` attribute gives the length of each deflection vector, +combining its two components: + +$\lvert \alpha \rvert = \sqrt{\alpha_y^2 + \alpha_x^2}$ + +The magnitude is measured in arcseconds, just like the individual components. + +Below, we print the position of the first pixel and the magnitude of its +deflection. For our spherical isothermal profile, the deflection magnitude +away from the centre is equal to the Einstein radius, so we expect +approximately 1.6 arcseconds at this pixel. ```python -print("Deflection angle's `Grid2D` at pixel 0:") + +print("Position of the first pixel (y,x), in arcseconds:") print(deflections.grid.native[0, 0]) -print("Deflection angle magnitude at pixel 0:") + +print("Deflection magnitude at the first pixel, in arcseconds:") print(deflections.magnitudes.native[0, 0]) ``` - Deflection angle's `Grid2D` at pixel 0: + Position of the first pixel (y,x), in arcseconds: [ 5. -5.] - Deflection angle magnitude at pixel 0: + Deflection magnitude at the first pixel, in arcseconds: 1.6 -We can use `aplt.plot_array` to visualize the deflection angles, which displays the y and x components separately. +We can see how the deflections vary across the image by plotting their +y and x components separately. + +For each component, we construct an `Array2D` using the image-plane grid's +mask. This places each value at the pixel where it was calculated. -On this plot, you’ll see yellow and white lines called **critical curves**. These curves are important in lensing -and will be explained in detail in the next tutorial. +The colours show the signed deflection component in arcseconds. In the +y-component plot, the sign changes across the horizontal line through the +lens centre. In the x-component plot, it changes across the vertical line. + +For this spherical profile, the components vary with direction even though +the total deflection magnitude is constant away from the centre. Compare +the two plots: their patterns should be related by a rotation. ```python -deflections = sis_mass_profile.deflections_yx_2d_from(grid=image_plane_grid) -deflections_y = aa.Array2D(values=deflections.slim[:, 0], mask=image_plane_grid.mask) -aplt.plot_array(array=deflections_y, title="Deflections Y") -deflections = sis_mass_profile.deflections_yx_2d_from(grid=image_plane_grid) -deflections_x = aa.Array2D(values=deflections.slim[:, 1], mask=image_plane_grid.mask) -aplt.plot_array(array=deflections_x, title="Deflections X") + +deflections_y = aa.Array2D( + values=deflections.slim[:, 0], + mask=image_plane_grid.mask, +) +aplt.plot_array( + array=deflections_y, + title="Y Deflection (arcseconds)", +) + +deflections_x = aa.Array2D( + values=deflections.slim[:, 1], + mask=image_plane_grid.mask, +) +aplt.plot_array( + array=deflections_x, + title="X Deflection (arcseconds)", +) ``` - + ![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_15_0.png) - - + + ![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_15_1.png) - -Mass profiles also have additional properties used in lensing calculations: -- **convergence**: Represents the surface mass density of the profile in dimensionless units. -- **potential**: Represents the "lensing potential" of the mass profile in dimensionless units. -- **magnification**: Indicates how much brighter light rays appear due to the focusing effect of lensing. +A mass profile also lets us calculate other quantities that describe +the lens and its effect on the source's appearance: + +- **Convergence** describes the projected mass per unit area, divided by + a reference surface density called the critical surface density. + This reference depends on the lens and source redshifts, which set + the relevant distances for a chosen cosmology. Convergence is + therefore dimensionless. -These quantities can be calculated using `*_from` methods and are returned as `Array2D` objects. +- **Lensing potential** is a mathematical function whose spatial variation + determines the deflection angles. Its gradient gives the deflection + vector. With our coordinates and deflections expressed in arcseconds, + the potential is expressed in arcseconds squared. + +- **Magnification** describes how lensing changes the apparent area of a + small source region. Lensing preserves surface brightness, but a larger + image covers more sky and therefore contains more total light. The + absolute magnification gives the local area and flux factor; its sign + records whether the image orientation is reversed. + +We will explore these quantities further as we develop the lensing +formalism. For now, we calculate them on our image-plane grid. + +Convergence and potential are calculated directly from the mass profile. +For magnification, we use `LensCalc`, which calculates it from the way +the deflections vary across the grid. Each result is an `Array2D`. ```python -convergence = sis_mass_profile.convergence_2d_from(grid=image_plane_grid) -potential_2d = sis_mass_profile.potential_2d_from(grid=image_plane_grid) + +convergence = sis_mass_profile.convergence_2d_from( + grid=image_plane_grid +) + +potential_2d = sis_mass_profile.potential_2d_from( + grid=image_plane_grid +) + magnification_2d = al.LensCalc.from_mass_obj( mass_obj=sis_mass_profile ).magnification_2d_from(grid=image_plane_grid) ``` -The same plotter API can be used to visualize these properties: + .../PyAutoGalaxy/autogalaxy/operate/lens_calc.py:575: UserWarning: LensCalc Hessian: 1 of 10201 points did not converge after 20 halvings (largest relative error estimate 5.00e-01); values kept. + warnings.warn( + + +Let's plot the convergence and lensing potential. + +The convergence is largest near the centre and decreases outwards, +showing how the projected mass density falls with distance from the +centre of this profile. + +The spherical isothermal profile is singular at its exact centre: +its idealised density grows without bound there. The central pixel +therefore needs care when interpreting the numerical plot. + +The potential has a different pattern, increasing with distance from +the centre for this profile. It is not another image of the mass density. +Its spatial variation determines the deflections. + +Both plots should be circularly symmetric because we chose a spherical +mass profile. ```python + aplt.plot_array( - array=sis_mass_profile.convergence_2d_from(grid=image_plane_grid), + array=convergence, title="Convergence", ) + aplt.plot_array( - array=sis_mass_profile.potential_2d_from(grid=image_plane_grid), title="Potential" + array=potential_2d, + title="Lensing Potential (arcseconds squared)", ) ``` - + ![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_19_0.png) - - + + ![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_19_1.png) - -One-dimensional plots can also be made using the same projection technique as in the previous tutorial: + +We can also examine the convergence along a line extending outwards +from the mass profile's centre. + +Because our profile is spherical, the result is the same in every +direction. We will sample along the positive x direction, at radii +from 0.1 to 5.0 arcseconds. Starting away from zero avoids the +singularity at the centre of the isothermal profile. + +The convergence should decrease as we move outwards. For this profile, +doubling the radius halves the convergence. ```python -grid_2d_projected = image_plane_grid.grid_2d_radial_projected_from( - centre=sis_mass_profile.centre, angle=sis_mass_profile.angle() + +import numpy as np + +radii = np.linspace(0.1, 5.0, 100) + +radial_grid = al.Grid2DIrregular( + values=[ + (sis_mass_profile.centre[0], sis_mass_profile.centre[1] + radius) + for radius in radii + ] ) -convergence_1d = sis_mass_profile.convergence_2d_from(grid=grid_2d_projected) +convergence_1d = sis_mass_profile.convergence_2d_from(grid=radial_grid) -plt.plot(grid_2d_projected[:, 1], convergence_1d) -plt.xlabel("Radius (arcseconds)") -plt.ylabel("Luminosity") +plt.plot(radii, convergence_1d) +plt.xlabel("Radius from profile centre (arcseconds)") +plt.ylabel("Convergence") plt.show() plt.close() ``` - + ![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_21_0.png) - -The **convergence** and **potential** can be better understood when plotted in logarithmic space: + +In the convergence image, the large values near the centre can make +the variation farther out difficult to see. + +A logarithmic colour scale helps us display a wide range of positive +values. Equal steps in colour then represent equal ratios of values, +rather than equal differences. + +Below, we plot convergence and potential using logarithmic colour +scales. Compare these with the earlier plots: the underlying quantities +are unchanged, but different parts of their variation become easier +to distinguish. + +A logarithmic scale only represents positive values. The singular +centre of this idealised profile should still be treated with care. ```python + aplt.plot_array( - array=sis_mass_profile.convergence_2d_from(grid=image_plane_grid), - title="Convergence in Log10 Space", + array=convergence, + title="Convergence (logarithmic colour scale)", use_log10=True, ) + aplt.plot_array( - array=sis_mass_profile.potential_2d_from(grid=image_plane_grid), - title="Potential in Log10 Space", + array=potential_2d, + title="Lensing Potential (logarithmic colour scale)", use_log10=True, ) ``` - + ![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_23_0.png) - - + + ![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_23_1.png) - -__Ray Tracing Grids__ -We now have all the tools we need to perform our first ray-tracing calculation. +__Ray Tracing Grids__ -Ray tracing uses a mass profile's deflection angles to map coordinates from the image-plane (where we observe the -lensed source) to the source-plane (where the source truly is). This mapping is described by the **lens equation**: +We can now map image-plane coordinates to the source plane using +the **lens equation**: $\beta = \theta - \alpha(\theta)$ -where $\theta$ are the image-plane coordinates, $\alpha(\theta)$ are the deflection angles of the mass profile, and -$\beta$ are the corresponding source-plane coordinates. +Here, $\theta$ is an image-plane position, $\alpha(\theta)$ is its +deflection vector, and $\beta$ is the corresponding source-plane +position. Each has (y,x) components measured in arcseconds. + +For example, at image-plane position (0.0, 2.0), the deflection is +(0.0, 1.6), giving source-plane position (0.0, 0.4) arcseconds. -We compute the deflection angles of our mass profile on the `image_plane_grid`, and then use the grid's -`grid_2d_via_deflection_grid_from` method to subtract them and produce the ray-traced `source_plane_grid`. +The method below performs this subtraction for every grid coordinate. ```python -deflections = sis_mass_profile.deflections_yx_2d_from(grid=image_plane_grid) + +deflections = sis_mass_profile.deflections_yx_2d_from( + grid=image_plane_grid +) source_plane_grid = image_plane_grid.grid_2d_via_deflection_grid_from( deflection_grid=deflections ) ``` -Let's plot the image-plane grid and the ray-traced source-plane grid. +Let's plot the image-plane grid and its mapped source-plane coordinates. -The image-plane grid is uniform, but the source-plane grid is distorted. This distortion is caused by the mass -profile's deflection angles, which bend the light rays as they pass the lens galaxy. The coordinates near the -center of the mass are deflected the most. +The image-plane grid is uniform, but the source-plane coordinates +are unevenly spaced. Each point still corresponds to one original +image-plane pixel. + +For our spherical isothermal profile, the deflection magnitude is +1.6 arcseconds everywhere away from the centre. The direction varies +across the grid, producing the pattern below; points nearer the +centre are not deflected more strongly. ```python -aplt.plot_grid(grid=image_plane_grid, title="Image Plane Grid") -aplt.plot_grid(grid=source_plane_grid, title="Source Plane Grid (Ray Traced)") + +aplt.plot_grid( + grid=image_plane_grid, + title="Image Plane Grid", +) + +aplt.plot_grid( + grid=source_plane_grid, + title="Source Plane Grid (Ray Traced)", +) ``` - + ![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_27_0.png) - - + + ![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_27_1.png) - + + + +The source-plane grid covers a wide area, but many of its points +land close together near the centre. Zooming in helps us see +their spacing. + +This is related to magnification: a small region of the source +can appear over a much larger area in the image plane. When we +trace those image-plane points back, many therefore land within +that small source-plane region. + +We often zoom in when plotting source planes so that this central +detail is easier to see. The plot below shows the central +2-by-2 arcseconds. Only the displayed limits change; the grid +and ray-tracing calculation stay the same. + +For these grid displays, we use `autoarray.plot` (imported as `aaplt`), +which provides the `extent` and grouped `indexes` options. + + +```python + +aaplt.plot_grid( + grid=source_plane_grid, + title="Source Plane (Zoomed In)", + extent=(-1.0, 1.0, -1.0, 1.0), +) +``` + + + +![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_29_0.png) + + + +__Mappings__ + +Each image-plane coordinate maps to a source-plane coordinate. +We can show this by highlighting groups of points in matching colours. + +As in the previous tutorial, indexes refer to positions in the +grid's `slim` ordering. Each inner list below selects five points; +the plotting function gives each group a different colour. + +We use the same indexes in both panels because ray tracing preserves +the order of the points. Follow each coloured group from the image +plane to the source plane and look at how its spacing changes. + +These indexes are chosen for our 101-by-101 grid. Try selecting +different indexes to follow other parts of the grid. + +To inspect the central points more closely, try changing `extent` +in the source-plane plot to (-1.0, 1.0, -1.0, 1.0). The four values +set the minimum and maximum x coordinates, then the minimum and +maximum y coordinates. Restore the limits below to compare both +planes at the same scale. + + +```python + +indexes = [ + [5118, 5119, 5120, 5121, 5122], + [3078, 3079, 3080, 3081, 3082], + [7098, 7099, 7100, 7101, 7102], +] + +fig, axes = plt.subplots(1, 2, figsize=(12, 5)) + +aaplt.plot_grid( + grid=image_plane_grid, + indexes=indexes, + ax=axes[0], + title="Image Plane", + extent=(-5.5, 5.5, -5.5, 5.5), +) + +aaplt.plot_grid( + grid=source_plane_grid, + indexes=indexes, + ax=axes[1], + title="Source Plane", + extent=(-5.5, 5.5, -5.5, 5.5), +) + +plt.tight_layout() +plt.show() +plt.close(fig) +``` + + + +![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_31_0.png) + __Ray Tracing Images__ -The source-plane grid tells us where each image-plane coordinate lands in the source-plane after being deflected. +The source-plane grid tells us where the light at each image-plane +position originated. To calculate its brightness, we evaluate a +source light profile at those mapped positions. + +We use an `ExponentialCore` light profile centred at (0.1, 0.1) +arcseconds in the source plane. This places the source slightly +away from exact alignment with the lens centre. -To compute the lensed image of a source galaxy, we place a light profile in the source-plane and evaluate its light -on the ray-traced `source_plane_grid`. Because many image-plane coordinates map to the same region of the -source-plane, the source appears multiply imaged, forming arcs or a complete Einstein ring. +Each calculated intensity remains associated with its original +image-plane pixel. The resulting array therefore describes the +lensed image seen on the sky, even though we evaluated the light +profile at source-plane coordinates. -Let's create a source light profile and compute its lensed image. +Different parts of the image plane can map onto the same region +of the source. This is how one source galaxy can appear as +multiple images or extended arcs. ```python + source_light_profile = al.lp.ExponentialCore( centre=(0.1, 0.1), ell_comps=(0.0, 0.1), @@ -409,40 +680,60 @@ source_light_profile = al.lp.ExponentialCore( effective_radius=0.2, ) -lensed_image = source_light_profile.image_2d_from(grid=source_plane_grid) +lensed_image = source_light_profile.image_2d_from( + grid=source_plane_grid +) ``` -When we plot this image, the source's light appears as a strongly lensed Einstein ring. +Let's plot the lensed source. Look for its light stretched around +the lens centre into a ring-like image. -This is the **image-plane image** or **observed image** we discussed at the start of the tutorial: the appearance -of the source *after* its light has been deflected by the lens galaxy's mass. +This image is calculated from our chosen mass and light profiles. -*Exercise*: Try changing the `centre` of the source light profile. Observe how moving the source relative to the -lens galaxy changes the lensed image from a ring into arcs or multiple images. +Try changing the source profile's `centre` in the preceding cell: + +- Start with (0.0, 0.0) arcseconds to align the source with the lens. +- Then try (0.0, 0.5) arcseconds to move the source off-centre. + +After each change, rerun the source-profile and `lensed_image` +calculations, then plot the result below. Moving the source off-centre +should make the lensed light less evenly distributed around the lens. + +Restore `centre=(0.1, 0.1)` and rerun those cells before continuing. ```python -aplt.plot_array(array=lensed_image, title="Lensed Source Image") + +aplt.plot_array( + array=lensed_image, + title="Lensed Source Image", +) ``` - -![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_31_0.png) - + +![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_35_0.png) + __Galaxies__ -In the previous tutorial we saw that a `Galaxy` can contain one or more light profiles. A `Galaxy` can also contain -mass profiles, and can contain both at the same time. +In the previous tutorial, we put light profiles inside `Galaxy` +objects. A galaxy can also contain mass profiles. -This lets us construct realistic lens and source galaxies: +Let's place our mass profile in a lens galaxy at redshift 0.5, +and our source light profile in a source galaxy at redshift 1.0. -- The **lens galaxy** has a mass profile (which deflects light) and typically a light profile (its own emission). -- The **source galaxy** has a light profile (the light we see lensed), and is at a higher redshift. +Our lens galaxy contains only a mass profile, so it deflects light +but contributes no light of its own to this example. The source +galaxy contains the light profile whose lensed image we have +just calculated. + +Printing the galaxies shows their redshifts and profiles. ```python + lens_galaxy = al.Galaxy( redshift=0.5, mass=sis_mass_profile, @@ -480,107 +771,419 @@ print(source_galaxy) __Tracer__ -Performing the ray-tracing calculation manually, as we did above, becomes cumbersome once we have multiple galaxies -at multiple redshifts. +A `Tracer` brings our galaxies together and performs the ray tracing +for us. -The `Tracer` object automates the entire ray-tracing process. We create it from a list of galaxies, ordered by their -redshift, and it uses their redshifts and a cosmological model to set up the strong lens system. +We supply the lens and source galaxies. Their redshifts identify +which galaxy is in front and which is behind. ```python + tracer = al.Tracer(galaxies=[lens_galaxy, source_galaxy]) ``` -The `Tracer` has an `image_2d_from` method, just like light profiles and galaxies. It performs all the ray-tracing -for us and returns the image of the entire strong lens system. +Like a light profile or galaxy, a `Tracer` has an `image_2d_from` +method. + +We pass it the original image-plane grid. It calculates the +deflections, traces the grid to the source plane and evaluates +the source's light there. -This produces the same lensed Einstein ring we computed manually above, but in a single line of code. +The plot should reproduce the lensed image we calculated manually, +because we supplied the same mass and light profiles. + +A tracer also includes any light emitted by the lens galaxy. +Here, there is none, so the image contains only the lensed source. ```python + image = tracer.image_2d_from(grid=image_plane_grid) -aplt.plot_array(array=image, title="Image of Strong Lens System via Tracer") +aplt.plot_array( + array=image, + title="Lensed Image via Tracer", +) ``` - -![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_37_0.png) - +![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_41_0.png) + + + +We can display several views of the lens system together using +`aplt.subplot_tracer`. + +Compare the lensed image with the source-plane image, which shows +the source light profile before lensing. The lens-light panel +contains no emission because our lens galaxy has no light profile. -The `subplot_tracer` method plots a subplot of the most important quantities of the strong lens system, including -its image, convergence, potential and deflection angles. +The remaining panels show convergence, potential, the two +deflection components and magnification. These describe the same +mass profile we examined earlier. + +**🤖 Ask AI:** How does moving the source away from alignment with the +lens change an Einstein ring into separate arcs or images? ```python + aplt.subplot_tracer(tracer=tracer, grid=image_plane_grid) ``` + .../PyAutoGalaxy/autogalaxy/operate/lens_calc.py:575: UserWarning: LensCalc Hessian: 1 of 10201 points did not converge after 20 halvings (largest relative error estimate 5.00e-01); values kept. + warnings.warn( - -![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_39_0.png) - -__Mappings__ -The `Tracer` also gives us access to the grids of every plane in the strong lens system, via the -`traced_grid_2d_list_from` method. +![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_43_1.png) + -This returns a list, where the first entry is the image-plane grid and the second entry is the ray-traced -source-plane grid. These are the same two grids we computed manually earlier, but now produced by the tracer. + +The `Tracer` can also return the grids used in its ray-tracing +calculation, through `traced_grid_2d_list_from`. + +For our two-galaxy system, the first entry is the original +image-plane grid and the second is the ray-traced source-plane +grid. These correspond to the two grids we calculated manually. ```python -traced_grid_list = tracer.traced_grid_2d_list_from(grid=image_plane_grid) + +traced_grid_list = tracer.traced_grid_2d_list_from( + grid=image_plane_grid +) image_plane_grid_traced = traced_grid_list[0] source_plane_grid_traced = traced_grid_list[1] ``` -By plotting the image-plane and source-plane grids together, we can visualize the **mappings** between them. +__Units__ -Every coordinate in the image-plane maps to a coordinate in the source-plane via the lens equation. This mapping is -the heart of strong lens modeling: to fit a lens, we ray-trace the image-plane grid to the source-plane, evaluate -the source's light there, and compare the resulting lensed image to the observed data. +Throughout this tutorial, we have measured positions and radii in +arcseconds: angles on the sky. What physical size does an angle +of one arcsecond represent? + +That depends on the distance to the galaxy. We express galaxy +sizes in kiloparsecs, where one kiloparsec is 1,000 parsecs, +or approximately 3,260 light-years. + +To convert an angular size into a physical size, we use the +galaxy's redshift and a cosmology: a model of the Universe's +expansion that relates redshifts to distances. + +Our tracer already has a cosmology. Unless we supply another, +it uses the Planck 2015 cosmology. + +Let's calculate how many kiloparsecs correspond to one arcsecond +at the redshifts of our lens and source. ```python -aplt.plot_grid(grid=image_plane_grid_traced, title="Image Plane Grid") -aplt.plot_grid(grid=source_plane_grid_traced, title="Source Plane Grid") + +cosmology = tracer.cosmology + +kpc_per_arcsec_lens = cosmology.kpc_per_arcsec_from( + redshift=lens_galaxy.redshift +) +kpc_per_arcsec_source = cosmology.kpc_per_arcsec_from( + redshift=source_galaxy.redshift +) + +print( + f"Lens plane: {kpc_per_arcsec_lens:.3f} kpc per arcsecond" +) +print( + f"Source plane: {kpc_per_arcsec_source:.3f} kpc per arcsecond" +) ``` + Lens plane: 6.288 kpc per arcsecond + Source plane: 8.232 kpc per arcsecond - -![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_43_0.png) - +The conversion differs between the two planes because the +galaxies are at different distances. +For example, we can multiply the lens's Einstein radius in +arcseconds by the lens-plane conversion to express it in +kiloparsecs. - -![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_43_1.png) - +```python -__Wrap Up__ +einstein_radius_kpc = ( + sis_mass_profile.einstein_radius * kpc_per_arcsec_lens +) + +print(f"Einstein radius: {einstein_radius_kpc:.3f} kpc") +``` -In this tutorial, you performed your first lensing calculations. Let's summarise what we've learnt: + Einstein radius: 10.061 kpc -- **Mass Profiles**: Mass profiles are analytic functions that describe the mass distribution of a galaxy. They are -used to compute deflection angles, as well as the convergence and gravitational potential. -- **Ray Tracing Grids**: The lens equation, $\beta = \theta - \alpha(\theta)$, uses deflection angles to map -image-plane coordinates to the source-plane, producing a distorted ray-traced grid. +For a source galaxy's physical size, we use the source-plane +conversion instead. -- **Ray Tracing Images**: By evaluating a source galaxy's light on the ray-traced source-plane grid, we compute the -lensed image of the source, which appears as arcs or an Einstein ring. +We will continue to calculate and plot coordinates in arcseconds. +These conversion factors let us express our model's sizes in +physical units when needed. -- **Galaxies**: A `Galaxy` can contain both light and mass profiles, allowing us to construct realistic lens and +Tutorial 3 explains the cosmological distances behind this +conversion, as part of its optional mathematical discussion. + +__More Complexity__ + +Our tracer currently contains one spherical lens and one source. +Let's extend this to a system with two lens galaxies and two source galaxies. -- **Tracer**: The `Tracer` object automates the ray-tracing process for a system of galaxies at different redshifts, -computing the image of the entire strong lens system in a single line of code. +We first add a light profile to the main lens, representing its +central concentration of stars, or bulge. This light contributes +to the observed image. The separate mass profile determines +how the galaxy deflects light. + +We also replace the spherical mass profile with an elliptical +one. Its projected mass contours are now ellipses, so the +deflection pattern is no longer rotationally symmetric. + +Finally, we add an external shear. Surrounding matter can +distort the lensed images even when we do not model each +neighbouring structure individually. External shear approximates +this effect as a directional stretching across the image. + +Shear treats two perpendicular directions differently, so it +can turn a small circular source into an elongated image. +The main lens produces shear too; "external" describes the +additional contribution from its surroundings. + +We represent this contribution with a `MassField` at the lens +redshift. Its two dimensionless components, `gamma_1` and +`gamma_2`, specify its strength and orientation. The field +contributes deflections but no light. + + +```python + +lens_galaxy = al.Galaxy( + redshift=0.5, + bulge=al.lp.SersicSph( + centre=(0.0, 0.0), + intensity=2.0, + effective_radius=0.5, + sersic_index=2.5, + ), + mass=al.mp.Isothermal( + centre=(0.0, 0.0), + ell_comps=(0.0, -0.111111), + einstein_radius=1.6, + ), +) + +field = al.MassField( + redshift=0.5, + shear=al.mp.ExternalShear( + gamma_1=0.05, + gamma_2=0.0, + ), +) +``` + +Let's add a smaller companion, or satellite galaxy, at the same +redshift as the main lens. + +Its centre is at (1.0, 0.0) arcseconds, placing it one arcsecond +from the main lens along the y direction. It has both a light +profile and a mass profile, so it contributes visible light +and additional deflections. + +Its Einstein-radius parameter is 0.4 arcseconds, compared with +1.6 arcseconds for the main lens. This gives it a smaller lensing +strength, although its effect can still matter for images +passing close to it. + +Unlike the external shear, this galaxy is represented explicitly: +we specify where it is and how its light and mass are distributed. + + +```python + +lens_satellite = al.Galaxy( + redshift=0.5, + bulge=al.lp.DevVaucouleursSph( + centre=(1.0, 0.0), + intensity=2.0, + effective_radius=0.2, + ), + mass=al.mp.IsothermalSph( + centre=(1.0, 0.0), + einstein_radius=0.4, + ), +) +``` + +We also create two source galaxies at redshift 1.0. + +The first has two light components: a compact bulge and a more +extended disk. Both share the same centre, so their light adds +together to describe one galaxy. The second source has only a +disk and lies at a different source-plane position. + +Names such as `bulge` and `disk` help us describe the components. +The chosen light profiles and their parameters determine the +actual brightness distribution. + +Because both sources have the same redshift, they occupy the +same source plane. Adding a galaxy does not necessarily add +another plane. + + +```python + +source_0 = al.Galaxy( + redshift=1.0, + bulge=al.lp.DevVaucouleursSph( + centre=(0.1, 0.2), + intensity=0.3, + effective_radius=0.3, + ), + disk=al.lp.ExponentialCore( + centre=(0.1, 0.2), + ell_comps=(0.111111, 0.0), + intensity=3.0, + effective_radius=2.0, + ), +) + +source_1 = al.Galaxy( + redshift=1.0, + disk=al.lp.ExponentialCore( + centre=(-0.3, -0.5), + ell_comps=(0.1, 0.0), + intensity=8.0, + effective_radius=1.0, + ), +) +``` + +__Multi Galaxy Ray Tracing__ + +We now pass our four galaxies and external shear to a tracer. + +The main lens and its satellite share redshift 0.5, while both +sources share redshift 1.0. The tracer therefore groups the +galaxies into two planes, with two galaxies in each. + +To calculate the image, the tracer follows the same steps +we used earlier: + +1. Evaluate the light of both foreground galaxies on the + image-plane grid. + +2. Add the deflections from the main lens, its satellite + and the external shear. + +3. Subtract these total deflections from the image-plane + coordinates to obtain the source-plane coordinates. + +4. Evaluate both source galaxies' light at those traced + coordinates and add their contributions. + +5. Add the foreground light to the lensed source light + to form the complete image. + +The next plot shows the combined image. It contains the +foreground galaxies as well as the distorted images of +the two sources. + + +```python + +tracer = al.Tracer( + galaxies=[ + lens_galaxy, + lens_satellite, + source_0, + source_1, + ], + fields=[field], + cosmology=cosmology, +) + +image = tracer.image_2d_from(grid=image_plane_grid) + +aplt.plot_array( + array=image, + title="Two Lens Galaxies and Two Sources", +) +``` + + + +![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_58_0.png) + + + +Let's separate the views using the tracer subplot. + +The lens-light panel shows the main lens and satellite. +The source-plane panel shows both sources before lensing, +while the full image combines foreground light with the +lensed source images. + +To see the satellite's effect, remove `lens_satellite` from +the tracer's galaxy list and rerun the image and subplot +cells. Its light disappears, and the source images change +because its deflections are also removed. + +Restore it to the list and rerun those cells to return +to the original system. + +**🤖 Ask AI:** In this example, how could I distinguish the +satellite galaxy's contribution to the observed light from +its effect on the lensed source images? + + +```python + +aplt.subplot_tracer( + tracer=tracer, + grid=image_plane_grid, +) +``` + + .../PyAutoGalaxy/autogalaxy/operate/lens_calc.py:575: UserWarning: LensCalc Hessian: 2 of 10201 points did not converge after 20 halvings (largest relative error estimate 2.76e+00); values kept. + warnings.warn( + + + + +![png](tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_60_1.png) + + + +__Wrap Up__ + +We began by building a lensed image step by step: calculate +deflections, trace coordinates with the lens equation, and +evaluate the source's light at those coordinates. + +A `Tracer` performs these steps for us. It also lets us extend +the same calculation to several galaxies, combining their +light and accounting for their mass. + +We have now built a system with two foreground galaxies, +two sources and an external shear. The underlying idea is +still the same coordinate mapping we started with. + +We also used galaxy redshifts and a cosmology to connect +angular sizes in arcseconds to physical sizes in kiloparsecs. -In the next tutorial, we'll extend these ideas to more complex mass and light distributions, building towards the -realistic strong lens systems we observe in real data. +Tutorial 3 explains the mathematics behind these calculations, +including convergence, shear, magnification, critical curves +and caustics. You can follow its physical explanations and +figures without working through every equation, and return +to the mathematics when you need it. diff --git a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_15_0.png b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_15_0.png index c44dd65..1cb4e0b 100644 Binary files a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_15_0.png and b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_15_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_15_1.png b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_15_1.png index 49e593b..ca81346 100644 Binary files a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_15_1.png and b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_15_1.png differ diff --git a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_19_1.png b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_19_1.png index 033aea9..9484e49 100644 Binary files a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_19_1.png and b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_19_1.png differ diff --git a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_21_0.png b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_21_0.png index 90e2bd6..d48ff3f 100644 Binary files a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_21_0.png and b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_21_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_23_0.png b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_23_0.png index 94904c5..97204d6 100644 Binary files a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_23_0.png and b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_23_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_23_1.png b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_23_1.png index 966287b..c3d2c37 100644 Binary files a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_23_1.png and b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_23_1.png differ diff --git a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_29_0.png b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_29_0.png new file mode 100644 index 0000000..11ec1a1 Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_29_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_31_0.png b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_31_0.png index a809159..dce2a53 100644 Binary files a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_31_0.png and b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_31_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_35_0.png b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_35_0.png new file mode 100644 index 0000000..a809159 Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_35_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_37_0.png b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_37_0.png deleted file mode 100644 index a6e9872..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_37_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_39_0.png b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_39_0.png deleted file mode 100644 index 88cd4b4..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_39_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_41_0.png b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_41_0.png new file mode 100644 index 0000000..7129f6e Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_41_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_43_0.png b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_43_0.png deleted file mode 100644 index eeed8b3..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_43_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_43_1.png b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_43_1.png index 8534434..1dbe3d4 100644 Binary files a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_43_1.png and b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_43_1.png differ diff --git a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_58_0.png b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_58_0.png new file mode 100644 index 0000000..1887a18 Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_58_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_60_1.png b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_60_1.png new file mode 100644 index 0000000..59ef531 Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_2_ray_tracing_files/tutorial_2_ray_tracing_60_1.png differ diff --git a/markdown/chapter_1_introduction/tutorial_3_more_ray_tracing.md b/markdown/chapter_1_introduction/tutorial_3_more_ray_tracing.md index 1aba94f..7e12a09 100644 --- a/markdown/chapter_1_introduction/tutorial_3_more_ray_tracing.md +++ b/markdown/chapter_1_introduction/tutorial_3_more_ray_tracing.md @@ -3,39 +3,45 @@ > Run it yourself via the [Python script](../../scripts/chapter_1_introduction/tutorial_3_more_ray_tracing.py) or the [Jupyter notebook](../../notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb). Tutorial 3: More Ray Tracing -============================ +=========================== -We'll now reinforce the ideas that we learnt about ray-tracing in the previous tutorial and introduce the following -new concepts: +In tutorial 2, we used the lens equation to trace coordinates from +the image plane to the source plane and build an image of a +strong lens. -- What critical curves and caustics are. - - That by specifying redshifts and a cosmology, the results are converted from arc-second coordinates to physical - units of kiloparsecs (kpc). Again, if you're not an Astronomer, you may not be familiar with the unit of parsec, it - may be worth a quick Google! - - That a `Tracer` can be given any number of galaxies. +We will now connect that picture to the quantities used to describe +gravitational lensing: convergence, deflection angles, potential, +shear and magnification. We will also explain critical curves and +caustics, the Einstein radius and time delays. -Up to now, the planes have also had just one lens galaxy or source galaxy at a time. In this example, the tracer will -have multiple galaxies at each redshift, meaning that each plane has more than one galaxy. In terms of lensing -calculations: +This tutorial includes the mathematics behind these ideas, but +following every equation is optional. You can do strong-lensing +science with a physical understanding of how mass bends light, +changes image shapes and produces multiple images. PyAutoLens +performs the calculations; your job is to understand what your +model represents and what the observations can tell you. -- If two or more lens galaxies are at the same redshift in the image-plane, the convergences, potentials and -deflection angles of their mass profiles are summed when performing lensing calculations. +Each mathematical section therefore explains the idea in words +and connects it to code or a figure. On a first pass, you can focus +on those explanations and outputs, then return to the equations +when you want to understand a calculation in more detail. -- If two or more source galaxies are at the same redshift in the source-plane, their light can simply be summed before -ray tracing. - -The `Tracer` fully accounts for this. +We assume you are familiar with the lens equation from tutorial 2. __Contents__ -- **Initial Setup:** To begin, lets setup the grid we'll ray-trace using. -- **Concise Code:** Lets set up the tracer used in the previous tutorial. -- **Critical Curves:** We can finally explain what the black lines that have appeared on many of the plots. -- **Caustics:** In the previous tutorial, we plotted the critical curves of the mass profile on the image-plane. -- **Units:** Lets plot the lensing quantities again. -- **More Complexity:** We now make a lens with some attributes we didn`t in the last tutorial. -- **Multi Galaxy Ray Tracing:** Now lets pass our 4 galaxies to a `Tracer`, which means the following will occur. -- **Wrap Up:** Summary of the script and next steps. +- **Initial Setup:** Create the image-plane grid. +- **Concise Code:** Build a familiar lens and source in fewer steps. +- **Cosmological Distances:** Define the distances used in lensing. +- **Convergence:** Express projected mass as a dimensionless density. +- **Deflection Angles:** Relate the mass distribution to ray tracing. +- **The Lensing Potential:** Connect deflections and convergence through a scalar field. +- **Shear and Magnification:** Describe changes in image shape, area and total brightness. +- **Critical Curves and Caustics:** Locate strong stretching and its source-plane counterpart. +- **Einstein Radius:** Connect the scale of a strong lens to its enclosed projected mass. +- **Time Delays:** Explain why different images arrive at different times. +- **Wrap Up:** Review the physical meaning of the lensing quantities. +- **Env:** Preserve the grid used to resolve the critical curves. ```python @@ -44,7 +50,9 @@ from autolens import jax_wrapper # Sets JAX environment before other imports from autolens import setup_notebook; setup_notebook() +import matplotlib.pyplot as plt import numpy as np +import autoarray as aa import autolens as al import autolens.plot as aplt ``` @@ -54,20 +62,21 @@ import autolens.plot as aplt __Initial Setup__ -To begin, lets setup the grid we'll ray-trace using. But, lets do something crazy and use a higher resolution than -the previous tutorials! +We begin with a grid of 250 by 250 image-plane coordinates, +separated by 0.02 arcseconds. It covers a field 5 arcseconds across +and samples the lens more finely than the grids used earlier. -Lets also stop calling it the `image_plane_grid`, and just remember from now on our `grid` is in the image-plane. +We will call it `grid` from now on. Unless we explicitly trace it +to another plane, its coordinates are in the image plane. +The two printed shapes show the grid's arrangement and its total +number of coordinates. -```python -grid = al.Grid2D.uniform(shape_native=(250, 250), pixel_scales=0.02) -``` -The grid is now shape 250 x 250, which has more image-pixels than the 100 x 100 grid used previously. +```python +grid = al.Grid2D.uniform(shape_native=(250, 250), pixel_scales=0.02) -```python print(grid.shape_native) print(grid.shape_slim) ``` @@ -78,16 +87,23 @@ print(grid.shape_slim) __Concise Code__ -Lets set up the tracer used in the previous tutorial. +Let's build a lens and source using the same approach as tutorial 2. +We can define each profile directly inside its galaxy, keeping the +whole system together in a short block of code. -Up to now, we have set up each profile one line at a time, making the code long and cumbersome to read. +The lens has a spherical isothermal mass profile at redshift 0.5. +The source has a spherical light profile at redshift 1.0 and is +centred behind the lens. -From here on, we'll set up galaxies in a single block of code, making it more concise and readable. +We will use this tracer throughout the mathematical sections, +with the same default cosmology as tutorial 2. ```python + lens = al.Galaxy( - redshift=0.5, mass=al.mp.IsothermalSph(centre=(0.0, 0.0), einstein_radius=1.6) + redshift=0.5, + mass=al.mp.IsothermalSph(centre=(0.0, 0.0), einstein_radius=1.6), ) source = al.Galaxy( @@ -102,475 +118,972 @@ source = al.Galaxy( ) tracer = al.Tracer(galaxies=[lens, source]) +mass_profile = lens.mass +cosmology = tracer.cosmology +lens_calc = al.LensCalc.from_tracer(tracer=tracer) ``` -__Critical Curves__ +__Cosmological Distances__ -We can finally explain what the black lines that have appeared on many of the plots throughout this chapter -actually are. +In tutorial 2, we converted angular sizes into kiloparsecs. +The distance used in that conversion is called the +**angular diameter distance**. -These lines are called the 'critical curves', and they define line of infinite magnification due to a mass profile. -They therefore mark where in the image-plane a mass profile perfectly `focuses` light rays such that if a source is -located there, it will appear very bright: potentially 10-100x as brighter than its intrinsic luminosity. +It relates an object's physical size, $l$, perpendicular to our +line of sight to its angular size, $\theta$: -The outer white line is a `tangential_critical_curve`, because it describes how the image of the source galaxy is stretched -tangentially. There is also an inner `radial_critical_curve` which appears in yellow on figures, which describes how the -image of the source galaxy is stretched radially. +$$ +l = D\,\theta. +$$ -However, a radial critical curve only appears when the lens galaxy's mass profile is shallower than isothermal (e.g. -when its inner mass slope is less steep than a steep power-law). To make it appear below, we therefore change -the mass profile of our lens galaxy to a `PowerLawSph` with a slope of 1.8. +Here $D$ is the angular diameter distance and $\theta$ must be +expressed in radians. -In the next section, we'll introduce 'caustics', which are where the critical curves map to in the source-plane. +Three angular diameter distances describe the geometry of our +lens system: +- $D_l$: from the observer to the lens. +- $D_s$: from the observer to the source. +- $D_{ls}$: from the lens to the source. -```python -mass_profile = al.mp.PowerLawSph(centre=(0.0, 0.0), einstein_radius=1.6, slope=1.8) +These distances account for the expansion of the Universe. +In general, $D_{ls}$ is not equal to $D_s - D_l$. -lens = al.Galaxy(redshift=0.5, mass=mass_profile) +The cosmology calculates each distance from the relevant +redshifts. The values below are in kiloparsecs. -tangential_critical_curve_list = al.LensCalc.from_mass_obj( - mass_obj=mass_profile -).tangential_critical_curve_list_from(grid=grid) -radial_critical_curves_list = al.LensCalc.from_mass_obj( - mass_obj=mass_profile -).radial_critical_curve_list_from(grid=grid) +```python + +D_l = cosmology.angular_diameter_distance_to_earth_in_kpc_from(redshift=0.5) +D_s = cosmology.angular_diameter_distance_to_earth_in_kpc_from(redshift=1.0) +D_ls = cosmology.angular_diameter_distance_between_redshifts_in_kpc_from( + redshift_0=0.5, redshift_1=1.0 +) + +print(f"Observer to lens: {D_l:.3e} kpc") +print(f"Observer to source: {D_s:.3e} kpc") +print(f"Lens to source: {D_ls:.3e} kpc") ``` - .../PyAutoGalaxy/autogalaxy/operate/lens_calc.py:565: UserWarning: LensCalc Hessian: 1 of 9801 points did not converge after 20 halvings (largest relative error estimate 4.26e-01); values kept. - warnings.warn( - .../PyAutoGalaxy/autogalaxy/operate/lens_calc.py:565: UserWarning: LensCalc Hessian: 1 of 9801 points did not converge after 20 halvings (largest relative error estimate 4.26e-01); values kept. - warnings.warn( + Observer to lens: 1.297e+06 kpc + Observer to source: 1.698e+06 kpc + Lens to source: 7.252e+05 kpc -__Caustics__ +One radian contains approximately 206,265 arcseconds. The +conversion used in tutorial 2 therefore follows directly: -In the previous section, we plotted the critical curves of the mass profile on the image-plane. We will now plot the -'caustics', which correspond to each critical curve ray-traced to the source-plane. This is computed by using the -lens galaxy mass profile's to calculate the deflection angles at the critical curves and ray-trace them to the -source-plane. +$$ +l\;[\mathrm{kpc}] += +\frac{D\;[\mathrm{kpc}]}{206265} +\,\theta\;[\mathrm{arcsec}]. +$$ -As discussed in the previous section, critical curves mark regions of infinite magnification. Thus, if a source -appears near a caustic in the source plane it will appear significantly brighter than its true luminosity. +For a lens-plane size we use $D_l$; for a source-plane size +we use $D_s$. The third distance, $D_{ls}$, enters the lensing +strength through the geometry between the lens and source. -We again have to use a mass profile with a slope below 2.0 to ensure a radial critical curve and therefore radial -caustic is formed. As above, the tangential critical curve is white and maps to the tangential caustic in the source-plane, -which is also white. The radial critical curve is yellow and maps to the radial caustic, which is also yellow. +The physical deflection angle, $\hat{\boldsymbol{\alpha}}$, +describes how much the light ray bends as it passes the lens. +The displacement used in our lens equation also accounts for +the distances between observer, lens and source: +$\boldsymbol{\alpha} = (D_{ls}/D_s)\hat{\boldsymbol{\alpha}}$. +This is called the **reduced deflection angle**. -We can plot both the tangential and radial critical curves and caustics using the `lines=`/`positions=` overlays object. The -critical curves are plotted only for the image-plane grid, whereas the caustic in the source plane. +The deflections returned by PyAutoLens are these reduced angles, +expressed in arcseconds. They are the displacement we subtract +from an image-plane position to obtain its source-plane position, +as we did in tutorial 2. We will continue to call them +"deflection angles" throughout this tutorial. +__Convergence__ -```python -sis_mass_profile = al.mp.IsothermalSph(centre=(0.0, 0.0), einstein_radius=1.6) +Imagine adding up the lens galaxy's mass along our line of sight. +The result is its **surface mass density**, $\Sigma$: mass per +unit area projected onto the lens plane. -tracer = al.Tracer(galaxies=[lens, source]) +For a galaxy-scale lens, we usually treat the deflection as +occurring in one thin plane. Within this approximation, this +projected distribution describes how the galaxy's mass bends +the light. + +The same projected mass distribution has a different lensing +strength for different lens and source distances. We account +for that geometry using the **critical surface density**: + +$$ +\Sigma_{\mathrm{cr}} += +\frac{c^2}{4\pi G} +\frac{D_s}{D_l D_{ls}}, +$$ + +where $c$ is the speed of light and $G$ is Newton's gravitational +constant. + +Dividing the surface mass density by this reference value gives +the **convergence**: + +$$ +\kappa(\boldsymbol{\theta}) += +\frac{\Sigma(\boldsymbol{\theta})}{\Sigma_{\mathrm{cr}}}. +$$ + +Convergence is therefore dimensionless. A value of 0.5 means +that the local surface mass density is half the critical +surface density for this lens and source geometry. -tangential_critical_curve_list = al.LensCalc.from_tracer( - tracer=tracer -).tangential_critical_curve_list_from(grid=grid) -radial_critical_curves_list = al.LensCalc.from_tracer( - tracer=tracer -).radial_critical_curve_list_from(grid=grid) +Let's calculate the critical surface density in solar masses +per square kiloparsec, then plot our lens's convergence. -traced_grid_list = tracer.traced_grid_2d_list_from(grid=grid) -source_plane_grid = np.asarray(traced_grid_list[1]) -source_plane_grid = source_plane_grid[np.isfinite(source_plane_grid).all(axis=1)] +```python -aplt.plot_grid(grid=traced_grid_list[0], title="Plane 0 Grid") -aplt.plot_grid( - grid=al.Grid2DIrregular(values=source_plane_grid), - title="Plane 1 Grid", +sigma_cr_kpc = ( + cosmology.critical_surface_density_between_redshifts_solar_mass_per_kpc2_from( + redshift_0=0.5, redshift_1=1.0 + ) ) -tangential_caustic_list = al.LensCalc.from_tracer( - tracer=tracer -).tangential_caustic_list_from(grid=grid) -radial_caustics_list = al.LensCalc.from_tracer(tracer=tracer).radial_caustic_list_from( - grid=grid +print( + "Critical surface density: " + f"{sigma_cr_kpc:.3e} solar masses per square kiloparsec" ) +convergence = tracer.convergence_2d_from(grid=grid) + +aplt.plot_array(array=convergence, title="Convergence", use_log10=True, cb_unit="") ``` + Critical surface density: 3.002e+09 solar masses per square kiloparsec - -![png](tutorial_3_more_ray_tracing_files/tutorial_3_more_ray_tracing_11_0.png) - - -![png](tutorial_3_more_ray_tracing_files/tutorial_3_more_ray_tracing_11_1.png) - +![png](tutorial_3_more_ray_tracing_files/tutorial_3_more_ray_tracing_10_1.png) - .../PyAutoGalaxy/autogalaxy/operate/lens_calc.py:565: UserWarning: LensCalc Hessian: 1 of 9801 points did not converge after 20 halvings (largest relative error estimate 4.26e-01); values kept. - warnings.warn( +The convergence is largest near the centre and decreases +outwards, following the projected mass distribution of our +isothermal lens. -We can also plot the caustic on the source-plane image. +Convergence values of order one indicate surface densities +relevant to strong lensing. For a circular lens, the Einstein +radius encloses a region whose **mean convergence** is one: +the average surface mass density inside it equals +$\Sigma_{\mathrm{cr}}$. + +This is an average over the enclosed area, rather than the +convergence at its edge. We will return to this connection +when we use the Einstein radius to measure the lens's mass. + +__Deflection Angles__ + +The convergence describes the projected mass distribution. +To calculate a ray's deflection, we add the contributions +from mass across the lens plane: + +$$ +\boldsymbol{\alpha}(\boldsymbol{\theta}) += +\frac{1}{\pi} +\int +\kappa(\boldsymbol{\theta}') +\frac{\boldsymbol{\theta}-\boldsymbol{\theta}'} +{|\boldsymbol{\theta}-\boldsymbol{\theta}'|^2} +\,d^2\boldsymbol{\theta}'. +$$ + +Here $\boldsymbol{\theta}$ is the position where we want the +deflection, while $\boldsymbol{\theta}'$ runs over the mass +distribution. The integral adds the contribution from each +small patch of projected mass. + +The deflection therefore depends on more than the mass at +the ray's position. Surrounding mass contributes too, which +is why the satellite galaxy and external shear in tutorial 2 +could change the source images. + +For our spherical isothermal profile, this integral has an +analytic solution. PyAutoLens evaluates that solution when +we call `deflections_yx_2d_from`; other profiles may use +numerical calculations. + +Let's plot the two components of the reduced deflection angle, +in arcseconds, as we did in tutorial 2. ```python -aplt.plot_array(array=tracer.image_2d_list_from(grid=grid)[1], title="Plane 1 Image") + +deflections = tracer.deflections_yx_2d_from(grid=grid) + +deflections_y = aa.Array2D(values=deflections.slim[:, 0], mask=grid.mask) +deflections_x = aa.Array2D(values=deflections.slim[:, 1], mask=grid.mask) + +aplt.plot_array( + array=deflections_y, title="Deflection Angles (y component)", cb_unit=" arcsec" +) +aplt.plot_array( + array=deflections_x, title="Deflection Angles (x component)", cb_unit=" arcsec" +) ``` - + ![png](tutorial_3_more_ray_tracing_files/tutorial_3_more_ray_tracing_13_0.png) - -Caustics also mark the regions in the source-plane where the multiplicity of the strong lens changes. Each time -a source crosses a caustic, the number of images it produces changes by two. Try and show this yourself by changing -the (y,x) centre of the source-plane galaxy's light profile! + + + +![png](tutorial_3_more_ray_tracing_files/tutorial_3_more_ray_tracing_13_1.png) + + + +Each component changes sign across the lens centre. Together, +they describe the displacement we subtract from each +image-plane coordinate when tracing it to the source plane. + +__The Lensing Potential__ + +We can describe the same lens using a single scalar field: +the **lensing potential**, $\psi$. + +Its gradient gives the deflection angles: + +$$ +\boldsymbol{\alpha} = \nabla\psi. +$$ + +A gradient describes how a quantity changes with position. +Here, the change in potential along the y direction gives +the y deflection, and the change along x gives the x deflection. + +The convergence is related to the potential's second +derivatives: + +$$ +\kappa += +\frac{1}{2}\nabla^2\psi += +\frac{1}{2} +\left( +\frac{\partial^2\psi}{\partial\theta_y^2} ++ +\frac{\partial^2\psi}{\partial\theta_x^2} +\right). +$$ + +The symbol $\nabla^2$, called the Laplacian, means adding +these two second derivatives. This relation is the +two-dimensional Poisson equation for gravitational lensing. + +We can therefore describe the projected mass through +convergence, or describe its lensing effect through the +potential. Their spatial derivatives connect the two. + +Let's plot the potential of our lens. With coordinates and +deflections in arcseconds, its units are arcseconds squared. ```python -source = al.Galaxy( - redshift=1.0, - light=al.lp.SersicCoreSph( - centre=(0.0, 0.0), - intensity=1.0, - effective_radius=1.0, - sersic_index=1.0, - ), + +potential = tracer.potential_2d_from(grid=grid) + +aplt.plot_array(array=potential, title="Lensing Potential", cb_unit=r" arcsec$^2$") +``` + + + +![png](tutorial_3_more_ray_tracing_files/tutorial_3_more_ray_tracing_16_0.png) + + + +For this spherical lens, the potential has circular contours. +Its slope points radially outwards, matching the direction +of the deflection vectors used in our lens equation. + +We can check $\boldsymbol{\alpha} = \nabla\psi$ directly. + +First, we calculate the deflections using the mass profile's +analytic expression. Then we estimate them from changes in +the potential between neighbouring grid points. + +The two calculations should agree closely over most of the +grid. Numerical differentiation is less accurate near the +central cusp and at the grid boundaries. + +We will plot the magnitude of the difference between the +two deflection vectors at each grid point, in arcseconds. +Brighter regions indicate larger differences. We also print +the median of these magnitudes to summarise the typical +difference across the grid. + + +```python + +deflections_analytic = mass_profile.deflections_yx_2d_from(grid=grid) +deflections_via_potential = mass_profile.deflections_2d_via_potential_2d_from( + grid=grid ) -tracer = al.Tracer(galaxies=[lens, source]) +difference_yx = ( + np.asarray(deflections_analytic) - np.asarray(deflections_via_potential) +) -aplt.plot_array(array=tracer.image_2d_list_from(grid=grid)[1], title="Plane 1 Image") +difference_magnitude = np.sqrt(np.sum(difference_yx**2, axis=1)) + +difference_map = aa.Array2D(values=difference_magnitude, mask=grid.mask) + +aplt.plot_array( + array=difference_map, + title="Deflection Difference Magnitude (arcseconds)", + cb_unit=" arcsec", +) + +print( + "Median deflection difference magnitude: " + f"{np.median(difference_magnitude):.3e} arcsec" +) ``` - -![png](tutorial_3_more_ray_tracing_files/tutorial_3_more_ray_tracing_15_0.png) - +![png](tutorial_3_more_ray_tracing_files/tutorial_3_more_ray_tracing_19_0.png) + + + + Median deflection difference magnitude: 3.134e-05 arcsec + + +__Shear and Magnification__ + +Nearby rays generally experience slightly different deflections. +Those differences change an image's shape and size. + +To describe this locally, we calculate how each deflection +component changes with position. Since deflections are +derivatives of the potential, these are its second derivatives. +Together they form the **Hessian matrix**: + +$$ +H_{ij} += +\frac{\partial^2\psi} +{\partial\theta_i\,\partial\theta_j}. +$$ -__Units__ +The indices $i$ and $j$ each stand for y or x. The diagonal +entries describe changes along the same coordinate direction; +the other entries describe changes across the two directions. -Lets plot the lensing quantities again. However, we'll now use the `Units` object of the **PyAutoLens** plotter module -to set `in_kpc=True` and therefore plot the y and x axes in kiloparsecs. +Differentiating the lens equation gives the **Jacobian matrix**: -This conversion is performed automatically, using the galaxy redshifts and cosmology. +$$ +A += +\frac{\partial\boldsymbol{\beta}} +{\partial\boldsymbol{\theta}} += +I-H. +$$ + +Here $I$ is the identity matrix. The Jacobian maps a small +image-plane displacement to a source-plane displacement: + +$$ +\delta\boldsymbol{\beta} += +A\,\delta\boldsymbol{\theta}. +$$ + +Its inverse, where it exists, tells us how a small source +region is stretched into an image. + +`LensCalc` calculates the Hessian from the tracer's +deflection field. ```python -aplt.subplot_tracer(tracer=tracer, grid=grid) -aplt.subplot_galaxies_images(tracer=tracer, grid=grid) +hessian_yy, hessian_xy, hessian_yx, hessian_xx = lens_calc.hessian_from(grid=grid) + +print(f"H_yy at the first grid point: {hessian_yy[0]:.4f}") +print(f"H_xx at the first grid point: {hessian_xx[0]:.4f}") ``` - .../PyAutoGalaxy/autogalaxy/operate/lens_calc.py:565: UserWarning: LensCalc Hessian: 1 of 9801 points did not converge after 20 halvings (largest relative error estimate 4.26e-01); values kept. - warnings.warn( + H_yy at the first grid point: 0.2272 + H_xx at the first grid point: 0.2272 + + +The Hessian separates into two useful contributions. +The **convergence** describes the part that acts equally +in every direction: +$$ +\kappa = \frac{1}{2}(H_{xx}+H_{yy}). +$$ - -![png](tutorial_3_more_ray_tracing_files/tutorial_3_more_ray_tracing_17_1.png) - +This is the same convergence we defined from surface mass +density earlier. +The **shear** describes the directional part of the distortion. +Its two components are +$$ +\gamma_1 = \frac{1}{2}(H_{xx}-H_{yy}), +\qquad +\gamma_2 = H_{xy}, +$$ - -![png](tutorial_3_more_ray_tracing_files/tutorial_3_more_ray_tracing_17_2.png) - +with magnitude +$$ +|\gamma| = \sqrt{\gamma_1^2+\gamma_2^2}. +$$ -If you're not too familiar with Cosmology, it will be unclear how exactly we converted the distance units from -arcseconds to kiloparsecs. You'll need to read up on your Cosmology lecture to understand this properly. +These components describe the strength and orientation of +the distortion. Shear allows a circular source to form an +elongated image. -You can create a `Cosmology` object, which provides many methods for calculation different cosmological quantities, -which are shown below (if you're not too familiar with cosmology don't worry that you don't know what these mean, -it isn't massively important for using **PyAutoLens**). +In tutorial 2, we added an external shear to represent the +effect of surrounding matter. Here we calculate the shear +produced by the lens itself. Even a spherical mass distribution +produces shear: its symmetry does not mean that radial and +tangential image stretching are equal. -We will use a flat lambda CDM cosmology, which is the standard cosmological model often assumed in scientific studies. +Let's calculate the shear and print its magnitude at the +first grid point. ```python -cosmology = al.cosmo.FlatLambdaCDM(H0=70, Om0=0.3) - -print("Image-plane arcsec-per-kpc:") -print(cosmology.arcsec_per_kpc_from(redshift=0.5)) -print("Image-plane kpc-per-arcsec:") -print(cosmology.kpc_per_arcsec_from(redshift=0.5)) -print("Angular Diameter Distance to Image-plane (kpc):") -print(cosmology.angular_diameter_distance_to_earth_in_kpc_from(redshift=0.5)) - -print("Source-plane arcsec-per-kpc:") -print(cosmology.arcsec_per_kpc_from(redshift=1.0)) -print("Source-plane kpc-per-arcsec:") -print(cosmology.kpc_per_arcsec_from(redshift=1.0)) -print("Angular Diameter Distance to Source-plane:") -print(cosmology.angular_diameter_distance_to_earth_in_kpc_from(redshift=1.0)) - -print("Angular Diameter Distance From Image To Source Plane:") + +shear = lens_calc.shear_yx_2d_via_hessian_from(grid=grid) + print( - cosmology.angular_diameter_distance_between_redshifts_in_kpc_from( - redshift_0=0.5, redshift_1=1.0 - ) -) -print("Lensing Critical convergence:") -print( - cosmology.critical_surface_density_between_redshifts_solar_mass_per_kpc2_from( - redshift_0=0.5, redshift_1=1.0 - ) + "Shear magnitude at the first grid point: " + f"{shear.magnitudes[0]:.4f}" ) ``` - Image-plane arcsec-per-kpc: - 0.1638289752817242 - Image-plane kpc-per-arcsec: - 6.103926355398221 - Angular Diameter Distance to Image-plane (kpc): - 1259025.187042171 - Source-plane arcsec-per-kpc: - 0.12487552857882515 - Source-plane kpc-per-arcsec: - 8.007974111346966 - Angular Diameter Distance to Source-plane: - 1651763.228507974 - Angular Diameter Distance From Image To Source Plane: - 707494.3382263458 - Lensing Critical convergence: - 3083526795.6972556 + Shear magnitude at the first grid point: 0.2272 + + +The **magnification**, $\mu$, describes the change in area +between a small source region and its image: +$$ +\mu += +\frac{1}{\det A} += +\frac{1}{(1-\kappa)^2-|\gamma|^2}. +$$ -__More Complexity__ +Its absolute value gives the area ratio. Lensing preserves +surface brightness, so increasing the area also increases +the total light received from that source region. -We now make a lens with some attributes we didn`t in the last tutorial: +- $|\mu| > 1$: the image region is magnified. +- $|\mu| < 1$: it is demagnified. +- $\mu < 0$: its orientation is reversed, like a reflection. - - A light profile representing a `bulge` of stars, meaning the lens galaxy's light will appear in the image for the - first time. - - An external shear, which accounts for the deflection of light due to line-of-sight structures. +Magnification varies across an extended source, so its total +brightness depends on the combined contributions from its +different regions. + +Let's plot the signed magnification across the image plane. +Look for the circular region where its magnitude becomes +large and its sign changes. ```python -lens = al.Galaxy( - redshift=0.5, - bulge=al.lp.SersicSph( - centre=(0.0, 0.0), intensity=2.0, effective_radius=0.5, sersic_index=2.5 - ), - mass=al.mp.Isothermal( - centre=(0.0, 0.0), ell_comps=(0.0, -0.111111), einstein_radius=1.6 - ), + +magnification = lens_calc.magnification_2d_from(grid=grid) + +aplt.plot_array( + array=magnification, + title="Magnification", + cb_unit="", ) -field = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0)) +``` + + + +![png](tutorial_3_more_ray_tracing_files/tutorial_3_more_ray_tracing_25_0.png) -print(lens) + + +For our spherical lens, we can separate the stretching into +two directions: tangentially around the lens centre and +radially towards or away from it. + +The corresponding eigenvalues of the Jacobian are + +$$ +\lambda_t = 1-\kappa-|\gamma|, +\qquad +\lambda_r = 1-\kappa+|\gamma|. +$$ + +The image stretches by factors $1/|\lambda_t|$ and +$1/|\lambda_r|$ along these directions. Their product gives +the absolute magnification. + +When an eigenvalue approaches zero, the stretching in its +direction becomes very large. This is how long, thin arcs +can form. + + +```python + +tangential_eigen_values = lens_calc.tangential_eigen_value_from(grid=grid) +radial_eigen_values = lens_calc.radial_eigen_value_from(grid=grid) + +print( + "Tangential eigenvalue at the first grid point: " + f"{tangential_eigen_values[0]:.4f}" +) +print( + "Radial eigenvalue at the first grid point: " + f"{radial_eigen_values[0]:.4f}" +) ``` - Redshift: 0.5 - Light Profiles: - SersicSph - centre: (0.0, 0.0) - ell_comps: (0.0, 0.0) - intensity: 2.0 - effective_radius: 0.5 - sersic_index: 2.5 - Mass Profiles: - Isothermal - centre: (0.0, 0.0) - ell_comps: (0.0, -0.111111) - einstein_radius: 1.6 - slope: 2.0 - core_radius: 0.0 + Tangential eigenvalue at the first grid point: 0.5456 + Radial eigenvalue at the first grid point: 1.0000 + + +__Critical Curves and Caustics__ + +**Critical curves** mark positions in the image plane where +the magnification of an infinitesimally small source formally +becomes infinite: +$$ +\det A = 0. +$$ -Lets also create a small satellite galaxy nearby the lens galaxy and at the same redshift. +A tangential critical curve occurs where $\lambda_t=0$; +a radial critical curve occurs where $\lambda_r=0$. +Images near them can be strongly stretched in the +corresponding direction. + +Real galaxies have finite size. They can form bright, +extended arcs near critical curves without having +infinite total brightness. + +Our spherical isothermal lens has a tangential critical +curve but no radial critical curve. The plot below should +therefore show one circle, at a radius of 1.6 arcseconds. ```python -lens_satellite = al.Galaxy( - redshift=0.5, - bulge=al.lp.DevVaucouleursSph( - centre=(1.0, 0.0), intensity=2.0, effective_radius=0.2 - ), - mass=al.mp.IsothermalSph(centre=(1.0, 0.0), einstein_radius=0.4), + +tangential_critical_curves = ( + lens_calc.tangential_critical_curve_list_from( + grid=grid, pixel_scale=grid.pixel_scale + ) +) +radial_critical_curves = ( + lens_calc.radial_critical_curve_list_from( + grid=grid, pixel_scale=grid.pixel_scale + ) ) -print(lens_satellite) +fig, ax = plt.subplots(figsize=(6, 6)) + +for curves, colour, label in [ + (tangential_critical_curves, "black", "Tangential"), + (radial_critical_curves, "orange", "Radial"), +]: + for index, curve in enumerate(curves): + coordinates = np.asarray(curve) + ax.plot( + coordinates[:, 1], + coordinates[:, 0], + color=colour, + label=label if index == 0 else None, + ) + +ax.set( + title="Critical Curves: Image Plane", + xlabel="x (arcseconds)", + ylabel="y (arcseconds)", + xlim=(-2.0, 2.0), + ylim=(-2.0, 2.0), +) +ax.set_aspect("equal") +ax.legend() +plt.show() +plt.close(fig) ``` - Redshift: 0.5 - Light Profiles: - DevVaucouleursSph - centre: (1.0, 0.0) - ell_comps: (0.0, 0.0) - intensity: 2.0 - effective_radius: 0.2 - sersic_index: 4.0 - Mass Profiles: - IsothermalSph - centre: (1.0, 0.0) - ell_comps: (0.0, 0.0) - einstein_radius: 0.4 - slope: 2.0 - core_radius: 0.0 -Lets have a quick look at the appearance of our lens galaxy and its satellite. +![png](tutorial_3_more_ray_tracing_files/tutorial_3_more_ray_tracing_29_0.png) -And their deflection angles, noting that the satellite does not contribute as much to the deflections. -```python +Ray-tracing a critical curve to the source plane gives +a **caustic**: +$$ +\boldsymbol{\beta}_{\mathrm{caustic}} += +\boldsymbol{\theta}_{\mathrm{critical}} +- +\boldsymbol{\alpha}( + \boldsymbol{\theta}_{\mathrm{critical}} +). +$$ -# NOTE: In the new API, pass title directly as a string: -# title="Lens Galaxy Deflections (x)" +Critical curves tell us where strongly stretched images +appear. Caustics tell us where a source must lie to +produce those images. -``` +For our spherical lens, the entire tangential critical +circle maps to one source-plane point: the origin. +A source centred there produces an Einstein ring. -Now, lets make two source galaxies at redshift 1.0. Instead of using the name `light` for the light profiles, lets -instead use more descriptive names that indicate what morphological component of the galaxy the light profile -represents. In this case, we'll use the terms `bulge` and `disk`, the two main structures that a galaxy can be made of +The plot below displays the mapped coordinates as points. +They should gather at the origin, with any small spread +arising from the numerical calculation. ```python -source_0 = al.Galaxy( - redshift=1.0, - bulge=al.lp.DevVaucouleursSph( - centre=(0.1, 0.2), intensity=0.3, effective_radius=0.3 - ), - disk=al.lp.ExponentialCore( - centre=(0.1, 0.2), - ell_comps=(0.111111, 0.0), - intensity=3.0, - effective_radius=2.0, - ), + +tangential_caustics = lens_calc.tangential_caustic_list_from( + grid=grid, pixel_scale=grid.pixel_scale +) +radial_caustics = lens_calc.radial_caustic_list_from( + grid=grid, pixel_scale=grid.pixel_scale ) -source_1 = al.Galaxy( - redshift=1.0, - disk=al.lp.ExponentialCore( - centre=(-0.3, -0.5), - ell_comps=(0.1, 0.0), - intensity=8.0, - effective_radius=1.0, +fig, ax = plt.subplots(figsize=(6, 6)) + +for caustics, colour, label in [ + (tangential_caustics, "black", "Tangential"), + (radial_caustics, "orange", "Radial"), +]: + for index, caustic in enumerate(caustics): + coordinates = np.asarray(caustic) + ax.scatter( + coordinates[:, 1], + coordinates[:, 0], + s=8, + color=colour, + label=label if index == 0 else None, + ) + +ax.set( + title="Caustics: Source Plane", + xlabel="x (arcseconds)", + ylabel="y (arcseconds)", + xlim=(-1.2, 1.2), + ylim=(-1.2, 1.2), +) +ax.set_aspect("equal") +ax.legend() +plt.show() +plt.close(fig) +``` + + + +![png](tutorial_3_more_ray_tracing_files/tutorial_3_more_ray_tracing_31_0.png) + + + +We can reveal a radial critical curve by making the lens's +central mass distribution shallower. + +The code below replaces the spherical isothermal profile +with a spherical power-law profile whose slope is 1.8. +The isothermal slope is 2.0. We keep the same centre, +Einstein-radius parameter, source and cosmology. + + +```python + +lens = al.Galaxy( + redshift=0.5, + mass=al.mp.PowerLawSph( + centre=(0.0, 0.0), + einstein_radius=1.6, + slope=1.8, ), ) -print(source_0) -print(source_1) +tracer = al.Tracer(galaxies=[lens, source], cosmology=cosmology) +mass_profile = lens.mass +lens_calc = al.LensCalc.from_tracer(tracer=tracer) ``` - Redshift: 1.0 - Light Profiles: - DevVaucouleursSph - centre: (0.1, 0.2) - ell_comps: (0.0, 0.0) - intensity: 0.3 - effective_radius: 0.3 - sersic_index: 4.0 - ExponentialCore - centre: (0.1, 0.2) - ell_comps: (0.111111, 0.0) - intensity: 3.0 - effective_radius: 2.0 - sersic_index: 1.0 - radius_break: 0.01 - alpha: 3.0 - gamma: 0.25 - Redshift: 1.0 - Light Profiles: - ExponentialCore - centre: (-0.3, -0.5) - ell_comps: (0.1, 0.0) - intensity: 8.0 - effective_radius: 1.0 - sersic_index: 1.0 - radius_break: 0.01 - alpha: 3.0 - gamma: 0.25 - - -Lets look at our source galaxies (before lensing) - -__Multi Galaxy Ray Tracing__ - -Now lets pass our 4 galaxies to a `Tracer`, which means the following will occur: - - - Using the galaxy redshifts, an image-plane and source-plane will be created, each with two galaxies. - -We also pass the tracer below a Planck15 cosmology, where the cosmology of the Universe describes exactly how -ray-tracing is performed. +Rerun the two plotting cells immediately above, including +their critical-curve and caustic calculations. + +The image-plane plot should now show an inner radial critical +curve as well as the outer tangential critical curve. +The source-plane plot should show a circular radial +caustic around the central tangential caustic. + +Caustics also mark changes in the number of images. +For a point source crossing a smooth part of the radial +caustic in this example, two images appear or disappear. +An extended galaxy can straddle the caustic, so different +parts of it can have different numbers of images. + +The following cell restores our spherical isothermal lens +for the remaining sections. ```python -tracer = al.Tracer( - galaxies=[lens, lens_satellite, source_0, source_1], - cosmology=al.cosmo.Planck15(), - fields=[field], + +lens = al.Galaxy( + redshift=0.5, + mass=al.mp.IsothermalSph( + centre=(0.0, 0.0), + einstein_radius=1.6, + ), ) + +tracer = al.Tracer(galaxies=[lens, source], cosmology=cosmology) +mass_profile = lens.mass +lens_calc = al.LensCalc.from_tracer(tracer=tracer) ``` -We can now plot the tracer`s image, which now there are two galaxies in each plane is computed as follows: +__Einstein Radius__ + +For a circular lens with a source directly behind its centre, +the source forms an Einstein ring. Its angular radius is +the **Einstein radius**, $\theta_E$. - 1) First, using the image-plane grid, the images of the lens galaxy and its satellite are computed. +Our spherical isothermal lens has a circular tangential +critical curve at this radius. - 2) Using the mass profiles of the lens and its satellite, their deflection angles are computed. +For a non-circular lens, we can define an **effective Einstein +radius** using the area enclosed by the tangential critical +curve: - 3) These deflection angles are summed, such that the deflection of light due to the mass profiles of both galaxies in - the image-plane is accounted for. +$$ +\theta_E = \sqrt{\frac{A_{\mathrm{crit}}}{\pi}}. +$$ - 4) These deflection angles are used to trace every image-grid coordinate to the source-plane. +This is the radius of a circle enclosing the same area. +It is the definition used by `LensCalc`. - 5) The image of the source galaxies is computed by summing both of their images and ray-tracing their light back to - the image-plane. - -This process is pretty much the same as we have seen in previous tutorials when there is one galaxy per plane. We -are simply summing the images and deflection angles of the galaxies before using them to perform ray-tracing. +Let's recover the Einstein radius from our critical curve +and convert it into kiloparsecs at the lens redshift. ```python -aplt.plot_array(array=tracer.image_2d_from(grid=grid), title="Image") + +einstein_radius = lens_calc.einstein_radius_from( + grid=grid, pixel_scale=grid.pixel_scale +) + +kpc_per_arcsec_lens = cosmology.kpc_per_arcsec_from( + redshift=lens.redshift +) +einstein_radius_kpc = einstein_radius * kpc_per_arcsec_lens + +print(f"Einstein radius: {einstein_radius:.4f} arcsec") +print(f"Einstein radius: {einstein_radius_kpc:.4f} kpc") ``` + Einstein radius: 1.6000 arcsec + Einstein radius: 10.0612 kpc - -![png](tutorial_3_more_ray_tracing_files/tutorial_3_more_ray_tracing_31_0.png) - +The recovered angular radius should be close to the +1.6 arcseconds specified in our spherical mass profile. +Small differences arise from locating the critical curve +on a finite grid. + +Two simple mass distributions have useful expressions +for the Einstein radius. + +For a point mass $M$: -As we did previously, we can plot the source plane grid to see how each coordinate was traced. +$$ +\theta_E += +\sqrt{ +\frac{4GM}{c^2} +\frac{D_{ls}}{D_l D_s} +}. +$$ + +For a singular isothermal sphere, with one-dimensional +velocity dispersion $\sigma_v$: + +$$ +\theta_E += +4\pi +\left(\frac{\sigma_v}{c}\right)^2 +\frac{D_{ls}}{D_s}. +$$ + +Both expressions give angles in radians when the physical +quantities use consistent units. + +They show how the Einstein radius connects the lens's mass +or velocity dispersion to the observer–lens–source geometry. +Our `IsothermalSph` profile specifies this angular scale +directly through its `einstein_radius` parameter. + +For a circular lens, the mean convergence inside the Einstein +radius equals one. Its enclosed projected mass is therefore + +$$ +M( ✏️ **This page is auto-generated from [`scripts/chapter_1_introduction/tutorial_6_data.py`](../../scripts/chapter_1_introduction/tutorial_6_data.py) — do not edit it directly.** +> ✏️ **This page is auto-generated from [`scripts/chapter_1_introduction/tutorial_5_data.py`](../../scripts/chapter_1_introduction/tutorial_5_data.py) — do not edit it directly.** > It shows the example fully executed, with its real output images. -> Run it yourself via the [Python script](../../scripts/chapter_1_introduction/tutorial_6_data.py) or the [Jupyter notebook](../../notebooks/chapter_1_introduction/tutorial_6_data.ipynb). +> Run it yourself via the [Python script](../../scripts/chapter_1_introduction/tutorial_5_data.py) or the [Jupyter notebook](../../notebooks/chapter_1_introduction/tutorial_5_data.ipynb). -Tutorial 6: Data +Tutorial 5: Data ================ In the last tutorials, we use tracers to create images of strong lenses. However, those images don't accurately @@ -56,25 +56,7 @@ import autolens as al import autolens.plot as aplt ``` - .../PyAutoNerves/autonerves/workspace.py:206: UserWarning: Cannot verify the workspace at HowToLens/scripts/chapter_1_introduction is compatible with the installed library version (2026.7.23.1): no `version.minimum_library_version` or `version.workspace_version` key in config/general.yaml and no version.txt at the workspace root. - - If you cloned the workspace from `main` rather than a release tag, set `version.workspace_version_check: False` in config/general.yaml to silence this warning. The `main` branch updates more frequently than library releases, so version mismatches are expected and not actionable for `main`-branch users. - - You can also set the environment variable PYAUTO_SKIP_WORKSPACE_VERSION_CHECK=1 to disable temporarily. - warnings.warn(_missing_version_warning(root, library_version)) - .../PyAutoNerves/autonerves/workspace.py:206: UserWarning: Cannot verify the workspace at HowToLens/scripts/chapter_1_introduction is compatible with the installed library version (2026.7.23.1): no `version.minimum_library_version` or `version.workspace_version` key in config/general.yaml and no version.txt at the workspace root. - - If you cloned the workspace from `main` rather than a release tag, set `version.workspace_version_check: False` in config/general.yaml to silence this warning. The `main` branch updates more frequently than library releases, so version mismatches are expected and not actionable for `main`-branch users. - - You can also set the environment variable PYAUTO_SKIP_WORKSPACE_VERSION_CHECK=1 to disable temporarily. - warnings.warn(_missing_version_warning(root, library_version)) - Working Directory has been set to `HowToLens` - .../PyAutoNerves/autonerves/workspace.py:206: UserWarning: Cannot verify the workspace at HowToLens/scripts/chapter_1_introduction is compatible with the installed library version (2026.7.23.1): no `version.minimum_library_version` or `version.workspace_version` key in config/general.yaml and no version.txt at the workspace root. - - If you cloned the workspace from `main` rather than a release tag, set `version.workspace_version_check: False` in config/general.yaml to silence this warning. The `main` branch updates more frequently than library releases, so version mismatches are expected and not actionable for `main`-branch users. - - You can also set the environment variable PYAUTO_SKIP_WORKSPACE_VERSION_CHECK=1 to disable temporarily. - warnings.warn(_missing_version_warning(root, library_version)) + Working Directory has been set to `render-workspace` __Initial Setup__ @@ -133,9 +115,9 @@ aplt.plot_array( ``` - -![png](tutorial_6_data_files/tutorial_6_data_7_0.png) - + +![png](tutorial_5_data_files/tutorial_5_data_7_0.png) + __Optics Blurring__ @@ -168,9 +150,9 @@ aplt.plot_array(array=psf.kernel, title="PSF 2D Kernel") ``` - -![png](tutorial_6_data_files/tutorial_6_data_11_0.png) - + +![png](tutorial_5_data_files/tutorial_5_data_11_0.png) + The PSF is often more informative when plotted on a log10 scale. This approach allows us to clearly observe values @@ -183,9 +165,9 @@ aplt.plot_array(array=psf.kernel, title="PSF 2D Kernel (Log10)", use_log10=True) ``` - -![png](tutorial_6_data_files/tutorial_6_data_13_0.png) - + +![png](tutorial_5_data_files/tutorial_5_data_13_0.png) + Next, we'll manually perform a 2D convolution of the PSF with the image of the galaxy. This convolution simulates the @@ -216,7 +198,7 @@ blurred_image = convolved_image.trimmed_after_convolution_from( ) # Trimming back to the original size. ``` - .../PyAutoArray/autoarray/operators/convolver.py:1424: UserWarning: No blurring_image provided. Only the direct image will be convolved. This may change the correctness of the PSF convolution. + ~/Code/PyAutoLabs/.worktrees/howtolens-ray-tracing-merge/PyAutoArray/autoarray/operators/convolver.py:1484: UserWarning: No blurring_image provided. Only the direct image will be convolved. This may change the correctness of the PSF convolution. warnings.warn( @@ -232,15 +214,15 @@ aplt.plot_array(array=blurred_image, title="Tracer Image After PSF") ``` - -![png](tutorial_6_data_files/tutorial_6_data_17_0.png) - + +![png](tutorial_5_data_files/tutorial_5_data_17_0.png) + + - -![png](tutorial_6_data_files/tutorial_6_data_17_1.png) - +![png](tutorial_5_data_files/tutorial_5_data_17_1.png) + __Poisson Noise__ @@ -295,9 +277,9 @@ aplt.plot_array( ``` - -![png](tutorial_6_data_files/tutorial_6_data_21_0.png) - + +![png](tutorial_5_data_files/tutorial_5_data_21_0.png) + It is challenging to see the Poisson noise directly in the image above, as it is often subtle. To make the noise more @@ -319,9 +301,9 @@ aplt.plot_array( ``` - -![png](tutorial_6_data_files/tutorial_6_data_23_0.png) - + +![png](tutorial_5_data_files/tutorial_5_data_23_0.png) + __Background Sky__ @@ -380,15 +362,15 @@ aplt.plot_array( ``` - -![png](tutorial_6_data_files/tutorial_6_data_25_0.png) - + +![png](tutorial_5_data_files/tutorial_5_data_25_0.png) + + - -![png](tutorial_6_data_files/tutorial_6_data_25_1.png) - +![png](tutorial_5_data_files/tutorial_5_data_25_1.png) + __Simulator__ @@ -408,7 +390,7 @@ simulator = al.SimulatorImaging( dataset = simulator.via_tracer_from(tracer=tracer, grid=grid) ``` - .../PyAutoArray/autoarray/operators/convolver.py:1424: UserWarning: No blurring_image provided. Only the direct image will be convolved. This may change the correctness of the PSF convolution. + ~/Code/PyAutoLabs/.worktrees/howtolens-ray-tracing-merge/PyAutoArray/autoarray/operators/convolver.py:1484: UserWarning: No blurring_image provided. Only the direct image will be convolved. This may change the correctness of the PSF convolution. warnings.warn( @@ -422,9 +404,9 @@ aplt.plot_array(array=dataset.data, title="Simulated Imaging Data") ``` - -![png](tutorial_6_data_files/tutorial_6_data_29_0.png) - + +![png](tutorial_5_data_files/tutorial_5_data_29_0.png) + The dataset also includes the `psf` (Point Spread Function) used to blur the strong lens image. @@ -439,9 +421,9 @@ aplt.plot_array(array=dataset.psf.kernel, title="Simulated PSF") ``` - -![png](tutorial_6_data_files/tutorial_6_data_31_0.png) - + +![png](tutorial_5_data_files/tutorial_5_data_31_0.png) + The dataset includes a `noise_map`, which represents the Root Mean Square (RMS) standard deviation of the noise @@ -461,9 +443,9 @@ aplt.plot_array(array=dataset.noise_map, title="Simulated Noise Map") ``` - -![png](tutorial_6_data_files/tutorial_6_data_33_0.png) - + +![png](tutorial_5_data_files/tutorial_5_data_33_0.png) + The `signal-to-noise_map` shows the ratio of the signal in each pixel to the noise level in that pixel. It is @@ -482,9 +464,9 @@ aplt.plot_array(array=dataset.signal_to_noise_map, title="Signal-To-Noise Map") ``` - -![png](tutorial_6_data_files/tutorial_6_data_35_0.png) - + +![png](tutorial_5_data_files/tutorial_5_data_35_0.png) + The `aplt.subplot_imaging_dataset` object can display all of these components together, making it a powerful tool for visualizing @@ -501,9 +483,9 @@ aplt.subplot_imaging_dataset(dataset=dataset) ``` - -![png](tutorial_6_data_files/tutorial_6_data_37_0.png) - + +![png](tutorial_5_data_files/tutorial_5_data_37_0.png) + __Output__ @@ -594,9 +576,9 @@ aplt.subplot_interferometer_dirty_images(dataset=dataset) - -![png](tutorial_6_data_files/tutorial_6_data_41_1.png) - + +![png](tutorial_5_data_files/tutorial_5_data_41_1.png) + __Weak Lensing Data__ @@ -646,14 +628,14 @@ aplt.subplot_weak_dataset(dataset=dataset) noise_map : ArrayIrregular([0.25, 0.25, 0.25, ..., 0.25, 0.25, 0.25], shape=(1500,)) redshifts : None is_reduced : False - + Wrote dataset to dataset/weak_lensing/simple - -![png](tutorial_6_data_files/tutorial_6_data_43_1.png) - + +![png](tutorial_5_data_files/tutorial_5_data_43_1.png) + __Wrap Up__ diff --git a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_11_0.png b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_11_0.png similarity index 100% rename from markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_11_0.png rename to markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_11_0.png diff --git a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_13_0.png b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_13_0.png similarity index 100% rename from markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_13_0.png rename to markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_13_0.png diff --git a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_17_0.png b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_17_0.png similarity index 100% rename from markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_17_0.png rename to markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_17_0.png diff --git a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_17_1.png b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_17_1.png similarity index 100% rename from markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_17_1.png rename to markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_17_1.png diff --git a/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_21_0.png b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_21_0.png new file mode 100644 index 0000000..bf61cdf Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_21_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_23_0.png b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_23_0.png new file mode 100644 index 0000000..aab0d04 Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_23_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_25_0.png b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_25_0.png new file mode 100644 index 0000000..40b54b6 Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_25_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_25_1.png b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_25_1.png new file mode 100644 index 0000000..2819650 Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_25_1.png differ diff --git a/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_29_0.png b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_29_0.png new file mode 100644 index 0000000..73e28d6 Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_29_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_31_0.png b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_31_0.png similarity index 100% rename from markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_31_0.png rename to markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_31_0.png diff --git a/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_33_0.png b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_33_0.png new file mode 100644 index 0000000..78546e8 Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_33_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_35_0.png b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_35_0.png new file mode 100644 index 0000000..dd9abe6 Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_35_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_37_0.png b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_37_0.png new file mode 100644 index 0000000..e305929 Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_37_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_41_1.png b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_41_1.png new file mode 100644 index 0000000..c62e3c1 Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_41_1.png differ diff --git a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_43_1.png b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_43_1.png similarity index 100% rename from markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_43_1.png rename to markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_43_1.png diff --git a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_7_0.png b/markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_7_0.png similarity index 100% rename from markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_7_0.png rename to markdown/chapter_1_introduction/tutorial_5_data_files/tutorial_5_data_7_0.png diff --git a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism.md b/markdown/chapter_1_introduction/tutorial_5_lensing_formalism.md deleted file mode 100644 index bb3df02..0000000 --- a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism.md +++ /dev/null @@ -1,734 +0,0 @@ -> ✏️ **This page is auto-generated from [`scripts/chapter_1_introduction/tutorial_5_lensing_formalism.py`](../../scripts/chapter_1_introduction/tutorial_5_lensing_formalism.py) — do not edit it directly.** -> It shows the example fully executed, with its real output images. -> Run it yourself via the [Python script](../../scripts/chapter_1_introduction/tutorial_5_lensing_formalism.py) or the [Jupyter notebook](../../notebooks/chapter_1_introduction/tutorial_5_lensing_formalism.ipynb). - -Tutorial 5: Lensing Formalism -============================= - -This tutorial is the equations lecture of **HowToLens**. - -Every other tutorial in this series deliberately defers the formal mathematics of gravitational lensing, so that you -could first learn lensing hands-on: in the earlier tutorials we created grids, evaluated light and mass profiles, -ray-traced coordinates from the image-plane to the source-plane and looked at quantities like the convergence, -deflection angles and critical curves visually, without ever writing down their formal definitions. - -This tutorial gathers all of that algebra in one place. Each quantity you have already computed and plotted — -deflection angles, convergence, potential, magnification, critical curves, the Einstein radius — is now given its -formal mathematical definition, explained in plain words, and tied back to the exact **PyAutoLens** method that -computes it. The goal is that after this tutorial, every symbol in a lensing paper maps to a line of code you know. - -None of this mathematics is required to use **PyAutoLens** or to analyse strong lenses — the library computes -everything for you. But understanding where each quantity comes from will make you a better lens modeler, and this -is the single place in **HowToLens** where the formalism lives, so you can return here whenever you need it. - -We will build one simple strong lens system — an elliptical isothermal (SIE) lens galaxy and a Sersic source — and -reuse it throughout, computing every quantity from the same tracer so you can see how they all fit together. - -__Contents__ - -- **Initial Setup:** Build the grid, SIE lens, Sersic source and `Tracer` reused throughout the tutorial. -- **Cosmological Distances:** Angular diameter distances D_l, D_s, D_ls and how arcseconds convert to kiloparsecs. -- **The Lens Equation:** beta = theta - alpha(theta), the mapping from image-plane to source-plane, and multiple images. -- **Convergence:** Surface mass density Sigma, the critical surface density Sigma_cr and kappa = Sigma / Sigma_cr. -- **Deflection Angles:** The integral relating the convergence field to the deflection angles. -- **The Lensing Potential:** The scalar potential psi, with alpha = grad psi and kappa = (1/2) laplacian psi. -- **Shear and Magnification:** The Hessian, the Jacobian matrix A, shear gamma and magnification mu = 1 / det(A). -- **Critical Curves and Caustics:** Where det(A) = 0 in the image-plane, and its map to the source-plane. -- **Einstein Radius:** Its definition, the SIS and point-mass closed forms, and why it is the robust mass measurement. -- **Time Delays:** The Fermat potential and the time-delay surface, in brief. -- **Wrap Up:** Summary of the script and next steps. - - -```python - -from autolens import jax_wrapper # Sets JAX environment before other imports - -from autolens import setup_notebook; setup_notebook() - -import matplotlib.pyplot as plt -import numpy as np -import autolens as al -import autoarray as aa -import autolens.plot as aplt -``` - - .../PyAutoNerves/autonerves/workspace.py:206: UserWarning: Cannot verify the workspace at HowToLens/scripts/chapter_1_introduction is compatible with the installed library version (2026.7.23.1): no `version.minimum_library_version` or `version.workspace_version` key in config/general.yaml and no version.txt at the workspace root. - - If you cloned the workspace from `main` rather than a release tag, set `version.workspace_version_check: False` in config/general.yaml to silence this warning. The `main` branch updates more frequently than library releases, so version mismatches are expected and not actionable for `main`-branch users. - - You can also set the environment variable PYAUTO_SKIP_WORKSPACE_VERSION_CHECK=1 to disable temporarily. - warnings.warn(_missing_version_warning(root, library_version)) - .../PyAutoNerves/autonerves/workspace.py:206: UserWarning: Cannot verify the workspace at HowToLens/scripts/chapter_1_introduction is compatible with the installed library version (2026.7.23.1): no `version.minimum_library_version` or `version.workspace_version` key in config/general.yaml and no version.txt at the workspace root. - - If you cloned the workspace from `main` rather than a release tag, set `version.workspace_version_check: False` in config/general.yaml to silence this warning. The `main` branch updates more frequently than library releases, so version mismatches are expected and not actionable for `main`-branch users. - - You can also set the environment variable PYAUTO_SKIP_WORKSPACE_VERSION_CHECK=1 to disable temporarily. - warnings.warn(_missing_version_warning(root, library_version)) - Working Directory has been set to `HowToLens` - .../PyAutoNerves/autonerves/workspace.py:206: UserWarning: Cannot verify the workspace at HowToLens/scripts/chapter_1_introduction is compatible with the installed library version (2026.7.23.1): no `version.minimum_library_version` or `version.workspace_version` key in config/general.yaml and no version.txt at the workspace root. - - If you cloned the workspace from `main` rather than a release tag, set `version.workspace_version_check: False` in config/general.yaml to silence this warning. The `main` branch updates more frequently than library releases, so version mismatches are expected and not actionable for `main`-branch users. - - You can also set the environment variable PYAUTO_SKIP_WORKSPACE_VERSION_CHECK=1 to disable temporarily. - warnings.warn(_missing_version_warning(root, library_version)) - - -__Initial Setup__ - -We first build the strong lens system used throughout this tutorial, mirroring the objects introduced in tutorials -2 and 3: a 2D grid of (y,x) arcsecond coordinates, a lens galaxy with an elliptical isothermal (`Isothermal`) mass -profile — the singular isothermal ellipsoid, or SIE, the workhorse mass model of galaxy-scale lensing — and a -source galaxy with a Sersic light profile. - - -```python -grid = al.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.05) - -mass_profile = al.mp.Isothermal( - centre=(0.0, 0.0), - ell_comps=al.convert.ell_comps_from(axis_ratio=0.8, angle=45.0), - einstein_radius=1.6, -) - -lens_galaxy = al.Galaxy(redshift=0.5, mass=mass_profile) - -source_galaxy = al.Galaxy( - redshift=1.0, - bulge=al.lp.SersicCore( - centre=(0.0, 0.1), - ell_comps=(0.1, 0.0), - intensity=0.3, - effective_radius=0.3, - sersic_index=1.0, - ), -) -``` - -We combine these into a `Tracer` with a Planck 2015 cosmology. The redshifts of the two galaxies (0.5 and 1.0) and -the cosmology together fix every distance that appears in the equations below. - - -```python -cosmology = al.cosmo.Planck15() - -tracer = al.Tracer(galaxies=[lens_galaxy, source_galaxy], cosmology=cosmology) -``` - -Here is the lensed image of this system, which by now should look familiar. Every equation in this tutorial is -describing some aspect of how this image forms. - - -```python -image = tracer.image_2d_from(grid=grid) -aplt.plot_array(array=image, title="Lensed Image of the Source Galaxy") -``` - - - -![png](tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_7_0.png) - - - -We also create a `LensCalc` object from the tracer. As we saw in tutorial 3, this is **PyAutoLens**'s calculator for -derived lensing quantities — everything it computes is derived from the tracer's deflection angles, which is a theme -we will see repeatedly below. - - -```python -lens_calc = al.LensCalc.from_tracer(tracer=tracer) -``` - -__Cosmological Distances__ - -Gravitational lensing is a geometric effect, so distances are everywhere in its equations. The distances used are -**angular diameter distances**, defined so that an object of physical size l at angular diameter distance D subtends -an angle (in radians): - - theta = l / D - -Three distances appear in every lensing formula: - -- D_l — the angular diameter distance from the observer to the lens (deflector) galaxy. -- D_s — the angular diameter distance from the observer to the source galaxy. -- D_ls — the angular diameter distance from the lens to the source. - -In an expanding Universe angular diameter distances do not add linearly, so D_ls != D_s - D_l. Each is computed by -integrating the cosmological expansion history between the two redshifts, which is why the tracer requires both -galaxy redshifts and a cosmology. - -The `Cosmology` object computes each of these directly (values below are in kiloparsecs): - - -```python -D_l = cosmology.angular_diameter_distance_to_earth_in_kpc_from(redshift=0.5) -D_s = cosmology.angular_diameter_distance_to_earth_in_kpc_from(redshift=1.0) -D_ls = cosmology.angular_diameter_distance_between_redshifts_in_kpc_from( - redshift_0=0.5, redshift_1=1.0 -) - -print(f"D_l (kpc) = {D_l:.3e}") -print(f"D_s (kpc) = {D_s:.3e}") -print(f"D_ls (kpc) = {D_ls:.3e}") -``` - - D_l (kpc) = 1.297e+06 - D_s (kpc) = 1.698e+06 - D_ls (kpc) = 7.252e+05 - - -The angular diameter distance is also what converts **PyAutoLens**'s internal angular units of arcseconds into -physical distances. An angle of 1.0" at redshift z corresponds to a physical size: - - l = D(z) * (1.0" in radians) - -The `Cosmology` object wraps this up as a `kpc_per_arcsec` conversion factor, which differs between the image-plane -(lens redshift) and source-plane (source redshift) because the two planes are at different distances. - - -```python -kpc_per_arcsec_lens = cosmology.kpc_per_arcsec_from(redshift=0.5) -kpc_per_arcsec_source = cosmology.kpc_per_arcsec_from(redshift=1.0) - -print(f"kpc per arcsec at the lens (z=0.5) = {kpc_per_arcsec_lens:.4f}") -print(f"kpc per arcsec at the source (z=1.0) = {kpc_per_arcsec_source:.4f}") -``` - - kpc per arcsec at the lens (z=0.5) = 6.2882 - kpc per arcsec at the source (z=1.0) = 8.2319 - - -So our lens's Einstein radius of 1.6" corresponds to a physical scale of roughly 1.6 * 6.3 ~ 10 kpc at the lens -redshift — a sensible size for the inner regions of a massive elliptical galaxy. - -__The Lens Equation__ - -The fundamental equation of gravitational lensing is the **lens equation**, which we met in tutorial 2: - - beta = theta - alpha(theta) - -where: - -- theta is the observed (image-plane) angular position of a light ray, in arcseconds. -- alpha(theta) is the (scaled) deflection angle — how much the ray is bent by the lens's gravity at position theta. -- beta is the true (source-plane) position — where the source would appear if there were no lens. - -In plain words: to find where a light ray we observe at theta really came from, subtract the deflection the lens -applied to it. This is exactly the ray-tracing calculation we performed in tutorial 2, and it is worth knowing that -the deflection angle here is the "scaled" deflection: the physical bending angle of the ray multiplied by the -distance ratio D_ls / D_s, which is the convention that makes the lens equation take the simple form above. - -The lens equation is trivial to evaluate one way (given theta, compute beta), but it cannot be inverted -analytically: for a strong lens, *multiple* image-plane positions theta can satisfy the equation for the *same* -source position beta. This is why strong lenses produce multiple images of a single source — and why lens modeling -works "forwards", ray-tracing image-plane grids to the source-plane rather than the other way around. - -In code, the lens equation is one line — the same `grid_2d_via_deflection_grid_from` call from tutorial 2: - - -```python -deflections = tracer.deflections_yx_2d_from(grid=grid) - -source_plane_grid = grid.grid_2d_via_deflection_grid_from(deflection_grid=deflections) - -aplt.plot_grid(grid=grid, title="Image-Plane Grid (theta)") -aplt.plot_grid(grid=source_plane_grid, title="Source-Plane Grid (beta)") -``` - - - -![png](tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_15_0.png) - - - - - -![png](tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_15_1.png) - - - -__Convergence__ - -The lens galaxy's mass enters lensing via its **surface mass density** Sigma(theta): the galaxy's 3D mass density -integrated along the line of sight, giving a projected 2D mass per unit area (e.g. in solar masses per kpc^2). -Lensing only cares about this projection — two very different 3D distributions with the same projected Sigma -deflect light identically. - -Whether a lens is "strong" is set by comparing Sigma to the **critical surface density**: - - Sigma_cr = (c^2 / (4 pi G)) * (D_s / (D_l * D_ls)) - -This is a purely cosmological quantity — it depends only on the constants c and G and the three distances from the -previous section. It has a beautiful interpretation: it is the surface density a lens needs, given this observer / -lens / source geometry, to be capable of producing multiple images. - - -```python -sigma_cr_kpc = cosmology.critical_surface_density_between_redshifts_solar_mass_per_kpc2_from( - redshift_0=0.5, redshift_1=1.0 -) -sigma_cr_arcsec = cosmology.critical_surface_density_between_redshifts_from( - redshift_0=0.5, redshift_1=1.0 -) - -print(f"Sigma_cr (solar masses per kpc^2) = {sigma_cr_kpc:.3e}") -print(f"Sigma_cr (solar masses per arcsec^2) = {sigma_cr_arcsec:.3e}") -``` - - Sigma_cr (solar masses per kpc^2) = 3.002e+09 - Sigma_cr (solar masses per arcsec^2) = 1.187e+11 - - -The **convergence** kappa is the surface mass density in units of the critical density: - - kappa(theta) = Sigma(theta) / Sigma_cr - -This is the dimensionless quantity **PyAutoLens** has been plotting since tutorial 2 whenever we called -`convergence_2d_from`: - -- kappa >= 1 — the lens is super-critical at that point; multiple imaging is possible. -- kappa < 1 — the lens is sub-critical there. - -Because kappa is dimensionless, lens models can be composed and fitted without knowing the galaxy redshifts at all — -the redshifts and Sigma_cr are only needed at the end, to convert the inferred kappa back into physical masses. - - -```python -convergence = tracer.convergence_2d_from(grid=grid) - -aplt.plot_array(array=convergence, title="Convergence (kappa)", use_log10=True) -``` - - - -![png](tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_19_0.png) - - - -__Deflection Angles__ - -The convergence field determines the deflection angles everywhere, via a 2D integral over the whole image-plane: - - alpha(theta) = (1 / pi) * integral d^2 theta' kappa(theta') * (theta - theta') / |theta - theta'|^2 - -In plain words: every patch of mass in the lens plane pulls on every light ray. The deflection at position theta is -the sum (integral) of the pulls from all mass elements kappa(theta'), each pointing from the mass element towards -the ray and falling off as 1/distance — the 2D (projected) analogue of Newtonian gravity's inverse-square law. - -Two things follow from this integral being over *all* theta': - -- The deflection at a point depends on the mass distribution *everywhere*, not just the mass at that point. Even - mass well outside the region where images form contributes deflections (this is why external shear from - neighbouring galaxies matters, as we saw in tutorial 3). - -- For simple analytic profiles (isothermal, power-law, Sersic-like) this integral has closed-form solutions, which - is exactly what a **PyAutoLens** mass profile is: an analytic kappa(theta) paired with its analytic alpha(theta). - -The `deflections_yx_2d_from` method we have used since tutorial 2 evaluates this integral's closed-form solution. -The deflections form a 2D vector field, so we plot its y and x components separately: - - -```python -deflections = tracer.deflections_yx_2d_from(grid=grid) - -deflections_y = aa.Array2D(values=deflections.slim[:, 0], mask=grid.mask) -aplt.plot_array(array=deflections_y, title="Deflection Angles (y component)") - -deflections_x = aa.Array2D(values=deflections.slim[:, 1], mask=grid.mask) -aplt.plot_array(array=deflections_x, title="Deflection Angles (x component)") -``` - - - -![png](tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_21_0.png) - - - - - -![png](tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_21_1.png) - - - -__The Lensing Potential__ - -The deflection field is not arbitrary — it is the gradient of a scalar field, the **lensing potential** psi(theta): - - alpha(theta) = grad psi(theta) - -The potential is itself an integral over the convergence: - - psi(theta) = (1 / pi) * integral d^2 theta' kappa(theta') * ln|theta - theta'| - -and taking the divergence of the gradient (the Laplacian) recovers the convergence with a factor of a half: - - kappa(theta) = (1/2) * laplacian psi(theta) - -This is the 2D Poisson equation of lensing — the projected analogue of Newtonian gravity's del^2 Phi = 4 pi G rho. -The potential is the single most economical description of a lens: one scalar field from which the deflections -(first derivatives), and the convergence, shear and magnification (second derivatives) all follow. - -The `potential_2d_from` method returns psi, which we have plotted before without defining it: - - -```python -potential = tracer.potential_2d_from(grid=grid) - -aplt.plot_array(array=potential, title="Lensing Potential (psi)") -``` - - - -![png](tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_23_0.png) - - - -We can verify alpha = grad psi numerically. Mass profiles have a `deflections_2d_via_potential_2d_from` method which -computes the deflections by numerically differentiating the potential, rather than using the profile's closed-form -deflection formula. Across the grid the two agree closely — we print the median absolute difference, since the -finite-difference derivative is inaccurate right at the isothermal profile's central cusp, where the potential is -not smooth (the closed-form deflections have no such problem): - - -```python -deflections_analytic = mass_profile.deflections_yx_2d_from(grid=grid) -deflections_via_potential = mass_profile.deflections_2d_via_potential_2d_from(grid=grid) - -difference = np.median( - np.abs(np.asarray(deflections_analytic) - np.asarray(deflections_via_potential)) -) -print(f"Median |alpha_analytic - grad psi| = {difference:.3e} arcsec") -``` - - Median |alpha_analytic - grad psi| = 1.095e-04 arcsec - - -__Shear and Magnification__ - -How a small image is distorted by lensing is governed by how the deflection angles *change* across it — the second -derivatives of the potential. These form the 2x2 **Hessian** matrix, which `LensCalc` computes by finite -differences of the deflection field (as we saw in the workspace guides, this works for any mass distribution): - - H_yy = d(alpha_y) / d(theta_y) H_xy = d(alpha_x) / d(theta_y) - H_yx = d(alpha_y) / d(theta_x) H_xx = d(alpha_x) / d(theta_x) - - -```python -hessian_yy, hessian_xy, hessian_yx, hessian_xx = lens_calc.hessian_from(grid=grid) - -print(f"Hessian components at pixel 0: H_yy = {hessian_yy[0]:.4f}, H_xx = {hessian_xx[0]:.4f}") -``` - - Hessian components at pixel 0: H_yy = 0.2032, H_xx = 0.2032 - - -Differentiating the lens equation beta = theta - alpha(theta) gives the **Jacobian matrix** A, which maps a small -displacement in the source-plane to the corresponding displacement in the image-plane: - - A = d(beta) / d(theta) = I - H = | 1 - H_yy -H_xy | - | -H_yx 1 - H_xx | - -The Jacobian decomposes into two physically distinct distortions: - -- The **convergence** kappa = (1/2) * (H_yy + H_xx) — the isotropic part, which magnifies an image uniformly - without changing its shape. (Note this is the same kappa as before: the trace of the Hessian recovers the - Poisson equation kappa = (1/2) laplacian psi.) - -- The **shear** gamma — the anisotropic part, which stretches an image along one axis and squeezes it along the - perpendicular axis. It has two components and a magnitude: - - gamma_1 = (1/2) * (H_xx - H_yy) - gamma_2 = H_xy - |gamma| = sqrt(gamma_1^2 + gamma_2^2) - -The shear is why lensed images near the lens are stretched into tangential arcs — the tidal field of the lens -elongates them around it. - - -```python -shear = lens_calc.shear_yx_2d_via_hessian_from(grid=grid) - -print(f"Shear magnitude at pixel 0: |gamma| = {shear.magnitudes[0]:.4f}") -``` - - Shear magnitude at pixel 0: |gamma| = 0.2032 - - -The **magnification** mu is the inverse of the Jacobian's determinant: - - mu = 1 / det(A) = 1 / [ (1 - kappa)^2 - |gamma|^2 ] - -Lensing conserves surface brightness, so a lensed image that covers more sky than the unlensed source appears -brighter in total by exactly the factor |mu|: - -- |mu| > 1 — the image is magnified (larger and brighter than the unlensed source). -- |mu| < 1 — the image is demagnified. -- mu < 0 — the image has negative parity: it is a mirror image of the source. - -The determinant factorises into two eigenvalues, giving the **tangential** and **radial** magnifications: - - lambda_t = 1 - kappa - |gamma| (tangential eigenvalue) - lambda_r = 1 - kappa + |gamma| (radial eigenvalue) - - mu = 1 / (lambda_t * lambda_r) - -An image is stretched by 1/lambda_t in the tangential direction (around the lens) and 1/lambda_r in the radial -direction (towards/away from the lens). Giant tangential arcs form where lambda_t is close to zero. - - -```python -magnification = lens_calc.magnification_2d_from(grid=grid) - -aplt.plot_array(array=magnification, title="Magnification (mu)") - -tangential_eigen_values = lens_calc.tangential_eigen_value_from(grid=grid) -radial_eigen_values = lens_calc.radial_eigen_value_from(grid=grid) - -print(f"Tangential eigenvalue at pixel 0: {tangential_eigen_values[0]:.4f}") -print(f"Radial eigenvalue at pixel 0: {radial_eigen_values[0]:.4f}") -``` - - - -![png](tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_31_0.png) - - - - Tangential eigenvalue at pixel 0: 0.5937 - Radial eigenvalue at pixel 0: 1.0000 - - -__Critical Curves and Caustics__ - -Where either eigenvalue passes through zero, det(A) = 0 and the magnification formally diverges to infinity. The -closed curves in the image-plane where this happens are the **critical curves** — the white and yellow lines that -have appeared on plots since tutorial 2, and which we explored visually in tutorial 3: - -- The **tangential critical curve** (lambda_t = 0) — roughly traces the Einstein ring; sources near its source-plane - counterpart form giant tangential arcs. -- The **radial critical curve** (lambda_r = 0) — an inner curve associated with radially stretched central images. - -Ray-tracing each critical curve through the lens equation maps it to the source-plane, where it is called a -**caustic**: - - caustic = critical_curve - alpha(critical_curve) - -Caustics divide the source-plane into regions of different image multiplicity: each time a source crosses a -caustic, the number of images it produces changes by two. For our SIE lens, a source inside the tangential caustic -produces four images (plus a faint central image); between the tangential and radial caustics, two; and outside -both caustics, just one — the source is no longer multiply imaged at all. - -`LensCalc` computes both by locating the zero-contours of the eigenvalue fields on the grid: - - -```python -tangential_critical_curve_list = lens_calc.tangential_critical_curve_list_from(grid=grid) -radial_critical_curve_list = lens_calc.radial_critical_curve_list_from(grid=grid) - -tangential_caustic_list = lens_calc.tangential_caustic_list_from(grid=grid) -radial_caustic_list = lens_calc.radial_caustic_list_from(grid=grid) - -print(f"Number of tangential critical curves: {len(tangential_critical_curve_list)}") -print(f"Number of radial critical curves: {len(radial_critical_curve_list)}") -``` - - Number of tangential critical curves: 1 - Number of radial critical curves: 0 - - -Lets plot the critical curves (image-plane) and caustics (source-plane) of our SIE side by side. Note how the -elliptical lens produces a tangential caustic with four cusps — the origin of the four-image "quad" configurations -seen in many real lenses. - - -```python -plt.figure(figsize=(10, 5)) - -plt.subplot(1, 2, 1) -for curve in tangential_critical_curve_list: - curve = np.asarray(curve) - plt.plot(curve[:, 1], curve[:, 0], color="black", label="Tangential") -for curve in radial_critical_curve_list: - curve = np.asarray(curve) - plt.plot(curve[:, 1], curve[:, 0], color="orange", label="Radial") -plt.gca().set_aspect("equal") -plt.title("Critical Curves (Image-Plane)") -plt.xlabel("x (arcsec)") -plt.ylabel("y (arcsec)") -plt.legend() - -plt.subplot(1, 2, 2) -for curve in tangential_caustic_list: - curve = np.asarray(curve) - plt.plot(curve[:, 1], curve[:, 0], color="black", label="Tangential") -for curve in radial_caustic_list: - curve = np.asarray(curve) - plt.plot(curve[:, 1], curve[:, 0], color="orange", label="Radial") -plt.gca().set_aspect("equal") -plt.title("Caustics (Source-Plane)") -plt.xlabel("x (arcsec)") -plt.ylabel("y (arcsec)") -plt.legend() - -plt.show() -plt.close() -``` - - - -![png](tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_35_0.png) - - - -__Einstein Radius__ - -The **Einstein radius** theta_E is the characteristic angular scale of a strong lens. For a circular lens with the -source perfectly aligned behind it, it is the radius of the Einstein ring the source forms. More generally (and -this is the definition **PyAutoLens** uses), it is the radius of the circle enclosing the same area as the -tangential critical curve: - - theta_E = sqrt(A_crit / pi) - -sometimes called the "effective" Einstein radius, since an elliptical lens's critical curve is not a circle. - -Two closed-form results are worth memorising. For a **point mass** M: - - theta_E = sqrt( (4 G M / c^2) * (D_ls / (D_l * D_s)) ) - -and for a **singular isothermal sphere** (SIS) with velocity dispersion sigma_v: - - theta_E = 4 pi * (sigma_v / c)^2 * (D_ls / D_s) - -The Einstein radius is also the radius within which the *mean* convergence equals exactly one — so measuring -theta_E directly measures the projected mass enclosed within it: - - M(< theta_E) = pi * theta_E^2 * Sigma_cr - -This is why the Einstein radius is celebrated as one of the most robust mass measurements in all of astrophysics: -the data pin down theta_E via the image separations almost independently of the assumed mass profile, so the -enclosed Einstein mass is trusted even when the profile's slope is not. (The main caveat, the mass-sheet -degeneracy, is discussed in the lens modeling chapters.) - -`LensCalc` computes the Einstein radius from the area of the tangential critical curve, and the enclosed -"Einstein mass" in angular units (pi * theta_E^2), which Sigma_cr converts to solar masses: - - -```python -einstein_radius = lens_calc.einstein_radius_from(grid=grid) - -print(f"Einstein radius (arcsec) = {einstein_radius:.4f}") -print(f"Einstein radius (kpc) = {einstein_radius * kpc_per_arcsec_lens:.4f}") - -einstein_mass_angular = lens_calc.einstein_mass_angular_from(grid=grid) -einstein_mass_solar = einstein_mass_angular * sigma_cr_arcsec - -print(f"Einstein mass (angular, arcsec^2) = {einstein_mass_angular:.4f}") -print(f"Einstein mass (solar masses) = {einstein_mass_solar:.4e}") -``` - - Einstein radius (arcsec) = 1.5901 - Einstein radius (kpc) = 9.9992 - Einstein mass (angular, arcsec^2) = 7.9437 - Einstein mass (solar masses) = 9.4290e+11 - - -Reassuringly, the Einstein radius computed from the critical curve area (~1.6") matches the `einstein_radius=1.6` -parameter we gave the `Isothermal` profile — for isothermal profiles the model parameter *is* the effective -Einstein radius, which is exactly why **PyAutoLens** parameterizes its mass profiles this way: the non-linear -search then varies the quantity the data constrain most directly. - -As a second check, an `IsothermalSph` (the SIS) has a perfectly circular critical curve, so its recovered Einstein -radius equals its input parameter even more precisely: - - -```python -sis = al.mp.IsothermalSph(centre=(0.0, 0.0), einstein_radius=1.6) - -sis_einstein_radius = al.LensCalc.from_mass_obj(mass_obj=sis).einstein_radius_from( - grid=grid -) - -print(f"SIS input Einstein radius = 1.6, recovered = {sis_einstein_radius:.4f}") -``` - - SIS input Einstein radius = 1.6, recovered = 1.6000 - - -__Time Delays__ - -The final piece of the formalism is time. Light rays forming different images of the same source travel different -paths and through different depths of the lens's gravitational potential, so they arrive at different times. Both -effects are captured by the **Fermat potential** (or time-delay surface): - - phi(theta) = (1/2) * |theta - beta|^2 - psi(theta) - -The first term is the **geometric delay** — the extra path length of a bent ray. The second is the **gravitational -(Shapiro) delay** — light slowing as it climbs through the lens's potential. Fermat's principle states that images -form at the stationary points (minima, maxima and saddle points) of this surface, which is a wonderfully compact -restatement of the lens equation: grad phi = 0 is exactly beta = theta - alpha(theta). - -The observable **time delay** between two images A and B is the difference in their Fermat potentials, scaled by -the cosmological distances: - - Delta t_AB = (1 + z_l) / c * (D_l * D_s / D_ls) * [ phi(theta_A) - phi(theta_B) ] - -The distance combination (1 + z_l) * D_l * D_s / D_ls is called the **time-delay distance**, and because it is -inversely proportional to the Hubble constant, measuring time delays between the images of a variable source (a -quasar or supernova) turns a strong lens into a cosmological probe. - -We only touch on this here — time delays belong to the modeling of lensed point sources, introduced in tutorial 4 -and covered in depth by the `autolens_workspace` point-source material. For now, we simply plot the Fermat -potential of our lens system: - - -```python -fermat_potential = lens_calc.fermat_potential_from(grid=grid) - -aplt.plot_array(array=fermat_potential, title="Fermat Potential (phi)") -``` - - - -![png](tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_41_0.png) - - - -__Wrap Up__ - -This was the mathematics lecture of **HowToLens** — every formal definition deferred by the other tutorials, in one -place. Lets summarise the chain of quantities, because it has a beautiful logical structure where everything flows -from the mass distribution and a handful of distances: - -- **Distances**: the angular diameter distances D_l, D_s and D_ls set the geometry, convert arcseconds to - kiloparsecs and define the critical surface density Sigma_cr. - -- **Convergence**: kappa = Sigma / Sigma_cr is the dimensionless projected mass; kappa >= 1 marks super-critical - regions capable of multiple imaging. - -- **Deflections and potential**: kappa determines the deflection field alpha (a 2D gravity integral) and the - lensing potential psi, tied together by alpha = grad psi and kappa = (1/2) laplacian psi. - -- **The lens equation**: beta = theta - alpha(theta) maps the image-plane to the source-plane; its - non-invertibility is why multiple images form. - -- **Distortion**: the Jacobian A = I - H decomposes into convergence (isotropic) and shear gamma (anisotropic); - magnification is mu = 1 / det(A) = 1 / (lambda_t * lambda_r). - -- **Critical curves and caustics**: where det(A) = 0, magnification diverges; caustics are their source-plane - images and set the image multiplicity. - -- **Einstein radius**: the area-equivalent radius of the tangential critical curve, whose enclosed mass - M(< theta_E) = pi * theta_E^2 * Sigma_cr is the most robust measurement strong lensing delivers. - -- **Time delays**: the Fermat potential phi = (1/2)|theta - beta|^2 - psi locates images at its stationary points - and its differences, scaled by the time-delay distance, give observable delays. - -You do not need to memorise any of this to continue — **PyAutoLens** computes every one of these quantities via the -methods used above — but you now know what each method is computing and can return to this tutorial whenever a -symbol needs unpacking. - -In the next tutorial, we turn from theory to observation: how telescope optics, exposure times and noise turn the -pristine images of a tracer into the CCD imaging data we actually observe, and how to simulate such data ourselves. - -Finally, a signpost for much later: chapter 3's tutorial 5 on the Bayesian formalism is this tutorial's twin — the -equivalent equations lecture for pixelized source reconstruction, deriving the linear inversion and Bayesian -evidence that underpin chapter 3 just as this tutorial derived the lensing quantities underpinning chapter 1. diff --git a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_15_0.png b/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_15_0.png deleted file mode 100644 index d222956..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_15_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_15_1.png b/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_15_1.png deleted file mode 100644 index 13446cd..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_15_1.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_19_0.png b/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_19_0.png deleted file mode 100644 index 83a9ce4..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_19_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_21_0.png b/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_21_0.png deleted file mode 100644 index 5a3585d..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_21_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_21_1.png b/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_21_1.png deleted file mode 100644 index 282c775..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_21_1.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_23_0.png b/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_23_0.png deleted file mode 100644 index 4f1141b..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_23_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_31_0.png b/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_31_0.png deleted file mode 100644 index e05fa83..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_31_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_35_0.png b/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_35_0.png deleted file mode 100644 index e0a5690..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_35_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_41_0.png b/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_41_0.png deleted file mode 100644 index a7fce8c..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_41_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_7_0.png b/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_7_0.png deleted file mode 100644 index bb0aa74..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_5_lensing_formalism_files/tutorial_5_lensing_formalism_7_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_21_0.png b/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_21_0.png deleted file mode 100644 index 929c56a..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_21_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_23_0.png b/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_23_0.png deleted file mode 100644 index 240e688..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_23_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_25_0.png b/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_25_0.png deleted file mode 100644 index 4982c3d..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_25_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_25_1.png b/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_25_1.png deleted file mode 100644 index 8a889b7..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_25_1.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_29_0.png b/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_29_0.png deleted file mode 100644 index 8a05120..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_29_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_33_0.png b/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_33_0.png deleted file mode 100644 index 6cf10ed..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_33_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_35_0.png b/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_35_0.png deleted file mode 100644 index 93f03b9..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_35_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_37_0.png b/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_37_0.png deleted file mode 100644 index 6319217..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_37_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_41_1.png b/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_41_1.png deleted file mode 100644 index 3adb63a..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_6_data_files/tutorial_6_data_41_1.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting.md b/markdown/chapter_1_introduction/tutorial_6_fitting.md similarity index 86% rename from markdown/chapter_1_introduction/tutorial_7_fitting.md rename to markdown/chapter_1_introduction/tutorial_6_fitting.md index 8088499..0d28db1 100644 --- a/markdown/chapter_1_introduction/tutorial_7_fitting.md +++ b/markdown/chapter_1_introduction/tutorial_6_fitting.md @@ -1,8 +1,8 @@ -> ✏️ **This page is auto-generated from [`scripts/chapter_1_introduction/tutorial_7_fitting.py`](../../scripts/chapter_1_introduction/tutorial_7_fitting.py) — do not edit it directly.** +> ✏️ **This page is auto-generated from [`scripts/chapter_1_introduction/tutorial_6_fitting.py`](../../scripts/chapter_1_introduction/tutorial_6_fitting.py) — do not edit it directly.** > It shows the example fully executed, with its real output images. -> Run it yourself via the [Python script](../../scripts/chapter_1_introduction/tutorial_7_fitting.py) or the [Jupyter notebook](../../notebooks/chapter_1_introduction/tutorial_7_fitting.ipynb). +> Run it yourself via the [Python script](../../scripts/chapter_1_introduction/tutorial_6_fitting.py) or the [Jupyter notebook](../../notebooks/chapter_1_introduction/tutorial_6_fitting.ipynb). -Tutorial 7: Fitting +Tutorial 6: Fitting =================== In previous tutorials, we used light profiles to create simulated images of a tracer and visualized how these images @@ -37,7 +37,7 @@ Here is an overview of what we'll cover in this tutorial: __Contents__ - **Dataset:** Load the imaging dataset that we previously simulated, consisting of the image, noise map, and PSF. -- **Dataset Auto-Simulation:** Create the dataset by running the tutorial 6 script if it is not on your hard-disk. +- **Dataset Auto-Simulation:** Create the dataset by running the tutorial 5 script if it is not on your hard-disk. - **Mask:** Apply a mask to the data, excluding regions with low signal-to-noise ratios from the analysis. - **Masked Grid:** In tutorials 1 and 2, we emphasized that the `Grid2D` object is crucial for evaluating a lens's. - **Fitting:** Fit the lens model to the dataset and inspect the results. @@ -58,25 +58,7 @@ import autolens as al import autolens.plot as aplt ``` - .../PyAutoNerves/autonerves/workspace.py:206: UserWarning: Cannot verify the workspace at HowToLens/scripts/chapter_1_introduction is compatible with the installed library version (2026.7.23.1): no `version.minimum_library_version` or `version.workspace_version` key in config/general.yaml and no version.txt at the workspace root. - - If you cloned the workspace from `main` rather than a release tag, set `version.workspace_version_check: False` in config/general.yaml to silence this warning. The `main` branch updates more frequently than library releases, so version mismatches are expected and not actionable for `main`-branch users. - - You can also set the environment variable PYAUTO_SKIP_WORKSPACE_VERSION_CHECK=1 to disable temporarily. - warnings.warn(_missing_version_warning(root, library_version)) - .../PyAutoNerves/autonerves/workspace.py:206: UserWarning: Cannot verify the workspace at HowToLens/scripts/chapter_1_introduction is compatible with the installed library version (2026.7.23.1): no `version.minimum_library_version` or `version.workspace_version` key in config/general.yaml and no version.txt at the workspace root. - - If you cloned the workspace from `main` rather than a release tag, set `version.workspace_version_check: False` in config/general.yaml to silence this warning. The `main` branch updates more frequently than library releases, so version mismatches are expected and not actionable for `main`-branch users. - - You can also set the environment variable PYAUTO_SKIP_WORKSPACE_VERSION_CHECK=1 to disable temporarily. - warnings.warn(_missing_version_warning(root, library_version)) - Working Directory has been set to `HowToLens` - .../PyAutoNerves/autonerves/workspace.py:206: UserWarning: Cannot verify the workspace at HowToLens/scripts/chapter_1_introduction is compatible with the installed library version (2026.7.23.1): no `version.minimum_library_version` or `version.workspace_version` key in config/general.yaml and no version.txt at the workspace root. - - If you cloned the workspace from `main` rather than a release tag, set `version.workspace_version_check: False` in config/general.yaml to silence this warning. The `main` branch updates more frequently than library releases, so version mismatches are expected and not actionable for `main`-branch users. - - You can also set the environment variable PYAUTO_SKIP_WORKSPACE_VERSION_CHECK=1 to disable temporarily. - warnings.warn(_missing_version_warning(root, library_version)) + Working Directory has been set to `render-workspace` __Dataset__ @@ -97,7 +79,7 @@ dataset_path = Path("dataset") / "imaging" / "howtolens" __Dataset Auto-Simulation__ -The `howtolens` dataset is the one built up and saved in tutorial 6 (`tutorial_6_data.py`). If it does +The `howtolens` dataset is the one built up and saved in tutorial 5 (`tutorial_5_data.py`). If it does not already exist on your system, it is created by running that script. This ensures every example script can be run without manually simulating data first. @@ -108,7 +90,7 @@ if al.util.dataset.should_simulate(str(dataset_path)): import sys subprocess.run( - [sys.executable, "scripts/chapter_1_introduction/tutorial_6_data.py"], + [sys.executable, "scripts/chapter_1_introduction/tutorial_5_data.py"], check=True, ) @@ -126,7 +108,7 @@ The `Imaging` object contains three key components: `data`, `noise_map`, and `ps - `noise_map`: A map indicating the uncertainty or noise level in each pixel of the image, reflecting how much the observed signal in each pixel might fluctuate due to instrumental or background noise. - + - `psf`: The Point Spread Function, which describes how a point source of light is spread out in the image by the telescope's optics. It characterizes the blurring effect introduced by the instrument. @@ -146,17 +128,17 @@ aplt.subplot_imaging_dataset(dataset=dataset) ``` Value of first pixel in imaging data: - 0.053333333333333316 + 0.0 Value of first pixel in noise map: - 0.02260776661041756 + 0.018257418583505537 Value of first pixel in PSF: 2.210334945638401e-12 - -![png](tutorial_7_fitting_files/tutorial_7_fitting_7_1.png) - + +![png](tutorial_6_fitting_files/tutorial_6_fitting_7_1.png) + __Mask__ @@ -217,9 +199,9 @@ aplt.plot_array(array=dataset.data, title="Imaging Data With Mask") ``` - -![png](tutorial_7_fitting_files/tutorial_7_fitting_11_0.png) - + +![png](tutorial_6_fitting_files/tutorial_6_fitting_11_0.png) + Once we are satisfied with the mask, we apply it to the imaging data using the `apply_mask()` method. This ensures @@ -230,7 +212,7 @@ that only the unmasked regions are considered during the analysis. dataset = dataset.apply_mask(mask=mask) ``` - 2026-08-06 13:37:34,866 - autoarray.dataset.imaging.dataset - INFO - IMAGING - Data masked, contains a total of 2809 image-pixels + 2026-10-31 15:19:55,624 - autoarray.dataset.imaging.dataset - INFO - IMAGING - Data masked, contains a total of 2809 image-pixels When we plot the masked imaging data again, the mask is now automatically included in the plot, even though we did @@ -244,9 +226,9 @@ aplt.plot_array(array=dataset.data, title="Masked Imaging Data") ``` - -![png](tutorial_7_fitting_files/tutorial_7_fitting_15_0.png) - + +![png](tutorial_6_fitting_files/tutorial_6_fitting_15_0.png) + The mask is now stored as an additional attribute of the `Imaging` object, meaning it remains attached to the @@ -319,9 +301,9 @@ print(dataset.noise_map.slim[0]) ``` First unmasked image value: - 0.4633333333333334 + 0.5466666666666666 First unmasked noise map value: - 0.043333333333333335 + 0.04642796092394706 Additionally, we can verify that the `native` data structure has zeros at the edges where the mask is applied and @@ -339,7 +321,7 @@ print(dataset.data.native[centre]) Example masked pixel in the image's native representation at its edge: 0.0 Example unmasked pixel in the image's native representation at its center: - 0.52 + 0.48 __Masked Grid__ @@ -362,9 +344,9 @@ aplt.plot_grid(grid=masked_grid, title="Masked Grid2D") ``` - -![png](tutorial_7_fitting_files/tutorial_7_fitting_27_0.png) - + +![png](tutorial_6_fitting_files/tutorial_6_fitting_27_0.png) + By plotting this masked grid over the lens image, we can see that the grid aligns with the unmasked pixels of the @@ -379,9 +361,9 @@ aplt.plot_array(array=dataset.data, title="Image Data With 2D Grid Overlaid") ``` - -![png](tutorial_7_fitting_files/tutorial_7_fitting_29_0.png) - + +![png](tutorial_6_fitting_files/tutorial_6_fitting_29_0.png) + __Fitting__ @@ -419,9 +401,9 @@ aplt.plot_array(array=tracer.image_2d_from(grid=dataset.grid), title="Image") ``` - -![png](tutorial_7_fitting_files/tutorial_7_fitting_31_0.png) - + +![png](tutorial_6_fitting_files/tutorial_6_fitting_31_0.png) + Next, let's plot the image of the tracer. This should look familiar, as it is the same image we saw in @@ -437,9 +419,9 @@ aplt.plot_array( ``` - -![png](tutorial_7_fitting_files/tutorial_7_fitting_33_0.png) - + +![png](tutorial_6_fitting_files/tutorial_6_fitting_33_0.png) + Now, we proceed to fit the image by passing both the `Imaging` and `Tracer` objects to a `FitImaging` object. @@ -478,13 +460,13 @@ aplt.plot_array(array=fit.model_data, title="Model Image") ``` First model image pixel: - 0.4831484402089213 + 0.4831484402089215 + + +![png](tutorial_6_fitting_files/tutorial_6_fitting_37_1.png) - -![png](tutorial_7_fitting_files/tutorial_7_fitting_37_1.png) - Even before computing other fit quantities, we can normally assess if the fit is going to be good by visually comparing @@ -500,15 +482,15 @@ aplt.plot_array(array=fit.model_data, title="Model Image") ``` - -![png](tutorial_7_fitting_files/tutorial_7_fitting_39_0.png) - +![png](tutorial_6_fitting_files/tutorial_6_fitting_39_0.png) - -![png](tutorial_7_fitting_files/tutorial_7_fitting_39_1.png) - + + + +![png](tutorial_6_fitting_files/tutorial_6_fitting_39_1.png) + The `residual_map` is the different between the observed image and model image, showing where in the image the fit is @@ -534,15 +516,15 @@ aplt.plot_array(array=fit.residual_map, title="Residual Map") ``` First residual-map pixel: - -0.019815106875587907 + 0.06351822645774513 First residual-map pixel via fit: - -0.019815106875587907 + 0.06351822645774513 + - -![png](tutorial_7_fitting_files/tutorial_7_fitting_41_1.png) - +![png](tutorial_6_fitting_files/tutorial_6_fitting_41_1.png) + Are these residuals indicative of a good fit to the data? Without considering the noise in the data, it's difficult @@ -572,15 +554,15 @@ aplt.plot_array(array=fit.normalized_residual_map, title="Normalized Residual Ma ``` First normalized residual-map pixel: - -0.45727169712895166 + 1.3681028671880158 First normalized residual-map pixel via fit: - -0.45727169712895166 + 1.3681028671880158 + + +![png](tutorial_6_fitting_files/tutorial_6_fitting_43_1.png) - -![png](tutorial_7_fitting_files/tutorial_7_fitting_43_1.png) - Next, we define the `chi_squared_map`, which is obtained by squaring the `normalized_residual_map` and serves as a @@ -609,15 +591,15 @@ aplt.plot_array(array=fit.chi_squared_map, title="Chi Squared Map") ``` First chi-squared pixel: - 0.2090974049951917 + 1.8717054552080694 First chi-squared pixel via fit: - 0.2090974049951917 + 1.8717054552080694 - -![png](tutorial_7_fitting_files/tutorial_7_fitting_45_1.png) - + +![png](tutorial_6_fitting_files/tutorial_6_fitting_45_1.png) + Now, we consolidate all the information in our `chi_squared_map` into a single measure of goodness-of-fit @@ -641,8 +623,8 @@ print("Chi-squared = ", chi_squared) print("Chi-squared via fit = ", fit.chi_squared) ``` - Chi-squared = 2870.509352378347 - Chi-squared via fit = 2870.509352378347 + Chi-squared = 2691.0651916094116 + Chi-squared via fit = 2691.0651916094116 The reduced chi-squared is the `chi_squared` value divided by the number of data points (e.g., the number of pixels @@ -661,7 +643,7 @@ reduced_chi_squared = chi_squared / dataset.mask.pixels_in_mask print("Reduced Chi-squared = ", reduced_chi_squared) ``` - Reduced Chi-squared = 1.0218972418577241 + Reduced Chi-squared = 0.9580153761514459 Another quantity that contributes to our final assessment of the goodness-of-fit is the `noise_normalization`. @@ -686,8 +668,8 @@ print("Noise Normalization = ", noise_normalization) print("Noise Normalization via fit = ", fit.noise_normalization) ``` - Noise Normalization = -8670.33617182735 - Noise Normalization via fit = -8670.33617182735 + Noise Normalization = -8670.900754470584 + Noise Normalization via fit = -8670.900754470584 From the `chi_squared` and `noise_normalization`, we can define a final goodness-of-fit measure known as @@ -708,8 +690,8 @@ print("Log Likelihood = ", log_likelihood) print("Log Likelihood via fit = ", fit.log_likelihood) ``` - Log Likelihood = 2899.9134097245014 - Log Likelihood via fit = 2899.9134097245014 + Log Likelihood = 2989.917781430586 + Log Likelihood via fit = 2989.917781430586 In the previous discussion, we noted that a lower \(\chi^2\) value indicates a better fit of the model to the @@ -749,9 +731,9 @@ aplt.subplot_fit_imaging(fit=fit) ``` - -![png](tutorial_7_fitting_files/tutorial_7_fitting_55_0.png) - + +![png](tutorial_6_fitting_files/tutorial_6_fitting_55_0.png) + If you're familiar with model-fitting, you've likely encountered terms like 'residuals', 'chi-squared', @@ -799,9 +781,9 @@ aplt.plot_array(array=tracer.image_2d_from(grid=dataset.grid), title="Image") ``` - -![png](tutorial_7_fitting_files/tutorial_7_fitting_57_0.png) - + +![png](tutorial_6_fitting_files/tutorial_6_fitting_57_0.png) + After implementing this slight adjustment, we can now plot the fit. In doing so, we observe that residuals have @@ -816,9 +798,9 @@ aplt.subplot_fit_imaging(fit=fit_bad) ``` - -![png](tutorial_7_fitting_files/tutorial_7_fitting_59_0.png) - + +![png](tutorial_6_fitting_files/tutorial_6_fitting_59_0.png) + Next, we can compare the log likelihood of our current model to the log likelihood value we computed previously. @@ -832,9 +814,9 @@ print(fit_bad.log_likelihood) ``` Previous Likelihood: - 2899.9134097245014 + 2989.917781430586 New Likelihood: - -64618.8911885303 + -63995.617030193636 As expected, we observe that the log likelihood has decreased! This decline confirms that our new model is indeed a @@ -872,9 +854,9 @@ aplt.subplot_fit_imaging(fit=fit_very_bad) ``` - -![png](tutorial_7_fitting_files/tutorial_7_fitting_63_0.png) - + +![png](tutorial_6_fitting_files/tutorial_6_fitting_63_0.png) + It is now evident that this model provides a terrible fit to the data. The tracer does not resemble a plausible @@ -892,10 +874,10 @@ print(fit_very_bad.log_likelihood) ``` Previous Likelihoods: - 2899.9134097245014 - -64618.8911885303 + 2989.917781430586 + -63995.617030193636 New Likelihood: - -1599395.1803587012 + -1597962.1455931114 __Model Fitting__ @@ -946,19 +928,19 @@ dataset = dataset.apply_mask(mask=mask) aplt.subplot_imaging_dataset(dataset=dataset) ``` - Figure(700x700) - .../PyAutoArray/autoarray/operators/convolver.py:1424: UserWarning: No blurring_image provided. Only the direct image will be convolved. This may change the correctness of the PSF convolution. + ~/Code/PyAutoLabs/.worktrees/howtolens-ray-tracing-merge/PyAutoArray/autoarray/operators/convolver.py:1484: UserWarning: No blurring_image provided. Only the direct image will be convolved. This may change the correctness of the PSF convolution. warnings.warn( + Figure(700x700) Figure(1800x1800) Figure(1800x1800) Figure(700x700) - 2026-08-06 13:38:03,369 - autoarray.dataset.imaging.dataset - INFO - IMAGING - Data masked, contains a total of 2828 image-pixels + 2026-10-31 15:20:24,619 - autoarray.dataset.imaging.dataset - INFO - IMAGING - Data masked, contains a total of 2828 image-pixels - -![png](tutorial_7_fitting_files/tutorial_7_fitting_67_1.png) - + +![png](tutorial_6_fitting_files/tutorial_6_fitting_67_1.png) + Now, you'll try to determine the best-fit model for this image, corresponding to the parameters used to simulate the @@ -1009,13 +991,13 @@ print(fit.log_likelihood) ``` - -![png](tutorial_7_fitting_files/tutorial_7_fitting_69_0.png) - + +![png](tutorial_6_fitting_files/tutorial_6_fitting_69_0.png) + Log Likelihood: - -468816.25824381993 + -478614.91332766664 Manually guessing model parameters repeatedly is a very inefficient and slow way to find the best fit. If the model @@ -1038,17 +1020,17 @@ Let's summarise what we have covered: - **Dataset**: We loaded the imaging dataset that we previously simulated, consisting of the tracer image, noise map, and PSF. - + - **Mask**: We applied a circular mask to the data, excluding regions with low signal-to-noise ratios from the analysis. - **Masked Grid**: We created a masked grid, which contains only the coordinates of unmasked pixels, to evaluate the tracer's light profile. - + - **Fitting**: We fitted the data with a lens model, computing key quantities like the model image, residuals, chi-squared, and log likelihood to assess the quality of the fit. - + - **Bad Fits**: We demonstrated how even small deviations from the true parameters can significantly impact the fit quality, leading to decreased log likelihood values. - + - **Model Fitting**: We performed a basic model fit on a simple dataset, adjusting the model parameters to improve the fit quality. diff --git a/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_11_0.png b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_11_0.png new file mode 100644 index 0000000..29db98d Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_11_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_15_0.png b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_15_0.png new file mode 100644 index 0000000..d14849a Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_15_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_27_0.png b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_27_0.png similarity index 100% rename from markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_27_0.png rename to markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_27_0.png diff --git a/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_29_0.png b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_29_0.png new file mode 100644 index 0000000..cebce45 Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_29_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_31_0.png b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_31_0.png similarity index 100% rename from markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_31_0.png rename to markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_31_0.png diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_33_0.png b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_33_0.png similarity index 100% rename from markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_33_0.png rename to markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_33_0.png diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_37_1.png b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_37_1.png similarity index 100% rename from markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_37_1.png rename to markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_37_1.png diff --git a/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_39_0.png b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_39_0.png new file mode 100644 index 0000000..a40b75d Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_39_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_39_1.png b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_39_1.png similarity index 100% rename from markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_39_1.png rename to markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_39_1.png diff --git a/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_41_1.png b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_41_1.png new file mode 100644 index 0000000..51d2e5e Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_41_1.png differ diff --git a/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_43_1.png b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_43_1.png new file mode 100644 index 0000000..5e1fca5 Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_43_1.png differ diff --git a/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_45_1.png b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_45_1.png new file mode 100644 index 0000000..86ad605 Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_45_1.png differ diff --git a/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_55_0.png b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_55_0.png new file mode 100644 index 0000000..5e64dfc Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_55_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_57_0.png b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_57_0.png similarity index 100% rename from markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_57_0.png rename to markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_57_0.png diff --git a/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_59_0.png b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_59_0.png new file mode 100644 index 0000000..d6b9961 Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_59_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_63_0.png b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_63_0.png new file mode 100644 index 0000000..c3dced5 Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_63_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_67_1.png b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_67_1.png new file mode 100644 index 0000000..a402e7e Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_67_1.png differ diff --git a/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_69_0.png b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_69_0.png new file mode 100644 index 0000000..90187e2 Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_69_0.png differ diff --git a/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_7_1.png b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_7_1.png new file mode 100644 index 0000000..d460d6d Binary files /dev/null and b/markdown/chapter_1_introduction/tutorial_6_fitting_files/tutorial_6_fitting_7_1.png differ diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_11_0.png b/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_11_0.png deleted file mode 100644 index 929a443..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_11_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_15_0.png b/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_15_0.png deleted file mode 100644 index 346f639..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_15_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_29_0.png b/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_29_0.png deleted file mode 100644 index cbf2744..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_29_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_39_0.png b/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_39_0.png deleted file mode 100644 index 6821f77..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_39_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_41_1.png b/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_41_1.png deleted file mode 100644 index aa448f0..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_41_1.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_43_1.png b/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_43_1.png deleted file mode 100644 index a57d604..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_43_1.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_45_1.png b/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_45_1.png deleted file mode 100644 index a1535a4..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_45_1.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_55_0.png b/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_55_0.png deleted file mode 100644 index f425a6e..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_55_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_59_0.png b/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_59_0.png deleted file mode 100644 index c73f419..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_59_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_63_0.png b/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_63_0.png deleted file mode 100644 index b910b25..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_63_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_67_1.png b/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_67_1.png deleted file mode 100644 index 985ddd3..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_67_1.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_69_0.png b/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_69_0.png deleted file mode 100644 index c5b142f..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_69_0.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_7_1.png b/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_7_1.png deleted file mode 100644 index fcf9a90..0000000 Binary files a/markdown/chapter_1_introduction/tutorial_7_fitting_files/tutorial_7_fitting_7_1.png and /dev/null differ diff --git a/markdown/chapter_1_introduction/tutorial_8_summary.md b/markdown/chapter_1_introduction/tutorial_7_summary.md similarity index 73% rename from markdown/chapter_1_introduction/tutorial_8_summary.md rename to markdown/chapter_1_introduction/tutorial_7_summary.md index 71482a1..026c5fa 100644 --- a/markdown/chapter_1_introduction/tutorial_8_summary.md +++ b/markdown/chapter_1_introduction/tutorial_7_summary.md @@ -1,8 +1,8 @@ -> ✏️ **This page is auto-generated from [`scripts/chapter_1_introduction/tutorial_8_summary.py`](../../scripts/chapter_1_introduction/tutorial_8_summary.py) — do not edit it directly.** +> ✏️ **This page is auto-generated from [`scripts/chapter_1_introduction/tutorial_7_summary.py`](../../scripts/chapter_1_introduction/tutorial_7_summary.py) — do not edit it directly.** > It shows the example fully executed, with its real output images. -> Run it yourself via the [Python script](../../scripts/chapter_1_introduction/tutorial_8_summary.py) or the [Jupyter notebook](../../notebooks/chapter_1_introduction/tutorial_8_summary.ipynb). +> Run it yourself via the [Python script](../../scripts/chapter_1_introduction/tutorial_7_summary.py) or the [Jupyter notebook](../../notebooks/chapter_1_introduction/tutorial_7_summary.ipynb). -Tutorial 8: Summary +Tutorial 7: Summary =================== In this chapter, we have learnt that: @@ -40,25 +40,7 @@ import autolens as al import autolens.plot as aplt ``` - .../PyAutoNerves/autonerves/workspace.py:206: UserWarning: Cannot verify the workspace at HowToLens/scripts/chapter_1_introduction is compatible with the installed library version (2026.7.23.1): no `version.minimum_library_version` or `version.workspace_version` key in config/general.yaml and no version.txt at the workspace root. - - If you cloned the workspace from `main` rather than a release tag, set `version.workspace_version_check: False` in config/general.yaml to silence this warning. The `main` branch updates more frequently than library releases, so version mismatches are expected and not actionable for `main`-branch users. - - You can also set the environment variable PYAUTO_SKIP_WORKSPACE_VERSION_CHECK=1 to disable temporarily. - warnings.warn(_missing_version_warning(root, library_version)) - .../PyAutoNerves/autonerves/workspace.py:206: UserWarning: Cannot verify the workspace at HowToLens/scripts/chapter_1_introduction is compatible with the installed library version (2026.7.23.1): no `version.minimum_library_version` or `version.workspace_version` key in config/general.yaml and no version.txt at the workspace root. - - If you cloned the workspace from `main` rather than a release tag, set `version.workspace_version_check: False` in config/general.yaml to silence this warning. The `main` branch updates more frequently than library releases, so version mismatches are expected and not actionable for `main`-branch users. - - You can also set the environment variable PYAUTO_SKIP_WORKSPACE_VERSION_CHECK=1 to disable temporarily. - warnings.warn(_missing_version_warning(root, library_version)) - Working Directory has been set to `HowToLens` - .../PyAutoNerves/autonerves/workspace.py:206: UserWarning: Cannot verify the workspace at HowToLens/scripts/chapter_1_introduction is compatible with the installed library version (2026.7.23.1): no `version.minimum_library_version` or `version.workspace_version` key in config/general.yaml and no version.txt at the workspace root. - - If you cloned the workspace from `main` rather than a release tag, set `version.workspace_version_check: False` in config/general.yaml to silence this warning. The `main` branch updates more frequently than library releases, so version mismatches are expected and not actionable for `main`-branch users. - - You can also set the environment variable PYAUTO_SKIP_WORKSPACE_VERSION_CHECK=1 to disable temporarily. - warnings.warn(_missing_version_warning(root, library_version)) + Working Directory has been set to `render-workspace` __Start__ @@ -127,8 +109,8 @@ print(tracer.planes[1][0].disk) print() ``` - - + + [Redshift: 0.5 Mass Profiles: Isothermal @@ -146,7 +128,7 @@ print() radius_break: 0.025 alpha: 3.0 gamma: 0.25 - + SersicCore centre: (0.1, 0.1) ell_comps: (0.0, 0.111111) @@ -156,7 +138,7 @@ print() radius_break: 0.025 alpha: 3.0 gamma: 0.25 - + Once we have a tracer we can therefore use any of the plotting function objects throughout this chapter to plot @@ -174,9 +156,9 @@ source_plane_grid = tracer.traced_grid_2d_list_from(grid=grid)[1] ``` - -![png](tutorial_8_summary_files/tutorial_8_summary_7_0.png) - + +![png](tutorial_7_summary_files/tutorial_7_summary_7_0.png) + Understanding how these objects decompose into the different components of a strong lens is important for general @@ -201,15 +183,15 @@ aplt.plot_array( ``` - -![png](tutorial_8_summary_files/tutorial_8_summary_9_0.png) - + +![png](tutorial_7_summary_files/tutorial_7_summary_9_0.png) - -![png](tutorial_8_summary_files/tutorial_8_summary_9_1.png) - + + +![png](tutorial_7_summary_files/tutorial_7_summary_9_1.png) + __Visualization__ @@ -240,9 +222,9 @@ aplt.plot_array( ``` - -![png](tutorial_8_summary_files/tutorial_8_summary_11_0.png) - + +![png](tutorial_7_summary_files/tutorial_7_summary_11_0.png) + And, we're done, not just with the tutorial, but the chapter! diff --git a/markdown/chapter_1_introduction/tutorial_8_summary_files/tutorial_8_summary_11_0.png b/markdown/chapter_1_introduction/tutorial_7_summary_files/tutorial_7_summary_11_0.png similarity index 100% rename from markdown/chapter_1_introduction/tutorial_8_summary_files/tutorial_8_summary_11_0.png rename to markdown/chapter_1_introduction/tutorial_7_summary_files/tutorial_7_summary_11_0.png diff --git a/markdown/chapter_1_introduction/tutorial_8_summary_files/tutorial_8_summary_7_0.png b/markdown/chapter_1_introduction/tutorial_7_summary_files/tutorial_7_summary_7_0.png similarity index 100% rename from markdown/chapter_1_introduction/tutorial_8_summary_files/tutorial_8_summary_7_0.png rename to markdown/chapter_1_introduction/tutorial_7_summary_files/tutorial_7_summary_7_0.png diff --git a/markdown/chapter_1_introduction/tutorial_8_summary_files/tutorial_8_summary_9_0.png b/markdown/chapter_1_introduction/tutorial_7_summary_files/tutorial_7_summary_9_0.png similarity index 100% rename from markdown/chapter_1_introduction/tutorial_8_summary_files/tutorial_8_summary_9_0.png rename to markdown/chapter_1_introduction/tutorial_7_summary_files/tutorial_7_summary_9_0.png diff --git a/markdown/chapter_1_introduction/tutorial_8_summary_files/tutorial_8_summary_9_1.png b/markdown/chapter_1_introduction/tutorial_7_summary_files/tutorial_7_summary_9_1.png similarity index 100% rename from markdown/chapter_1_introduction/tutorial_8_summary_files/tutorial_8_summary_9_1.png rename to markdown/chapter_1_introduction/tutorial_7_summary_files/tutorial_7_summary_9_1.png diff --git a/notebooks/chapter_1_introduction/README.md b/notebooks/chapter_1_introduction/README.md index 003d058..1b8e854 100644 --- a/notebooks/chapter_1_introduction/README.md +++ b/notebooks/chapter_1_introduction/README.md @@ -8,16 +8,14 @@ In chapter 1, we introduce you to strong gravitational lensing and the core **Py - [Tutorial 1: Grids And Galaxies](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb) — Using grids of (y,x) coordinates with galaxies made up of light profiles. -- [Tutorial 2: Ray Tracing](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb) — Using grids, galaxies and mass profiles to perform strong lens ray-tracing. +- [Tutorial 2: Ray Tracing](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb) — Using grids, galaxies and mass profiles to perform strong lens ray-tracing. -- [Tutorial 3: More Ray Tracing](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb) — Advanced strong lens ray-tracing. +- [Tutorial 3: More Ray Tracing](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb) — The optional mathematics of ray tracing, magnification, critical curves and time delays. - [Tutorial 4: Point Sources](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_4_point_sources.ipynb) — How lensing calculations change when the source galaxy is a point source (e.g. a quasar). -- [Tutorial 5: Lensing Formalism](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_5_lensing_formalism.ipynb) — The algebraic lensing formalism used to describe strong lensing. +- [Tutorial 5: Data](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_5_data.ipynb) — Loading and inspecting telescope imaging data of a strong lens. -- [Tutorial 6: Data](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_6_data.ipynb) — Loading and inspecting telescope imaging data of a strong lens. +- [Tutorial 6: Fitting](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_6_fitting.ipynb) — Fitting data with a strong lens model. -- [Tutorial 7: Fitting](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_7_fitting.ipynb) — Fitting data with a strong lens model. - -- [Tutorial 8: Summary](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_8_summary.ipynb) — A summary of the chapter. +- [Tutorial 7: Summary](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_7_summary.ipynb) — A summary of the chapter. diff --git a/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb b/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb index 6e74ea9..514a1e4 100644 --- a/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb @@ -33,8 +33,8 @@ "![The COSMOS-Web Ring, labelled with the lens galaxy, lensed source galaxy and extra galaxy](https://raw.githubusercontent.com/PyAutoLabs/autolens_assistant/main/docs/images/cosmos_web_ring_rgb_labelled.png)\n", "\n", "The extra galaxy labelled in both figures is distinct from the main lens and\n", - "lensed source. As in the previous tutorial, we leave systems with additional\n", - "galaxies until Chapter 4 and use one lens galaxy and one source galaxy here.\n", + "lensed source. We begin with one lens and one source, then add more galaxies\n", + "at the end of this tutorial.\n", "\n", "These figures are also used in the [COSMOS-Web Ring guided example](https://github.com/PyAutoLabs/autolens_assistant/blob/main/docs/colab/cosmos_web_ring_colab.py).\n", "\n", @@ -57,9 +57,9 @@ "perpendicular to our line of sight, at the respective distances of the lens\n", "and source. They do not describe the orientations of the galaxies themselves.\n", "\n", - "In this tutorial, we use one foreground lens galaxy and one background source\n", - "galaxy. We will first trace the rays ourselves using grids, then use a `Tracer`\n", - "to perform the same calculation for us.\n", + "We will first trace the rays ourselves using grids, then use a `Tracer`\n", + "to perform the same calculation for us. Finally, we will extend the tracer\n", + "to include two lens galaxies and two source galaxies.\n", "\n", "The resulting **lensed image** shows how the foreground galaxy's gravity\n", "distorts the appearance of the source.\n", @@ -73,6 +73,9 @@ "- **Ray Tracing Images:** Evaluate the source's light profile on the ray-traced grid.\n", "- **Galaxies:** Combine light and mass profiles into lens and source galaxies.\n", "- **Tracer:** Perform the ray-tracing calculation using a `Tracer`.\n", + "- **Units:** Convert angular sizes into physical sizes using redshifts and a cosmology.\n", + "- **More Complexity:** Add lens light, elliptical mass, external shear and additional galaxies.\n", + "- **Multi Galaxy Ray Tracing:** Combine two lens galaxies and two sources in one tracer.\n", "- **Wrap Up:** Review what we have learned and the next steps.\n", "- **Env:** Preserve the grid used by the mapping example." ] @@ -959,31 +962,381 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Units__\n", + "\n", + "Throughout this tutorial, we have measured positions and radii in\n", + "arcseconds: angles on the sky. What physical size does an angle\n", + "of one arcsecond represent?\n", + "\n", + "That depends on the distance to the galaxy. We express galaxy\n", + "sizes in kiloparsecs, where one kiloparsec is 1,000 parsecs,\n", + "or approximately 3,260 light-years.\n", + "\n", + "To convert an angular size into a physical size, we use the\n", + "galaxy's redshift and a cosmology: a model of the Universe's\n", + "expansion that relates redshifts to distances.\n", + "\n", + "Our tracer already has a cosmology. Unless we supply another,\n", + "it uses the Planck 2015 cosmology.\n", + "\n", + "Let's calculate how many kiloparsecs correspond to one arcsecond\n", + "at the redshifts of our lens and source." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "cosmology = tracer.cosmology\n", + "\n", + "kpc_per_arcsec_lens = cosmology.kpc_per_arcsec_from(\n", + " redshift=lens_galaxy.redshift\n", + ")\n", + "kpc_per_arcsec_source = cosmology.kpc_per_arcsec_from(\n", + " redshift=source_galaxy.redshift\n", + ")\n", + "\n", + "print(\n", + " f\"Lens plane: {kpc_per_arcsec_lens:.3f} kpc per arcsecond\"\n", + ")\n", + "print(\n", + " f\"Source plane: {kpc_per_arcsec_source:.3f} kpc per arcsecond\"\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The conversion differs between the two planes because the\n", + "galaxies are at different distances.\n", + "\n", + "For example, we can multiply the lens's Einstein radius in\n", + "arcseconds by the lens-plane conversion to express it in\n", + "kiloparsecs." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "einstein_radius_kpc = (\n", + " sis_mass_profile.einstein_radius * kpc_per_arcsec_lens\n", + ")\n", + "\n", + "print(f\"Einstein radius: {einstein_radius_kpc:.3f} kpc\")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For a source galaxy's physical size, we use the source-plane\n", + "conversion instead.\n", + "\n", + "We will continue to calculate and plot coordinates in arcseconds.\n", + "These conversion factors let us express our model's sizes in\n", + "physical units when needed.\n", + "\n", + "Tutorial 3 explains the cosmological distances behind this\n", + "conversion, as part of its optional mathematical discussion." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__More Complexity__\n", + "\n", + "Our tracer currently contains one spherical lens and one source.\n", + "Let's extend this to a system with two lens galaxies and two\n", + "source galaxies.\n", + "\n", + "We first add a light profile to the main lens, representing its\n", + "central concentration of stars, or bulge. This light contributes\n", + "to the observed image. The separate mass profile determines\n", + "how the galaxy deflects light.\n", + "\n", + "We also replace the spherical mass profile with an elliptical\n", + "one. Its projected mass contours are now ellipses, so the\n", + "deflection pattern is no longer rotationally symmetric.\n", + "\n", + "Finally, we add an external shear. Surrounding matter can\n", + "distort the lensed images even when we do not model each\n", + "neighbouring structure individually. External shear approximates\n", + "this effect as a directional stretching across the image.\n", + "\n", + "Shear treats two perpendicular directions differently, so it\n", + "can turn a small circular source into an elongated image.\n", + "The main lens produces shear too; \"external\" describes the\n", + "additional contribution from its surroundings.\n", + "\n", + "We represent this contribution with a `MassField` at the lens\n", + "redshift. Its two dimensionless components, `gamma_1` and\n", + "`gamma_2`, specify its strength and orientation. The field\n", + "contributes deflections but no light." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "lens_galaxy = al.Galaxy(\n", + " redshift=0.5,\n", + " bulge=al.lp.SersicSph(\n", + " centre=(0.0, 0.0),\n", + " intensity=2.0,\n", + " effective_radius=0.5,\n", + " sersic_index=2.5,\n", + " ),\n", + " mass=al.mp.Isothermal(\n", + " centre=(0.0, 0.0),\n", + " ell_comps=(0.0, -0.111111),\n", + " einstein_radius=1.6,\n", + " ),\n", + ")\n", + "\n", + "field = al.MassField(\n", + " redshift=0.5,\n", + " shear=al.mp.ExternalShear(\n", + " gamma_1=0.05,\n", + " gamma_2=0.0,\n", + " ),\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let's add a smaller companion, or satellite galaxy, at the same\n", + "redshift as the main lens.\n", + "\n", + "Its centre is at (1.0, 0.0) arcseconds, placing it one arcsecond\n", + "from the main lens along the y direction. It has both a light\n", + "profile and a mass profile, so it contributes visible light\n", + "and additional deflections.\n", + "\n", + "Its Einstein-radius parameter is 0.4 arcseconds, compared with\n", + "1.6 arcseconds for the main lens. This gives it a smaller lensing\n", + "strength, although its effect can still matter for images\n", + "passing close to it.\n", + "\n", + "Unlike the external shear, this galaxy is represented explicitly:\n", + "we specify where it is and how its light and mass are distributed." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "lens_satellite = al.Galaxy(\n", + " redshift=0.5,\n", + " bulge=al.lp.DevVaucouleursSph(\n", + " centre=(1.0, 0.0),\n", + " intensity=2.0,\n", + " effective_radius=0.2,\n", + " ),\n", + " mass=al.mp.IsothermalSph(\n", + " centre=(1.0, 0.0),\n", + " einstein_radius=0.4,\n", + " ),\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We also create two source galaxies at redshift 1.0.\n", + "\n", + "The first has two light components: a compact bulge and a more\n", + "extended disk. Both share the same centre, so their light adds\n", + "together to describe one galaxy. The second source has only a\n", + "disk and lies at a different source-plane position.\n", + "\n", + "Names such as `bulge` and `disk` help us describe the components.\n", + "The chosen light profiles and their parameters determine the\n", + "actual brightness distribution.\n", + "\n", + "Because both sources have the same redshift, they occupy the\n", + "same source plane. Adding a galaxy does not necessarily add\n", + "another plane." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "source_0 = al.Galaxy(\n", + " redshift=1.0,\n", + " bulge=al.lp.DevVaucouleursSph(\n", + " centre=(0.1, 0.2),\n", + " intensity=0.3,\n", + " effective_radius=0.3,\n", + " ),\n", + " disk=al.lp.ExponentialCore(\n", + " centre=(0.1, 0.2),\n", + " ell_comps=(0.111111, 0.0),\n", + " intensity=3.0,\n", + " effective_radius=2.0,\n", + " ),\n", + ")\n", + "\n", + "source_1 = al.Galaxy(\n", + " redshift=1.0,\n", + " disk=al.lp.ExponentialCore(\n", + " centre=(-0.3, -0.5),\n", + " ell_comps=(0.1, 0.0),\n", + " intensity=8.0,\n", + " effective_radius=1.0,\n", + " ),\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Multi Galaxy Ray Tracing__\n", + "\n", + "We now pass our four galaxies and external shear to a tracer.\n", + "\n", + "The main lens and its satellite share redshift 0.5, while both\n", + "sources share redshift 1.0. The tracer therefore groups the\n", + "galaxies into two planes, with two galaxies in each.\n", + "\n", + "To calculate the image, the tracer follows the same steps\n", + "we used earlier:\n", + "\n", + "1. Evaluate the light of both foreground galaxies on the\n", + " image-plane grid.\n", + "\n", + "2. Add the deflections from the main lens, its satellite\n", + " and the external shear.\n", + "\n", + "3. Subtract these total deflections from the image-plane\n", + " coordinates to obtain the source-plane coordinates.\n", + "\n", + "4. Evaluate both source galaxies' light at those traced\n", + " coordinates and add their contributions.\n", + "\n", + "5. Add the foreground light to the lensed source light\n", + " to form the complete image.\n", + "\n", + "The next plot shows the combined image. It contains the\n", + "foreground galaxies as well as the distorted images of\n", + "the two sources." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "tracer = al.Tracer(\n", + " galaxies=[\n", + " lens_galaxy,\n", + " lens_satellite,\n", + " source_0,\n", + " source_1,\n", + " ],\n", + " fields=[field],\n", + " cosmology=cosmology,\n", + ")\n", + "\n", + "image = tracer.image_2d_from(grid=image_plane_grid)\n", + "\n", + "aplt.plot_array(\n", + " array=image,\n", + " title=\"Two Lens Galaxies and Two Sources\",\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let's separate the views using the tracer subplot.\n", + "\n", + "The lens-light panel shows the main lens and satellite.\n", + "The source-plane panel shows both sources before lensing,\n", + "while the full image combines foreground light with the\n", + "lensed source images.\n", + "\n", + "To see the satellite's effect, remove `lens_satellite` from\n", + "the tracer's galaxy list and rerun the image and subplot\n", + "cells. Its light disappears, and the source images change\n", + "because its deflections are also removed.\n", + "\n", + "Restore it to the list and rerun those cells to return\n", + "to the original system.\n", + "\n", + "**\ud83e\udd16 Ask AI:** In this example, how could I distinguish the\n", + "satellite galaxy's contribution to the observed light from\n", + "its effect on the lensed source images?" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "aplt.subplot_tracer(\n", + " tracer=tracer,\n", + " grid=image_plane_grid,\n", + ")" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Wrap Up__\n", "\n", - "In this tutorial, we built a lensed image step by step:\n", - "\n", - "- A **mass profile** describes the lens galaxy's mass distribution\n", - " and lets us calculate its deflection angles.\n", - "- The **lens equation**, $\\beta = \\theta - \\alpha(\\theta)$, maps\n", - " image-plane coordinates to source-plane coordinates.\n", - "- Evaluating a source **light profile** at those mapped coordinates\n", - " gives the brightness of each pixel in the lensed image.\n", - "- **Galaxy** objects hold the profiles and redshifts of the lens\n", - " and source.\n", - "- A **Tracer** brings these galaxies together and performs the\n", - " calculation for us.\n", - "\n", - "The manual calculation and the `Tracer` describe the same lens\n", - "system. Working through both shows what happens when we ask a\n", - "tracer to calculate an image.\n", - "\n", - "In Tutorial 3, we will build on this example and explore more\n", - "of the ray-tracing calculation." + "We began by building a lensed image step by step: calculate\n", + "deflections, trace coordinates with the lens equation, and\n", + "evaluate the source's light at those coordinates.\n", + "\n", + "A `Tracer` performs these steps for us. It also lets us extend\n", + "the same calculation to several galaxies, combining their\n", + "light and accounting for their mass.\n", + "\n", + "We have now built a system with two foreground galaxies,\n", + "two sources and an external shear. The underlying idea is\n", + "still the same coordinate mapping we started with.\n", + "\n", + "We also used galaxy redshifts and a cosmology to connect\n", + "angular sizes in arcseconds to physical sizes in kiloparsecs.\n", + "\n", + "Tutorial 3 explains the mathematics behind these calculations,\n", + "including convergence, shear, magnification, critical curves\n", + "and caustics. You can follow its physical explanations and\n", + "figures without working through every equation, and return\n", + "to the mathematics when you need it." ] } ], diff --git a/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb b/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb index e3e3015..c47d917 100644 --- a/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb @@ -5,39 +5,45 @@ "metadata": {}, "source": [ "Tutorial 3: More Ray Tracing\n", - "============================\n", + "===========================\n", "\n", - "We'll now reinforce the ideas that we learnt about ray-tracing in the previous tutorial and introduce the following\n", - "new concepts:\n", + "In tutorial 2, we used the lens equation to trace coordinates from\n", + "the image plane to the source plane and build an image of a\n", + "strong lens.\n", "\n", - "- What critical curves and caustics are.\n", - " - That by specifying redshifts and a cosmology, the results are converted from arc-second coordinates to physical\n", - " units of kiloparsecs (kpc). Again, if you're not an Astronomer, you may not be familiar with the unit of parsec, it\n", - " may be worth a quick Google!\n", - " - That a `Tracer` can be given any number of galaxies.\n", + "We will now connect that picture to the quantities used to describe\n", + "gravitational lensing: convergence, deflection angles, potential,\n", + "shear and magnification. We will also explain critical curves and\n", + "caustics, the Einstein radius and time delays.\n", "\n", - "Up to now, the planes have also had just one lens galaxy or source galaxy at a time. In this example, the tracer will\n", - "have multiple galaxies at each redshift, meaning that each plane has more than one galaxy. In terms of lensing\n", - "calculations:\n", + "This tutorial includes the mathematics behind these ideas, but\n", + "following every equation is optional. You can do strong-lensing\n", + "science with a physical understanding of how mass bends light,\n", + "changes image shapes and produces multiple images. PyAutoLens\n", + "performs the calculations; your job is to understand what your\n", + "model represents and what the observations can tell you.\n", "\n", - "- If two or more lens galaxies are at the same redshift in the image-plane, the convergences, potentials and\n", - "deflection angles of their mass profiles are summed when performing lensing calculations.\n", + "Each mathematical section therefore explains the idea in words\n", + "and connects it to code or a figure. On a first pass, you can focus\n", + "on those explanations and outputs, then return to the equations\n", + "when you want to understand a calculation in more detail.\n", "\n", - "- If two or more source galaxies are at the same redshift in the source-plane, their light can simply be summed before\n", - "ray tracing.\n", - "\n", - "The `Tracer` fully accounts for this.\n", + "We assume you are familiar with the lens equation from tutorial 2.\n", "\n", "__Contents__\n", "\n", - "- **Initial Setup:** To begin, lets setup the grid we'll ray-trace using.\n", - "- **Concise Code:** Lets set up the tracer used in the previous tutorial.\n", - "- **Critical Curves:** We can finally explain what the black lines that have appeared on many of the plots.\n", - "- **Caustics:** In the previous tutorial, we plotted the critical curves of the mass profile on the image-plane.\n", - "- **Units:** Lets plot the lensing quantities again.\n", - "- **More Complexity:** We now make a lens with some attributes we didn`t in the last tutorial.\n", - "- **Multi Galaxy Ray Tracing:** Now lets pass our 4 galaxies to a `Tracer`, which means the following will occur.\n", - "- **Wrap Up:** Summary of the script and next steps." + "- **Initial Setup:** Create the image-plane grid.\n", + "- **Concise Code:** Build a familiar lens and source in fewer steps.\n", + "- **Cosmological Distances:** Define the distances used in lensing.\n", + "- **Convergence:** Express projected mass as a dimensionless density.\n", + "- **Deflection Angles:** Relate the mass distribution to ray tracing.\n", + "- **The Lensing Potential:** Connect deflections and convergence through a scalar field.\n", + "- **Shear and Magnification:** Describe changes in image shape, area and total brightness.\n", + "- **Critical Curves and Caustics:** Locate strong stretching and its source-plane counterpart.\n", + "- **Einstein Radius:** Connect the scale of a strong lens to its enclosed projected mass.\n", + "- **Time Delays:** Explain why different images arrive at different times.\n", + "- **Wrap Up:** Review the physical meaning of the lensing quantities.\n", + "- **Env:** Preserve the grid used to resolve the critical curves." ] }, { @@ -87,7 +93,9 @@ "\n", "from autolens import setup_notebook; setup_notebook()\n", "\n", + "import matplotlib.pyplot as plt\n", "import numpy as np\n", + "import autoarray as aa\n", "import autolens as al\n", "import autolens.plot as aplt" ], @@ -100,32 +108,24 @@ "source": [ "__Initial Setup__\n", "\n", - "To begin, lets setup the grid we'll ray-trace using. But, lets do something crazy and use a higher resolution than \n", - "the previous tutorials!\n", + "We begin with a grid of 250 by 250 image-plane coordinates,\n", + "separated by 0.02 arcseconds. It covers a field 5 arcseconds across\n", + "and samples the lens more finely than the grids used earlier.\n", "\n", - "Lets also stop calling it the `image_plane_grid`, and just remember from now on our `grid` is in the image-plane." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "grid = al.Grid2D.uniform(shape_native=(250, 250), pixel_scales=0.02)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The grid is now shape 250 x 250, which has more image-pixels than the 100 x 100 grid used previously." + "We will call it `grid` from now on. Unless we explicitly trace it\n", + "to another plane, its coordinates are in the image plane.\n", + "\n", + "The two printed shapes show the grid's arrangement and its total\n", + "number of coordinates." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", + "grid = al.Grid2D.uniform(shape_native=(250, 250), pixel_scales=0.02)\n", + "\n", "print(grid.shape_native)\n", "print(grid.shape_slim)" ], @@ -138,19 +138,26 @@ "source": [ "__Concise Code__\n", "\n", - "Lets set up the tracer used in the previous tutorial.\n", + "Let's build a lens and source using the same approach as tutorial 2.\n", + "We can define each profile directly inside its galaxy, keeping the\n", + "whole system together in a short block of code.\n", "\n", - "Up to now, we have set up each profile one line at a time, making the code long and cumbersome to read.\n", + "The lens has a spherical isothermal mass profile at redshift 0.5.\n", + "The source has a spherical light profile at redshift 1.0 and is\n", + "centred behind the lens.\n", "\n", - "From here on, we'll set up galaxies in a single block of code, making it more concise and readable." + "We will use this tracer throughout the mathematical sections,\n", + "with the same default cosmology as tutorial 2." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "lens = al.Galaxy(\n", - " redshift=0.5, mass=al.mp.IsothermalSph(centre=(0.0, 0.0), einstein_radius=1.6)\n", + " redshift=0.5,\n", + " mass=al.mp.IsothermalSph(centre=(0.0, 0.0), einstein_radius=1.6),\n", ")\n", "\n", "source = al.Galaxy(\n", @@ -164,7 +171,10 @@ " ),\n", ")\n", "\n", - "tracer = al.Tracer(galaxies=[lens, source])" + "tracer = al.Tracer(galaxies=[lens, source])\n", + "mass_profile = lens.mass\n", + "cosmology = tracer.cosmology\n", + "lens_calc = al.LensCalc.from_tracer(tracer=tracer)" ], "outputs": [], "execution_count": null @@ -173,40 +183,50 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Critical Curves__\n", + "__Cosmological Distances__\n", + "\n", + "In tutorial 2, we converted angular sizes into kiloparsecs.\n", + "The distance used in that conversion is called the\n", + "**angular diameter distance**.\n", "\n", - "We can finally explain what the black lines that have appeared on many of the plots throughout this chapter\n", - "actually are.\n", + "It relates an object's physical size, $l$, perpendicular to our\n", + "line of sight to its angular size, $\\theta$:\n", "\n", - "These lines are called the 'critical curves', and they define line of infinite magnification due to a mass profile. \n", - "They therefore mark where in the image-plane a mass profile perfectly `focuses` light rays such that if a source is \n", - "located there, it will appear very bright: potentially 10-100x as brighter than its intrinsic luminosity.\n", + "$$\n", + "l = D\\,\\theta.\n", + "$$\n", "\n", - "The outer white line is a `tangential_critical_curve`, because it describes how the image of the source galaxy is stretched\n", - "tangentially. There is also an inner `radial_critical_curve` which appears in yellow on figures, which describes how the \n", - "image of the source galaxy is stretched radially. \n", + "Here $D$ is the angular diameter distance and $\\theta$ must be\n", + "expressed in radians.\n", "\n", - "However, a radial critical curve only appears when the lens galaxy's mass profile is shallower than isothermal (e.g. \n", - "when its inner mass slope is less steep than a steep power-law). To make it appear below, we therefore change\n", - "the mass profile of our lens galaxy to a `PowerLawSph` with a slope of 1.8.\n", + "Three angular diameter distances describe the geometry of our\n", + "lens system:\n", "\n", - "In the next section, we'll introduce 'caustics', which are where the critical curves map to in the source-plane." + "- $D_l$: from the observer to the lens.\n", + "- $D_s$: from the observer to the source.\n", + "- $D_{ls}$: from the lens to the source.\n", + "\n", + "These distances account for the expansion of the Universe.\n", + "In general, $D_{ls}$ is not equal to $D_s - D_l$.\n", + "\n", + "The cosmology calculates each distance from the relevant\n", + "redshifts. The values below are in kiloparsecs." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "mass_profile = al.mp.PowerLawSph(centre=(0.0, 0.0), einstein_radius=1.6, slope=1.8)\n", "\n", - "lens = al.Galaxy(redshift=0.5, mass=mass_profile)\n", + "D_l = cosmology.angular_diameter_distance_to_earth_in_kpc_from(redshift=0.5)\n", + "D_s = cosmology.angular_diameter_distance_to_earth_in_kpc_from(redshift=1.0)\n", + "D_ls = cosmology.angular_diameter_distance_between_redshifts_in_kpc_from(\n", + " redshift_0=0.5, redshift_1=1.0\n", + ")\n", "\n", - "tangential_critical_curve_list = al.LensCalc.from_mass_obj(\n", - " mass_obj=mass_profile\n", - ").tangential_critical_curve_list_from(grid=grid)\n", - "radial_critical_curves_list = al.LensCalc.from_mass_obj(\n", - " mass_obj=mass_profile\n", - ").radial_critical_curve_list_from(grid=grid)\n" + "print(f\"Observer to lens: {D_l:.3e} kpc\")\n", + "print(f\"Observer to source: {D_s:.3e} kpc\")\n", + "print(f\"Lens to source: {D_ls:.3e} kpc\")" ], "outputs": [], "execution_count": null @@ -215,56 +235,178 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Caustics__\n", + "One radian contains approximately 206,265 arcseconds. The\n", + "conversion used in tutorial 2 therefore follows directly:\n", + "\n", + "$$\n", + "l\\;[\\mathrm{kpc}]\n", + "=\n", + "\\frac{D\\;[\\mathrm{kpc}]}{206265}\n", + "\\,\\theta\\;[\\mathrm{arcsec}].\n", + "$$\n", + "\n", + "For a lens-plane size we use $D_l$; for a source-plane size\n", + "we use $D_s$. The third distance, $D_{ls}$, enters the lensing\n", + "strength through the geometry between the lens and source.\n", + "\n", + "The physical deflection angle, $\\hat{\\boldsymbol{\\alpha}}$,\n", + "describes how much the light ray bends as it passes the lens.\n", + "The displacement used in our lens equation also accounts for\n", + "the distances between observer, lens and source:\n", + "$\\boldsymbol{\\alpha} = (D_{ls}/D_s)\\hat{\\boldsymbol{\\alpha}}$.\n", + "This is called the **reduced deflection angle**.\n", + "\n", + "The deflections returned by PyAutoLens are these reduced angles,\n", + "expressed in arcseconds. They are the displacement we subtract\n", + "from an image-plane position to obtain its source-plane position,\n", + "as we did in tutorial 2. We will continue to call them\n", + "\"deflection angles\" throughout this tutorial." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Convergence__\n", + "\n", + "Imagine adding up the lens galaxy's mass along our line of sight.\n", + "The result is its **surface mass density**, $\\Sigma$: mass per\n", + "unit area projected onto the lens plane.\n", + "\n", + "For a galaxy-scale lens, we usually treat the deflection as\n", + "occurring in one thin plane. Within this approximation, this\n", + "projected distribution describes how the galaxy's mass bends\n", + "the light.\n", + "\n", + "The same projected mass distribution has a different lensing\n", + "strength for different lens and source distances. We account\n", + "for that geometry using the **critical surface density**:\n", + "\n", + "$$\n", + "\\Sigma_{\\mathrm{cr}}\n", + "=\n", + "\\frac{c^2}{4\\pi G}\n", + "\\frac{D_s}{D_l D_{ls}},\n", + "$$\n", + "\n", + "where $c$ is the speed of light and $G$ is Newton's gravitational\n", + "constant.\n", + "\n", + "Dividing the surface mass density by this reference value gives\n", + "the **convergence**:\n", + "\n", + "$$\n", + "\\kappa(\\boldsymbol{\\theta})\n", + "=\n", + "\\frac{\\Sigma(\\boldsymbol{\\theta})}{\\Sigma_{\\mathrm{cr}}}.\n", + "$$\n", + "\n", + "Convergence is therefore dimensionless. A value of 0.5 means\n", + "that the local surface mass density is half the critical\n", + "surface density for this lens and source geometry.\n", + "\n", + "Let's calculate the critical surface density in solar masses\n", + "per square kiloparsec, then plot our lens's convergence." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ "\n", - "In the previous section, we plotted the critical curves of the mass profile on the image-plane. We will now plot the\n", - "'caustics', which correspond to each critical curve ray-traced to the source-plane. This is computed by using the \n", - "lens galaxy mass profile's to calculate the deflection angles at the critical curves and ray-trace them to the \n", - "source-plane.\n", + "sigma_cr_kpc = (\n", + " cosmology.critical_surface_density_between_redshifts_solar_mass_per_kpc2_from(\n", + " redshift_0=0.5, redshift_1=1.0\n", + " )\n", + ")\n", "\n", - "As discussed in the previous section, critical curves mark regions of infinite magnification. Thus, if a source\n", - "appears near a caustic in the source plane it will appear significantly brighter than its true luminosity. \n", + "print(\n", + " \"Critical surface density: \"\n", + " f\"{sigma_cr_kpc:.3e} solar masses per square kiloparsec\"\n", + ")\n", "\n", - "We again have to use a mass profile with a slope below 2.0 to ensure a radial critical curve and therefore radial\n", - "caustic is formed. As above, the tangential critical curve is white and maps to the tangential caustic in the source-plane,\n", - "which is also white. The radial critical curve is yellow and maps to the radial caustic, which is also yellow.\n", + "convergence = tracer.convergence_2d_from(grid=grid)\n", "\n", - "We can plot both the tangential and radial critical curves and caustics using the `lines=`/`positions=` overlays object. The \n", - "critical curves are plotted only for the image-plane grid, whereas the caustic in the source plane." + "aplt.plot_array(array=convergence, title=\"Convergence\", use_log10=True, cb_unit=\"\")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The convergence is largest near the centre and decreases\n", + "outwards, following the projected mass distribution of our\n", + "isothermal lens.\n", + "\n", + "Convergence values of order one indicate surface densities\n", + "relevant to strong lensing. For a circular lens, the Einstein\n", + "radius encloses a region whose **mean convergence** is one:\n", + "the average surface mass density inside it equals\n", + "$\\Sigma_{\\mathrm{cr}}$.\n", + "\n", + "This is an average over the enclosed area, rather than the\n", + "convergence at its edge. We will return to this connection\n", + "when we use the Einstein radius to measure the lens's mass." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Deflection Angles__\n", + "\n", + "The convergence describes the projected mass distribution.\n", + "To calculate a ray's deflection, we add the contributions\n", + "from mass across the lens plane:\n", + "\n", + "$$\n", + "\\boldsymbol{\\alpha}(\\boldsymbol{\\theta})\n", + "=\n", + "\\frac{1}{\\pi}\n", + "\\int\n", + "\\kappa(\\boldsymbol{\\theta}')\n", + "\\frac{\\boldsymbol{\\theta}-\\boldsymbol{\\theta}'}\n", + "{|\\boldsymbol{\\theta}-\\boldsymbol{\\theta}'|^2}\n", + "\\,d^2\\boldsymbol{\\theta}'.\n", + "$$\n", + "\n", + "Here $\\boldsymbol{\\theta}$ is the position where we want the\n", + "deflection, while $\\boldsymbol{\\theta}'$ runs over the mass\n", + "distribution. The integral adds the contribution from each\n", + "small patch of projected mass.\n", + "\n", + "The deflection therefore depends on more than the mass at\n", + "the ray's position. Surrounding mass contributes too, which\n", + "is why the satellite galaxy and external shear in tutorial 2\n", + "could change the source images.\n", + "\n", + "For our spherical isothermal profile, this integral has an\n", + "analytic solution. PyAutoLens evaluates that solution when\n", + "we call `deflections_yx_2d_from`; other profiles may use\n", + "numerical calculations.\n", + "\n", + "Let's plot the two components of the reduced deflection angle,\n", + "in arcseconds, as we did in tutorial 2." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "sis_mass_profile = al.mp.IsothermalSph(centre=(0.0, 0.0), einstein_radius=1.6)\n", "\n", - "tracer = al.Tracer(galaxies=[lens, source])\n", - "\n", - "tangential_critical_curve_list = al.LensCalc.from_tracer(\n", - " tracer=tracer\n", - ").tangential_critical_curve_list_from(grid=grid)\n", - "radial_critical_curves_list = al.LensCalc.from_tracer(\n", - " tracer=tracer\n", - ").radial_critical_curve_list_from(grid=grid)\n", + "deflections = tracer.deflections_yx_2d_from(grid=grid)\n", "\n", + "deflections_y = aa.Array2D(values=deflections.slim[:, 0], mask=grid.mask)\n", + "deflections_x = aa.Array2D(values=deflections.slim[:, 1], mask=grid.mask)\n", "\n", - "traced_grid_list = tracer.traced_grid_2d_list_from(grid=grid)\n", - "source_plane_grid = np.asarray(traced_grid_list[1])\n", - "source_plane_grid = source_plane_grid[np.isfinite(source_plane_grid).all(axis=1)]\n", - "\n", - "aplt.plot_grid(grid=traced_grid_list[0], title=\"Plane 0 Grid\")\n", - "aplt.plot_grid(\n", - " grid=al.Grid2DIrregular(values=source_plane_grid),\n", - " title=\"Plane 1 Grid\",\n", + "aplt.plot_array(\n", + " array=deflections_y, title=\"Deflection Angles (y component)\", cb_unit=\" arcsec\"\n", ")\n", - "\n", - "tangential_caustic_list = al.LensCalc.from_tracer(\n", - " tracer=tracer\n", - ").tangential_caustic_list_from(grid=grid)\n", - "radial_caustics_list = al.LensCalc.from_tracer(tracer=tracer).radial_caustic_list_from(\n", - " grid=grid\n", - ")\n" + "aplt.plot_array(\n", + " array=deflections_x, title=\"Deflection Angles (x component)\", cb_unit=\" arcsec\"\n", + ")" ], "outputs": [], "execution_count": null @@ -273,14 +415,66 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can also plot the caustic on the source-plane image." + "Each component changes sign across the lens centre. Together,\n", + "they describe the displacement we subtract from each\n", + "image-plane coordinate when tracing it to the source plane." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__The Lensing Potential__\n", + "\n", + "We can describe the same lens using a single scalar field:\n", + "the **lensing potential**, $\\psi$.\n", + "\n", + "Its gradient gives the deflection angles:\n", + "\n", + "$$\n", + "\\boldsymbol{\\alpha} = \\nabla\\psi.\n", + "$$\n", + "\n", + "A gradient describes how a quantity changes with position.\n", + "Here, the change in potential along the y direction gives\n", + "the y deflection, and the change along x gives the x deflection.\n", + "\n", + "The convergence is related to the potential's second\n", + "derivatives:\n", + "\n", + "$$\n", + "\\kappa\n", + "=\n", + "\\frac{1}{2}\\nabla^2\\psi\n", + "=\n", + "\\frac{1}{2}\n", + "\\left(\n", + "\\frac{\\partial^2\\psi}{\\partial\\theta_y^2}\n", + "+\n", + "\\frac{\\partial^2\\psi}{\\partial\\theta_x^2}\n", + "\\right).\n", + "$$\n", + "\n", + "The symbol $\\nabla^2$, called the Laplacian, means adding\n", + "these two second derivatives. This relation is the\n", + "two-dimensional Poisson equation for gravitational lensing.\n", + "\n", + "We can therefore describe the projected mass through\n", + "convergence, or describe its lensing effect through the\n", + "potential. Their spatial derivatives connect the two.\n", + "\n", + "Let's plot the potential of our lens. With coordinates and\n", + "deflections in arcseconds, its units are arcseconds squared." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "aplt.plot_array(array=tracer.image_2d_list_from(grid=grid)[1], title=\"Plane 1 Image\")" + "\n", + "potential = tracer.potential_2d_from(grid=grid)\n", + "\n", + "aplt.plot_array(array=potential, title=\"Lensing Potential\", cb_unit=r\" arcsec$^2$\")" ], "outputs": [], "execution_count": null @@ -289,28 +483,125 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Caustics also mark the regions in the source-plane where the multiplicity of the strong lens changes. Each time\n", - "a source crosses a caustic, the number of images it produces changes by two. Try and show this yourself by changing\n", - "the (y,x) centre of the source-plane galaxy's light profile!" + "For this spherical lens, the potential has circular contours.\n", + "Its slope points radially outwards, matching the direction\n", + "of the deflection vectors used in our lens equation." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can check $\\boldsymbol{\\alpha} = \\nabla\\psi$ directly.\n", + "\n", + "First, we calculate the deflections using the mass profile's\n", + "analytic expression. Then we estimate them from changes in\n", + "the potential between neighbouring grid points.\n", + "\n", + "The two calculations should agree closely over most of the\n", + "grid. Numerical differentiation is less accurate near the\n", + "central cusp and at the grid boundaries.\n", + "\n", + "We will plot the magnitude of the difference between the\n", + "two deflection vectors at each grid point, in arcseconds.\n", + "Brighter regions indicate larger differences. We also print\n", + "the median of these magnitudes to summarise the typical\n", + "difference across the grid." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "source = al.Galaxy(\n", - " redshift=1.0,\n", - " light=al.lp.SersicCoreSph(\n", - " centre=(0.0, 0.0),\n", - " intensity=1.0,\n", - " effective_radius=1.0,\n", - " sersic_index=1.0,\n", - " ),\n", + "\n", + "deflections_analytic = mass_profile.deflections_yx_2d_from(grid=grid)\n", + "deflections_via_potential = mass_profile.deflections_2d_via_potential_2d_from(\n", + " grid=grid\n", ")\n", "\n", - "tracer = al.Tracer(galaxies=[lens, source])\n", + "difference_yx = (\n", + " np.asarray(deflections_analytic) - np.asarray(deflections_via_potential)\n", + ")\n", + "\n", + "difference_magnitude = np.sqrt(np.sum(difference_yx**2, axis=1))\n", + "\n", + "difference_map = aa.Array2D(values=difference_magnitude, mask=grid.mask)\n", + "\n", + "aplt.plot_array(\n", + " array=difference_map,\n", + " title=\"Deflection Difference Magnitude (arcseconds)\",\n", + " cb_unit=\" arcsec\",\n", + ")\n", + "\n", + "print(\n", + " \"Median deflection difference magnitude: \"\n", + " f\"{np.median(difference_magnitude):.3e} arcsec\"\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Shear and Magnification__\n", + "\n", + "Nearby rays generally experience slightly different deflections.\n", + "Those differences change an image's shape and size.\n", + "\n", + "To describe this locally, we calculate how each deflection\n", + "component changes with position. Since deflections are\n", + "derivatives of the potential, these are its second derivatives.\n", + "Together they form the **Hessian matrix**:\n", + "\n", + "$$\n", + "H_{ij}\n", + "=\n", + "\\frac{\\partial^2\\psi}\n", + "{\\partial\\theta_i\\,\\partial\\theta_j}.\n", + "$$\n", + "\n", + "The indices $i$ and $j$ each stand for y or x. The diagonal\n", + "entries describe changes along the same coordinate direction;\n", + "the other entries describe changes across the two directions.\n", + "\n", + "Differentiating the lens equation gives the **Jacobian matrix**:\n", + "\n", + "$$\n", + "A\n", + "=\n", + "\\frac{\\partial\\boldsymbol{\\beta}}\n", + "{\\partial\\boldsymbol{\\theta}}\n", + "=\n", + "I-H.\n", + "$$\n", + "\n", + "Here $I$ is the identity matrix. The Jacobian maps a small\n", + "image-plane displacement to a source-plane displacement:\n", + "\n", + "$$\n", + "\\delta\\boldsymbol{\\beta}\n", + "=\n", + "A\\,\\delta\\boldsymbol{\\theta}.\n", + "$$\n", + "\n", + "Its inverse, where it exists, tells us how a small source\n", + "region is stretched into an image.\n", + "\n", + "`LensCalc` calculates the Hessian from the tracer's\n", + "deflection field." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "hessian_yy, hessian_xy, hessian_yx, hessian_xx = lens_calc.hessian_from(grid=grid)\n", "\n", - "aplt.plot_array(array=tracer.image_2d_list_from(grid=grid)[1], title=\"Plane 1 Image\")" + "print(f\"H_yy at the first grid point: {hessian_yy[0]:.4f}\")\n", + "print(f\"H_xx at the first grid point: {hessian_xx[0]:.4f}\")" ], "outputs": [], "execution_count": null @@ -319,12 +610,45 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Units__\n", + "The Hessian separates into two useful contributions.\n", "\n", - "Lets plot the lensing quantities again. However, we'll now use the `Units` object of the **PyAutoLens** plotter module \n", - "to set `in_kpc=True` and therefore plot the y and x axes in kiloparsecs.\n", + "The **convergence** describes the part that acts equally\n", + "in every direction:\n", "\n", - "This conversion is performed automatically, using the galaxy redshifts and cosmology." + "$$\n", + "\\kappa = \\frac{1}{2}(H_{xx}+H_{yy}).\n", + "$$\n", + "\n", + "This is the same convergence we defined from surface mass\n", + "density earlier.\n", + "\n", + "The **shear** describes the directional part of the distortion.\n", + "Its two components are\n", + "\n", + "$$\n", + "\\gamma_1 = \\frac{1}{2}(H_{xx}-H_{yy}),\n", + "\\qquad\n", + "\\gamma_2 = H_{xy},\n", + "$$\n", + "\n", + "with magnitude\n", + "\n", + "$$\n", + "|\\gamma| = \\sqrt{\\gamma_1^2+\\gamma_2^2}.\n", + "$$\n", + "\n", + "These components describe the strength and orientation of\n", + "the distortion. Shear allows a circular source to form an\n", + "elongated image.\n", + "\n", + "In tutorial 2, we added an external shear to represent the\n", + "effect of surrounding matter. Here we calculate the shear\n", + "produced by the lens itself. Even a spherical mass distribution\n", + "produces shear: its symmetry does not mean that radial and\n", + "tangential image stretching are equal.\n", + "\n", + "Let's calculate the shear and print its magnitude at the\n", + "first grid point." ] }, { @@ -332,8 +656,12 @@ "metadata": {}, "source": [ "\n", - "aplt.subplot_tracer(tracer=tracer, grid=grid)\n", - "aplt.subplot_galaxies_images(tracer=tracer, grid=grid)" + "shear = lens_calc.shear_yx_2d_via_hessian_from(grid=grid)\n", + "\n", + "print(\n", + " \"Shear magnitude at the first grid point: \"\n", + " f\"{shear.magnitudes[0]:.4f}\"\n", + ")" ], "outputs": [], "execution_count": null @@ -342,47 +670,90 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "If you're not too familiar with Cosmology, it will be unclear how exactly we converted the distance units from\n", - "arcseconds to kiloparsecs. You'll need to read up on your Cosmology lecture to understand this properly.\n", + "The **magnification**, $\\mu$, describes the change in area\n", + "between a small source region and its image:\n", + "\n", + "$$\n", + "\\mu\n", + "=\n", + "\\frac{1}{\\det A}\n", + "=\n", + "\\frac{1}{(1-\\kappa)^2-|\\gamma|^2}.\n", + "$$\n", + "\n", + "Its absolute value gives the area ratio. Lensing preserves\n", + "surface brightness, so increasing the area also increases\n", + "the total light received from that source region.\n", + "\n", + "- $|\\mu| > 1$: the image region is magnified.\n", + "- $|\\mu| < 1$: it is demagnified.\n", + "- $\\mu < 0$: its orientation is reversed, like a reflection.\n", + "\n", + "Magnification varies across an extended source, so its total\n", + "brightness depends on the combined contributions from its\n", + "different regions.\n", + "\n", + "Let's plot the signed magnification across the image plane.\n", + "Look for the circular region where its magnitude becomes\n", + "large and its sign changes." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "magnification = lens_calc.magnification_2d_from(grid=grid)\n", + "\n", + "aplt.plot_array(\n", + " array=magnification,\n", + " title=\"Magnification\",\n", + " cb_unit=\"\",\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For our spherical lens, we can separate the stretching into\n", + "two directions: tangentially around the lens centre and\n", + "radially towards or away from it.\n", + "\n", + "The corresponding eigenvalues of the Jacobian are\n", "\n", - "You can create a `Cosmology` object, which provides many methods for calculation different cosmological quantities, \n", - "which are shown below (if you're not too familiar with cosmology don't worry that you don't know what these mean, \n", - "it isn't massively important for using **PyAutoLens**).\n", + "$$\n", + "\\lambda_t = 1-\\kappa-|\\gamma|,\n", + "\\qquad\n", + "\\lambda_r = 1-\\kappa+|\\gamma|.\n", + "$$\n", "\n", - "We will use a flat lambda CDM cosmology, which is the standard cosmological model often assumed in scientific studies." + "The image stretches by factors $1/|\\lambda_t|$ and\n", + "$1/|\\lambda_r|$ along these directions. Their product gives\n", + "the absolute magnification.\n", + "\n", + "When an eigenvalue approaches zero, the stretching in its\n", + "direction becomes very large. This is how long, thin arcs\n", + "can form." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "cosmology = al.cosmo.FlatLambdaCDM(H0=70, Om0=0.3)\n", - "\n", - "print(\"Image-plane arcsec-per-kpc:\")\n", - "print(cosmology.arcsec_per_kpc_from(redshift=0.5))\n", - "print(\"Image-plane kpc-per-arcsec:\")\n", - "print(cosmology.kpc_per_arcsec_from(redshift=0.5))\n", - "print(\"Angular Diameter Distance to Image-plane (kpc):\")\n", - "print(cosmology.angular_diameter_distance_to_earth_in_kpc_from(redshift=0.5))\n", "\n", - "print(\"Source-plane arcsec-per-kpc:\")\n", - "print(cosmology.arcsec_per_kpc_from(redshift=1.0))\n", - "print(\"Source-plane kpc-per-arcsec:\")\n", - "print(cosmology.kpc_per_arcsec_from(redshift=1.0))\n", - "print(\"Angular Diameter Distance to Source-plane:\")\n", - "print(cosmology.angular_diameter_distance_to_earth_in_kpc_from(redshift=1.0))\n", + "tangential_eigen_values = lens_calc.tangential_eigen_value_from(grid=grid)\n", + "radial_eigen_values = lens_calc.radial_eigen_value_from(grid=grid)\n", "\n", - "print(\"Angular Diameter Distance From Image To Source Plane:\")\n", "print(\n", - " cosmology.angular_diameter_distance_between_redshifts_in_kpc_from(\n", - " redshift_0=0.5, redshift_1=1.0\n", - " )\n", + " \"Tangential eigenvalue at the first grid point: \"\n", + " f\"{tangential_eigen_values[0]:.4f}\"\n", ")\n", - "print(\"Lensing Critical convergence:\")\n", "print(\n", - " cosmology.critical_surface_density_between_redshifts_solar_mass_per_kpc2_from(\n", - " redshift_0=0.5, redshift_1=1.0\n", - " )\n", + " \"Radial eigenvalue at the first grid point: \"\n", + " f\"{radial_eigen_values[0]:.4f}\"\n", ")" ], "outputs": [], @@ -392,31 +763,72 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__More Complexity__\n", + "__Critical Curves and Caustics__\n", "\n", - "We now make a lens with some attributes we didn`t in the last tutorial:\n", + "**Critical curves** mark positions in the image plane where\n", + "the magnification of an infinitesimally small source formally\n", + "becomes infinite:\n", "\n", - " - A light profile representing a `bulge` of stars, meaning the lens galaxy's light will appear in the image for the\n", - " first time.\n", - " - An external shear, which accounts for the deflection of light due to line-of-sight structures." + "$$\n", + "\\det A = 0.\n", + "$$\n", + "\n", + "A tangential critical curve occurs where $\\lambda_t=0$;\n", + "a radial critical curve occurs where $\\lambda_r=0$.\n", + "Images near them can be strongly stretched in the\n", + "corresponding direction.\n", + "\n", + "Real galaxies have finite size. They can form bright,\n", + "extended arcs near critical curves without having\n", + "infinite total brightness.\n", + "\n", + "Our spherical isothermal lens has a tangential critical\n", + "curve but no radial critical curve. The plot below should\n", + "therefore show one circle, at a radius of 1.6 arcseconds." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "lens = al.Galaxy(\n", - " redshift=0.5,\n", - " bulge=al.lp.SersicSph(\n", - " centre=(0.0, 0.0), intensity=2.0, effective_radius=0.5, sersic_index=2.5\n", - " ),\n", - " mass=al.mp.Isothermal(\n", - " centre=(0.0, 0.0), ell_comps=(0.0, -0.111111), einstein_radius=1.6\n", - " ),\n", + "\n", + "tangential_critical_curves = (\n", + " lens_calc.tangential_critical_curve_list_from(\n", + " grid=grid, pixel_scale=grid.pixel_scale\n", + " )\n", + ")\n", + "radial_critical_curves = (\n", + " lens_calc.radial_critical_curve_list_from(\n", + " grid=grid, pixel_scale=grid.pixel_scale\n", + " )\n", ")\n", - "field = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\n", "\n", - "print(lens)" + "fig, ax = plt.subplots(figsize=(6, 6))\n", + "\n", + "for curves, colour, label in [\n", + " (tangential_critical_curves, \"black\", \"Tangential\"),\n", + " (radial_critical_curves, \"orange\", \"Radial\"),\n", + "]:\n", + " for index, curve in enumerate(curves):\n", + " coordinates = np.asarray(curve)\n", + " ax.plot(\n", + " coordinates[:, 1],\n", + " coordinates[:, 0],\n", + " color=colour,\n", + " label=label if index == 0 else None,\n", + " )\n", + "\n", + "ax.set(\n", + " title=\"Critical Curves: Image Plane\",\n", + " xlabel=\"x (arcseconds)\",\n", + " ylabel=\"y (arcseconds)\",\n", + " xlim=(-2.0, 2.0),\n", + " ylim=(-2.0, 2.0),\n", + ")\n", + "ax.set_aspect(\"equal\")\n", + "ax.legend()\n", + "plt.show()\n", + "plt.close(fig)" ], "outputs": [], "execution_count": null @@ -425,22 +837,71 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Lets also create a small satellite galaxy nearby the lens galaxy and at the same redshift." + "Ray-tracing a critical curve to the source plane gives\n", + "a **caustic**:\n", + "\n", + "$$\n", + "\\boldsymbol{\\beta}_{\\mathrm{caustic}}\n", + "=\n", + "\\boldsymbol{\\theta}_{\\mathrm{critical}}\n", + "-\n", + "\\boldsymbol{\\alpha}(\n", + " \\boldsymbol{\\theta}_{\\mathrm{critical}}\n", + ").\n", + "$$\n", + "\n", + "Critical curves tell us where strongly stretched images\n", + "appear. Caustics tell us where a source must lie to\n", + "produce those images.\n", + "\n", + "For our spherical lens, the entire tangential critical\n", + "circle maps to one source-plane point: the origin.\n", + "A source centred there produces an Einstein ring.\n", + "\n", + "The plot below displays the mapped coordinates as points.\n", + "They should gather at the origin, with any small spread\n", + "arising from the numerical calculation." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "lens_satellite = al.Galaxy(\n", - " redshift=0.5,\n", - " bulge=al.lp.DevVaucouleursSph(\n", - " centre=(1.0, 0.0), intensity=2.0, effective_radius=0.2\n", - " ),\n", - " mass=al.mp.IsothermalSph(centre=(1.0, 0.0), einstein_radius=0.4),\n", + "\n", + "tangential_caustics = lens_calc.tangential_caustic_list_from(\n", + " grid=grid, pixel_scale=grid.pixel_scale\n", + ")\n", + "radial_caustics = lens_calc.radial_caustic_list_from(\n", + " grid=grid, pixel_scale=grid.pixel_scale\n", ")\n", "\n", - "print(lens_satellite)" + "fig, ax = plt.subplots(figsize=(6, 6))\n", + "\n", + "for caustics, colour, label in [\n", + " (tangential_caustics, \"black\", \"Tangential\"),\n", + " (radial_caustics, \"orange\", \"Radial\"),\n", + "]:\n", + " for index, caustic in enumerate(caustics):\n", + " coordinates = np.asarray(caustic)\n", + " ax.scatter(\n", + " coordinates[:, 1],\n", + " coordinates[:, 0],\n", + " s=8,\n", + " color=colour,\n", + " label=label if index == 0 else None,\n", + " )\n", + "\n", + "ax.set(\n", + " title=\"Caustics: Source Plane\",\n", + " xlabel=\"x (arcseconds)\",\n", + " ylabel=\"y (arcseconds)\",\n", + " xlim=(-1.2, 1.2),\n", + " ylim=(-1.2, 1.2),\n", + ")\n", + "ax.set_aspect(\"equal\")\n", + "ax.legend()\n", + "plt.show()\n", + "plt.close(fig)" ], "outputs": [], "execution_count": null @@ -449,9 +910,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Lets have a quick look at the appearance of our lens galaxy and its satellite.\n", + "We can reveal a radial critical curve by making the lens's\n", + "central mass distribution shallower.\n", "\n", - "And their deflection angles, noting that the satellite does not contribute as much to the deflections." + "The code below replaces the spherical isothermal profile\n", + "with a spherical power-law profile whose slope is 1.8.\n", + "The isothermal slope is 2.0. We keep the same centre,\n", + "Einstein-radius parameter, source and cosmology." ] }, { @@ -459,9 +924,18 @@ "metadata": {}, "source": [ "\n", + "lens = al.Galaxy(\n", + " redshift=0.5,\n", + " mass=al.mp.PowerLawSph(\n", + " centre=(0.0, 0.0),\n", + " einstein_radius=1.6,\n", + " slope=1.8,\n", + " ),\n", + ")\n", "\n", - "# NOTE: In the new API, pass title directly as a string:\n", - "# title=\"Lens Galaxy Deflections (x)\"\n" + "tracer = al.Tracer(galaxies=[lens, source], cosmology=cosmology)\n", + "mass_profile = lens.mass\n", + "lens_calc = al.LensCalc.from_tracer(tracer=tracer)" ], "outputs": [], "execution_count": null @@ -470,40 +944,40 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Now, lets make two source galaxies at redshift 1.0. Instead of using the name `light` for the light profiles, lets \n", - "instead use more descriptive names that indicate what morphological component of the galaxy the light profile \n", - "represents. In this case, we'll use the terms `bulge` and `disk`, the two main structures that a galaxy can be made of" + "Rerun the two plotting cells immediately above, including\n", + "their critical-curve and caustic calculations.\n", + "\n", + "The image-plane plot should now show an inner radial critical\n", + "curve as well as the outer tangential critical curve.\n", + "The source-plane plot should show a circular radial\n", + "caustic around the central tangential caustic.\n", + "\n", + "Caustics also mark changes in the number of images.\n", + "For a point source crossing a smooth part of the radial\n", + "caustic in this example, two images appear or disappear.\n", + "An extended galaxy can straddle the caustic, so different\n", + "parts of it can have different numbers of images.\n", + "\n", + "The following cell restores our spherical isothermal lens\n", + "for the remaining sections." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "source_0 = al.Galaxy(\n", - " redshift=1.0,\n", - " bulge=al.lp.DevVaucouleursSph(\n", - " centre=(0.1, 0.2), intensity=0.3, effective_radius=0.3\n", - " ),\n", - " disk=al.lp.ExponentialCore(\n", - " centre=(0.1, 0.2),\n", - " ell_comps=(0.111111, 0.0),\n", - " intensity=3.0,\n", - " effective_radius=2.0,\n", - " ),\n", - ")\n", "\n", - "source_1 = al.Galaxy(\n", - " redshift=1.0,\n", - " disk=al.lp.ExponentialCore(\n", - " centre=(-0.3, -0.5),\n", - " ell_comps=(0.1, 0.0),\n", - " intensity=8.0,\n", - " effective_radius=1.0,\n", + "lens = al.Galaxy(\n", + " redshift=0.5,\n", + " mass=al.mp.IsothermalSph(\n", + " centre=(0.0, 0.0),\n", + " einstein_radius=1.6,\n", " ),\n", ")\n", "\n", - "print(source_0)\n", - "print(source_1)" + "tracer = al.Tracer(galaxies=[lens, source], cosmology=cosmology)\n", + "mass_profile = lens.mass\n", + "lens_calc = al.LensCalc.from_tracer(tracer=tracer)" ], "outputs": [], "execution_count": null @@ -512,27 +986,46 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Lets look at our source galaxies (before lensing)\n", + "__Einstein Radius__\n", + "\n", + "For a circular lens with a source directly behind its centre,\n", + "the source forms an Einstein ring. Its angular radius is\n", + "the **Einstein radius**, $\\theta_E$.\n", "\n", - "__Multi Galaxy Ray Tracing__\n", + "Our spherical isothermal lens has a circular tangential\n", + "critical curve at this radius.\n", "\n", - "Now lets pass our 4 galaxies to a `Tracer`, which means the following will occur:\n", + "For a non-circular lens, we can define an **effective Einstein\n", + "radius** using the area enclosed by the tangential critical\n", + "curve:\n", "\n", - " - Using the galaxy redshifts, an image-plane and source-plane will be created, each with two galaxies.\n", + "$$\n", + "\\theta_E = \\sqrt{\\frac{A_{\\mathrm{crit}}}{\\pi}}.\n", + "$$\n", "\n", - "We also pass the tracer below a Planck15 cosmology, where the cosmology of the Universe describes exactly how\n", - "ray-tracing is performed." + "This is the radius of a circle enclosing the same area.\n", + "It is the definition used by `LensCalc`.\n", + "\n", + "Let's recover the Einstein radius from our critical curve\n", + "and convert it into kiloparsecs at the lens redshift." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "tracer = al.Tracer(\n", - " galaxies=[lens, lens_satellite, source_0, source_1],\n", - " cosmology=al.cosmo.Planck15(),\n", - " fields=[field],\n", - ")" + "\n", + "einstein_radius = lens_calc.einstein_radius_from(\n", + " grid=grid, pixel_scale=grid.pixel_scale\n", + ")\n", + "\n", + "kpc_per_arcsec_lens = cosmology.kpc_per_arcsec_from(\n", + " redshift=lens.redshift\n", + ")\n", + "einstein_radius_kpc = einstein_radius * kpc_per_arcsec_lens\n", + "\n", + "print(f\"Einstein radius: {einstein_radius:.4f} arcsec\")\n", + "print(f\"Einstein radius: {einstein_radius_kpc:.4f} kpc\")" ], "outputs": [], "execution_count": null @@ -541,45 +1034,81 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can now plot the tracer`s image, which now there are two galaxies in each plane is computed as follows:\n", - "\n", - " 1) First, using the image-plane grid, the images of the lens galaxy and its satellite are computed.\n", - "\n", - " 2) Using the mass profiles of the lens and its satellite, their deflection angles are computed.\n", - "\n", - " 3) These deflection angles are summed, such that the deflection of light due to the mass profiles of both galaxies in \n", - " the image-plane is accounted for.\n", - "\n", - " 4) These deflection angles are used to trace every image-grid coordinate to the source-plane.\n", - "\n", - " 5) The image of the source galaxies is computed by summing both of their images and ray-tracing their light back to \n", - " the image-plane.\n", - " \n", - "This process is pretty much the same as we have seen in previous tutorials when there is one galaxy per plane. We\n", - "are simply summing the images and deflection angles of the galaxies before using them to perform ray-tracing." + "The recovered angular radius should be close to the\n", + "1.6 arcseconds specified in our spherical mass profile.\n", + "Small differences arise from locating the critical curve\n", + "on a finite grid." ] }, { - "cell_type": "code", + "cell_type": "markdown", "metadata": {}, "source": [ - "aplt.plot_array(array=tracer.image_2d_from(grid=grid), title=\"Image\")" - ], - "outputs": [], - "execution_count": null + "Two simple mass distributions have useful expressions\n", + "for the Einstein radius.\n", + "\n", + "For a point mass $M$:\n", + "\n", + "$$\n", + "\\theta_E\n", + "=\n", + "\\sqrt{\n", + "\\frac{4GM}{c^2}\n", + "\\frac{D_{ls}}{D_l D_s}\n", + "}.\n", + "$$\n", + "\n", + "For a singular isothermal sphere, with one-dimensional\n", + "velocity dispersion $\\sigma_v$:\n", + "\n", + "$$\n", + "\\theta_E\n", + "=\n", + "4\\pi\n", + "\\left(\\frac{\\sigma_v}{c}\\right)^2\n", + "\\frac{D_{ls}}{D_s}.\n", + "$$\n", + "\n", + "Both expressions give angles in radians when the physical\n", + "quantities use consistent units.\n", + "\n", + "They show how the Einstein radius connects the lens's mass\n", + "or velocity dispersion to the observer\u2013lens\u2013source geometry.\n", + "Our `IsothermalSph` profile specifies this angular scale\n", + "directly through its `einstein_radius` parameter." + ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "As we did previously, we can plot the source plane grid to see how each coordinate was traced. " + "For a circular lens, the mean convergence inside the Einstein\n", + "radius equals one. Its enclosed projected mass is therefore\n", + "\n", + "$$\n", + "M(\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch — quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch — single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly — build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch — multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI — extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) — multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) — for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot — how light deflects, how critical curves and\n caustics arise.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action — building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** — [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` — ray tracing, profiles, numpy\n arrays, visualization.\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth — or build a\ntraining set for neural-network classifiers — you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating — single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* — chooses the branch.\n- *\"What's the ground truth?\"* — lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* — pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch — galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid — defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer — lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_fits(\n data_path=dataset_path / \"data.fits\",\n noise_map_path=dataset_path / \"noise_map.fits\",\n psf_path=dataset_path / \"psf.fits\",\n overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot — saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` — `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch — many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch — interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n → [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour — see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates — the forward physics\n the simulator runs.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice — grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb in HowToLens).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoLens calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoLens docs (https://pyautolens.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` \u2014 image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* \u2014 pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* \u2014 if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual \u2014 what convergence is, why caustics matter, what\na critical curve traces \u2014 see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions \u2014\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch \u2014 quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch \u2014 single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly \u2014 build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch \u2014 multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI \u2014 extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) \u2014 multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) \u2014 for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot \u2014 how light deflects, how critical curves and\n caustics arise.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action \u2014 building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` \u2014 ray tracing, profiles, numpy\n arrays, visualization.\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth \u2014 or build a\ntraining set for neural-network classifiers \u2014 you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating \u2014 single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* \u2014 chooses the branch.\n- *\"What's the ground truth?\"* \u2014 lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* \u2014 pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch \u2014 galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid \u2014 defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer \u2014 lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_fits(\n data_path=dataset_path / \"data.fits\",\n noise_map_path=dataset_path / \"noise_map.fits\",\n psf_path=dataset_path / \"psf.fits\",\n overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot \u2014 saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` \u2014 `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch \u2014 many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch \u2014 interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n \u2192 [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour \u2014 see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates \u2014 the forward physics\n the simulator runs.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice \u2014 grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_1_introduction/tutorial_6_data.ipynb b/notebooks/chapter_1_introduction/tutorial_5_data.ipynb similarity index 99% rename from notebooks/chapter_1_introduction/tutorial_6_data.ipynb rename to notebooks/chapter_1_introduction/tutorial_5_data.ipynb index 9db0087..494ee31 100644 --- a/notebooks/chapter_1_introduction/tutorial_6_data.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_5_data.ipynb @@ -4,7 +4,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Tutorial 6: Data\n", + "Tutorial 5: Data\n", "================\n", "\n", "In the last tutorials, we use tracers to create images of strong lenses. However, those images don't accurately\n", @@ -792,7 +792,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_1_introduction/tutorial_6_data.ipynb in HowToLens).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoLens calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoLens docs (https://pyautolens.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` \u2014 image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* \u2014 pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* \u2014 if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual \u2014 what convergence is, why caustics matter, what\na critical curve traces \u2014 see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions \u2014\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch \u2014 quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch \u2014 single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly \u2014 build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch \u2014 multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI \u2014 extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) \u2014 multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) \u2014 for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot \u2014 how light deflects, how critical curves and\n caustics arise.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action \u2014 building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` \u2014 ray tracing, profiles, numpy\n arrays, visualization.\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth \u2014 or build a\ntraining set for neural-network classifiers \u2014 you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating \u2014 single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* \u2014 chooses the branch.\n- *\"What's the ground truth?\"* \u2014 lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* \u2014 pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch \u2014 galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid \u2014 defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer \u2014 lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_fits(\n data_path=dataset_path / \"data.fits\",\n noise_map_path=dataset_path / \"noise_map.fits\",\n psf_path=dataset_path / \"psf.fits\",\n overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot \u2014 saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` \u2014 `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch \u2014 many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch \u2014 interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n \u2192 [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour \u2014 see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates \u2014 the forward physics\n the simulator runs.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice \u2014 grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_1_introduction/tutorial_5_data.ipynb in HowToLens).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoLens calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoLens docs (https://pyautolens.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` \u2014 image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* \u2014 pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* \u2014 if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual \u2014 what convergence is, why caustics matter, what\na critical curve traces \u2014 see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions \u2014\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch \u2014 quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch \u2014 single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly \u2014 build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch \u2014 multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI \u2014 extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) \u2014 multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) \u2014 for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot \u2014 how light deflects, how critical curves and\n caustics arise.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action \u2014 building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` \u2014 ray tracing, profiles, numpy\n arrays, visualization.\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth \u2014 or build a\ntraining set for neural-network classifiers \u2014 you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating \u2014 single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* \u2014 chooses the branch.\n- *\"What's the ground truth?\"* \u2014 lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* \u2014 pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch \u2014 galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid \u2014 defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer \u2014 lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_fits(\n data_path=dataset_path / \"data.fits\",\n noise_map_path=dataset_path / \"noise_map.fits\",\n psf_path=dataset_path / \"psf.fits\",\n overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot \u2014 saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` \u2014 `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch \u2014 many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch \u2014 interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n \u2192 [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour \u2014 see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates \u2014 the forward physics\n the simulator runs.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice \u2014 grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_1_introduction/tutorial_5_lensing_formalism.ipynb b/notebooks/chapter_1_introduction/tutorial_5_lensing_formalism.ipynb deleted file mode 100644 index b7dee11..0000000 --- a/notebooks/chapter_1_introduction/tutorial_5_lensing_formalism.ipynb +++ /dev/null @@ -1,885 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 5: Lensing Formalism\n", - "=============================\n", - "\n", - "This tutorial is the equations lecture of **HowToLens**.\n", - "\n", - "Every other tutorial in this series deliberately defers the formal mathematics of gravitational lensing, so that you\n", - "could first learn lensing hands-on: in the earlier tutorials we created grids, evaluated light and mass profiles,\n", - "ray-traced coordinates from the image-plane to the source-plane and looked at quantities like the convergence,\n", - "deflection angles and critical curves visually, without ever writing down their formal definitions.\n", - "\n", - "This tutorial gathers all of that algebra in one place. Each quantity you have already computed and plotted \u2014\n", - "deflection angles, convergence, potential, magnification, critical curves, the Einstein radius \u2014 is now given its\n", - "formal mathematical definition, explained in plain words, and tied back to the exact **PyAutoLens** method that\n", - "computes it. The goal is that after this tutorial, every symbol in a lensing paper maps to a line of code you know.\n", - "\n", - "None of this mathematics is required to use **PyAutoLens** or to analyse strong lenses \u2014 the library computes\n", - "everything for you. But understanding where each quantity comes from will make you a better lens modeler, and this\n", - "is the single place in **HowToLens** where the formalism lives, so you can return here whenever you need it.\n", - "\n", - "We will build one simple strong lens system \u2014 an elliptical isothermal (SIE) lens galaxy and a Sersic source \u2014 and\n", - "reuse it throughout, computing every quantity from the same tracer so you can see how they all fit together.\n", - "\n", - "__Contents__\n", - "\n", - "- **Initial Setup:** Build the grid, SIE lens, Sersic source and `Tracer` reused throughout the tutorial.\n", - "- **Cosmological Distances:** Angular diameter distances D_l, D_s, D_ls and how arcseconds convert to kiloparsecs.\n", - "- **The Lens Equation:** beta = theta - alpha(theta), the mapping from image-plane to source-plane, and multiple images.\n", - "- **Convergence:** Surface mass density Sigma, the critical surface density Sigma_cr and kappa = Sigma / Sigma_cr.\n", - "- **Deflection Angles:** The integral relating the convergence field to the deflection angles.\n", - "- **The Lensing Potential:** The scalar potential psi, with alpha = grad psi and kappa = (1/2) laplacian psi.\n", - "- **Shear and Magnification:** The Hessian, the Jacobian matrix A, shear gamma and magnification mu = 1 / det(A).\n", - "- **Critical Curves and Caustics:** Where det(A) = 0 in the image-plane, and its map to the source-plane.\n", - "- **Einstein Radius:** Its definition, the SIS and point-mass closed forms, and why it is the robust mass measurement.\n", - "- **Time Delays:** The Fermat potential and the time-delay surface, in brief.\n", - "- **Wrap Up:** Summary of the script and next steps." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Google Colab Setup__\n", - "\n", - "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "jupyter": { - "source_hidden": true - } - }, - "outputs": [], - "source": [ - "# @title Set up Google Colab { display-mode: \"form\" }\n", - "try:\n", - " import google.colab\n", - "except ImportError:\n", - " from autolens import setup_colab as _setup_colab\n", - "else:\n", - " import importlib\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.check_call(\n", - " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", - " )\n", - " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", - "\n", - "_setup_colab.setup(\"howtolens\")" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autolens import jax_wrapper # Sets JAX environment before other imports\n", - "\n", - "from autolens import setup_notebook; setup_notebook()\n", - "\n", - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "import autolens as al\n", - "import autoarray as aa\n", - "import autolens.plot as aplt" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Initial Setup__\n", - "\n", - "We first build the strong lens system used throughout this tutorial, mirroring the objects introduced in tutorials\n", - "2 and 3: a 2D grid of (y,x) arcsecond coordinates, a lens galaxy with an elliptical isothermal (`Isothermal`) mass\n", - "profile \u2014 the singular isothermal ellipsoid, or SIE, the workhorse mass model of galaxy-scale lensing \u2014 and a\n", - "source galaxy with a Sersic light profile." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "grid = al.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.05)\n", - "\n", - "mass_profile = al.mp.Isothermal(\n", - " centre=(0.0, 0.0),\n", - " ell_comps=al.convert.ell_comps_from(axis_ratio=0.8, angle=45.0),\n", - " einstein_radius=1.6,\n", - ")\n", - "\n", - "lens_galaxy = al.Galaxy(redshift=0.5, mass=mass_profile)\n", - "\n", - "source_galaxy = al.Galaxy(\n", - " redshift=1.0,\n", - " bulge=al.lp.SersicCore(\n", - " centre=(0.0, 0.1),\n", - " ell_comps=(0.1, 0.0),\n", - " intensity=0.3,\n", - " effective_radius=0.3,\n", - " sersic_index=1.0,\n", - " ),\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We combine these into a `Tracer` with a Planck 2015 cosmology. The redshifts of the two galaxies (0.5 and 1.0) and\n", - "the cosmology together fix every distance that appears in the equations below." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "cosmology = al.cosmo.Planck15()\n", - "\n", - "tracer = al.Tracer(galaxies=[lens_galaxy, source_galaxy], cosmology=cosmology)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Here is the lensed image of this system, which by now should look familiar. Every equation in this tutorial is\n", - "describing some aspect of how this image forms." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "image = tracer.image_2d_from(grid=grid)\n", - "aplt.plot_array(array=image, title=\"Lensed Image of the Source Galaxy\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We also create a `LensCalc` object from the tracer. As we saw in tutorial 3, this is **PyAutoLens**'s calculator for\n", - "derived lensing quantities \u2014 everything it computes is derived from the tracer's deflection angles, which is a theme\n", - "we will see repeatedly below." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "lens_calc = al.LensCalc.from_tracer(tracer=tracer)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Cosmological Distances__\n", - "\n", - "Gravitational lensing is a geometric effect, so distances are everywhere in its equations. The distances used are\n", - "**angular diameter distances**, defined so that an object of physical size l at angular diameter distance D subtends\n", - "an angle (in radians):\n", - "\n", - " theta = l / D\n", - "\n", - "Three distances appear in every lensing formula:\n", - "\n", - "- D_l \u2014 the angular diameter distance from the observer to the lens (deflector) galaxy.\n", - "- D_s \u2014 the angular diameter distance from the observer to the source galaxy.\n", - "- D_ls \u2014 the angular diameter distance from the lens to the source.\n", - "\n", - "In an expanding Universe angular diameter distances do not add linearly, so D_ls != D_s - D_l. Each is computed by\n", - "integrating the cosmological expansion history between the two redshifts, which is why the tracer requires both\n", - "galaxy redshifts and a cosmology.\n", - "\n", - "The `Cosmology` object computes each of these directly (values below are in kiloparsecs):" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "D_l = cosmology.angular_diameter_distance_to_earth_in_kpc_from(redshift=0.5)\n", - "D_s = cosmology.angular_diameter_distance_to_earth_in_kpc_from(redshift=1.0)\n", - "D_ls = cosmology.angular_diameter_distance_between_redshifts_in_kpc_from(\n", - " redshift_0=0.5, redshift_1=1.0\n", - ")\n", - "\n", - "print(f\"D_l (kpc) = {D_l:.3e}\")\n", - "print(f\"D_s (kpc) = {D_s:.3e}\")\n", - "print(f\"D_ls (kpc) = {D_ls:.3e}\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The angular diameter distance is also what converts **PyAutoLens**'s internal angular units of arcseconds into\n", - "physical distances. An angle of 1.0\" at redshift z corresponds to a physical size:\n", - "\n", - " l = D(z) * (1.0\" in radians)\n", - "\n", - "The `Cosmology` object wraps this up as a `kpc_per_arcsec` conversion factor, which differs between the image-plane\n", - "(lens redshift) and source-plane (source redshift) because the two planes are at different distances." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "kpc_per_arcsec_lens = cosmology.kpc_per_arcsec_from(redshift=0.5)\n", - "kpc_per_arcsec_source = cosmology.kpc_per_arcsec_from(redshift=1.0)\n", - "\n", - "print(f\"kpc per arcsec at the lens (z=0.5) = {kpc_per_arcsec_lens:.4f}\")\n", - "print(f\"kpc per arcsec at the source (z=1.0) = {kpc_per_arcsec_source:.4f}\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "So our lens's Einstein radius of 1.6\" corresponds to a physical scale of roughly 1.6 * 6.3 ~ 10 kpc at the lens\n", - "redshift \u2014 a sensible size for the inner regions of a massive elliptical galaxy.\n", - "\n", - "__The Lens Equation__\n", - "\n", - "The fundamental equation of gravitational lensing is the **lens equation**, which we met in tutorial 2:\n", - "\n", - " beta = theta - alpha(theta)\n", - "\n", - "where:\n", - "\n", - "- theta is the observed (image-plane) angular position of a light ray, in arcseconds.\n", - "- alpha(theta) is the (scaled) deflection angle \u2014 how much the ray is bent by the lens's gravity at position theta.\n", - "- beta is the true (source-plane) position \u2014 where the source would appear if there were no lens.\n", - "\n", - "In plain words: to find where a light ray we observe at theta really came from, subtract the deflection the lens\n", - "applied to it. This is exactly the ray-tracing calculation we performed in tutorial 2, and it is worth knowing that\n", - "the deflection angle here is the \"scaled\" deflection: the physical bending angle of the ray multiplied by the\n", - "distance ratio D_ls / D_s, which is the convention that makes the lens equation take the simple form above.\n", - "\n", - "The lens equation is trivial to evaluate one way (given theta, compute beta), but it cannot be inverted\n", - "analytically: for a strong lens, *multiple* image-plane positions theta can satisfy the equation for the *same*\n", - "source position beta. This is why strong lenses produce multiple images of a single source \u2014 and why lens modeling\n", - "works \"forwards\", ray-tracing image-plane grids to the source-plane rather than the other way around.\n", - "\n", - "In code, the lens equation is one line \u2014 the same `grid_2d_via_deflection_grid_from` call from tutorial 2:" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "deflections = tracer.deflections_yx_2d_from(grid=grid)\n", - "\n", - "source_plane_grid = grid.grid_2d_via_deflection_grid_from(deflection_grid=deflections)\n", - "\n", - "aplt.plot_grid(grid=grid, title=\"Image-Plane Grid (theta)\")\n", - "aplt.plot_grid(grid=source_plane_grid, title=\"Source-Plane Grid (beta)\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Convergence__\n", - "\n", - "The lens galaxy's mass enters lensing via its **surface mass density** Sigma(theta): the galaxy's 3D mass density\n", - "integrated along the line of sight, giving a projected 2D mass per unit area (e.g. in solar masses per kpc^2).\n", - "Lensing only cares about this projection \u2014 two very different 3D distributions with the same projected Sigma\n", - "deflect light identically.\n", - "\n", - "Whether a lens is \"strong\" is set by comparing Sigma to the **critical surface density**:\n", - "\n", - " Sigma_cr = (c^2 / (4 pi G)) * (D_s / (D_l * D_ls))\n", - "\n", - "This is a purely cosmological quantity \u2014 it depends only on the constants c and G and the three distances from the\n", - "previous section. It has a beautiful interpretation: it is the surface density a lens needs, given this observer /\n", - "lens / source geometry, to be capable of producing multiple images." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "sigma_cr_kpc = (\n", - " cosmology.critical_surface_density_between_redshifts_solar_mass_per_kpc2_from(\n", - " redshift_0=0.5, redshift_1=1.0\n", - " )\n", - ")\n", - "sigma_cr_arcsec = cosmology.critical_surface_density_between_redshifts_from(\n", - " redshift_0=0.5, redshift_1=1.0\n", - ")\n", - "\n", - "print(f\"Sigma_cr (solar masses per kpc^2) = {sigma_cr_kpc:.3e}\")\n", - "print(f\"Sigma_cr (solar masses per arcsec^2) = {sigma_cr_arcsec:.3e}\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The **convergence** kappa is the surface mass density in units of the critical density:\n", - "\n", - " kappa(theta) = Sigma(theta) / Sigma_cr\n", - "\n", - "This is the dimensionless quantity **PyAutoLens** has been plotting since tutorial 2 whenever we called\n", - "`convergence_2d_from`:\n", - "\n", - "- kappa >= 1 \u2014 the lens is super-critical at that point; multiple imaging is possible.\n", - "- kappa < 1 \u2014 the lens is sub-critical there.\n", - "\n", - "Because kappa is dimensionless, lens models can be composed and fitted without knowing the galaxy redshifts at all \u2014\n", - "the redshifts and Sigma_cr are only needed at the end, to convert the inferred kappa back into physical masses." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "convergence = tracer.convergence_2d_from(grid=grid)\n", - "\n", - "aplt.plot_array(array=convergence, title=\"Convergence (kappa)\", use_log10=True)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Deflection Angles__\n", - "\n", - "The convergence field determines the deflection angles everywhere, via a 2D integral over the whole image-plane:\n", - "\n", - " alpha(theta) = (1 / pi) * integral d^2 theta' kappa(theta') * (theta - theta') / |theta - theta'|^2\n", - "\n", - "In plain words: every patch of mass in the lens plane pulls on every light ray. The deflection at position theta is\n", - "the sum (integral) of the pulls from all mass elements kappa(theta'), each pointing from the mass element towards\n", - "the ray and falling off as 1/distance \u2014 the 2D (projected) analogue of Newtonian gravity's inverse-square law.\n", - "\n", - "Two things follow from this integral being over *all* theta':\n", - "\n", - "- The deflection at a point depends on the mass distribution *everywhere*, not just the mass at that point. Even\n", - " mass well outside the region where images form contributes deflections (this is why external shear from\n", - " neighbouring galaxies matters, as we saw in tutorial 3).\n", - "\n", - "- For simple analytic profiles (isothermal, power-law, Sersic-like) this integral has closed-form solutions, which\n", - " is exactly what a **PyAutoLens** mass profile is: an analytic kappa(theta) paired with its analytic alpha(theta).\n", - "\n", - "The `deflections_yx_2d_from` method we have used since tutorial 2 evaluates this integral's closed-form solution.\n", - "The deflections form a 2D vector field, so we plot its y and x components separately:" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "deflections = tracer.deflections_yx_2d_from(grid=grid)\n", - "\n", - "deflections_y = aa.Array2D(values=deflections.slim[:, 0], mask=grid.mask)\n", - "aplt.plot_array(array=deflections_y, title=\"Deflection Angles (y component)\")\n", - "\n", - "deflections_x = aa.Array2D(values=deflections.slim[:, 1], mask=grid.mask)\n", - "aplt.plot_array(array=deflections_x, title=\"Deflection Angles (x component)\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__The Lensing Potential__\n", - "\n", - "The deflection field is not arbitrary \u2014 it is the gradient of a scalar field, the **lensing potential** psi(theta):\n", - "\n", - " alpha(theta) = grad psi(theta)\n", - "\n", - "The potential is itself an integral over the convergence:\n", - "\n", - " psi(theta) = (1 / pi) * integral d^2 theta' kappa(theta') * ln|theta - theta'|\n", - "\n", - "and taking the divergence of the gradient (the Laplacian) recovers the convergence with a factor of a half:\n", - "\n", - " kappa(theta) = (1/2) * laplacian psi(theta)\n", - "\n", - "This is the 2D Poisson equation of lensing \u2014 the projected analogue of Newtonian gravity's del^2 Phi = 4 pi G rho.\n", - "The potential is the single most economical description of a lens: one scalar field from which the deflections\n", - "(first derivatives), and the convergence, shear and magnification (second derivatives) all follow.\n", - "\n", - "The `potential_2d_from` method returns psi, which we have plotted before without defining it:" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "potential = tracer.potential_2d_from(grid=grid)\n", - "\n", - "aplt.plot_array(array=potential, title=\"Lensing Potential (psi)\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can verify alpha = grad psi numerically. Mass profiles have a `deflections_2d_via_potential_2d_from` method which\n", - "computes the deflections by numerically differentiating the potential, rather than using the profile's closed-form\n", - "deflection formula. Across the grid the two agree closely \u2014 we print the median absolute difference, since the\n", - "finite-difference derivative is inaccurate right at the isothermal profile's central cusp, where the potential is\n", - "not smooth (the closed-form deflections have no such problem):" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "deflections_analytic = mass_profile.deflections_yx_2d_from(grid=grid)\n", - "deflections_via_potential = mass_profile.deflections_2d_via_potential_2d_from(grid=grid)\n", - "\n", - "difference = np.median(\n", - " np.abs(np.asarray(deflections_analytic) - np.asarray(deflections_via_potential))\n", - ")\n", - "print(f\"Median |alpha_analytic - grad psi| = {difference:.3e} arcsec\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Shear and Magnification__\n", - "\n", - "How a small image is distorted by lensing is governed by how the deflection angles *change* across it \u2014 the second\n", - "derivatives of the potential. These form the 2x2 **Hessian** matrix, which `LensCalc` computes by finite\n", - "differences of the deflection field (as we saw in the workspace guides, this works for any mass distribution):\n", - "\n", - " H_yy = d(alpha_y) / d(theta_y) H_xy = d(alpha_x) / d(theta_y)\n", - " H_yx = d(alpha_y) / d(theta_x) H_xx = d(alpha_x) / d(theta_x)" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "hessian_yy, hessian_xy, hessian_yx, hessian_xx = lens_calc.hessian_from(grid=grid)\n", - "\n", - "print(\n", - " f\"Hessian components at pixel 0: H_yy = {hessian_yy[0]:.4f}, H_xx = {hessian_xx[0]:.4f}\"\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Differentiating the lens equation beta = theta - alpha(theta) gives the **Jacobian matrix** A, which maps a small\n", - "displacement in the source-plane to the corresponding displacement in the image-plane:\n", - "\n", - " A = d(beta) / d(theta) = I - H = | 1 - H_yy -H_xy |\n", - " | -H_yx 1 - H_xx |\n", - "\n", - "The Jacobian decomposes into two physically distinct distortions:\n", - "\n", - "- The **convergence** kappa = (1/2) * (H_yy + H_xx) \u2014 the isotropic part, which magnifies an image uniformly\n", - " without changing its shape. (Note this is the same kappa as before: the trace of the Hessian recovers the\n", - " Poisson equation kappa = (1/2) laplacian psi.)\n", - "\n", - "- The **shear** gamma \u2014 the anisotropic part, which stretches an image along one axis and squeezes it along the\n", - " perpendicular axis. It has two components and a magnitude:\n", - "\n", - " gamma_1 = (1/2) * (H_xx - H_yy)\n", - " gamma_2 = H_xy\n", - " |gamma| = sqrt(gamma_1^2 + gamma_2^2)\n", - "\n", - "The shear is why lensed images near the lens are stretched into tangential arcs \u2014 the tidal field of the lens\n", - "elongates them around it." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "shear = lens_calc.shear_yx_2d_via_hessian_from(grid=grid)\n", - "\n", - "print(f\"Shear magnitude at pixel 0: |gamma| = {shear.magnitudes[0]:.4f}\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The **magnification** mu is the inverse of the Jacobian's determinant:\n", - "\n", - " mu = 1 / det(A) = 1 / [ (1 - kappa)^2 - |gamma|^2 ]\n", - "\n", - "Lensing conserves surface brightness, so a lensed image that covers more sky than the unlensed source appears\n", - "brighter in total by exactly the factor |mu|:\n", - "\n", - "- |mu| > 1 \u2014 the image is magnified (larger and brighter than the unlensed source).\n", - "- |mu| < 1 \u2014 the image is demagnified.\n", - "- mu < 0 \u2014 the image has negative parity: it is a mirror image of the source.\n", - "\n", - "The determinant factorises into two eigenvalues, giving the **tangential** and **radial** magnifications:\n", - "\n", - " lambda_t = 1 - kappa - |gamma| (tangential eigenvalue)\n", - " lambda_r = 1 - kappa + |gamma| (radial eigenvalue)\n", - "\n", - " mu = 1 / (lambda_t * lambda_r)\n", - "\n", - "An image is stretched by 1/lambda_t in the tangential direction (around the lens) and 1/lambda_r in the radial\n", - "direction (towards/away from the lens). Giant tangential arcs form where lambda_t is close to zero." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "magnification = lens_calc.magnification_2d_from(grid=grid)\n", - "\n", - "aplt.plot_array(array=magnification, title=\"Magnification (mu)\")\n", - "\n", - "tangential_eigen_values = lens_calc.tangential_eigen_value_from(grid=grid)\n", - "radial_eigen_values = lens_calc.radial_eigen_value_from(grid=grid)\n", - "\n", - "print(f\"Tangential eigenvalue at pixel 0: {tangential_eigen_values[0]:.4f}\")\n", - "print(f\"Radial eigenvalue at pixel 0: {radial_eigen_values[0]:.4f}\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Critical Curves and Caustics__\n", - "\n", - "Where either eigenvalue passes through zero, det(A) = 0 and the magnification formally diverges to infinity. The\n", - "closed curves in the image-plane where this happens are the **critical curves** \u2014 the white and yellow lines that\n", - "have appeared on plots since tutorial 2, and which we explored visually in tutorial 3:\n", - "\n", - "- The **tangential critical curve** (lambda_t = 0) \u2014 roughly traces the Einstein ring; sources near its source-plane\n", - " counterpart form giant tangential arcs.\n", - "- The **radial critical curve** (lambda_r = 0) \u2014 an inner curve associated with radially stretched central images.\n", - "\n", - "Ray-tracing each critical curve through the lens equation maps it to the source-plane, where it is called a\n", - "**caustic**:\n", - "\n", - " caustic = critical_curve - alpha(critical_curve)\n", - "\n", - "Caustics divide the source-plane into regions of different image multiplicity: each time a source crosses a\n", - "caustic, the number of images it produces changes by two. For our SIE lens, a source inside the tangential caustic\n", - "produces four images (plus a faint central image); between the tangential and radial caustics, two; and outside\n", - "both caustics, just one \u2014 the source is no longer multiply imaged at all.\n", - "\n", - "`LensCalc` computes both by locating the zero-contours of the eigenvalue fields on the grid:" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "tangential_critical_curve_list = lens_calc.tangential_critical_curve_list_from(\n", - " grid=grid\n", - ")\n", - "radial_critical_curve_list = lens_calc.radial_critical_curve_list_from(grid=grid)\n", - "\n", - "tangential_caustic_list = lens_calc.tangential_caustic_list_from(grid=grid)\n", - "radial_caustic_list = lens_calc.radial_caustic_list_from(grid=grid)\n", - "\n", - "print(f\"Number of tangential critical curves: {len(tangential_critical_curve_list)}\")\n", - "print(f\"Number of radial critical curves: {len(radial_critical_curve_list)}\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Lets plot the critical curves (image-plane) and caustics (source-plane) of our SIE side by side. Note how the\n", - "elliptical lens produces a tangential caustic with four cusps \u2014 the origin of the four-image \"quad\" configurations\n", - "seen in many real lenses." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "plt.figure(figsize=(10, 5))\n", - "\n", - "plt.subplot(1, 2, 1)\n", - "for curve in tangential_critical_curve_list:\n", - " curve = np.asarray(curve)\n", - " plt.plot(curve[:, 1], curve[:, 0], color=\"black\", label=\"Tangential\")\n", - "for curve in radial_critical_curve_list:\n", - " curve = np.asarray(curve)\n", - " plt.plot(curve[:, 1], curve[:, 0], color=\"orange\", label=\"Radial\")\n", - "plt.gca().set_aspect(\"equal\")\n", - "plt.title(\"Critical Curves (Image-Plane)\")\n", - "plt.xlabel(\"x (arcsec)\")\n", - "plt.ylabel(\"y (arcsec)\")\n", - "plt.legend()\n", - "\n", - "plt.subplot(1, 2, 2)\n", - "for curve in tangential_caustic_list:\n", - " curve = np.asarray(curve)\n", - " plt.plot(curve[:, 1], curve[:, 0], color=\"black\", label=\"Tangential\")\n", - "for curve in radial_caustic_list:\n", - " curve = np.asarray(curve)\n", - " plt.plot(curve[:, 1], curve[:, 0], color=\"orange\", label=\"Radial\")\n", - "plt.gca().set_aspect(\"equal\")\n", - "plt.title(\"Caustics (Source-Plane)\")\n", - "plt.xlabel(\"x (arcsec)\")\n", - "plt.ylabel(\"y (arcsec)\")\n", - "plt.legend()\n", - "\n", - "plt.show()\n", - "plt.close()" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Einstein Radius__\n", - "\n", - "The **Einstein radius** theta_E is the characteristic angular scale of a strong lens. For a circular lens with the\n", - "source perfectly aligned behind it, it is the radius of the Einstein ring the source forms. More generally (and\n", - "this is the definition **PyAutoLens** uses), it is the radius of the circle enclosing the same area as the\n", - "tangential critical curve:\n", - "\n", - " theta_E = sqrt(A_crit / pi)\n", - "\n", - "sometimes called the \"effective\" Einstein radius, since an elliptical lens's critical curve is not a circle.\n", - "\n", - "Two closed-form results are worth memorising. For a **point mass** M:\n", - "\n", - " theta_E = sqrt( (4 G M / c^2) * (D_ls / (D_l * D_s)) )\n", - "\n", - "and for a **singular isothermal sphere** (SIS) with velocity dispersion sigma_v:\n", - "\n", - " theta_E = 4 pi * (sigma_v / c)^2 * (D_ls / D_s)\n", - "\n", - "The Einstein radius is also the radius within which the *mean* convergence equals exactly one \u2014 so measuring\n", - "theta_E directly measures the projected mass enclosed within it:\n", - "\n", - " M(< theta_E) = pi * theta_E^2 * Sigma_cr\n", - "\n", - "This is why the Einstein radius is celebrated as one of the most robust mass measurements in all of astrophysics:\n", - "the data pin down theta_E via the image separations almost independently of the assumed mass profile, so the\n", - "enclosed Einstein mass is trusted even when the profile's slope is not. (The main caveat, the mass-sheet\n", - "degeneracy, is discussed in the lens modeling chapters.)\n", - "\n", - "`LensCalc` computes the Einstein radius from the area of the tangential critical curve, and the enclosed\n", - "\"Einstein mass\" in angular units (pi * theta_E^2), which Sigma_cr converts to solar masses:" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "einstein_radius = lens_calc.einstein_radius_from(grid=grid)\n", - "\n", - "print(f\"Einstein radius (arcsec) = {einstein_radius:.4f}\")\n", - "print(f\"Einstein radius (kpc) = {einstein_radius * kpc_per_arcsec_lens:.4f}\")\n", - "\n", - "einstein_mass_angular = lens_calc.einstein_mass_angular_from(grid=grid)\n", - "einstein_mass_solar = einstein_mass_angular * sigma_cr_arcsec\n", - "\n", - "print(f\"Einstein mass (angular, arcsec^2) = {einstein_mass_angular:.4f}\")\n", - "print(f\"Einstein mass (solar masses) = {einstein_mass_solar:.4e}\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Reassuringly, the Einstein radius computed from the critical curve area (~1.6\") matches the `einstein_radius=1.6`\n", - "parameter we gave the `Isothermal` profile \u2014 for isothermal profiles the model parameter *is* the effective\n", - "Einstein radius, which is exactly why **PyAutoLens** parameterizes its mass profiles this way: the non-linear\n", - "search then varies the quantity the data constrain most directly.\n", - "\n", - "As a second check, an `IsothermalSph` (the SIS) has a perfectly circular critical curve, so its recovered Einstein\n", - "radius equals its input parameter even more precisely:" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "sis = al.mp.IsothermalSph(centre=(0.0, 0.0), einstein_radius=1.6)\n", - "\n", - "sis_einstein_radius = al.LensCalc.from_mass_obj(mass_obj=sis).einstein_radius_from(\n", - " grid=grid\n", - ")\n", - "\n", - "print(f\"SIS input Einstein radius = 1.6, recovered = {sis_einstein_radius:.4f}\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Time Delays__\n", - "\n", - "The final piece of the formalism is time. Light rays forming different images of the same source travel different\n", - "paths and through different depths of the lens's gravitational potential, so they arrive at different times. Both\n", - "effects are captured by the **Fermat potential** (or time-delay surface):\n", - "\n", - " phi(theta) = (1/2) * |theta - beta|^2 - psi(theta)\n", - "\n", - "The first term is the **geometric delay** \u2014 the extra path length of a bent ray. The second is the **gravitational\n", - "(Shapiro) delay** \u2014 light slowing as it climbs through the lens's potential. Fermat's principle states that images\n", - "form at the stationary points (minima, maxima and saddle points) of this surface, which is a wonderfully compact\n", - "restatement of the lens equation: grad phi = 0 is exactly beta = theta - alpha(theta).\n", - "\n", - "The observable **time delay** between two images A and B is the difference in their Fermat potentials, scaled by\n", - "the cosmological distances:\n", - "\n", - " Delta t_AB = (1 + z_l) / c * (D_l * D_s / D_ls) * [ phi(theta_A) - phi(theta_B) ]\n", - "\n", - "The distance combination (1 + z_l) * D_l * D_s / D_ls is called the **time-delay distance**, and because it is\n", - "inversely proportional to the Hubble constant, measuring time delays between the images of a variable source (a\n", - "quasar or supernova) turns a strong lens into a cosmological probe.\n", - "\n", - "We only touch on this here \u2014 time delays belong to the modeling of lensed point sources, introduced in tutorial 4\n", - "and covered in depth by the `autolens_workspace` point-source material. For now, we simply plot the Fermat\n", - "potential of our lens system:" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "fermat_potential = lens_calc.fermat_potential_from(grid=grid)\n", - "\n", - "aplt.plot_array(array=fermat_potential, title=\"Fermat Potential (phi)\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Wrap Up__\n", - "\n", - "This was the mathematics lecture of **HowToLens** \u2014 every formal definition deferred by the other tutorials, in one\n", - "place. Lets summarise the chain of quantities, because it has a beautiful logical structure where everything flows\n", - "from the mass distribution and a handful of distances:\n", - "\n", - "- **Distances**: the angular diameter distances D_l, D_s and D_ls set the geometry, convert arcseconds to\n", - " kiloparsecs and define the critical surface density Sigma_cr.\n", - "\n", - "- **Convergence**: kappa = Sigma / Sigma_cr is the dimensionless projected mass; kappa >= 1 marks super-critical\n", - " regions capable of multiple imaging.\n", - "\n", - "- **Deflections and potential**: kappa determines the deflection field alpha (a 2D gravity integral) and the\n", - " lensing potential psi, tied together by alpha = grad psi and kappa = (1/2) laplacian psi.\n", - "\n", - "- **The lens equation**: beta = theta - alpha(theta) maps the image-plane to the source-plane; its\n", - " non-invertibility is why multiple images form.\n", - "\n", - "- **Distortion**: the Jacobian A = I - H decomposes into convergence (isotropic) and shear gamma (anisotropic);\n", - " magnification is mu = 1 / det(A) = 1 / (lambda_t * lambda_r).\n", - "\n", - "- **Critical curves and caustics**: where det(A) = 0, magnification diverges; caustics are their source-plane\n", - " images and set the image multiplicity.\n", - "\n", - "- **Einstein radius**: the area-equivalent radius of the tangential critical curve, whose enclosed mass\n", - " M(< theta_E) = pi * theta_E^2 * Sigma_cr is the most robust measurement strong lensing delivers.\n", - "\n", - "- **Time delays**: the Fermat potential phi = (1/2)|theta - beta|^2 - psi locates images at its stationary points\n", - " and its differences, scaled by the time-delay distance, give observable delays.\n", - "\n", - "You do not need to memorise any of this to continue \u2014 **PyAutoLens** computes every one of these quantities via the\n", - "methods used above \u2014 but you now know what each method is computing and can return to this tutorial whenever a\n", - "symbol needs unpacking.\n", - "\n", - "In the next tutorial, we turn from theory to observation: how telescope optics, exposure times and noise turn the\n", - "pristine images of a tracer into the CCD imaging data we actually observe, and how to simulate such data ourselves.\n", - "\n", - "Finally, a signpost for much later: chapter 3's tutorial 5 on the Bayesian formalism is this tutorial's twin \u2014 the\n", - "equivalent equations lecture for pixelized source reconstruction, deriving the linear inversion and Bayesian\n", - "evidence that underpin chapter 3 just as this tutorial derived the lensing quantities underpinning chapter 1." - ] - } - ], - "metadata": { - "anaconda-cloud": {}, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - }, - "colab": { - "aiContexts": { - "97746750-6915-569b-a61d-792a6bc69437": { - "id": "97746750-6915-569b-a61d-792a6bc69437", - "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_1_introduction/tutorial_5_lensing_formalism.ipynb in HowToLens).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoLens calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoLens docs (https://pyautolens.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` \u2014 image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* \u2014 pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* \u2014 if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual \u2014 what convergence is, why caustics matter, what\na critical curve traces \u2014 see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions \u2014\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch \u2014 quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch \u2014 single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly \u2014 build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch \u2014 multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI \u2014 extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) \u2014 multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) \u2014 for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot \u2014 how light deflects, how critical curves and\n caustics arise.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action \u2014 building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` \u2014 ray tracing, profiles, numpy\n arrays, visualization.\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth \u2014 or build a\ntraining set for neural-network classifiers \u2014 you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating \u2014 single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* \u2014 chooses the branch.\n- *\"What's the ground truth?\"* \u2014 lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* \u2014 pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch \u2014 galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid \u2014 defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer \u2014 lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_fits(\n data_path=dataset_path / \"data.fits\",\n noise_map_path=dataset_path / \"noise_map.fits\",\n psf_path=dataset_path / \"psf.fits\",\n overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot \u2014 saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` \u2014 `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch \u2014 many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch \u2014 interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n \u2192 [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour \u2014 see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates \u2014 the forward physics\n the simulator runs.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice \u2014 grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n" - } - }, - "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file diff --git a/notebooks/chapter_1_introduction/tutorial_7_fitting.ipynb b/notebooks/chapter_1_introduction/tutorial_6_fitting.ipynb similarity index 99% rename from notebooks/chapter_1_introduction/tutorial_7_fitting.ipynb rename to notebooks/chapter_1_introduction/tutorial_6_fitting.ipynb index 0a372e3..2906bcc 100644 --- a/notebooks/chapter_1_introduction/tutorial_7_fitting.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_6_fitting.ipynb @@ -4,7 +4,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Tutorial 7: Fitting\n", + "Tutorial 6: Fitting\n", "===================\n", "\n", "In previous tutorials, we used light profiles to create simulated images of a tracer and visualized how these images\n", @@ -39,7 +39,7 @@ "__Contents__\n", "\n", "- **Dataset:** Load the imaging dataset that we previously simulated, consisting of the image, noise map, and PSF.\n", - "- **Dataset Auto-Simulation:** Create the dataset by running the tutorial 6 script if it is not on your hard-disk.\n", + "- **Dataset Auto-Simulation:** Create the dataset by running the tutorial 5 script if it is not on your hard-disk.\n", "- **Mask:** Apply a mask to the data, excluding regions with low signal-to-noise ratios from the analysis.\n", "- **Masked Grid:** In tutorials 1 and 2, we emphasized that the `Grid2D` object is crucial for evaluating a lens's.\n", "- **Fitting:** Fit the lens model to the dataset and inspect the results.\n", @@ -134,7 +134,7 @@ "source": [ "__Dataset Auto-Simulation__\n", "\n", - "The `howtolens` dataset is the one built up and saved in tutorial 6 (`tutorial_6_data.py`). If it does\n", + "The `howtolens` dataset is the one built up and saved in tutorial 5 (`tutorial_5_data.py`). If it does\n", "not already exist on your system, it is created by running that script. This ensures every example\n", "script can be run without manually simulating data first." ] @@ -148,7 +148,7 @@ " import sys\n", "\n", " subprocess.run(\n", - " [sys.executable, \"scripts/chapter_1_introduction/tutorial_6_data.py\"],\n", + " [sys.executable, \"scripts/chapter_1_introduction/tutorial_5_data.py\"],\n", " check=True,\n", " )\n", "\n", @@ -1180,7 +1180,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_1_introduction/tutorial_7_fitting.ipynb in HowToLens).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoLens calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoLens docs (https://pyautolens.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` \u2014 image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* \u2014 pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* \u2014 if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual \u2014 what convergence is, why caustics matter, what\na critical curve traces \u2014 see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions \u2014\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch \u2014 quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch \u2014 single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly \u2014 build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch \u2014 multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI \u2014 extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) \u2014 multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) \u2014 for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot \u2014 how light deflects, how critical curves and\n caustics arise.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action \u2014 building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` \u2014 ray tracing, profiles, numpy\n arrays, visualization.\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth \u2014 or build a\ntraining set for neural-network classifiers \u2014 you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating \u2014 single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* \u2014 chooses the branch.\n- *\"What's the ground truth?\"* \u2014 lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* \u2014 pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch \u2014 galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid \u2014 defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer \u2014 lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_fits(\n data_path=dataset_path / \"data.fits\",\n noise_map_path=dataset_path / \"noise_map.fits\",\n psf_path=dataset_path / \"psf.fits\",\n overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot \u2014 saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` \u2014 `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch \u2014 many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch \u2014 interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n \u2192 [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour \u2014 see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates \u2014 the forward physics\n the simulator runs.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice \u2014 grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_1_introduction/tutorial_6_fitting.ipynb in HowToLens).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoLens calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoLens docs (https://pyautolens.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` \u2014 image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* \u2014 pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* \u2014 if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual \u2014 what convergence is, why caustics matter, what\na critical curve traces \u2014 see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions \u2014\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch \u2014 quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch \u2014 single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly \u2014 build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch \u2014 multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI \u2014 extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) \u2014 multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) \u2014 for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot \u2014 how light deflects, how critical curves and\n caustics arise.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action \u2014 building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` \u2014 ray tracing, profiles, numpy\n arrays, visualization.\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth \u2014 or build a\ntraining set for neural-network classifiers \u2014 you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating \u2014 single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* \u2014 chooses the branch.\n- *\"What's the ground truth?\"* \u2014 lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* \u2014 pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch \u2014 galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid \u2014 defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer \u2014 lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_fits(\n data_path=dataset_path / \"data.fits\",\n noise_map_path=dataset_path / \"noise_map.fits\",\n psf_path=dataset_path / \"psf.fits\",\n overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot \u2014 saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` \u2014 `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch \u2014 many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch \u2014 interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n \u2192 [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour \u2014 see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates \u2014 the forward physics\n the simulator runs.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice \u2014 grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_1_introduction/tutorial_8_summary.ipynb b/notebooks/chapter_1_introduction/tutorial_7_summary.ipynb similarity index 99% rename from notebooks/chapter_1_introduction/tutorial_8_summary.ipynb rename to notebooks/chapter_1_introduction/tutorial_7_summary.ipynb index c58f2cd..a075690 100644 --- a/notebooks/chapter_1_introduction/tutorial_8_summary.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_7_summary.ipynb @@ -4,7 +4,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Tutorial 8: Summary\n", + "Tutorial 7: Summary\n", "===================\n", "\n", "In this chapter, we have learnt that:\n", @@ -338,7 +338,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_1_introduction/tutorial_8_summary.ipynb in HowToLens).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoLens calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoLens docs (https://pyautolens.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` — image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* — pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* — if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual — what convergence is, why caustics matter, what\na critical curve traces — see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions —\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch — quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch — single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly — build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch — multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI — extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) — multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) — for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot — how light deflects, how critical curves and\n caustics arise.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action — building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** — [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` — ray tracing, profiles, numpy\n arrays, visualization.\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth — or build a\ntraining set for neural-network classifiers — you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating — single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* — chooses the branch.\n- *\"What's the ground truth?\"* — lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* — pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch — galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid — defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer — lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_fits(\n data_path=dataset_path / \"data.fits\",\n noise_map_path=dataset_path / \"noise_map.fits\",\n psf_path=dataset_path / \"psf.fits\",\n overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot — saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` — `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch — many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch — interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n → [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour — see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates — the forward physics\n the simulator runs.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice — grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_1_introduction/tutorial_7_summary.ipynb in HowToLens).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoLens calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoLens docs (https://pyautolens.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` — image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* — pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* — if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual — what convergence is, why caustics matter, what\na critical curve traces — see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions —\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch — quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch — single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly — build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch — multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI — extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) — multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) — for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot — how light deflects, how critical curves and\n caustics arise.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action — building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** — [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` — ray tracing, profiles, numpy\n arrays, visualization.\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth — or build a\ntraining set for neural-network classifiers — you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating — single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* — chooses the branch.\n- *\"What's the ground truth?\"* — lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* — pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch — galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid — defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer — lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_fits(\n data_path=dataset_path / \"data.fits\",\n noise_map_path=dataset_path / \"noise_map.fits\",\n psf_path=dataset_path / \"psf.fits\",\n overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot — saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` — `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch — many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch — interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n → [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour — see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates — the forward physics\n the simulator runs.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice — grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb b/notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb index 9ec4671..7564636 100644 --- a/notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb +++ b/notebooks/chapter_3_pixelizations/tutorial_5_bayesian_formalism.ipynb @@ -12,7 +12,7 @@ "fluxes that best fit the data, and regularization smooths the solution within a Bayesian framework.\n", "\n", "This tutorial collects the linear algebra behind all of that in one place. It is the counterpart of chapter 1's\n", - "tutorial 5 on the lensing formalism: the hands-on tutorials built intuition, and now we write down the equations.\n", + "tutorial 3 on the lensing formalism: the hands-on tutorials built intuition, and now we write down the equations.\n", "We will construct, step-by-step and in code, every matrix and vector the inversion uses, solve for the source\n", "reconstruction ourselves and compute the Bayesian evidence by hand, comparing our answer at the end to the\n", "`FitImaging` object which performs this calculation internally.\n", diff --git a/scripts/chapter_1_introduction/README.md b/scripts/chapter_1_introduction/README.md index 003d058..1b8e854 100644 --- a/scripts/chapter_1_introduction/README.md +++ b/scripts/chapter_1_introduction/README.md @@ -8,16 +8,14 @@ In chapter 1, we introduce you to strong gravitational lensing and the core **Py - [Tutorial 1: Grids And Galaxies](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb) — Using grids of (y,x) coordinates with galaxies made up of light profiles. -- [Tutorial 2: Ray Tracing](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb) — Using grids, galaxies and mass profiles to perform strong lens ray-tracing. +- [Tutorial 2: Ray Tracing](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb) — Using grids, galaxies and mass profiles to perform strong lens ray-tracing. -- [Tutorial 3: More Ray Tracing](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb) — Advanced strong lens ray-tracing. +- [Tutorial 3: More Ray Tracing](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb) — The optional mathematics of ray tracing, magnification, critical curves and time delays. - [Tutorial 4: Point Sources](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_4_point_sources.ipynb) — How lensing calculations change when the source galaxy is a point source (e.g. a quasar). -- [Tutorial 5: Lensing Formalism](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_5_lensing_formalism.ipynb) — The algebraic lensing formalism used to describe strong lensing. +- [Tutorial 5: Data](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_5_data.ipynb) — Loading and inspecting telescope imaging data of a strong lens. -- [Tutorial 6: Data](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_6_data.ipynb) — Loading and inspecting telescope imaging data of a strong lens. +- [Tutorial 6: Fitting](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_6_fitting.ipynb) — Fitting data with a strong lens model. -- [Tutorial 7: Fitting](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_7_fitting.ipynb) — Fitting data with a strong lens model. - -- [Tutorial 8: Summary](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_8_summary.ipynb) — A summary of the chapter. +- [Tutorial 7: Summary](https://colab.research.google.com/github/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_7_summary.ipynb) — A summary of the chapter. diff --git a/scripts/chapter_1_introduction/tutorial_2_ray_tracing.py b/scripts/chapter_1_introduction/tutorial_2_ray_tracing.py index 1c67e30..6292e31 100644 --- a/scripts/chapter_1_introduction/tutorial_2_ray_tracing.py +++ b/scripts/chapter_1_introduction/tutorial_2_ray_tracing.py @@ -28,8 +28,8 @@ ![The COSMOS-Web Ring, labelled with the lens galaxy, lensed source galaxy and extra galaxy](https://raw.githubusercontent.com/PyAutoLabs/autolens_assistant/main/docs/images/cosmos_web_ring_rgb_labelled.png) The extra galaxy labelled in both figures is distinct from the main lens and -lensed source. As in the previous tutorial, we leave systems with additional -galaxies until Chapter 4 and use one lens galaxy and one source galaxy here. +lensed source. We begin with one lens and one source, then add more galaxies +at the end of this tutorial. These figures are also used in the [COSMOS-Web Ring guided example](https://github.com/PyAutoLabs/autolens_assistant/blob/main/docs/colab/cosmos_web_ring_colab.py). @@ -52,9 +52,9 @@ perpendicular to our line of sight, at the respective distances of the lens and source. They do not describe the orientations of the galaxies themselves. -In this tutorial, we use one foreground lens galaxy and one background source -galaxy. We will first trace the rays ourselves using grids, then use a `Tracer` -to perform the same calculation for us. +We will first trace the rays ourselves using grids, then use a `Tracer` +to perform the same calculation for us. Finally, we will extend the tracer +to include two lens galaxies and two source galaxies. The resulting **lensed image** shows how the foreground galaxy's gravity distorts the appearance of the source. @@ -68,6 +68,9 @@ - **Ray Tracing Images:** Evaluate the source's light profile on the ray-traced grid. - **Galaxies:** Combine light and mass profiles into lens and source galaxies. - **Tracer:** Perform the ray-tracing calculation using a `Tracer`. +- **Units:** Convert angular sizes into physical sizes using redshifts and a cosmology. +- **More Complexity:** Add lens light, elliptical mass, external shear and additional galaxies. +- **Multi Galaxy Ray Tracing:** Combine two lens galaxies and two sources in one tracer. - **Wrap Up:** Review what we have learned and the next steps. - **Env:** Preserve the grid used by the mapping example. """ @@ -667,28 +670,298 @@ image_plane_grid_traced = traced_grid_list[0] source_plane_grid_traced = traced_grid_list[1] +""" +__Units__ + +Throughout this tutorial, we have measured positions and radii in +arcseconds: angles on the sky. What physical size does an angle +of one arcsecond represent? + +That depends on the distance to the galaxy. We express galaxy +sizes in kiloparsecs, where one kiloparsec is 1,000 parsecs, +or approximately 3,260 light-years. + +To convert an angular size into a physical size, we use the +galaxy's redshift and a cosmology: a model of the Universe's +expansion that relates redshifts to distances. + +Our tracer already has a cosmology. Unless we supply another, +it uses the Planck 2015 cosmology. + +Let's calculate how many kiloparsecs correspond to one arcsecond +at the redshifts of our lens and source. +""" + +cosmology = tracer.cosmology + +kpc_per_arcsec_lens = cosmology.kpc_per_arcsec_from( + redshift=lens_galaxy.redshift +) +kpc_per_arcsec_source = cosmology.kpc_per_arcsec_from( + redshift=source_galaxy.redshift +) + +print( + f"Lens plane: {kpc_per_arcsec_lens:.3f} kpc per arcsecond" +) +print( + f"Source plane: {kpc_per_arcsec_source:.3f} kpc per arcsecond" +) + +""" +The conversion differs between the two planes because the +galaxies are at different distances. + +For example, we can multiply the lens's Einstein radius in +arcseconds by the lens-plane conversion to express it in +kiloparsecs. +""" + +einstein_radius_kpc = ( + sis_mass_profile.einstein_radius * kpc_per_arcsec_lens +) + +print(f"Einstein radius: {einstein_radius_kpc:.3f} kpc") + +""" +For a source galaxy's physical size, we use the source-plane +conversion instead. + +We will continue to calculate and plot coordinates in arcseconds. +These conversion factors let us express our model's sizes in +physical units when needed. + +Tutorial 3 explains the cosmological distances behind this +conversion, as part of its optional mathematical discussion. +""" + +""" +__More Complexity__ + +Our tracer currently contains one spherical lens and one source. +Let's extend this to a system with two lens galaxies and two +source galaxies. + +We first add a light profile to the main lens, representing its +central concentration of stars, or bulge. This light contributes +to the observed image. The separate mass profile determines +how the galaxy deflects light. + +We also replace the spherical mass profile with an elliptical +one. Its projected mass contours are now ellipses, so the +deflection pattern is no longer rotationally symmetric. + +Finally, we add an external shear. Surrounding matter can +distort the lensed images even when we do not model each +neighbouring structure individually. External shear approximates +this effect as a directional stretching across the image. + +Shear treats two perpendicular directions differently, so it +can turn a small circular source into an elongated image. +The main lens produces shear too; "external" describes the +additional contribution from its surroundings. + +We represent this contribution with a `MassField` at the lens +redshift. Its two dimensionless components, `gamma_1` and +`gamma_2`, specify its strength and orientation. The field +contributes deflections but no light. +""" + +lens_galaxy = al.Galaxy( + redshift=0.5, + bulge=al.lp.SersicSph( + centre=(0.0, 0.0), + intensity=2.0, + effective_radius=0.5, + sersic_index=2.5, + ), + mass=al.mp.Isothermal( + centre=(0.0, 0.0), + ell_comps=(0.0, -0.111111), + einstein_radius=1.6, + ), +) + +field = al.MassField( + redshift=0.5, + shear=al.mp.ExternalShear( + gamma_1=0.05, + gamma_2=0.0, + ), +) + +""" +Let's add a smaller companion, or satellite galaxy, at the same +redshift as the main lens. + +Its centre is at (1.0, 0.0) arcseconds, placing it one arcsecond +from the main lens along the y direction. It has both a light +profile and a mass profile, so it contributes visible light +and additional deflections. + +Its Einstein-radius parameter is 0.4 arcseconds, compared with +1.6 arcseconds for the main lens. This gives it a smaller lensing +strength, although its effect can still matter for images +passing close to it. + +Unlike the external shear, this galaxy is represented explicitly: +we specify where it is and how its light and mass are distributed. +""" + +lens_satellite = al.Galaxy( + redshift=0.5, + bulge=al.lp.DevVaucouleursSph( + centre=(1.0, 0.0), + intensity=2.0, + effective_radius=0.2, + ), + mass=al.mp.IsothermalSph( + centre=(1.0, 0.0), + einstein_radius=0.4, + ), +) + +""" +We also create two source galaxies at redshift 1.0. + +The first has two light components: a compact bulge and a more +extended disk. Both share the same centre, so their light adds +together to describe one galaxy. The second source has only a +disk and lies at a different source-plane position. + +Names such as `bulge` and `disk` help us describe the components. +The chosen light profiles and their parameters determine the +actual brightness distribution. + +Because both sources have the same redshift, they occupy the +same source plane. Adding a galaxy does not necessarily add +another plane. +""" + +source_0 = al.Galaxy( + redshift=1.0, + bulge=al.lp.DevVaucouleursSph( + centre=(0.1, 0.2), + intensity=0.3, + effective_radius=0.3, + ), + disk=al.lp.ExponentialCore( + centre=(0.1, 0.2), + ell_comps=(0.111111, 0.0), + intensity=3.0, + effective_radius=2.0, + ), +) + +source_1 = al.Galaxy( + redshift=1.0, + disk=al.lp.ExponentialCore( + centre=(-0.3, -0.5), + ell_comps=(0.1, 0.0), + intensity=8.0, + effective_radius=1.0, + ), +) + +""" +__Multi Galaxy Ray Tracing__ + +We now pass our four galaxies and external shear to a tracer. + +The main lens and its satellite share redshift 0.5, while both +sources share redshift 1.0. The tracer therefore groups the +galaxies into two planes, with two galaxies in each. + +To calculate the image, the tracer follows the same steps +we used earlier: + +1. Evaluate the light of both foreground galaxies on the + image-plane grid. + +2. Add the deflections from the main lens, its satellite + and the external shear. + +3. Subtract these total deflections from the image-plane + coordinates to obtain the source-plane coordinates. + +4. Evaluate both source galaxies' light at those traced + coordinates and add their contributions. + +5. Add the foreground light to the lensed source light + to form the complete image. + +The next plot shows the combined image. It contains the +foreground galaxies as well as the distorted images of +the two sources. +""" + +tracer = al.Tracer( + galaxies=[ + lens_galaxy, + lens_satellite, + source_0, + source_1, + ], + fields=[field], + cosmology=cosmology, +) + +image = tracer.image_2d_from(grid=image_plane_grid) + +aplt.plot_array( + array=image, + title="Two Lens Galaxies and Two Sources", +) + +""" +Let's separate the views using the tracer subplot. + +The lens-light panel shows the main lens and satellite. +The source-plane panel shows both sources before lensing, +while the full image combines foreground light with the +lensed source images. + +To see the satellite's effect, remove `lens_satellite` from +the tracer's galaxy list and rerun the image and subplot +cells. Its light disappears, and the source images change +because its deflections are also removed. + +Restore it to the list and rerun those cells to return +to the original system. + +**🤖 Ask AI:** In this example, how could I distinguish the +satellite galaxy's contribution to the observed light from +its effect on the lensed source images? +""" + +aplt.subplot_tracer( + tracer=tracer, + grid=image_plane_grid, +) + r""" __Wrap Up__ -In this tutorial, we built a lensed image step by step: - -- A **mass profile** describes the lens galaxy's mass distribution - and lets us calculate its deflection angles. -- The **lens equation**, $\beta = \theta - \alpha(\theta)$, maps - image-plane coordinates to source-plane coordinates. -- Evaluating a source **light profile** at those mapped coordinates - gives the brightness of each pixel in the lensed image. -- **Galaxy** objects hold the profiles and redshifts of the lens - and source. -- A **Tracer** brings these galaxies together and performs the - calculation for us. - -The manual calculation and the `Tracer` describe the same lens -system. Working through both shows what happens when we ask a -tracer to calculate an image. - -In Tutorial 3, we will build on this example and explore more -of the ray-tracing calculation. +We began by building a lensed image step by step: calculate +deflections, trace coordinates with the lens equation, and +evaluate the source's light at those coordinates. + +A `Tracer` performs these steps for us. It also lets us extend +the same calculation to several galaxies, combining their +light and accounting for their mass. + +We have now built a system with two foreground galaxies, +two sources and an external shear. The underlying idea is +still the same coordinate mapping we started with. + +We also used galaxy redshifts and a cosmology to connect +angular sizes in arcseconds to physical sizes in kiloparsecs. + +Tutorial 3 explains the mathematics behind these calculations, +including convergence, shear, magnification, critical curves +and caustics. You can follow its physical explanations and +figures without working through every equation, and return +to the mathematics when you need it. """ """ diff --git a/scripts/chapter_1_introduction/tutorial_3_more_ray_tracing.py b/scripts/chapter_1_introduction/tutorial_3_more_ray_tracing.py index 34d27ee..2de94bd 100644 --- a/scripts/chapter_1_introduction/tutorial_3_more_ray_tracing.py +++ b/scripts/chapter_1_introduction/tutorial_3_more_ray_tracing.py @@ -1,76 +1,93 @@ """ Tutorial 3: More Ray Tracing -============================ +=========================== -We'll now reinforce the ideas that we learnt about ray-tracing in the previous tutorial and introduce the following -new concepts: +In tutorial 2, we used the lens equation to trace coordinates from +the image plane to the source plane and build an image of a +strong lens. -- What critical curves and caustics are. - - That by specifying redshifts and a cosmology, the results are converted from arc-second coordinates to physical - units of kiloparsecs (kpc). Again, if you're not an Astronomer, you may not be familiar with the unit of parsec, it - may be worth a quick Google! - - That a `Tracer` can be given any number of galaxies. +We will now connect that picture to the quantities used to describe +gravitational lensing: convergence, deflection angles, potential, +shear and magnification. We will also explain critical curves and +caustics, the Einstein radius and time delays. -Up to now, the planes have also had just one lens galaxy or source galaxy at a time. In this example, the tracer will -have multiple galaxies at each redshift, meaning that each plane has more than one galaxy. In terms of lensing -calculations: +This tutorial includes the mathematics behind these ideas, but +following every equation is optional. You can do strong-lensing +science with a physical understanding of how mass bends light, +changes image shapes and produces multiple images. PyAutoLens +performs the calculations; your job is to understand what your +model represents and what the observations can tell you. -- If two or more lens galaxies are at the same redshift in the image-plane, the convergences, potentials and -deflection angles of their mass profiles are summed when performing lensing calculations. +Each mathematical section therefore explains the idea in words +and connects it to code or a figure. On a first pass, you can focus +on those explanations and outputs, then return to the equations +when you want to understand a calculation in more detail. -- If two or more source galaxies are at the same redshift in the source-plane, their light can simply be summed before -ray tracing. - -The `Tracer` fully accounts for this. +We assume you are familiar with the lens equation from tutorial 2. __Contents__ -- **Initial Setup:** To begin, lets setup the grid we'll ray-trace using. -- **Concise Code:** Lets set up the tracer used in the previous tutorial. -- **Critical Curves:** We can finally explain what the black lines that have appeared on many of the plots. -- **Caustics:** In the previous tutorial, we plotted the critical curves of the mass profile on the image-plane. -- **Units:** Lets plot the lensing quantities again. -- **More Complexity:** We now make a lens with some attributes we didn`t in the last tutorial. -- **Multi Galaxy Ray Tracing:** Now lets pass our 4 galaxies to a `Tracer`, which means the following will occur. -- **Wrap Up:** Summary of the script and next steps. - +- **Initial Setup:** Create the image-plane grid. +- **Concise Code:** Build a familiar lens and source in fewer steps. +- **Cosmological Distances:** Define the distances used in lensing. +- **Convergence:** Express projected mass as a dimensionless density. +- **Deflection Angles:** Relate the mass distribution to ray tracing. +- **The Lensing Potential:** Connect deflections and convergence through a scalar field. +- **Shear and Magnification:** Describe changes in image shape, area and total brightness. +- **Critical Curves and Caustics:** Locate strong stretching and its source-plane counterpart. +- **Einstein Radius:** Connect the scale of a strong lens to its enclosed projected mass. +- **Time Delays:** Explain why different images arrive at different times. +- **Wrap Up:** Review the physical meaning of the lensing quantities. +- **Env:** Preserve the grid used to resolve the critical curves. """ from autolens import jax_wrapper # Sets JAX environment before other imports # from autolens import setup_notebook; setup_notebook() +import matplotlib.pyplot as plt import numpy as np +import autoarray as aa import autolens as al import autolens.plot as aplt """ __Initial Setup__ -To begin, lets setup the grid we'll ray-trace using. But, lets do something crazy and use a higher resolution than -the previous tutorials! +We begin with a grid of 250 by 250 image-plane coordinates, +separated by 0.02 arcseconds. It covers a field 5 arcseconds across +and samples the lens more finely than the grids used earlier. + +We will call it `grid` from now on. Unless we explicitly trace it +to another plane, its coordinates are in the image plane. -Lets also stop calling it the `image_plane_grid`, and just remember from now on our `grid` is in the image-plane. +The two printed shapes show the grid's arrangement and its total +number of coordinates. """ + grid = al.Grid2D.uniform(shape_native=(250, 250), pixel_scales=0.02) -""" -The grid is now shape 250 x 250, which has more image-pixels than the 100 x 100 grid used previously. -""" print(grid.shape_native) print(grid.shape_slim) """ __Concise Code__ -Lets set up the tracer used in the previous tutorial. +Let's build a lens and source using the same approach as tutorial 2. +We can define each profile directly inside its galaxy, keeping the +whole system together in a short block of code. -Up to now, we have set up each profile one line at a time, making the code long and cumbersome to read. +The lens has a spherical isothermal mass profile at redshift 0.5. +The source has a spherical light profile at redshift 1.0 and is +centred behind the lens. -From here on, we'll set up galaxies in a single block of code, making it more concise and readable. +We will use this tracer throughout the mathematical sections, +with the same default cosmology as tutorial 2. """ + lens = al.Galaxy( - redshift=0.5, mass=al.mp.IsothermalSph(centre=(0.0, 0.0), einstein_radius=1.6) + redshift=0.5, + mass=al.mp.IsothermalSph(centre=(0.0, 0.0), einstein_radius=1.6), ) source = al.Galaxy( @@ -85,298 +102,884 @@ ) tracer = al.Tracer(galaxies=[lens, source]) +mass_profile = lens.mass +cosmology = tracer.cosmology +lens_calc = al.LensCalc.from_tracer(tracer=tracer) -""" -__Critical Curves__ +r""" +__Cosmological Distances__ + +In tutorial 2, we converted angular sizes into kiloparsecs. +The distance used in that conversion is called the +**angular diameter distance**. + +It relates an object's physical size, $l$, perpendicular to our +line of sight to its angular size, $\theta$: + +$$ +l = D\,\theta. +$$ -We can finally explain what the black lines that have appeared on many of the plots throughout this chapter -actually are. +Here $D$ is the angular diameter distance and $\theta$ must be +expressed in radians. -These lines are called the 'critical curves', and they define line of infinite magnification due to a mass profile. -They therefore mark where in the image-plane a mass profile perfectly `focuses` light rays such that if a source is -located there, it will appear very bright: potentially 10-100x as brighter than its intrinsic luminosity. +Three angular diameter distances describe the geometry of our +lens system: -The outer white line is a `tangential_critical_curve`, because it describes how the image of the source galaxy is stretched -tangentially. There is also an inner `radial_critical_curve` which appears in yellow on figures, which describes how the -image of the source galaxy is stretched radially. +- $D_l$: from the observer to the lens. +- $D_s$: from the observer to the source. +- $D_{ls}$: from the lens to the source. -However, a radial critical curve only appears when the lens galaxy's mass profile is shallower than isothermal (e.g. -when its inner mass slope is less steep than a steep power-law). To make it appear below, we therefore change -the mass profile of our lens galaxy to a `PowerLawSph` with a slope of 1.8. +These distances account for the expansion of the Universe. +In general, $D_{ls}$ is not equal to $D_s - D_l$. -In the next section, we'll introduce 'caustics', which are where the critical curves map to in the source-plane. +The cosmology calculates each distance from the relevant +redshifts. The values below are in kiloparsecs. """ -mass_profile = al.mp.PowerLawSph(centre=(0.0, 0.0), einstein_radius=1.6, slope=1.8) -lens = al.Galaxy(redshift=0.5, mass=mass_profile) +D_l = cosmology.angular_diameter_distance_to_earth_in_kpc_from(redshift=0.5) +D_s = cosmology.angular_diameter_distance_to_earth_in_kpc_from(redshift=1.0) +D_ls = cosmology.angular_diameter_distance_between_redshifts_in_kpc_from( + redshift_0=0.5, redshift_1=1.0 +) + +print(f"Observer to lens: {D_l:.3e} kpc") +print(f"Observer to source: {D_s:.3e} kpc") +print(f"Lens to source: {D_ls:.3e} kpc") + +r""" +One radian contains approximately 206,265 arcseconds. The +conversion used in tutorial 2 therefore follows directly: -tangential_critical_curve_list = al.LensCalc.from_mass_obj( - mass_obj=mass_profile -).tangential_critical_curve_list_from(grid=grid) -radial_critical_curves_list = al.LensCalc.from_mass_obj( - mass_obj=mass_profile -).radial_critical_curve_list_from(grid=grid) +$$ +l\;[\mathrm{kpc}] += +\frac{D\;[\mathrm{kpc}]}{206265} +\,\theta\;[\mathrm{arcsec}]. +$$ +For a lens-plane size we use $D_l$; for a source-plane size +we use $D_s$. The third distance, $D_{ls}$, enters the lensing +strength through the geometry between the lens and source. +The physical deflection angle, $\hat{\boldsymbol{\alpha}}$, +describes how much the light ray bends as it passes the lens. +The displacement used in our lens equation also accounts for +the distances between observer, lens and source: +$\boldsymbol{\alpha} = (D_{ls}/D_s)\hat{\boldsymbol{\alpha}}$. +This is called the **reduced deflection angle**. + +The deflections returned by PyAutoLens are these reduced angles, +expressed in arcseconds. They are the displacement we subtract +from an image-plane position to obtain its source-plane position, +as we did in tutorial 2. We will continue to call them +"deflection angles" throughout this tutorial. """ -__Caustics__ -In the previous section, we plotted the critical curves of the mass profile on the image-plane. We will now plot the -'caustics', which correspond to each critical curve ray-traced to the source-plane. This is computed by using the -lens galaxy mass profile's to calculate the deflection angles at the critical curves and ray-trace them to the -source-plane. +r""" +__Convergence__ -As discussed in the previous section, critical curves mark regions of infinite magnification. Thus, if a source -appears near a caustic in the source plane it will appear significantly brighter than its true luminosity. +Imagine adding up the lens galaxy's mass along our line of sight. +The result is its **surface mass density**, $\Sigma$: mass per +unit area projected onto the lens plane. -We again have to use a mass profile with a slope below 2.0 to ensure a radial critical curve and therefore radial -caustic is formed. As above, the tangential critical curve is white and maps to the tangential caustic in the source-plane, -which is also white. The radial critical curve is yellow and maps to the radial caustic, which is also yellow. +For a galaxy-scale lens, we usually treat the deflection as +occurring in one thin plane. Within this approximation, this +projected distribution describes how the galaxy's mass bends +the light. -We can plot both the tangential and radial critical curves and caustics using the `lines=`/`positions=` overlays object. The -critical curves are plotted only for the image-plane grid, whereas the caustic in the source plane. -""" -sis_mass_profile = al.mp.IsothermalSph(centre=(0.0, 0.0), einstein_radius=1.6) +The same projected mass distribution has a different lensing +strength for different lens and source distances. We account +for that geometry using the **critical surface density**: -tracer = al.Tracer(galaxies=[lens, source]) +$$ +\Sigma_{\mathrm{cr}} += +\frac{c^2}{4\pi G} +\frac{D_s}{D_l D_{ls}}, +$$ -tangential_critical_curve_list = al.LensCalc.from_tracer( - tracer=tracer -).tangential_critical_curve_list_from(grid=grid) -radial_critical_curves_list = al.LensCalc.from_tracer( - tracer=tracer -).radial_critical_curve_list_from(grid=grid) +where $c$ is the speed of light and $G$ is Newton's gravitational +constant. +Dividing the surface mass density by this reference value gives +the **convergence**: -traced_grid_list = tracer.traced_grid_2d_list_from(grid=grid) -source_plane_grid = np.asarray(traced_grid_list[1]) -source_plane_grid = source_plane_grid[np.isfinite(source_plane_grid).all(axis=1)] +$$ +\kappa(\boldsymbol{\theta}) += +\frac{\Sigma(\boldsymbol{\theta})}{\Sigma_{\mathrm{cr}}}. +$$ -aplt.plot_grid(grid=traced_grid_list[0], title="Plane 0 Grid") -aplt.plot_grid( - grid=al.Grid2DIrregular(values=source_plane_grid), - title="Plane 1 Grid", +Convergence is therefore dimensionless. A value of 0.5 means +that the local surface mass density is half the critical +surface density for this lens and source geometry. + +Let's calculate the critical surface density in solar masses +per square kiloparsec, then plot our lens's convergence. +""" + +sigma_cr_kpc = ( + cosmology.critical_surface_density_between_redshifts_solar_mass_per_kpc2_from( + redshift_0=0.5, redshift_1=1.0 + ) ) -tangential_caustic_list = al.LensCalc.from_tracer( - tracer=tracer -).tangential_caustic_list_from(grid=grid) -radial_caustics_list = al.LensCalc.from_tracer(tracer=tracer).radial_caustic_list_from( - grid=grid +print( + "Critical surface density: " + f"{sigma_cr_kpc:.3e} solar masses per square kiloparsec" ) +convergence = tracer.convergence_2d_from(grid=grid) + +aplt.plot_array(array=convergence, title="Convergence", use_log10=True, cb_unit="") +r""" +The convergence is largest near the centre and decreases +outwards, following the projected mass distribution of our +isothermal lens. + +Convergence values of order one indicate surface densities +relevant to strong lensing. For a circular lens, the Einstein +radius encloses a region whose **mean convergence** is one: +the average surface mass density inside it equals +$\Sigma_{\mathrm{cr}}$. + +This is an average over the enclosed area, rather than the +convergence at its edge. We will return to this connection +when we use the Einstein radius to measure the lens's mass. """ -We can also plot the caustic on the source-plane image. + +r""" +__Deflection Angles__ + +The convergence describes the projected mass distribution. +To calculate a ray's deflection, we add the contributions +from mass across the lens plane: + +$$ +\boldsymbol{\alpha}(\boldsymbol{\theta}) += +\frac{1}{\pi} +\int +\kappa(\boldsymbol{\theta}') +\frac{\boldsymbol{\theta}-\boldsymbol{\theta}'} +{|\boldsymbol{\theta}-\boldsymbol{\theta}'|^2} +\,d^2\boldsymbol{\theta}'. +$$ + +Here $\boldsymbol{\theta}$ is the position where we want the +deflection, while $\boldsymbol{\theta}'$ runs over the mass +distribution. The integral adds the contribution from each +small patch of projected mass. + +The deflection therefore depends on more than the mass at +the ray's position. Surrounding mass contributes too, which +is why the satellite galaxy and external shear in tutorial 2 +could change the source images. + +For our spherical isothermal profile, this integral has an +analytic solution. PyAutoLens evaluates that solution when +we call `deflections_yx_2d_from`; other profiles may use +numerical calculations. + +Let's plot the two components of the reduced deflection angle, +in arcseconds, as we did in tutorial 2. """ -aplt.plot_array(array=tracer.image_2d_list_from(grid=grid)[1], title="Plane 1 Image") + +deflections = tracer.deflections_yx_2d_from(grid=grid) + +deflections_y = aa.Array2D(values=deflections.slim[:, 0], mask=grid.mask) +deflections_x = aa.Array2D(values=deflections.slim[:, 1], mask=grid.mask) + +aplt.plot_array( + array=deflections_y, title="Deflection Angles (y component)", cb_unit=" arcsec" +) +aplt.plot_array( + array=deflections_x, title="Deflection Angles (x component)", cb_unit=" arcsec" +) """ -Caustics also mark the regions in the source-plane where the multiplicity of the strong lens changes. Each time -a source crosses a caustic, the number of images it produces changes by two. Try and show this yourself by changing -the (y,x) centre of the source-plane galaxy's light profile! +Each component changes sign across the lens centre. Together, +they describe the displacement we subtract from each +image-plane coordinate when tracing it to the source plane. """ -source = al.Galaxy( - redshift=1.0, - light=al.lp.SersicCoreSph( - centre=(0.0, 0.0), - intensity=1.0, - effective_radius=1.0, - sersic_index=1.0, - ), -) -tracer = al.Tracer(galaxies=[lens, source]) +r""" +__The Lensing Potential__ + +We can describe the same lens using a single scalar field: +the **lensing potential**, $\psi$. + +Its gradient gives the deflection angles: + +$$ +\boldsymbol{\alpha} = \nabla\psi. +$$ -aplt.plot_array(array=tracer.image_2d_list_from(grid=grid)[1], title="Plane 1 Image") +A gradient describes how a quantity changes with position. +Here, the change in potential along the y direction gives +the y deflection, and the change along x gives the x deflection. +The convergence is related to the potential's second +derivatives: + +$$ +\kappa += +\frac{1}{2}\nabla^2\psi += +\frac{1}{2} +\left( +\frac{\partial^2\psi}{\partial\theta_y^2} ++ +\frac{\partial^2\psi}{\partial\theta_x^2} +\right). +$$ + +The symbol $\nabla^2$, called the Laplacian, means adding +these two second derivatives. This relation is the +two-dimensional Poisson equation for gravitational lensing. + +We can therefore describe the projected mass through +convergence, or describe its lensing effect through the +potential. Their spatial derivatives connect the two. + +Let's plot the potential of our lens. With coordinates and +deflections in arcseconds, its units are arcseconds squared. """ -__Units__ -Lets plot the lensing quantities again. However, we'll now use the `Units` object of the **PyAutoLens** plotter module -to set `in_kpc=True` and therefore plot the y and x axes in kiloparsecs. +potential = tracer.potential_2d_from(grid=grid) + +aplt.plot_array(array=potential, title="Lensing Potential", cb_unit=r" arcsec$^2$") -This conversion is performed automatically, using the galaxy redshifts and cosmology. +""" +For this spherical lens, the potential has circular contours. +Its slope points radially outwards, matching the direction +of the deflection vectors used in our lens equation. """ -aplt.subplot_tracer(tracer=tracer, grid=grid) -aplt.subplot_galaxies_images(tracer=tracer, grid=grid) +r""" +We can check $\boldsymbol{\alpha} = \nabla\psi$ directly. +First, we calculate the deflections using the mass profile's +analytic expression. Then we estimate them from changes in +the potential between neighbouring grid points. + +The two calculations should agree closely over most of the +grid. Numerical differentiation is less accurate near the +central cusp and at the grid boundaries. + +We will plot the magnitude of the difference between the +two deflection vectors at each grid point, in arcseconds. +Brighter regions indicate larger differences. We also print +the median of these magnitudes to summarise the typical +difference across the grid. """ -If you're not too familiar with Cosmology, it will be unclear how exactly we converted the distance units from -arcseconds to kiloparsecs. You'll need to read up on your Cosmology lecture to understand this properly. -You can create a `Cosmology` object, which provides many methods for calculation different cosmological quantities, -which are shown below (if you're not too familiar with cosmology don't worry that you don't know what these mean, -it isn't massively important for using **PyAutoLens**). +deflections_analytic = mass_profile.deflections_yx_2d_from(grid=grid) +deflections_via_potential = mass_profile.deflections_2d_via_potential_2d_from( + grid=grid +) + +difference_yx = ( + np.asarray(deflections_analytic) - np.asarray(deflections_via_potential) +) + +difference_magnitude = np.sqrt(np.sum(difference_yx**2, axis=1)) + +difference_map = aa.Array2D(values=difference_magnitude, mask=grid.mask) + +aplt.plot_array( + array=difference_map, + title="Deflection Difference Magnitude (arcseconds)", + cb_unit=" arcsec", +) + +print( + "Median deflection difference magnitude: " + f"{np.median(difference_magnitude):.3e} arcsec" +) + +r""" +__Shear and Magnification__ + +Nearby rays generally experience slightly different deflections. +Those differences change an image's shape and size. + +To describe this locally, we calculate how each deflection +component changes with position. Since deflections are +derivatives of the potential, these are its second derivatives. +Together they form the **Hessian matrix**: + +$$ +H_{ij} += +\frac{\partial^2\psi} +{\partial\theta_i\,\partial\theta_j}. +$$ + +The indices $i$ and $j$ each stand for y or x. The diagonal +entries describe changes along the same coordinate direction; +the other entries describe changes across the two directions. -We will use a flat lambda CDM cosmology, which is the standard cosmological model often assumed in scientific studies. +Differentiating the lens equation gives the **Jacobian matrix**: + +$$ +A += +\frac{\partial\boldsymbol{\beta}} +{\partial\boldsymbol{\theta}} += +I-H. +$$ + +Here $I$ is the identity matrix. The Jacobian maps a small +image-plane displacement to a source-plane displacement: + +$$ +\delta\boldsymbol{\beta} += +A\,\delta\boldsymbol{\theta}. +$$ + +Its inverse, where it exists, tells us how a small source +region is stretched into an image. + +`LensCalc` calculates the Hessian from the tracer's +deflection field. """ -cosmology = al.cosmo.FlatLambdaCDM(H0=70, Om0=0.3) -print("Image-plane arcsec-per-kpc:") -print(cosmology.arcsec_per_kpc_from(redshift=0.5)) -print("Image-plane kpc-per-arcsec:") -print(cosmology.kpc_per_arcsec_from(redshift=0.5)) -print("Angular Diameter Distance to Image-plane (kpc):") -print(cosmology.angular_diameter_distance_to_earth_in_kpc_from(redshift=0.5)) +hessian_yy, hessian_xy, hessian_yx, hessian_xx = lens_calc.hessian_from(grid=grid) + +print(f"H_yy at the first grid point: {hessian_yy[0]:.4f}") +print(f"H_xx at the first grid point: {hessian_xx[0]:.4f}") + +r""" +The Hessian separates into two useful contributions. + +The **convergence** describes the part that acts equally +in every direction: + +$$ +\kappa = \frac{1}{2}(H_{xx}+H_{yy}). +$$ + +This is the same convergence we defined from surface mass +density earlier. + +The **shear** describes the directional part of the distortion. +Its two components are + +$$ +\gamma_1 = \frac{1}{2}(H_{xx}-H_{yy}), +\qquad +\gamma_2 = H_{xy}, +$$ + +with magnitude + +$$ +|\gamma| = \sqrt{\gamma_1^2+\gamma_2^2}. +$$ + +These components describe the strength and orientation of +the distortion. Shear allows a circular source to form an +elongated image. + +In tutorial 2, we added an external shear to represent the +effect of surrounding matter. Here we calculate the shear +produced by the lens itself. Even a spherical mass distribution +produces shear: its symmetry does not mean that radial and +tangential image stretching are equal. + +Let's calculate the shear and print its magnitude at the +first grid point. +""" -print("Source-plane arcsec-per-kpc:") -print(cosmology.arcsec_per_kpc_from(redshift=1.0)) -print("Source-plane kpc-per-arcsec:") -print(cosmology.kpc_per_arcsec_from(redshift=1.0)) -print("Angular Diameter Distance to Source-plane:") -print(cosmology.angular_diameter_distance_to_earth_in_kpc_from(redshift=1.0)) +shear = lens_calc.shear_yx_2d_via_hessian_from(grid=grid) -print("Angular Diameter Distance From Image To Source Plane:") print( - cosmology.angular_diameter_distance_between_redshifts_in_kpc_from( - redshift_0=0.5, redshift_1=1.0 - ) + "Shear magnitude at the first grid point: " + f"{shear.magnitudes[0]:.4f}" +) + +r""" +The **magnification**, $\mu$, describes the change in area +between a small source region and its image: + +$$ +\mu += +\frac{1}{\det A} += +\frac{1}{(1-\kappa)^2-|\gamma|^2}. +$$ + +Its absolute value gives the area ratio. Lensing preserves +surface brightness, so increasing the area also increases +the total light received from that source region. + +- $|\mu| > 1$: the image region is magnified. +- $|\mu| < 1$: it is demagnified. +- $\mu < 0$: its orientation is reversed, like a reflection. + +Magnification varies across an extended source, so its total +brightness depends on the combined contributions from its +different regions. + +Let's plot the signed magnification across the image plane. +Look for the circular region where its magnitude becomes +large and its sign changes. +""" + +magnification = lens_calc.magnification_2d_from(grid=grid) + +aplt.plot_array( + array=magnification, + title="Magnification", + cb_unit="", ) -print("Lensing Critical convergence:") + +r""" +For our spherical lens, we can separate the stretching into +two directions: tangentially around the lens centre and +radially towards or away from it. + +The corresponding eigenvalues of the Jacobian are + +$$ +\lambda_t = 1-\kappa-|\gamma|, +\qquad +\lambda_r = 1-\kappa+|\gamma|. +$$ + +The image stretches by factors $1/|\lambda_t|$ and +$1/|\lambda_r|$ along these directions. Their product gives +the absolute magnification. + +When an eigenvalue approaches zero, the stretching in its +direction becomes very large. This is how long, thin arcs +can form. +""" + +tangential_eigen_values = lens_calc.tangential_eigen_value_from(grid=grid) +radial_eigen_values = lens_calc.radial_eigen_value_from(grid=grid) + print( - cosmology.critical_surface_density_between_redshifts_solar_mass_per_kpc2_from( - redshift_0=0.5, redshift_1=1.0 - ) + "Tangential eigenvalue at the first grid point: " + f"{tangential_eigen_values[0]:.4f}" +) +print( + "Radial eigenvalue at the first grid point: " + f"{radial_eigen_values[0]:.4f}" ) +r""" +__Critical Curves and Caustics__ + +**Critical curves** mark positions in the image plane where +the magnification of an infinitesimally small source formally +becomes infinite: + +$$ +\det A = 0. +$$ + +A tangential critical curve occurs where $\lambda_t=0$; +a radial critical curve occurs where $\lambda_r=0$. +Images near them can be strongly stretched in the +corresponding direction. + +Real galaxies have finite size. They can form bright, +extended arcs near critical curves without having +infinite total brightness. + +Our spherical isothermal lens has a tangential critical +curve but no radial critical curve. The plot below should +therefore show one circle, at a radius of 1.6 arcseconds. """ -__More Complexity__ -We now make a lens with some attributes we didn`t in the last tutorial: +tangential_critical_curves = ( + lens_calc.tangential_critical_curve_list_from( + grid=grid, pixel_scale=grid.pixel_scale + ) +) +radial_critical_curves = ( + lens_calc.radial_critical_curve_list_from( + grid=grid, pixel_scale=grid.pixel_scale + ) +) + +fig, ax = plt.subplots(figsize=(6, 6)) + +for curves, colour, label in [ + (tangential_critical_curves, "black", "Tangential"), + (radial_critical_curves, "orange", "Radial"), +]: + for index, curve in enumerate(curves): + coordinates = np.asarray(curve) + ax.plot( + coordinates[:, 1], + coordinates[:, 0], + color=colour, + label=label if index == 0 else None, + ) + +ax.set( + title="Critical Curves: Image Plane", + xlabel="x (arcseconds)", + ylabel="y (arcseconds)", + xlim=(-2.0, 2.0), + ylim=(-2.0, 2.0), +) +ax.set_aspect("equal") +ax.legend() +plt.show() +plt.close(fig) + +r""" +Ray-tracing a critical curve to the source plane gives +a **caustic**: + +$$ +\boldsymbol{\beta}_{\mathrm{caustic}} += +\boldsymbol{\theta}_{\mathrm{critical}} +- +\boldsymbol{\alpha}( + \boldsymbol{\theta}_{\mathrm{critical}} +). +$$ + +Critical curves tell us where strongly stretched images +appear. Caustics tell us where a source must lie to +produce those images. + +For our spherical lens, the entire tangential critical +circle maps to one source-plane point: the origin. +A source centred there produces an Einstein ring. + +The plot below displays the mapped coordinates as points. +They should gather at the origin, with any small spread +arising from the numerical calculation. +""" + +tangential_caustics = lens_calc.tangential_caustic_list_from( + grid=grid, pixel_scale=grid.pixel_scale +) +radial_caustics = lens_calc.radial_caustic_list_from( + grid=grid, pixel_scale=grid.pixel_scale +) + +fig, ax = plt.subplots(figsize=(6, 6)) + +for caustics, colour, label in [ + (tangential_caustics, "black", "Tangential"), + (radial_caustics, "orange", "Radial"), +]: + for index, caustic in enumerate(caustics): + coordinates = np.asarray(caustic) + ax.scatter( + coordinates[:, 1], + coordinates[:, 0], + s=8, + color=colour, + label=label if index == 0 else None, + ) + +ax.set( + title="Caustics: Source Plane", + xlabel="x (arcseconds)", + ylabel="y (arcseconds)", + xlim=(-1.2, 1.2), + ylim=(-1.2, 1.2), +) +ax.set_aspect("equal") +ax.legend() +plt.show() +plt.close(fig) + +""" +We can reveal a radial critical curve by making the lens's +central mass distribution shallower. - - A light profile representing a `bulge` of stars, meaning the lens galaxy's light will appear in the image for the - first time. - - An external shear, which accounts for the deflection of light due to line-of-sight structures. +The code below replaces the spherical isothermal profile +with a spherical power-law profile whose slope is 1.8. +The isothermal slope is 2.0. We keep the same centre, +Einstein-radius parameter, source and cosmology. """ + lens = al.Galaxy( redshift=0.5, - bulge=al.lp.SersicSph( - centre=(0.0, 0.0), intensity=2.0, effective_radius=0.5, sersic_index=2.5 - ), - mass=al.mp.Isothermal( - centre=(0.0, 0.0), ell_comps=(0.0, -0.111111), einstein_radius=1.6 + mass=al.mp.PowerLawSph( + centre=(0.0, 0.0), + einstein_radius=1.6, + slope=1.8, ), ) -field = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0)) -print(lens) +tracer = al.Tracer(galaxies=[lens, source], cosmology=cosmology) +mass_profile = lens.mass +lens_calc = al.LensCalc.from_tracer(tracer=tracer) """ -Lets also create a small satellite galaxy nearby the lens galaxy and at the same redshift. +Rerun the two plotting cells immediately above, including +their critical-curve and caustic calculations. + +The image-plane plot should now show an inner radial critical +curve as well as the outer tangential critical curve. +The source-plane plot should show a circular radial +caustic around the central tangential caustic. + +Caustics also mark changes in the number of images. +For a point source crossing a smooth part of the radial +caustic in this example, two images appear or disappear. +An extended galaxy can straddle the caustic, so different +parts of it can have different numbers of images. + +The following cell restores our spherical isothermal lens +for the remaining sections. """ -lens_satellite = al.Galaxy( + +lens = al.Galaxy( redshift=0.5, - bulge=al.lp.DevVaucouleursSph( - centre=(1.0, 0.0), intensity=2.0, effective_radius=0.2 + mass=al.mp.IsothermalSph( + centre=(0.0, 0.0), + einstein_radius=1.6, ), - mass=al.mp.IsothermalSph(centre=(1.0, 0.0), einstein_radius=0.4), ) -print(lens_satellite) +tracer = al.Tracer(galaxies=[lens, source], cosmology=cosmology) +mass_profile = lens.mass +lens_calc = al.LensCalc.from_tracer(tracer=tracer) -""" -Lets have a quick look at the appearance of our lens galaxy and its satellite. +r""" +__Einstein Radius__ -And their deflection angles, noting that the satellite does not contribute as much to the deflections. -""" +For a circular lens with a source directly behind its centre, +the source forms an Einstein ring. Its angular radius is +the **Einstein radius**, $\theta_E$. +Our spherical isothermal lens has a circular tangential +critical curve at this radius. -# NOTE: In the new API, pass title directly as a string: -# title="Lens Galaxy Deflections (x)" +For a non-circular lens, we can define an **effective Einstein +radius** using the area enclosed by the tangential critical +curve: +$$ +\theta_E = \sqrt{\frac{A_{\mathrm{crit}}}{\pi}}. +$$ +This is the radius of a circle enclosing the same area. +It is the definition used by `LensCalc`. + +Let's recover the Einstein radius from our critical curve +and convert it into kiloparsecs at the lens redshift. """ -Now, lets make two source galaxies at redshift 1.0. Instead of using the name `light` for the light profiles, lets -instead use more descriptive names that indicate what morphological component of the galaxy the light profile -represents. In this case, we'll use the terms `bulge` and `disk`, the two main structures that a galaxy can be made of -""" -source_0 = al.Galaxy( - redshift=1.0, - bulge=al.lp.DevVaucouleursSph( - centre=(0.1, 0.2), intensity=0.3, effective_radius=0.3 - ), - disk=al.lp.ExponentialCore( - centre=(0.1, 0.2), - ell_comps=(0.111111, 0.0), - intensity=3.0, - effective_radius=2.0, - ), + +einstein_radius = lens_calc.einstein_radius_from( + grid=grid, pixel_scale=grid.pixel_scale ) -source_1 = al.Galaxy( - redshift=1.0, - disk=al.lp.ExponentialCore( - centre=(-0.3, -0.5), - ell_comps=(0.1, 0.0), - intensity=8.0, - effective_radius=1.0, - ), +kpc_per_arcsec_lens = cosmology.kpc_per_arcsec_from( + redshift=lens.redshift ) +einstein_radius_kpc = einstein_radius * kpc_per_arcsec_lens -print(source_0) -print(source_1) +print(f"Einstein radius: {einstein_radius:.4f} arcsec") +print(f"Einstein radius: {einstein_radius_kpc:.4f} kpc") """ -Lets look at our source galaxies (before lensing) +The recovered angular radius should be close to the +1.6 arcseconds specified in our spherical mass profile. +Small differences arise from locating the critical curve +on a finite grid. +""" -__Multi Galaxy Ray Tracing__ +r""" +Two simple mass distributions have useful expressions +for the Einstein radius. -Now lets pass our 4 galaxies to a `Tracer`, which means the following will occur: +For a point mass $M$: - - Using the galaxy redshifts, an image-plane and source-plane will be created, each with two galaxies. +$$ +\theta_E += +\sqrt{ +\frac{4GM}{c^2} +\frac{D_{ls}}{D_l D_s} +}. +$$ -We also pass the tracer below a Planck15 cosmology, where the cosmology of the Universe describes exactly how -ray-tracing is performed. -""" -tracer = al.Tracer( - galaxies=[lens, lens_satellite, source_0, source_1], - cosmology=al.cosmo.Planck15(), - fields=[field], -) +For a singular isothermal sphere, with one-dimensional +velocity dispersion $\sigma_v$: + +$$ +\theta_E += +4\pi +\left(\frac{\sigma_v}{c}\right)^2 +\frac{D_{ls}}{D_s}. +$$ +Both expressions give angles in radians when the physical +quantities use consistent units. + +They show how the Einstein radius connects the lens's mass +or velocity dispersion to the observer–lens–source geometry. +Our `IsothermalSph` profile specifies this angular scale +directly through its `einstein_radius` parameter. """ -We can now plot the tracer`s image, which now there are two galaxies in each plane is computed as follows: - 1) First, using the image-plane grid, the images of the lens galaxy and its satellite are computed. +r""" +For a circular lens, the mean convergence inside the Einstein +radius equals one. Its enclosed projected mass is therefore + +$$ +M(= 1 — the lens is super-critical at that point; multiple imaging is possible. -- kappa < 1 — the lens is sub-critical there. - -Because kappa is dimensionless, lens models can be composed and fitted without knowing the galaxy redshifts at all — -the redshifts and Sigma_cr are only needed at the end, to convert the inferred kappa back into physical masses. -""" -convergence = tracer.convergence_2d_from(grid=grid) - -aplt.plot_array(array=convergence, title="Convergence (kappa)", use_log10=True) - -""" -__Deflection Angles__ - -The convergence field determines the deflection angles everywhere, via a 2D integral over the whole image-plane: - - alpha(theta) = (1 / pi) * integral d^2 theta' kappa(theta') * (theta - theta') / |theta - theta'|^2 - -In plain words: every patch of mass in the lens plane pulls on every light ray. The deflection at position theta is -the sum (integral) of the pulls from all mass elements kappa(theta'), each pointing from the mass element towards -the ray and falling off as 1/distance — the 2D (projected) analogue of Newtonian gravity's inverse-square law. - -Two things follow from this integral being over *all* theta': - -- The deflection at a point depends on the mass distribution *everywhere*, not just the mass at that point. Even - mass well outside the region where images form contributes deflections (this is why external shear from - neighbouring galaxies matters, as we saw in tutorial 3). - -- For simple analytic profiles (isothermal, power-law, Sersic-like) this integral has closed-form solutions, which - is exactly what a **PyAutoLens** mass profile is: an analytic kappa(theta) paired with its analytic alpha(theta). - -The `deflections_yx_2d_from` method we have used since tutorial 2 evaluates this integral's closed-form solution. -The deflections form a 2D vector field, so we plot its y and x components separately: -""" -deflections = tracer.deflections_yx_2d_from(grid=grid) - -deflections_y = aa.Array2D(values=deflections.slim[:, 0], mask=grid.mask) -aplt.plot_array(array=deflections_y, title="Deflection Angles (y component)") - -deflections_x = aa.Array2D(values=deflections.slim[:, 1], mask=grid.mask) -aplt.plot_array(array=deflections_x, title="Deflection Angles (x component)") - -""" -__The Lensing Potential__ - -The deflection field is not arbitrary — it is the gradient of a scalar field, the **lensing potential** psi(theta): - - alpha(theta) = grad psi(theta) - -The potential is itself an integral over the convergence: - - psi(theta) = (1 / pi) * integral d^2 theta' kappa(theta') * ln|theta - theta'| - -and taking the divergence of the gradient (the Laplacian) recovers the convergence with a factor of a half: - - kappa(theta) = (1/2) * laplacian psi(theta) - -This is the 2D Poisson equation of lensing — the projected analogue of Newtonian gravity's del^2 Phi = 4 pi G rho. -The potential is the single most economical description of a lens: one scalar field from which the deflections -(first derivatives), and the convergence, shear and magnification (second derivatives) all follow. - -The `potential_2d_from` method returns psi, which we have plotted before without defining it: -""" -potential = tracer.potential_2d_from(grid=grid) - -aplt.plot_array(array=potential, title="Lensing Potential (psi)") - -""" -We can verify alpha = grad psi numerically. Mass profiles have a `deflections_2d_via_potential_2d_from` method which -computes the deflections by numerically differentiating the potential, rather than using the profile's closed-form -deflection formula. Across the grid the two agree closely — we print the median absolute difference, since the -finite-difference derivative is inaccurate right at the isothermal profile's central cusp, where the potential is -not smooth (the closed-form deflections have no such problem): -""" -deflections_analytic = mass_profile.deflections_yx_2d_from(grid=grid) -deflections_via_potential = mass_profile.deflections_2d_via_potential_2d_from(grid=grid) - -difference = np.median( - np.abs(np.asarray(deflections_analytic) - np.asarray(deflections_via_potential)) -) -print(f"Median |alpha_analytic - grad psi| = {difference:.3e} arcsec") - -""" -__Shear and Magnification__ - -How a small image is distorted by lensing is governed by how the deflection angles *change* across it — the second -derivatives of the potential. These form the 2x2 **Hessian** matrix, which `LensCalc` computes by finite -differences of the deflection field (as we saw in the workspace guides, this works for any mass distribution): - - H_yy = d(alpha_y) / d(theta_y) H_xy = d(alpha_x) / d(theta_y) - H_yx = d(alpha_y) / d(theta_x) H_xx = d(alpha_x) / d(theta_x) -""" -hessian_yy, hessian_xy, hessian_yx, hessian_xx = lens_calc.hessian_from(grid=grid) - -print( - f"Hessian components at pixel 0: H_yy = {hessian_yy[0]:.4f}, H_xx = {hessian_xx[0]:.4f}" -) - -""" -Differentiating the lens equation beta = theta - alpha(theta) gives the **Jacobian matrix** A, which maps a small -displacement in the source-plane to the corresponding displacement in the image-plane: - - A = d(beta) / d(theta) = I - H = | 1 - H_yy -H_xy | - | -H_yx 1 - H_xx | - -The Jacobian decomposes into two physically distinct distortions: - -- The **convergence** kappa = (1/2) * (H_yy + H_xx) — the isotropic part, which magnifies an image uniformly - without changing its shape. (Note this is the same kappa as before: the trace of the Hessian recovers the - Poisson equation kappa = (1/2) laplacian psi.) - -- The **shear** gamma — the anisotropic part, which stretches an image along one axis and squeezes it along the - perpendicular axis. It has two components and a magnitude: - - gamma_1 = (1/2) * (H_xx - H_yy) - gamma_2 = H_xy - |gamma| = sqrt(gamma_1^2 + gamma_2^2) - -The shear is why lensed images near the lens are stretched into tangential arcs — the tidal field of the lens -elongates them around it. -""" -shear = lens_calc.shear_yx_2d_via_hessian_from(grid=grid) - -print(f"Shear magnitude at pixel 0: |gamma| = {shear.magnitudes[0]:.4f}") - -""" -The **magnification** mu is the inverse of the Jacobian's determinant: - - mu = 1 / det(A) = 1 / [ (1 - kappa)^2 - |gamma|^2 ] - -Lensing conserves surface brightness, so a lensed image that covers more sky than the unlensed source appears -brighter in total by exactly the factor |mu|: - -- |mu| > 1 — the image is magnified (larger and brighter than the unlensed source). -- |mu| < 1 — the image is demagnified. -- mu < 0 — the image has negative parity: it is a mirror image of the source. - -The determinant factorises into two eigenvalues, giving the **tangential** and **radial** magnifications: - - lambda_t = 1 - kappa - |gamma| (tangential eigenvalue) - lambda_r = 1 - kappa + |gamma| (radial eigenvalue) - - mu = 1 / (lambda_t * lambda_r) - -An image is stretched by 1/lambda_t in the tangential direction (around the lens) and 1/lambda_r in the radial -direction (towards/away from the lens). Giant tangential arcs form where lambda_t is close to zero. -""" -magnification = lens_calc.magnification_2d_from(grid=grid) - -aplt.plot_array(array=magnification, title="Magnification (mu)") - -tangential_eigen_values = lens_calc.tangential_eigen_value_from(grid=grid) -radial_eigen_values = lens_calc.radial_eigen_value_from(grid=grid) - -print(f"Tangential eigenvalue at pixel 0: {tangential_eigen_values[0]:.4f}") -print(f"Radial eigenvalue at pixel 0: {radial_eigen_values[0]:.4f}") - -""" -__Critical Curves and Caustics__ - -Where either eigenvalue passes through zero, det(A) = 0 and the magnification formally diverges to infinity. The -closed curves in the image-plane where this happens are the **critical curves** — the white and yellow lines that -have appeared on plots since tutorial 2, and which we explored visually in tutorial 3: - -- The **tangential critical curve** (lambda_t = 0) — roughly traces the Einstein ring; sources near its source-plane - counterpart form giant tangential arcs. -- The **radial critical curve** (lambda_r = 0) — an inner curve associated with radially stretched central images. - -Ray-tracing each critical curve through the lens equation maps it to the source-plane, where it is called a -**caustic**: - - caustic = critical_curve - alpha(critical_curve) - -Caustics divide the source-plane into regions of different image multiplicity: each time a source crosses a -caustic, the number of images it produces changes by two. For our SIE lens, a source inside the tangential caustic -produces four images (plus a faint central image); between the tangential and radial caustics, two; and outside -both caustics, just one — the source is no longer multiply imaged at all. - -`LensCalc` computes both by locating the zero-contours of the eigenvalue fields on the grid: -""" -tangential_critical_curve_list = lens_calc.tangential_critical_curve_list_from( - grid=grid -) -radial_critical_curve_list = lens_calc.radial_critical_curve_list_from(grid=grid) - -tangential_caustic_list = lens_calc.tangential_caustic_list_from(grid=grid) -radial_caustic_list = lens_calc.radial_caustic_list_from(grid=grid) - -print(f"Number of tangential critical curves: {len(tangential_critical_curve_list)}") -print(f"Number of radial critical curves: {len(radial_critical_curve_list)}") - -""" -Lets plot the critical curves (image-plane) and caustics (source-plane) of our SIE side by side. Note how the -elliptical lens produces a tangential caustic with four cusps — the origin of the four-image "quad" configurations -seen in many real lenses. -""" -plt.figure(figsize=(10, 5)) - -plt.subplot(1, 2, 1) -for curve in tangential_critical_curve_list: - curve = np.asarray(curve) - plt.plot(curve[:, 1], curve[:, 0], color="black", label="Tangential") -for curve in radial_critical_curve_list: - curve = np.asarray(curve) - plt.plot(curve[:, 1], curve[:, 0], color="orange", label="Radial") -plt.gca().set_aspect("equal") -plt.title("Critical Curves (Image-Plane)") -plt.xlabel("x (arcsec)") -plt.ylabel("y (arcsec)") -plt.legend() - -plt.subplot(1, 2, 2) -for curve in tangential_caustic_list: - curve = np.asarray(curve) - plt.plot(curve[:, 1], curve[:, 0], color="black", label="Tangential") -for curve in radial_caustic_list: - curve = np.asarray(curve) - plt.plot(curve[:, 1], curve[:, 0], color="orange", label="Radial") -plt.gca().set_aspect("equal") -plt.title("Caustics (Source-Plane)") -plt.xlabel("x (arcsec)") -plt.ylabel("y (arcsec)") -plt.legend() - -plt.show() -plt.close() - -""" -__Einstein Radius__ - -The **Einstein radius** theta_E is the characteristic angular scale of a strong lens. For a circular lens with the -source perfectly aligned behind it, it is the radius of the Einstein ring the source forms. More generally (and -this is the definition **PyAutoLens** uses), it is the radius of the circle enclosing the same area as the -tangential critical curve: - - theta_E = sqrt(A_crit / pi) - -sometimes called the "effective" Einstein radius, since an elliptical lens's critical curve is not a circle. - -Two closed-form results are worth memorising. For a **point mass** M: - - theta_E = sqrt( (4 G M / c^2) * (D_ls / (D_l * D_s)) ) - -and for a **singular isothermal sphere** (SIS) with velocity dispersion sigma_v: - - theta_E = 4 pi * (sigma_v / c)^2 * (D_ls / D_s) - -The Einstein radius is also the radius within which the *mean* convergence equals exactly one — so measuring -theta_E directly measures the projected mass enclosed within it: - - M(< theta_E) = pi * theta_E^2 * Sigma_cr - -This is why the Einstein radius is celebrated as one of the most robust mass measurements in all of astrophysics: -the data pin down theta_E via the image separations almost independently of the assumed mass profile, so the -enclosed Einstein mass is trusted even when the profile's slope is not. (The main caveat, the mass-sheet -degeneracy, is discussed in the lens modeling chapters.) - -`LensCalc` computes the Einstein radius from the area of the tangential critical curve, and the enclosed -"Einstein mass" in angular units (pi * theta_E^2), which Sigma_cr converts to solar masses: -""" -einstein_radius = lens_calc.einstein_radius_from(grid=grid) - -print(f"Einstein radius (arcsec) = {einstein_radius:.4f}") -print(f"Einstein radius (kpc) = {einstein_radius * kpc_per_arcsec_lens:.4f}") - -einstein_mass_angular = lens_calc.einstein_mass_angular_from(grid=grid) -einstein_mass_solar = einstein_mass_angular * sigma_cr_arcsec - -print(f"Einstein mass (angular, arcsec^2) = {einstein_mass_angular:.4f}") -print(f"Einstein mass (solar masses) = {einstein_mass_solar:.4e}") - -""" -Reassuringly, the Einstein radius computed from the critical curve area (~1.6") matches the `einstein_radius=1.6` -parameter we gave the `Isothermal` profile — for isothermal profiles the model parameter *is* the effective -Einstein radius, which is exactly why **PyAutoLens** parameterizes its mass profiles this way: the non-linear -search then varies the quantity the data constrain most directly. - -As a second check, an `IsothermalSph` (the SIS) has a perfectly circular critical curve, so its recovered Einstein -radius equals its input parameter even more precisely: -""" -sis = al.mp.IsothermalSph(centre=(0.0, 0.0), einstein_radius=1.6) - -sis_einstein_radius = al.LensCalc.from_mass_obj(mass_obj=sis).einstein_radius_from( - grid=grid -) - -print(f"SIS input Einstein radius = 1.6, recovered = {sis_einstein_radius:.4f}") - -""" -__Time Delays__ - -The final piece of the formalism is time. Light rays forming different images of the same source travel different -paths and through different depths of the lens's gravitational potential, so they arrive at different times. Both -effects are captured by the **Fermat potential** (or time-delay surface): - - phi(theta) = (1/2) * |theta - beta|^2 - psi(theta) - -The first term is the **geometric delay** — the extra path length of a bent ray. The second is the **gravitational -(Shapiro) delay** — light slowing as it climbs through the lens's potential. Fermat's principle states that images -form at the stationary points (minima, maxima and saddle points) of this surface, which is a wonderfully compact -restatement of the lens equation: grad phi = 0 is exactly beta = theta - alpha(theta). - -The observable **time delay** between two images A and B is the difference in their Fermat potentials, scaled by -the cosmological distances: - - Delta t_AB = (1 + z_l) / c * (D_l * D_s / D_ls) * [ phi(theta_A) - phi(theta_B) ] - -The distance combination (1 + z_l) * D_l * D_s / D_ls is called the **time-delay distance**, and because it is -inversely proportional to the Hubble constant, measuring time delays between the images of a variable source (a -quasar or supernova) turns a strong lens into a cosmological probe. - -We only touch on this here — time delays belong to the modeling of lensed point sources, introduced in tutorial 4 -and covered in depth by the `autolens_workspace` point-source material. For now, we simply plot the Fermat -potential of our lens system: -""" -fermat_potential = lens_calc.fermat_potential_from(grid=grid) - -aplt.plot_array(array=fermat_potential, title="Fermat Potential (phi)") - -""" -__Wrap Up__ - -This was the mathematics lecture of **HowToLens** — every formal definition deferred by the other tutorials, in one -place. Lets summarise the chain of quantities, because it has a beautiful logical structure where everything flows -from the mass distribution and a handful of distances: - -- **Distances**: the angular diameter distances D_l, D_s and D_ls set the geometry, convert arcseconds to - kiloparsecs and define the critical surface density Sigma_cr. - -- **Convergence**: kappa = Sigma / Sigma_cr is the dimensionless projected mass; kappa >= 1 marks super-critical - regions capable of multiple imaging. - -- **Deflections and potential**: kappa determines the deflection field alpha (a 2D gravity integral) and the - lensing potential psi, tied together by alpha = grad psi and kappa = (1/2) laplacian psi. - -- **The lens equation**: beta = theta - alpha(theta) maps the image-plane to the source-plane; its - non-invertibility is why multiple images form. - -- **Distortion**: the Jacobian A = I - H decomposes into convergence (isotropic) and shear gamma (anisotropic); - magnification is mu = 1 / det(A) = 1 / (lambda_t * lambda_r). - -- **Critical curves and caustics**: where det(A) = 0, magnification diverges; caustics are their source-plane - images and set the image multiplicity. - -- **Einstein radius**: the area-equivalent radius of the tangential critical curve, whose enclosed mass - M(< theta_E) = pi * theta_E^2 * Sigma_cr is the most robust measurement strong lensing delivers. - -- **Time delays**: the Fermat potential phi = (1/2)|theta - beta|^2 - psi locates images at its stationary points - and its differences, scaled by the time-delay distance, give observable delays. - -You do not need to memorise any of this to continue — **PyAutoLens** computes every one of these quantities via the -methods used above — but you now know what each method is computing and can return to this tutorial whenever a -symbol needs unpacking. - -In the next tutorial, we turn from theory to observation: how telescope optics, exposure times and noise turn the -pristine images of a tracer into the CCD imaging data we actually observe, and how to simulate such data ourselves. - -Finally, a signpost for much later: chapter 3's tutorial 5 on the Bayesian formalism is this tutorial's twin — the -equivalent equations lecture for pixelized source reconstruction, deriving the linear inversion and Bayesian -evidence that underpin chapter 3 just as this tutorial derived the lensing quantities underpinning chapter 1. -""" diff --git a/scripts/chapter_1_introduction/tutorial_7_fitting.py b/scripts/chapter_1_introduction/tutorial_6_fitting.py similarity index 99% rename from scripts/chapter_1_introduction/tutorial_7_fitting.py rename to scripts/chapter_1_introduction/tutorial_6_fitting.py index 9d82d04..376ea4e 100644 --- a/scripts/chapter_1_introduction/tutorial_7_fitting.py +++ b/scripts/chapter_1_introduction/tutorial_6_fitting.py @@ -1,5 +1,5 @@ """ -Tutorial 7: Fitting +Tutorial 6: Fitting =================== In previous tutorials, we used light profiles to create simulated images of a tracer and visualized how these images @@ -34,7 +34,7 @@ __Contents__ - **Dataset:** Load the imaging dataset that we previously simulated, consisting of the image, noise map, and PSF. -- **Dataset Auto-Simulation:** Create the dataset by running the tutorial 6 script if it is not on your hard-disk. +- **Dataset Auto-Simulation:** Create the dataset by running the tutorial 5 script if it is not on your hard-disk. - **Mask:** Apply a mask to the data, excluding regions with low signal-to-noise ratios from the analysis. - **Masked Grid:** In tutorials 1 and 2, we emphasized that the `Grid2D` object is crucial for evaluating a lens's. - **Fitting:** Fit the lens model to the dataset and inspect the results. @@ -70,7 +70,7 @@ """ __Dataset Auto-Simulation__ -The `howtolens` dataset is the one built up and saved in tutorial 6 (`tutorial_6_data.py`). If it does +The `howtolens` dataset is the one built up and saved in tutorial 5 (`tutorial_5_data.py`). If it does not already exist on your system, it is created by running that script. This ensures every example script can be run without manually simulating data first. """ @@ -79,7 +79,7 @@ import sys subprocess.run( - [sys.executable, "scripts/chapter_1_introduction/tutorial_6_data.py"], + [sys.executable, "scripts/chapter_1_introduction/tutorial_5_data.py"], check=True, ) diff --git a/scripts/chapter_1_introduction/tutorial_8_summary.py b/scripts/chapter_1_introduction/tutorial_7_summary.py similarity index 99% rename from scripts/chapter_1_introduction/tutorial_8_summary.py rename to scripts/chapter_1_introduction/tutorial_7_summary.py index ec1cd23..30ed86c 100644 --- a/scripts/chapter_1_introduction/tutorial_8_summary.py +++ b/scripts/chapter_1_introduction/tutorial_7_summary.py @@ -1,5 +1,5 @@ """ -Tutorial 8: Summary +Tutorial 7: Summary =================== In this chapter, we have learnt that: diff --git a/scripts/chapter_3_pixelizations/tutorial_5_bayesian_formalism.py b/scripts/chapter_3_pixelizations/tutorial_5_bayesian_formalism.py index 8e46f68..f0dca00 100644 --- a/scripts/chapter_3_pixelizations/tutorial_5_bayesian_formalism.py +++ b/scripts/chapter_3_pixelizations/tutorial_5_bayesian_formalism.py @@ -7,7 +7,7 @@ fluxes that best fit the data, and regularization smooths the solution within a Bayesian framework. This tutorial collects the linear algebra behind all of that in one place. It is the counterpart of chapter 1's -tutorial 5 on the lensing formalism: the hands-on tutorials built intuition, and now we write down the equations. +tutorial 3 on the lensing formalism: the hands-on tutorials built intuition, and now we write down the equations. We will construct, step-by-step and in code, every matrix and vector the inversion uses, solve for the source reconstruction ourselves and compute the Bayesian evidence by hand, comparing our answer at the end to the `FitImaging` object which performs this calculation internally. diff --git a/workspace_index.json b/workspace_index.json index 689121d..c07709c 100644 --- a/workspace_index.json +++ b/workspace_index.json @@ -48,6 +48,9 @@ "Ray Tracing Images", "Galaxies", "Tracer", + "Units", + "More Complexity", + "Multi Galaxy Ray Tracing", "Wrap Up", "Env" ], @@ -63,17 +66,21 @@ "contents": [ "Initial Setup", "Concise Code", - "Critical Curves", - "Caustics", - "Units", - "More Complexity", - "Multi Galaxy Ray Tracing", - "Wrap Up" + "Cosmological Distances", + "Convergence", + "Deflection Angles", + "The Lensing Potential", + "Shear and Magnification", + "Critical Curves and Caustics", + "Einstein Radius", + "Time Delays", + "Wrap Up", + "Env" ], "cross_refs": [], "notebook": "notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb", "path": "scripts/chapter_1_introduction/tutorial_3_more_ray_tracing.py", - "summary": "We'll now reinforce the ideas that we learnt about ray-tracing in the previous tutorial and introduce the following new concepts:", + "summary": "In tutorial 2, we used the lens equation to trace coordinates from the image plane to the source plane and build an image of a strong lens.", "title": "Tutorial 3: More Ray Tracing" }, { @@ -95,26 +102,6 @@ "summary": "In the previous tutorials, the background sources we lensed were galaxies: extended objects whose light spreads over many thousands of light years. When lensed, their light is warped into the arcs and Einstein rings we produced with the `Tracer`, spread across many pixels of the image.", "title": "Tutorial 4: Point Sources" }, - { - "contents": [ - "Initial Setup", - "Cosmological Distances", - "The Lens Equation", - "Convergence", - "Deflection Angles", - "The Lensing Potential", - "Shear and Magnification", - "Critical Curves and Caustics", - "Einstein Radius", - "Time Delays", - "Wrap Up" - ], - "cross_refs": [], - "notebook": "notebooks/chapter_1_introduction/tutorial_5_lensing_formalism.ipynb", - "path": "scripts/chapter_1_introduction/tutorial_5_lensing_formalism.py", - "summary": "This tutorial is the equations lecture of **HowToLens**.", - "title": "Tutorial 5: Lensing Formalism" - }, { "contents": [ "Initial Setup", @@ -131,10 +118,10 @@ "scripts/simulator/interferometer.py", "scripts/simulator/weak_lensing.py" ], - "notebook": "notebooks/chapter_1_introduction/tutorial_6_data.ipynb", - "path": "scripts/chapter_1_introduction/tutorial_6_data.py", + "notebook": "notebooks/chapter_1_introduction/tutorial_5_data.ipynb", + "path": "scripts/chapter_1_introduction/tutorial_5_data.py", "summary": "In the last tutorials, we use tracers to create images of strong lenses. However, those images don't accurately represent what we would observe through a telescope.", - "title": "Tutorial 6: Data" + "title": "Tutorial 5: Data" }, { "contents": [ @@ -148,12 +135,12 @@ "Wrap Up" ], "cross_refs": [ - "tutorial_6_data.py" + "tutorial_5_data.py" ], - "notebook": "notebooks/chapter_1_introduction/tutorial_7_fitting.ipynb", - "path": "scripts/chapter_1_introduction/tutorial_7_fitting.py", + "notebook": "notebooks/chapter_1_introduction/tutorial_6_fitting.ipynb", + "path": "scripts/chapter_1_introduction/tutorial_6_fitting.py", "summary": "In previous tutorials, we used light profiles to create simulated images of a tracer and visualized how these images would appear when captured by a CCD detector on a telescope like the Hubble Space Telescope.", - "title": "Tutorial 7: Fitting" + "title": "Tutorial 6: Fitting" }, { "contents": [ @@ -165,10 +152,10 @@ "Wrap Up" ], "cross_refs": [], - "notebook": "notebooks/chapter_1_introduction/tutorial_8_summary.ipynb", - "path": "scripts/chapter_1_introduction/tutorial_8_summary.py", + "notebook": "notebooks/chapter_1_introduction/tutorial_7_summary.ipynb", + "path": "scripts/chapter_1_introduction/tutorial_7_summary.py", "summary": "In this chapter, we have learnt that:", - "title": "Tutorial 8: Summary" + "title": "Tutorial 7: Summary" }, { "contents": [