From 14b6a08dba9eccc2bb82b25e9067781b0365c0cc Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sat, 31 Oct 2026 12:36:08 +0000 Subject: [PATCH 1/2] docs: clarify introductory lensing tutorials and ray mappings --- config/build/profile_smoke.yaml | 9 +- llms-full.txt | 8 +- .../tutorial_0_visualization.ipynb | 169 ++-- .../tutorial_1_grids_and_galaxies.ipynb | 798 ++++++++++-------- .../tutorial_2_ray_tracing.ipynb | 731 +++++++++++----- .../tutorial_0_visualization.py | 145 ++-- .../tutorial_1_grids_and_galaxies.py | 789 +++++++++-------- .../tutorial_2_ray_tracing.py | 701 ++++++++++----- workspace_index.json | 17 +- 9 files changed, 2088 insertions(+), 1279 deletions(-) diff --git a/config/build/profile_smoke.yaml b/config/build/profile_smoke.yaml index 2bcf776..4845f7a 100644 --- a/config/build/profile_smoke.yaml +++ b/config/build/profile_smoke.yaml @@ -31,7 +31,8 @@ defaults: # copied in from that repo's profile_smoke.yaml. HowToLens contains only # chapter_*/tutorial_*.py, so none of them ever matched a file here. # Do not copy override patterns between repos; a pattern that matches nothing -# is silently inert, not an override. The list is now empty, and `overrides: []` -# is written explicitly because env_config.py reads `.get("overrides", [])` — -# a bare `overrides:` key would load as None and raise on iteration. -overrides: [] +# is silently inert, not an override. +overrides: + # Fixed slim indexes illustrate mappings on the lesson's 101x101 grid. + - pattern: "chapter_1_introduction/tutorial_2_ray_tracing.py" + unset: [PYAUTO_SMALL_DATASETS] diff --git a/llms-full.txt b/llms-full.txt index 73ee54f..4face2e 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -9,12 +9,12 @@ AUTO-GENERATED by PyAutoHands — do not edit by hand; regenerate with generate. ## chapter_1_introduction -- [Tutorial 0: Visualization](scripts/chapter_1_introduction/tutorial_0_visualization.py): In this tutorial, we quickly cover visualization in **PyAutoLens** and make sure images display clearly in your Jupyter notebook and on your computer screen. +- [Tutorial 0: Visualization](scripts/chapter_1_introduction/tutorial_0_visualization.py): Plot a simulated image with **PyAutoLens**, compare views of the dataset, and adjust the display so you can inspect its structure. This tutorial introduces the plotting tools used throughout the course. - Contents: Directories, Dataset, Dataset Auto-Simulation, Subplots, Plot Customization, Overlays, Wrap Up -- [HowToLens: Introduction](scripts/chapter_1_introduction/tutorial_1_grids_and_galaxies.py): A strong gravitational lens is a system where two (or more) galaxies align perfectly down our line of sight from Earth such that the foreground galaxy's mass curves space-time in on itself, such that the light of a background source galaxy is deflected and magnified. This means we can see the background source galaxy multiple times, as multiple arcs or rings, because multiple paths through the foreground galaxy's mass are taken by the source's light. +- [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 (or galaxies) curves space-time around it, causing light rays from a background source to appear deflected. - - Contents: Grid, Mass Profiles, Ray Tracing Grids, Ray Tracing Images, Galaxies, Tracer, Mappings, Wrap Up +- [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 - [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 - [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. diff --git a/notebooks/chapter_1_introduction/tutorial_0_visualization.ipynb b/notebooks/chapter_1_introduction/tutorial_0_visualization.ipynb index ee700c3..a1f4ecd 100644 --- a/notebooks/chapter_1_introduction/tutorial_0_visualization.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_0_visualization.ipynb @@ -5,20 +5,20 @@ "metadata": {}, "source": [ "Tutorial 0: Visualization\n", - "=========================\n", + "========================\n", "\n", - "In this tutorial, we quickly cover visualization in **PyAutoLens** and make sure images display\n", - "clearly in your Jupyter notebook and on your computer screen.\n", + "Plot a simulated image with **PyAutoLens**, compare views of the dataset, and adjust the display so you\n", + "can inspect its structure. This tutorial introduces the plotting tools used throughout the course.\n", "\n", "__Contents__\n", "\n", - "- **Directories:** **HowToLens** assumes the working directory is the `HowToLens` repository root on your hard-disk.\n", - "- **Dataset:** Load and plot the strong lens dataset.\n", - "- **Dataset Auto-Simulation:** Create the dataset via its simulator script if it is not on your hard-disk.\n", - "- **Subplots:** In addition to plotting individual figures, **PyAutoLens** can plot `subplots` which show multiple.\n", - "- **Plot Customization:** Does the figure display correctly on your computer screen?\n", - "- **Overlays:** Overlays such as critical curves and image positions are added using the `lines=` and `positions=`.\n", - "- **Wrap Up:** Summary of the script and next steps." + "- **Directories:** Check where the tutorial looks for files.\n", + "- **Dataset:** Identify the simulated image we will use.\n", + "- **Dataset Auto-Simulation:** Generate the example if needed, load it and plot the image.\n", + "- **Subplots:** Compare several views of the dataset.\n", + "- **Plot Customization:** Adjust colour scaling and figure size.\n", + "- **Overlays:** Draw a model-derived curve on an unblurred lensed image.\n", + "- **Wrap Up:** Review the plotting tools and continue to Tutorial 1." ] }, { @@ -77,31 +77,39 @@ "source": [ "__Directories__\n", "\n", - "**HowToLens** assumes the working directory is the `HowToLens` repository root on your hard-disk. This setup\n", - "allows **PyAutoLens** to:\n", + "Run this tutorial from the `HowToLens` repository folder, which contains `config/`, `dataset/` and `scripts/`.\n", + "Relative paths in the tutorial are resolved from your current working directory.\n", "\n", - "- Load configuration settings from the config files in the `config/` folder.\n", + "The next cell prints that directory. Check that it points to your `HowToLens` folder before continuing.\n", "\n", - "- Load the example strong lens datasets in the `dataset/` folder.\n", - "\n", - "- Write the results of model-fits to your hard-disk in the `output/` folder.\n", - "\n", - "If you do not have a clone of **HowToLens** on your computer, you can download it here:\n", - "\n", - " https://github.com/PyAutoLabs/HowToLens\n", + "If you have not downloaded the tutorials, get them from [the HowToLens repository](https://github.com/PyAutoLabs/HowToLens)." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from pathlib import Path\n", "\n", - "If your working directory does not match this path on your computer, you can manually set it as follows (the\n", - "example below shows the path I would use on my laptop. The code is commented out so you do not use this path in\n", - "this tutorial!" + "print(Path.cwd())" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If the directory is incorrect, replace the example path below with the location of your repository and uncomment\n", + "the two lines. Then rerun the cell above to check the directory." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "# workspace_path = \"/Users/Jammy/Code/PyAuto/HowToLens\"\n", - "# #%cd $workspace_path\n", - "# print(f\"Working Directory has been set to `{workspace_path}`\")" + "# import os\n", + "# os.chdir(\"/path/to/HowToLens\")" ], "outputs": [], "execution_count": null @@ -112,19 +120,17 @@ "source": [ "__Dataset__\n", "\n", - "The `dataset_path` specifies where the dataset is located, which is the\n", - "directory `dataset/imaging/simple__no_lens_light` of the HowToLens repository.\n", + "We will use a simulated image of a gravitationally lensed galaxy. This example omits light from the foreground\n", + "lens galaxy so that we can focus on the lensed source.\n", "\n", - "The simulated images of strong lenses used throughout the **HowToLens** lectures are written to the `dataset`\n", - "directory at runtime by the simulator scripts in `scripts/simulator/`." + "The following path identifies the dataset folder within `HowToLens`. If the data are missing, the next section\n", + "generates them." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "from pathlib import Path\n", - "\n", "import autolens as al\n", "import autolens.plot as aplt\n", "\n", @@ -139,8 +145,8 @@ "source": [ "__Dataset Auto-Simulation__\n", "\n", - "If the dataset does not already exist on your system, it is created by running the corresponding\n", - "simulator script. This ensures every example script can be run without manually simulating data first." + "The next cell runs the simulator if the example dataset needs to be generated. You do not need to run the\n", + "simulator separately." ] }, { @@ -151,6 +157,7 @@ " import subprocess\n", " import sys\n", "\n", + " # Use the same Python interpreter as this tutorial.\n", " subprocess.run(\n", " [sys.executable, \"scripts/simulator/no_lens_light.py\"],\n", " check=True,\n", @@ -163,7 +170,12 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We now load this dataset from .fits files and create an instance of an `Imaging` object." + "We now load three FITS files into an `Imaging` object: the image, its noise map and the point-spread function\n", + "(PSF). The noise map describes the uncertainty in each pixel; the PSF describes how the image of a point source\n", + "is blurred.\n", + "\n", + "Each pixel spans 0.1 arcseconds on each side, matching the simulator settings. Loading these files does not\n", + "fit a model to the image." ] }, { @@ -184,7 +196,10 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can plot an image with `aplt.plot_array()`, passing the data array and a title." + "Plot the simulated image using `aplt.plot_array()`. Look for the background galaxy\u2019s light distorted into bright\n", + "features around the centre of the lens. The foreground galaxy contributes no light in this example.\n", + "\n", + "The simulation includes blurring by the PSF and noise, so the image includes both instrumental blurring and random fluctuations." ] }, { @@ -202,10 +217,14 @@ "source": [ "__Subplots__\n", "\n", - "In addition to plotting individual figures, **PyAutoLens** can plot `subplots` which show multiple\n", - "views of the dataset at once.\n", + "A subplot brings several views of the dataset into one figure. The next cell displays the image, noise map,\n", + "PSF and signal-to-noise map, alongside additional diagnostic panels.\n", + "\n", + "Compare the image with its logarithmic view, labelled \u201cData (log10)\u201d. The different colour scaling helps\n", + "reveal faint structure alongside bright features; it does not change the underlying data.\n", "\n", - "The `aplt.subplot_imaging_dataset()` function plots the data, noise-map and PSF together." + "For now, focus on these image panels and the noise map. We will introduce the numerical settings shown in\n", + "the other panels as they become relevant." ] }, { @@ -223,43 +242,63 @@ "source": [ "__Plot Customization__\n", "\n", - "Does the figure display correctly on your computer screen?\n", - "\n", - "If not, the default matplotlib settings can be customized via the config files in:\n", - "\n", - " config/visualize/\n", - "\n", - "Key config entries:\n", + "Change a figure's appearance by passing options to `aplt.plot_array()`. Here we use a logarithmic colour\n", + "scale to make faint structure easier to see. We create a 7-by-7-inch figure with Matplotlib and pass its axes\n", + "to the plotting function.\n", "\n", - " - `mat_wrap.yaml` -> Figure -> figure: -> figsize\n", - " - `mat_wrap.yaml` -> YLabel -> figure: -> fontsize\n", - " - `mat_wrap.yaml` -> XLabel -> figure: -> fontsize\n", - " - `mat_wrap.yaml` -> TickParams -> figure: -> labelsize\n", - " - `mat_wrap.yaml` -> YTicks -> figure: -> labelsize\n", - " - `mat_wrap.yaml` -> XTicks -> figure: -> labelsize\n", - "\n", - "For quick one-off adjustments you can pass `title=`, `colormap=`, and `use_log10=` directly:" + "Compare this plot with the first image. Logarithmic scaling changes how positive pixel values map to colours;\n", + "it does not change the image or make faint features more statistically significant." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "aplt.plot_array(array=dataset.data, title=\"Dataset Image (Log10)\", use_log10=True)" + "import matplotlib.pyplot as plt\n", + "\n", + "fig, ax = plt.subplots(figsize=(7, 7))\n", + "aplt.plot_array(\n", + " array=dataset.data,\n", + " title=\"Dataset Image (Log10)\",\n", + " use_log10=True,\n", + " ax=ax,\n", + ")\n", + "plt.show()\n", + "plt.close(fig)" ], "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Try changing `use_log10=True` to `False` and rerun the cell to return to a linear colour scale. To enlarge\n", + "the figure, change `figsize=(7, 7)` to `(9, 9)`. Restore the starting values to reproduce the plot above.\n", + "\n", + "You can also set `colormap=\"gray\"` to display the image in greyscale. For persistent defaults, explore\n", + "`config/visualize/general.yaml`; its `colormap` entry sets the default colour map and\n", + "`subplot_shape_to_figsize_factor` controls subplot sizes. The per-call options above are enough for this lesson.\n", + "\n", + "**\ud83e\udd16 Ask AI:** Why can logarithmic colour scaling make faint structure easier to see without increasing its\n", + "signal-to-noise ratio?" + ] + }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Overlays__\n", "\n", - "Overlays such as critical curves and image positions are added using the `lines=` and `positions=`\n", - "keyword arguments.\n", + "Overlays place reference curves or positions on an image. The `lines=` argument draws curves, while\n", + "`positions=` marks coordinates.\n", + "\n", + "Here we create a new, illustrative lens model and plot its unblurred lensed image with a tangential critical curve.\n", + "This curve is calculated from the model; it is not a feature measured directly from the image. Later tutorials\n", + "explain its lensing meaning.\n", "\n", - "For example, we can compute the critical curves of a tracer and overlay them on the image." + "This model differs from the one used to simulate the dataset above. We evaluate its image at fixed parameters,\n", + "without adding a PSF or noise and without fitting the dataset. Look for the curve drawn over the unblurred lensed image." ] }, { @@ -301,18 +340,10 @@ "source": [ "__Wrap Up__\n", "\n", - "Throughout the lectures you'll see lots more visuals plotted on figures and subplots.\n", - "\n", - "The key plotting functions you'll use are:\n", - "\n", - " - `aplt.plot_array(array, title, ...)` \u2014 plot any 2D array.\n", - " - `aplt.plot_grid(grid, title, ...)` \u2014 plot a 2D grid of coordinates.\n", - " - `aplt.subplot_imaging_dataset(dataset)` \u2014 multi-panel dataset overview.\n", - " - `aplt.subplot_tracer(tracer, grid)` \u2014 multi-panel tracer overview.\n", - " - `aplt.subplot_fit_imaging(fit)` \u2014 multi-panel fit overview.\n", + "You have plotted an image, compared dataset panels and changed the display without changing the pixel values.\n", + "Use `aplt.plot_array()` for an individual image and `aplt.subplot_imaging_dataset()` for a dataset overview.\n", "\n", - "Great! Hopefully, visualization in **PyAutoLens** is displaying nicely for us to get on with the\n", - "**HowToLens** lecture series." + "Next, open Tutorial 1: Grids and Galaxies to learn how coordinates and light profiles produce a galaxy image." ] } ], diff --git a/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb b/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb index b16005f..52c7629 100644 --- a/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb @@ -5,67 +5,71 @@ "metadata": {}, "source": [ "HowToLens: Introduction\n", - "=======================\n", + "======================\n", "\n", - "A strong gravitational lens is a system where two (or more) galaxies align perfectly down our line of sight from Earth\n", - "such that the foreground galaxy's mass curves space-time in on itself, such that the light of a background source galaxy\n", - "is deflected and magnified. This means we can see the background source galaxy multiple times, as multiple arcs or rings,\n", - "because multiple paths through the foreground galaxy's mass are taken by the source's light.\n", + "A distant galaxy can appear as multiple images, stretched arcs or a ring when its light passes a sufficiently\n", + "well-aligned foreground galaxy. The foreground galaxy\u2019s gravity deflects the light, allowing it to reach us\n", + "along different paths. This is strong gravitational lensing.\n", "\n", - "Here is a schematic of a strong gravitational lens:\n", + "We call the foreground galaxy the **lens** and the background galaxy the **source**. The side-on illustration\n", + "below shows two paths by which light from the source can reach the observer. It illustrates the geometry;\n", + "it is not drawn to scale.\n", "\n", - "![Schematic of Gravitational Lensing](https://raw.githubusercontent.com/PyAutoLabs/PyAutoLens/main/docs/overview/images/overview_1_lensing/schematic.jpg)\n", - "**Credit: F. Courbin, S. G. Djorgovski, G. Meylan, et al., Caltech / EPFL / WMKO**\n", - "https://www.astro.caltech.edu/~george/qsolens/\n", + "![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)\n", "\n", - "Today, Astronomers use computer software, statistical algorithms and image processing techniques analyse the light of\n", - "these strong gravitational lenses. They are used for a wide range of scientific studies, including studying dark matter\n", - "in the foreground lens galaxies, the morphology and structure of the background source galaxies, and even the expansion\n", - "of the Universe itself.\n", + "Looking towards the lens, we see the source\u2019s distorted images around it. The JWST image below shows the\n", + "COSMOS-Web Ring: the bright central galaxy is the lens, and the surrounding ring is light from the more\n", + "distant source galaxy.\n", "\n", - "The **HowToLens** series of tutorials will teach you how to perform this analysis yourself, using the open-source\n", - "software package **PyAutoLens**. By the end of the **HowToLens** series, you'll be able to take an image of\n", - "strong lens and study it using the same techniques that professional astronomers use today.\n", + "![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", - "Tutorial 1: Grids And Galaxies\n", - "==============================\n", + "Both figures label an **Extra Galaxy**. This is another galaxy visible near the ring in the image, distinct\n", + "from the main lens and the lensed source. Its light can overlap the region we want to model. Appearing nearby\n", + "on the sky does not by itself tell us whether it is at the same distance as the lens.\n", "\n", - "In this tutorial, we will introduce the first fundamental concepts and quantities used to study strong lenses.\n", - "These concepts will enable us to create images of galaxies and analyze how their light is distributed across space.\n", - "Additionally, we will explore how adjusting various properties of galaxies can alter their appearance. For instance,\n", - "we can change the size of a galaxy, rotate it, or modify its brightness.\n", + "For now, the strong lenses we consider in this chapter have one lens galaxy. Chapter 4 introduces systems\n", + "with additional galaxies and explains how to account for their light and, where relevant, their gravitational\n", + "effect on the source images.\n", "\n", - "To create these images, we first need to define 2D grids of \\((y, x)\\) coordinates. We will shift and rotate these\n", - "grids to manipulate the appearance of the galaxy in the generated images. The grid will serve as the input for light\n", - "profiles, which are analytic functions that describe the distribution of a galaxy's light. By evaluating these light\n", - "profiles on the grid, we can effectively generate images that represent the structure and characteristics of galaxies.\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", - "This tutorial won't yet perform any lensing calculations, which are introduced in the next tutorial.\n", + "By modelling these images, astronomers can study the distribution of mass in the lens, including dark matter,\n", + "and reconstruct the source galaxy\u2019s light. Some lens systems also allow measurements of the Universe\u2019s expansion.\n", "\n", - "Here is an overview of what we'll cover in this tutorial:\n", + "**HowToLens** teaches you to build and fit these models using **PyAutoLens**. We begin with simple descriptions\n", + "of galaxy light, then introduce gravitational lensing and the statistical methods used to compare models with data.\n", "\n", - "- **Grids**: We'll create a uniform grid of $(y,x)$ coordinates and show how it can be used to measure the light of a galaxy.\n", - "- **Geometry**: We'll show how to shift and rotate a grid, and convert it to elliptical coordinates.\n", - "- **Light Profiles**: We'll introduce light profiles, analytic functions that describe how a galaxy's light is distributed.\n", - "- **Galaxies**: We'll create galaxies containing light profiles and show how to compute their image.\n", - "- **Units**: We'll show how to convert the units of a galaxy's image to physical units like kiloparsecs.\n", + "Tutorial 1: Grids and Galaxies\n", + "=============================\n", "\n", + "In this tutorial, we will build an image of a galaxy from light profiles and explore how its appearance changes when we\n", + "adjust its position, orientation, size and brightness.\n", "\n", - "The imports below are required to run the HowToLens tutorials in a Jupiter notebook. They also import the\n", - "`autolens` package and the `autolens.plot` module which are used throughout the tutorials.\n", + "We start with a grid of positions on the sky, written in `(y, x)` order. A **light profile** is a mathematical\n", + "function that describes how a galaxy\u2019s light varies with position. It is a model: a simplified mathematical\n", + "description of the galaxy. Evaluating it on the grid gives us a **light-profile image**. Later, we will\n", + "include the telescope\u2019s blurring to construct a **model image** that can be compared with observed data.\n", + "\n", + "To describe a profile centred and oriented anywhere in the image, we express the grid coordinates relative\n", + "to that profile. We will work through these coordinate transformations before using the library\u2019s light\n", + "profiles and galaxy objects.\n", + "\n", + "The examples evaluate models with parameters that we choose. They do not yet fit a model to observed data.\n", + "\n", + "We introduce the deflection of light by gravity in the next tutorial.\n", "\n", "__Contents__\n", "\n", - "- **Grids:** A `Grid2D` is a set of two-dimensional $(y,x)$ coordinates that represent points in space where we.\n", - "- **Geometry:** The above grid is centered on the origin (0.0\", 0.0\").\n", - "- **Light Profiles:** Galaxies are collections of stars, gas, dust, and other astronomical objects that emit light.\n", - "- **One Dimension Projection:** We often want to calculative 1D quantities of a light profile, for example to plot how its light.\n", - "- **Galaxies:** Galaxies are collections of light profiles that represent a galaxy's luminous emission.\n", - "- **Units:** By assuming a redshift for a galaxy we can convert its quantities from arcseconds to kiloparsecs.\n", - "- **Wrap Up:** Summary of the script and next steps.\n", - "- **Advanced Topics:** Optional reference material for expert users, not needed on a first read.\n", - "- **Other Unit Conversion:** Other unit conversions a galaxy's redshift enables (e.g. AB magnitudes).\n", - "- **Over Sampling:** The adaptive over-sampling scheme used to evaluate light profiles accurately." + "- **Grids:** Create image coordinates and inspect their native and slim representations.\n", + "- **Geometry:** Express coordinates relative to a profile\u2019s centre, orientation and ellipticity.\n", + "- **Light Profiles:** Calculate S\u00e9rsic intensities and build light-profile images.\n", + "- **One Dimension Projection:** Sample intensity along a profile\u2019s major axis.\n", + "- **Galaxies:** Combine light profiles and galaxies, and compare their contributions.\n", + "- **Units:** Convert angular sizes into physical sizes using a cosmology.\n", + "- **Wrap Up:** Review the main ideas.\n", + "- **Advanced Topics:** Optional notes on units and numerical accuracy.\n", + "- **Other Unit Conversion:** Understand what brightness calibration requires.\n", + "- **Over Sampling:** Improve the numerical calculation within each pixel." ] }, { @@ -132,20 +136,17 @@ "source": [ "__Grids__\n", "\n", - "A `Grid2D` is a set of two-dimensional $(y,x)$ coordinates that represent points in space where we evaluate the \n", - "light emitted by a galaxy.\n", + "To build a galaxy image, we need positions at which to evaluate its light profile. A `Grid2D` stores these\n", + "positions in `(y, x)` order. For a uniform image grid, each coordinate marks the centre of a pixel.\n", "\n", - "Each coordinate on the grid is referred to as a 'pixel'. This is because we use the grid to measure the brightness of a \n", - "galaxy at each of these coordinates, allowing us to create an image of the galaxy.\n", + "We express positions in **arcseconds**, a unit of angle equal to 1/3600 of a degree. This describes distances\n", + "across the sky rather than physical distances within the galaxy.\n", "\n", - "Grids are defined in units of 'arc-seconds' (\"). An arc-second is a unit of angular measurement used by astronomers to \n", - "describe the apparent size of objects in the sky.\n", + "The grid below has 101 rows and 101 columns. Setting `pixel_scales=0.1` gives square pixels that span\n", + "0.1 arcseconds on each side.\n", "\n", - "The `pixel_scales` parameter sets how many arc-seconds each pixel represents. For example, if `pixel_scales=0.1`, \n", - "then each pixel covers 0.1\" of the sky.\n", - "\n", - "We create a uniform 2D grid of 101 x 101 pixels with a pixel scale of 0.1\", corresponding to an area \n", - "of 10.1\" x 10.1\", spanning from -5.05\" to 5.05\" in both the y and x directions." + "The image covers 10.1 by 10.1 arcseconds, with edges at \u22125.05 and +5.05 arcseconds. The pixel centres run\n", + "from \u22125.0 to +5.0 arcseconds along each axis, with the central pixel at `(0.0, 0.0)`." ] }, { @@ -153,11 +154,8 @@ "metadata": {}, "source": [ "grid = al.Grid2D.uniform(\n", - " shape_native=(\n", - " 101,\n", - " 101,\n", - " ), # The dimensions of the grid, which here is 101 x 101 pixels.\n", - " pixel_scales=0.1, # The conversion factor between pixel units and arc-seconds.\n", + " shape_native=(101, 101),\n", + " pixel_scales=0.1,\n", ")" ], "outputs": [], @@ -167,7 +165,10 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can visualize this grid as a uniform grid of dots, each representing a coordinate where the light is measured." + "Plot the grid to see where we will evaluate the light profile. Each dot marks a pixel centre, with neighbouring\n", + "dots separated by 0.1 arcseconds horizontally and vertically.\n", + "\n", + "This figure shows positions only. We have not yet assigned a brightness to any pixel." ] }, { @@ -183,23 +184,21 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Each coordinate in the grid corresponds to an arc-second position. Below, we print a few of these coordinates to see \n", - "the values." + "We can inspect individual coordinates using `grid.native[row, column]`. Rows and columns are numbered from\n", + "zero, and each entry contains a `(y, x)` pair in arcseconds.\n", + "\n", + "The first three entries below lie along the top row: their y coordinate stays at +5.0 while x increases\n", + "from \u22125.0 in steps of 0.1. The final entry starts the next row, where y decreases to +4.9." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(\"(y,x) pixel 0:\")\n", - "print(grid.native[0, 0]) # The coordinate of the first pixel.\n", - "print(\"(y,x) pixel 1:\")\n", - "print(grid.native[0, 1]) # The coordinate of the second pixel.\n", - "print(\"(y,x) pixel 2:\")\n", - "print(grid.native[0, 2]) # The coordinate of the third pixel.\n", - "print(\"(y,x) pixel 100:\")\n", - "print(grid.native[1, 0]) # The coordinate of the 100th pixel.\n", - "print(\"...\")" + "print(\"Row 0, column 0 (y, x):\", grid.native[0, 0])\n", + "print(\"Row 0, column 1 (y, x):\", grid.native[0, 1])\n", + "print(\"Row 0, column 2 (y, x):\", grid.native[0, 2])\n", + "print(\"Row 1, column 0 (y, x):\", grid.native[1, 0])" ], "outputs": [], "execution_count": null @@ -208,22 +207,21 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Grids have two internal representations, `native` and `slim`:\n", + "The same grid coordinates can be arranged in two ways:\n", "\n", - "- `native`: A 2D array with shape [total_y_pixels, total_x_pixels, 2], where the 2 corresponds to the (y,x) coordinates.\n", - "- `slim`: A 1D array with shape [total_y_pixels * total_x_pixels, 2], where the coordinates are 'flattened' into a single list.\n", + "- **`native`** preserves the rows and columns of the image. Use `grid.native[row, column]` to select a pixel\u2019s `(y, x)` coordinates.\n", + "- **`slim`** lists the coordinate pairs in row order. Use `grid.slim[index]` to select a pair from that list.\n", "\n", - "These formats are useful for different calculations and plotting. Here, we show the same coordinate using both formats." + "These are different arrangements of the same positions, not different grids. The two expressions below\n", + "return the coordinates of the same pixel." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(\"(y,x) pixel 0 (accessed via native):\")\n", - "print(grid.native[0, 0])\n", - "print(\"(y,x) pixel 0 (accessed via slim 1D):\")\n", - "print(grid.slim[0])" + "print(\"First coordinate via native:\", grid.native[0, 0])\n", + "print(\"First coordinate via slim:\", grid.slim[0])" ], "outputs": [], "execution_count": null @@ -232,16 +230,21 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can also check the shapes of the `Grid2D` object in both `native` and `slim` formats. For this grid, \n", - "the `native` shape is (101, 101, 2) and the `slim` shape is (10201, 2)." + "For this unmasked grid, `native` has shape `(101, 101, 2)`: 101 rows, 101 columns and two values per pixel\u2014the\n", + "y and x coordinates.\n", + "\n", + "The `slim` representation has shape `(10201, 2)`: one coordinate pair for each of the 101 \u00d7 101 pixels.\n", + "The final dimension remains two because each position still needs both y and x.\n", + "\n", + "Print the shapes below to check how the coordinates are arranged." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(grid.native.shape)\n", - "print(grid.slim.shape)" + "print(\"Native shape:\", grid.native.shape)\n", + "print(\"Slim shape:\", grid.slim.shape)" ], "outputs": [], "execution_count": null @@ -250,32 +253,38 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "For the HowToLens tutorials, you don't need to fully understand why grids have both native and slim representations. \n", - "Just note that both are used for calculations and plotting.\n", + "Try changing the grid definition above, then rerun the plotting and coordinate-inspection cells:\n", + "\n", + "- Keep `shape_native=(101, 101)` and change `pixel_scales` from `0.1` to `0.2`. The number of points stays the same, but their spacing doubles and the image covers 20.2 by 20.2 arcseconds.\n", + "- Restore `pixel_scales=0.1`, then change `shape_native` to `(51, 51)`. The spacing stays the same, but fewer pixels cover a smaller region: 5.1 by 5.1 arcseconds.\n", + "\n", + "Compare the axis ranges in the plots and the printed array shapes. Changing pixel scale changes the angular\n", + "spacing; changing the number of pixels changes how many positions we sample.\n", "\n", - "*Exercise*: Try creating grids with different shapes and pixel scales using the `al.Grid2D.uniform()` function above. \n", - "Observe how the grid coordinates change when you adjust `shape_native` and `pixel_scales`.\n", + "Before continuing, restore `shape_native=(101, 101)` and `pixel_scales=0.1`, then rerun the grid-definition cell.\n", "\n", "__Geometry__\n", "\n", - "The above grid is centered on the origin (0.0\", 0.0\"). Sometimes, we need to shift the grid to be centered on a \n", - "specific point, like the center of a galaxy.\n", + "Our grid describes positions relative to the image centre, `(0.0, 0.0)`. To evaluate a galaxy\u2019s light profile,\n", + "we first express those positions relative to the galaxy\u2019s centre.\n", "\n", - "We can shift the grid to a new center, (y_c, x_c), by subtracting this center from each coordinate." + "For a galaxy centred at `(0.3, 0.5)` arcseconds, subtract 0.3 from every y coordinate and 0.5 from every\n", + "x coordinate. The galaxy\u2019s centre then has coordinates `(0.0, 0.0)` in this new reference frame.\n", + "\n", + "This changes how we describe the positions; it does not move the pixels on the sky." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "centre = (0.3, 0.5) # Shifting the grid to be centered at y=0.3\", x=0.5\".\n", + "centre = (0.3, 0.5)\n", "\n", - "grid_shifted = grid\n", - "grid_shifted[:, 0] = grid_shifted[:, 0] - centre[0] # Shift in y-direction.\n", - "grid_shifted[:, 1] = grid_shifted[:, 1] - centre[1] # Shift in x-direction.\n", + "grid_shifted = grid.copy() # Preserve the original image coordinates.\n", + "grid_shifted[:, 0] = grid_shifted[:, 0] - centre[0]\n", + "grid_shifted[:, 1] = grid_shifted[:, 1] - centre[1]\n", "\n", - "print(\"(y,x) pixel 0 After Shift:\")\n", - "print(grid_shifted.native[0, 0]) # The coordinate of the first pixel after shifting." + "print(\"First coordinate relative to the galaxy centre:\", grid_shifted.native[0, 0])" ], "outputs": [], "execution_count": null @@ -284,17 +293,24 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The grid is now centered around (0.3\", 0.5\"). We can plot the shifted grid to see this change.\n", + "The first coordinate changes from `(5.0, -5.0)` to `(4.7, -5.5)` arcseconds. The grid\u2019s spacing and shape\n", + "are unchanged, but its coordinates now describe offsets from the galaxy\u2019s centre.\n", + "\n", + "In the plot below, the original image centre lies at `(-0.3, -0.5)`. The origin of this coordinate frame\n", + "represents the galaxy\u2019s centre.\n", "\n", - "*Exercise*: Try shifting the grid to a different center, for example (0.0\", 0.0\") or (2.0\", 3.0\"). Observe how the\n", - "center of the grid changes when you adjust the `centre` variable." + "Try setting `centre=(0.0, 0.0)` and rerunning the shift and plot cells: the coordinates should match the\n", + "original grid. Restore `centre=(0.3, 0.5)` and rerun both cells before continuing." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "aplt.plot_grid(grid=grid_shifted, title=\"Grid Centered Around (0.3, 0.5)\")" + "aplt.plot_grid(\n", + " grid=grid_shifted,\n", + " title=\"Coordinates Relative to the Galaxy Centre\",\n", + ")" ], "outputs": [], "execution_count": null @@ -303,13 +319,15 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Next, we can rotate the grid by an angle `phi` (in degrees). The rotation is counter-clockwise from the positive x-axis.\n", + "An elliptical light profile also has an orientation. Its **position angle** is measured anticlockwise\n", + "from the positive x-axis to its major axis.\n", "\n", - "To rotate the grid:\n", + "To express our coordinates in a frame aligned with that profile, we apply the inverse rotation. For a\n", + "position angle of 60 degrees, we rotate the coordinate values clockwise by 60 degrees.\n", "\n", - "1. Calculate the distance `radius` of each coordinate from the origin using $r = \\sqrt{y^2 + x^2}$.\n", - "2. Determine the angle `theta` counter clockwise from the positive x-axis using $\\theta = \\arctan(y / x)$.\n", - "3. Adjust `theta` by the rotation angle and convert back to Cartesian coordinates via $y = r \\sin(\\theta)$ and $x = r \\cos(\\theta)$." + "The code below finds each point\u2019s distance and angle from the galaxy\u2019s centre, subtracts the profile\u2019s\n", + "position angle, and converts back to `(y, x)` coordinates. `np.arctan2(y, x)` determines the angle while\n", + "accounting for which quadrant contains the point." ] }, { @@ -324,12 +342,11 @@ "radius = np.sqrt(y**2 + x**2)\n", "theta = np.arctan2(y, x) - np.radians(angle_degrees)\n", "\n", - "grid_rotated = grid_shifted\n", + "grid_rotated = grid_shifted.copy() # Preserve the unrotated offsets.\n", "grid_rotated[:, 0] = radius * np.sin(theta)\n", "grid_rotated[:, 1] = radius * np.cos(theta)\n", "\n", - "print(\"(y,x) pixel 0 After Rotation:\")\n", - "print(grid_rotated.native[0, 0]) # The coordinate of the first pixel after rotation." + "print(\"First coordinate in the profile frame:\", grid_rotated.native[0, 0])" ], "outputs": [], "execution_count": null @@ -338,17 +355,24 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The grid has now been rotated 60 degrees counter-clockwise. We can plot it to see the change.\n", + "The coordinates now describe positions in the profile\u2019s reference frame, with its major axis along x.\n", + "The transformation preserves each point\u2019s distance from the galaxy\u2019s centre.\n", "\n", - "*Exercise*: Try rotating the grid by a different angle, for example 30 degrees or 90 degrees. Observe how the grid\n", - "changes when you adjust the `angle_degrees` variable." + "Plot the transformed grid below. Its orientation has changed because we rotated the coordinate values\n", + "clockwise by 60 degrees.\n", + "\n", + "Try setting `angle_degrees=0.0` and rerunning the rotation and plot cells. The result should match\n", + "`grid_shifted`. Then try `30.0` to see a smaller rotation. Restore `60.0` and rerun both cells before continuing." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "aplt.plot_grid(grid=grid_rotated, title=\"Grid Rotated 60 Degrees\")" + "aplt.plot_grid(\n", + " grid=grid_rotated,\n", + " title=\"Coordinates in the Profile Frame\",\n", + ")" ], "outputs": [], "execution_count": null @@ -357,18 +381,21 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Next, we convert the rotated grid to elliptical coordinates using:\n", + "We can now assign an **elliptical radius** to each position. Points with the same elliptical radius lie\n", + "on an ellipse centred on the galaxy.\n", "\n", - "$\\eta = \\sqrt{(x_r)^2 + (y_r)^2/q^2}$\n", + "Let $q=b/a$ be the ratio of the ellipse\u2019s minor axis to its major axis. A circle has $q=1$; smaller values\n", + "describe more elongated ellipses. In the profile frame, the major axis lies along x, and the elliptical radius is\n", "\n", - "Where `q` is the axis-ratio of the ellipse and `(x_r, y_r)` are the rotated coordinates. \n", + "$\\eta = \\sqrt{x_r^2 + \\left(\\frac{y_r}{q}\\right)^2}$.\n", "\n", - "Elliptical coordinates are a system used to describe positions in relation to an ellipse rather than a circle. They \n", - "are particularly useful in astronomy when dealing with objects like galaxies, which often have elliptical shapes \n", - "due to their inclination or intrinsic shape.\n", + "Here, $y_r$ and $x_r$ are the shifted and rotated coordinates in arcseconds, so $\\eta$ is also in arcseconds.\n", "\n", - "*Exercise*: Try converting the grid to elliptical coordinates using a different axis-ratio, for example 0.3 or 0.8.\n", - "What happens to the grid when you adjust the `axis_ratio` variable?" + "For $q=0.5$, a point at `(y, x) = (0, 1)` has elliptical radius 1 arcsecond, while `(1, 0)` has elliptical\n", + "radius 2 arcseconds. Offsets along the minor axis therefore correspond to larger elliptical radii.\n", + "\n", + "The code below calculates one radius per grid position. It does not move the grid points. Try\n", + "`axis_ratio=1.0` to recover ordinary distance from the centre, then restore `0.5` before continuing." ] }, { @@ -376,7 +403,13 @@ "metadata": {}, "source": [ "axis_ratio = 0.5\n", - "eta = np.sqrt((grid_rotated[:, 0]) ** 2 + (grid_rotated[:, 1]) ** 2 / axis_ratio**2)" + "\n", + "y_rotated = grid_rotated[:, 0]\n", + "x_rotated = grid_rotated[:, 1]\n", + "\n", + "eta = np.sqrt(x_rotated**2 + (y_rotated / axis_ratio) ** 2)\n", + "\n", + "print(\"First ten elliptical radii (arcseconds):\", eta[:10])" ], "outputs": [], "execution_count": null @@ -385,35 +418,34 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Above, the angle $\\phi$ (in degrees) was used to rotate the grid, and the axis-ratio $q$ was used to convert the grid \n", - "to elliptical coordinates.\n", - "\n", - "From now on, we'll describe ellipticity using \"elliptical components\" $\\epsilon_{1}$ and $\\epsilon_{2}$, calculated \n", - "from $\\phi$ and $q$:\n", + "The axis ratio $q$ and position angle $\\phi$ together describe the ellipse\u2019s shape and orientation.\n", + "The library packages the same information into two **ellipticity components**, passed as `ell_comps`:\n", "\n", - "$\\epsilon_{1} = \\frac{1 - q}{1 + q} \\sin(2\\phi)$ \n", - "$\\epsilon_{2} = \\frac{1 - q}{1 + q} \\cos(2\\phi)$\n", + "$\\epsilon_y = \\frac{1-q}{1+q}\\sin(2\\phi)$,\n", + "$\\epsilon_x = \\frac{1-q}{1+q}\\cos(2\\phi)$.\n", "\n", - "We'll refer to these as `ell_comps` in the code for brevity.\n", + "The component order is `(epsilon_y, epsilon_x)`. These are dimensionless shape parameters, not spatial coordinates.\n", "\n", - "Future tutorials will explain why $\\epsilon_{1}$ and $\\epsilon_{2}$ are preferred over $q$ and $\\phi$.\n", + "The doubled angle reflects the symmetry of an ellipse: rotating it by 180 degrees leaves its appearance\n", + "unchanged. For a circle, $q=1$, both components are zero and the orientation has no effect.\n", "\n", - "*Exercise*: Try computing the elliptical components from the axis-ratio and angle above. What happens to the elliptical\n", - "components when you adjust the `axis_ratio` and `angle_degrees` variables?" + "The code below converts our axis ratio of 0.5 and position angle of 60 degrees into approximately\n", + "`(0.289, -0.167)`. We convert degrees to radians because NumPy\u2019s trigonometric functions expect radians." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "fac = (1 - axis_ratio) / (1 + axis_ratio)\n", - "epsilon_y = fac * np.sin(2 * np.radians(angle_degrees))\n", - "epsilon_x = fac * np.cos(2 * np.radians(angle_degrees))\n", + "ellipticity = (1 - axis_ratio) / (1 + axis_ratio)\n", + "angle_radians = np.radians(angle_degrees)\n", + "\n", + "epsilon_y = ellipticity * np.sin(2 * angle_radians)\n", + "epsilon_x = ellipticity * np.cos(2 * angle_radians)\n", "\n", "ell_comps = (epsilon_y, epsilon_x)\n", "\n", - "print(\"Elliptical Components:\")\n", - "print(ell_comps)\n" + "print(\"Ellipticity components:\", ell_comps)" ], "outputs": [], "execution_count": null @@ -424,51 +456,48 @@ "source": [ "__Light Profiles__\n", "\n", - "Galaxies are collections of stars, gas, dust, and other astronomical objects that emit light. Astronomers study this \n", - "light to understand various properties of galaxies.\n", + "We now have the geometry needed to describe an elliptical galaxy. A light profile assigns a brightness to\n", + "each position using its distance from the galaxy\u2019s centre.\n", + "\n", + "A commonly used model is the **S\u00e9rsic profile**:\n", "\n", - "To model the light of a galaxy, we use light profiles, which are mathematical functions that describe how a galaxy's \n", - "light is distributed across space. By applying these light profiles to 2D grids of $(y, x)$ coordinates, we can \n", - "create images that represent a galaxy's luminous emission.\n", + "$I(r)=I_e\\exp\\left\\{-k\\left[\\left(\\frac{r}{R_e}\\right)^{1/n}-1\\right]\\right\\}$.\n", "\n", - "A commonly used light profile is the `Sersic` profile, which is widely adopted in astronomy for representing galaxy \n", - "light. The `Sersic` profile is defined by the equation:\n", + "Its parameters are:\n", "\n", - "$I_{\\rm Ser} (\\eta_{\\rm l}) = I \\exp \\left\\{ -k \\left[ \\left( \\frac{\\eta}{R} \\right)^{\\frac{1}{n}} - 1 \\right] \\right\\}$\n", + "- $I_e$: the intensity at the effective radius, which sets the brightness scale.\n", + "- $R_e$: the effective radius, which describes the galaxy\u2019s size.\n", + "- $n$: the S\u00e9rsic index, which controls the radial shape of the profile.\n", + "- $k$: a value determined by $n$, chosen so that the effective radius encloses half the model\u2019s total light.\n", "\n", - "In this equation:\n", + "To match the library\u2019s convention, we use the **circularised radius** $r=\\sqrt{q}\\,\\eta$. A circle of radius\n", + "$r$ has the same area as the ellipse with major-axis radius $\\eta$ and axis ratio $q$. Accordingly, $R_e$\n", + "is the circularised size of the half-light ellipse; it does not generally describe a circular aperture\n", + "containing half the light.\n", "\n", - " - $\\eta$ represents the elliptical coordinates of the profile in arc-seconds (refer to earlier sections for elliptical coordinates).\n", - " - $I$ is the intensity normalization of the profile, given in arbitrary units, which controls the overall brightness of the Sersic profile.\n", - " - $R$ is the effective radius in arc-seconds, which determines the size of the profile.\n", - " - $n$ is the Sersic index, which defines how 'steep' the profile is, influencing the concentration of light.\n", - " - $k$ is a constant that ensures half the light of the profile lies within the radius $R$, where $k = 2n - \\frac{1}{3}$.\n", + "For this worked calculation, we use the simple approximation $k\\approx2n-1/3$. The half-light interpretation\n", + "is therefore approximate here; the library uses a more accurate expression.\n", "\n", - "We can evaluate this function using values for $(\\eta, I, R, n)$ to calculate the intensity of the profile at \n", - "a particular elliptical coordinate." + "The code below evaluates the profile at a circularised radius of 0.5 arcseconds, using $R_e=2.0$ arcseconds,\n", + "$n=1.0$, and an intensity scale of 1.0 in arbitrary units." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "elliptical_coordinate = (\n", - " 0.5 # The elliptical coordinate where we compute the intensity, in arc-seconds.\n", - ")\n", - "intensity = 1.0 # Intensity normalization of the profile in arbitrary units.\n", - "effective_radius = 2.0 # Effective radius of the profile in arc-seconds.\n", - "sersic_index = 1.0 # Sersic index of the profile.\n", - "k = 2 * sersic_index - (\n", - " 1.0 / 3.0\n", - ") # Calculating the constant k, note that this is an approximation.\n", - "\n", - "# Calculate the intensity of the Sersic profile at a specific elliptical coordinate.\n", - "sersic_value = np.exp(\n", - " -k * ((elliptical_coordinate / effective_radius) ** (1.0 / sersic_index) - 1.0)\n", + "radius = 0.5 # Circularised radius in arcseconds.\n", + "intensity = 1.0\n", + "effective_radius = 2.0\n", + "sersic_index = 1.0\n", + "\n", + "k = 2 * sersic_index - 1 / 3\n", + "\n", + "sersic_value = intensity * np.exp(\n", + " -k * ((radius / effective_radius) ** (1 / sersic_index) - 1)\n", ")\n", "\n", - "print(\"Intensity of Sersic Light Profile at Elliptical Coordinate 0.5:\")\n", - "print(sersic_value)" + "print(\"Intensity at radius 0.5 arcseconds:\", sersic_value)" ], "outputs": [], "execution_count": null @@ -477,17 +506,22 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The calculation above gives the intensity of the Sersic profile at an elliptical coordinate of 0.5.\n", + "The result is approximately 3.49 in our chosen intensity units. It exceeds `intensity=1.0` because this\n", + "position lies inside the effective radius, where the profile is brighter.\n", "\n", - "To create a complete image of the Sersic profile, we can evaluate the intensity at every point in our grid of \n", - "elliptical coordinates." + "To build an image, apply the same calculation at every grid position. First convert the elliptical radii\n", + "`eta` to circularised radii, then evaluate the S\u00e9rsic function for the whole array." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "sersic_image = np.exp(-k * ((eta / effective_radius) ** (1.0 / sersic_index) - 1.0))" + "circularised_radii = np.sqrt(axis_ratio) * eta\n", + "\n", + "sersic_image = intensity * np.exp(\n", + " -k * ((circularised_radii / effective_radius) ** (1 / sersic_index) - 1)\n", + ")" ], "outputs": [], "execution_count": null @@ -496,16 +530,18 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "When we plot the resulting image, we can see how the properties of the grid affect its appearance:\n", + "Plot the resulting brightness values at their original image positions. Look for a galaxy centred at\n", + "`(0.3, 0.5)` arcseconds, with its major axis oriented 60 degrees anticlockwise from the positive x-axis\n", + "and an axis ratio of 0.5.\n", "\n", - " - The peak intensity is at the position (0.3\", 0.5\"), where we shifted the grid.\n", - " - The image is elongated along a 60\u00b0 counter-clockwise angle, corresponding to the rotation of the grid.\n", - " - The image has an elliptical shape, consistent with the axis ratio of 0.5.\n", + "The clockwise coordinate transformation lets us evaluate this anticlockwise-oriented profile. We then\n", + "display the calculated brightnesses on the original image grid.\n", "\n", - "This demonstrates how the geometry of the grid directly influences the appearance of the light profile.\n", + "Try changing `intensity` from `1.0` to `2.0`, then rerun the intensity calculations and plot. Every calculated\n", + "intensity should double, although automatic colour scaling may make the image look unchanged. Check the\n", + "printed value and colour-bar labels.\n", "\n", - "*Exercise*: Try changing the values of `centre`, `ell_comps`, `effective_radius`, and `sersic_index` above. \n", - "Observe how these adjustments change the Sersic profile image." + "Restore `intensity=1.0` and rerun those cells before continuing." ] }, { @@ -513,7 +549,8 @@ "metadata": {}, "source": [ "aplt.plot_array(\n", - " array=aa.Array2D(values=sersic_image, mask=grid.mask), title=\"Sersic Image\"\n", + " array=aa.Array2D(values=sersic_image, mask=grid.mask),\n", + " title=\"S\u00e9rsic Image\",\n", ")" ], "outputs": [], @@ -523,10 +560,15 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Instead of manually handling these transformations, we can use `LightProfile` objects from the `light_profile` \n", - "module (`lp`) for faster and more efficient calculations.\n", + "We have worked through the geometry and intensity calculation explicitly. A `Sersic` light-profile object\n", + "brings these steps together: we supply its parameters, and the library evaluates the profile.\n", + "\n", + "The `lp` namespace contains the library\u2019s light profiles. Below, we create a S\u00e9rsic profile centred at\n", + "`(0.0, 0.0)`, with ellipticity components `(0.0, 0.1)`. These describe a mildly elliptical profile whose\n", + "major axis lies along x.\n", "\n", - "Below, we define a `Sersic` light profile using the `Sersic` object. We can print the profile to display its parameters." + "This is a different example from our manual calculation: its centre and ellipticity have changed.\n", + "The intensity, effective radius and S\u00e9rsic index retain their previous values." ] }, { @@ -550,13 +592,18 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "With this `Sersic` light profile, we can create an image by passing a grid to its `image_2d_from` method.\n", + "Pass the original image grid to `image_2d_from()`. The profile handles the shift into its own reference frame,\n", + "its orientation and the intensity calculation.\n", "\n", - "The calculation will internally handle all the coordinate transformations and intensity evaluations we performed \n", - "manually earlier, making it much simpler.\n", + "Use `grid`, rather than `grid_shifted` or `grid_rotated`: those transformed coordinates were part of our\n", + "manual demonstration.\n", "\n", - "The `Sersic` profile we created just above is different from the one we used to manually compute the image,\n", - "so the image will look different. However, the process is the same." + "Look for a galaxy centred on the origin and elongated along x. Its appearance differs from the previous\n", + "image because we changed the profile parameters. The library also uses a more accurate S\u00e9rsic constant\n", + "and samples within pixels to improve the image calculation; the optional over-sampling section explains\n", + "this later.\n", + "\n", + "This evaluates the model we specified. It does not fit the model to data." ] }, { @@ -565,7 +612,7 @@ "source": [ "image = sersic_light_profile.image_2d_from(grid=grid)\n", "\n", - "aplt.plot_array(array=image, title=\"Sersic Image via Light Profile\")" + "aplt.plot_array(array=image, title=\"S\u00e9rsic Image via Light Profile\")" ], "outputs": [], "execution_count": null @@ -574,42 +621,24 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The `image` is returned as an `Array2D` object. Similar to a `Grid2D`, it has two forms:\n", + "The result is an `Array2D`, which stores one intensity value per image pixel. Like the grid, it supports\n", + "`native` and `slim` representations:\n", "\n", - " - `native`: A 2D array with shape [total_y_image_pixels, total_x_image_pixels].\n", - " - `slim`: A 1D array that flattens this data into shape [total_y_image_pixels * total_x_image_pixels].\n", + "- `image.native` arranges the values into image rows and columns, with shape `(101, 101)`.\n", + "- `image.slim` lists the values in row order, with shape `(10201,)`.\n", "\n", - "The `native` form is often used for visualizations, while the `slim` form can be useful for certain calculations." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(\"Intensity of pixel 0:\")\n", - "print(image.native[0, 0])\n", - "print(\"Intensity of pixel 1:\")\n", - "print(image.slim[1])" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To visualize the light profile's image, we use `aplt.plot_array`.\n", + "Unlike grid coordinates, image intensities do not need a final dimension of size two: each pixel contains\n", + "a single value.\n", "\n", - "We provide it with the light profile and the grid, which are used to create and plot the image." + "The two expressions below access the same pixel, so they should print the same intensity." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "aplt.plot_array(\n", - " array=sersic_light_profile.image_2d_from(grid=grid), title=\"Image via Light Profile\"\n", - ")" + "print(\"First pixel via native:\", image.native[0, 0])\n", + "print(\"First pixel via slim:\", image.slim[0])" ], "outputs": [], "execution_count": null @@ -620,13 +649,14 @@ "source": [ "__One Dimension Projection__\n", "\n", - "We often want to calculative 1D quantities of a light profile, for example to plot how its light changes as\n", - "a function of radius.\n", + "A light-profile image shows the galaxy\u2019s two-dimensional appearance. We can also inspect how its intensity\n", + "changes along a line through its centre.\n", "\n", - "To do this, we must still input a 2D grid into the `image_2d_from` method, therefore we create a project 2D \n", - "radial grid as follows which has shape [Number_of_1d_coordinates, 2] and where all [:,0] entries are the same.\n", + "We still supply `(y, x)` positions to `image_2d_from()`, but those positions now lie along a line rather than\n", + "filling an image. The four points below lie along the positive x-axis, at distances of 0, 1, 2 and 3 arcseconds\n", + "from the origin.\n", "\n", - "A simple example of such a grid is as follows with 4 1D coordinates is:" + "`Grid2DIrregular` stores a list of positions without requiring a rectangular pixel grid." ] }, { @@ -635,10 +665,10 @@ "source": [ "grid_2d_projected = al.Grid2DIrregular(\n", " [\n", - " [1.000000e-06, 1.000000e-06],\n", - " [1.000000e-06, 1.000001e00],\n", - " [1.000000e-06, 2.000001e00],\n", - " [1.000000e-06, 3.000001e00],\n", + " (0.0, 0.0),\n", + " (0.0, 1.0),\n", + " (0.0, 2.0),\n", + " (0.0, 3.0),\n", " ]\n", ")" ], @@ -649,25 +679,30 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "As in this example, we often already have a 2D grid we are using to calculate images of a ligth profile\n", - "and it would be convenient to simply create `grid_2d_projected` from that.\n", + "For a smoother curve, sample more positions along the profile\u2019s major axis. The code below places 101 points\n", + "between the galaxy\u2019s centre and a distance of 5 arcseconds.\n", "\n", - "For example, we may want the project grid which traces it major axis in uniform radial steps.\n", + "The position angle determines the direction of this line. Multiplying each distance by its sine and cosine\n", + "gives the y and x offsets; adding the profile centre places the line correctly in the image.\n", "\n", - "This is easily computed using the `grid_2d_radial_project_from` function and passing the `centre` and `angle`\n", - "of a light profile we can make it align with the light profile itself.\n", - "\n", - "Note how in this example the two galaxy bulges are not rotationally aligned but we aligned the projected\n", - "grid with the first galaxy. The centres are aligned, but if they were not that would cause similar\n", - "issues." + "We then evaluate the light profile at these positions. This measures intensity along the major axis,\n", + "rather than averaging the image in circular rings." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "grid_2d_projected = grid.grid_2d_radial_projected_from(\n", - " centre=sersic_light_profile.centre, angle=sersic_light_profile.angle()\n", + "radii = np.linspace(0.0, 5.0, 101)\n", + "angle_radians = np.radians(sersic_light_profile.angle())\n", + "\n", + "grid_2d_projected = al.Grid2DIrregular(\n", + " np.column_stack(\n", + " (\n", + " sersic_light_profile.centre[0] + radii * np.sin(angle_radians),\n", + " sersic_light_profile.centre[1] + radii * np.cos(angle_radians),\n", + " )\n", + " )\n", ")\n", "\n", "image_1d = sersic_light_profile.image_2d_from(grid=grid_2d_projected)" @@ -679,29 +714,26 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can now plot the 1D radial profile of the light profile. This profile shows how the intensity of the light \n", - "changes as a function of distance from the profile's center. This is a more informative way to visualize the light p\n", - "rofile's distribution.\n", - "\n", - "When we plot 1D quantities, we do not use built-in plotting functions as in 2D, but instead use standard\n", - "matplotlib functionality.\n", + "Plot intensity against distance from the galaxy\u2019s centre. The curve should fall outwards as the profile\n", + "becomes fainter.\n", "\n", - "The reason is partly that 1D plotting is simple, but also because 1D plots have many different decisions\n", - "about what is plotted and how they are computed, meaning its better to give the user full control.\n", + "The horizontal axis is distance along the major axis in arcseconds, not the circularised radius used earlier.\n", + "The vertical axis is intensity in our chosen arbitrary units\u2014not luminosity integrated over the galaxy.\n", "\n", - "**Exercise**: Try plotting the 1D radial profile of Sersic profiles with different effective radii and Sersic indices.\n", - "Does the 1D representation show more clearly how the light distribution changes with these parameters?" + "Try changing `effective_radius` in the `Sersic` definition from `2.0` to `1.0`. Recreate the profile, then rerun\n", + "the sampling and plotting cells. The profile should become more compact. Restore `effective_radius=2.0`\n", + "and rerun those cells before continuing." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "plt.plot(grid_2d_projected[:, 1], image_1d)\n", - "plt.xlabel(\"Radius (arcseconds)\")\n", - "plt.ylabel(\"Luminosity\")\n", + "plt.plot(radii, image_1d)\n", + "plt.xlabel(\"Distance along major axis (arcseconds)\")\n", + "plt.ylabel(\"Intensity (arbitrary units)\")\n", "plt.show()\n", - "plt.close()\n" + "plt.close()" ], "outputs": [], "execution_count": null @@ -710,11 +742,15 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Since galaxy light distributions often cover a wide range of values, they are typically better visualized on a log10 \n", - "scale. This approach helps highlight details in the faint outskirts of a light profile.\n", + "A galaxy\u2019s bright centre and faint outskirts can span a wide range of intensities. On a linear colour scale,\n", + "the bright centre can dominate the image, making the outskirts difficult to see.\n", + "\n", + "Logarithmic colour scaling gives more of the colour range to faint emission. Equal colour intervals represent\n", + "equal ratios of intensity, rather than equal differences.\n", "\n", - "The `plot_array`/`subplot_\\*` object has a `use_log10` option that applies this transformation automatically. Below, you can see\n", - "that the image plotted in log10 space reveals more details." + "Plot the same light-profile image with `use_log10=True` and compare it with the earlier linear-scale plot.\n", + "Look for light extending beyond the bright centre that was difficult to distinguish before. The intensity\n", + "values have not changed; we have changed how they are displayed." ] }, { @@ -722,8 +758,8 @@ "metadata": {}, "source": [ "aplt.plot_array(\n", - " array=sersic_light_profile.image_2d_from(grid=grid),\n", - " title=\"Sersic Image\",\n", + " array=image,\n", + " title=\"S\u00e9rsic Light-Profile Image (Log Scale)\",\n", " use_log10=True,\n", ")" ], @@ -736,22 +772,19 @@ "source": [ "__Galaxies__\n", "\n", - "Now, let's introduce `Galaxy` objects, which are a key component in **PyAutoLens**.\n", - "\n", - "A light profile represents a single feature of a galaxy, such as its bulge or disk. To model a complete galaxy,\n", - "we combine multiple light profiles into a `Galaxy` object. This allows us to create images that include different\n", - "components of a galaxy.\n", + "Now, let\u2019s introduce `Galaxy` objects. A light profile can represent a component of a galaxy, such as its\n", + "bulge or disc. By combining light profiles in a `Galaxy`, we can describe their light together.\n", "\n", - "In addition to light profiles, a `Galaxy` has a `redshift`, which indicates how far away it is from Earth. The redshift\n", - "is essential for performing unit conversions using cosmological calculations, such as converting arc-seconds into\n", - "kiloparsecs. (A kiloparsec is a distance unit in astronomy, equal to about 3.26 million light-years.)\n", + "A `Galaxy` also has a **redshift**, which describes how much the wavelengths of its light have increased.\n", + "Together with a cosmological model, this lets us convert angular sizes in arcseconds into physical sizes\n", + "in kiloparsecs. A kiloparsec is approximately 3,260 light-years.\n", "\n", "Redshifts are especially important in strong lensing, where the foreground lens galaxy and background source galaxy\n", "lie at two different redshifts. We are not yet performing any lensing calculations in this tutorial, so for now we\n", "simply use a single galaxy to build up intuition for the `Galaxy` object.\n", "\n", - "Let's start by creating a galaxy with two `Sersic` light profiles, which we will consider to represent a bulge and\n", - "disk component of the galaxy, the two most important structures seen in galaxies." + "Let\u2019s create a galaxy with two S\u00e9rsic light profiles representing a bulge and a disc. In this example,\n", + "the bulge is smaller and rounder, while the disc is more extended and flattened." ] }, { @@ -785,9 +818,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can pass a 2D grid to a light profile to compute its image using the `image_2d_from` method.\n", + "We used `image_2d_from()` to calculate the image of a light profile. The same method works for a `Galaxy`:\n", + "it evaluates each light profile on the grid and adds their intensities together.\n", "\n", - "The same approach works for a `Galaxy` object:" + "The result is an `Array2D` containing the galaxy image. Below, we print the combined intensity in each of\n", + "the first three pixels of the top row." ] }, { @@ -796,13 +831,9 @@ "source": [ "image = galaxy.image_2d_from(grid=grid)\n", "\n", - "print(\"Intensity of `Grid2D` pixel 0:\")\n", - "print(image.native[0, 0])\n", - "print(\"Intensity of `Grid2D` pixel 1:\")\n", - "print(image.native[0, 1])\n", - "print(\"Intensity of `Grid2D` pixel 2:\")\n", - "print(image.native[0, 2])\n", - "print(\"...\")" + "print(\"Row 0, column 0 intensity:\", image.native[0, 0])\n", + "print(\"Row 0, column 1 intensity:\", image.native[0, 1])\n", + "print(\"Row 0, column 2 intensity:\", image.native[0, 2])" ], "outputs": [], "execution_count": null @@ -811,14 +842,20 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can plot the galaxy's image, just like how we did for a light profile." + "Let\u2019s plot the galaxy image. Each pixel contains light from both the bulge and the disc.\n", + "\n", + "The bright central region should stand out most clearly. The disc contributes light too, but its emission\n", + "is spread over a larger area and can be difficult to distinguish on this linear colour scale." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "aplt.plot_array(array=galaxy.image_2d_from(grid=grid), title=\"Galaxy Bulge+Disk Image\")" + "aplt.plot_array(\n", + " array=image,\n", + " title=\"Galaxy Bulge and Disc Image\",\n", + ")" ], "outputs": [], "execution_count": null @@ -827,11 +864,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The bulge dominates the center of the image, and is pretty much the only luminous emission we can see on a linear\n", - "scale. The disk's emission is present, but it is much fainter and spread over a larger area.\n", + "To see what each component contributes, plot the bulge and disc separately using\n", + "`aplt.subplot_galaxy_light_profiles()`.\n", + "\n", + "Look for the bulge\u2019s concentrated centre and the disc\u2019s broader, more flattened appearance. These are the\n", + "two light-profile images that add together to produce the galaxy image above.\n", "\n", - "We can confirm this using the `subplot_galaxy_light_profiles` method, which plots each individual light profile\n", - "separately." + "Each panel chooses its own colour scale, so compare the colour-bar values as well as the colours when\n", + "judging their relative brightness." ] }, { @@ -847,10 +887,12 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Because galaxy light distributions often follow a log10 pattern, plotting in log10 space helps reveal details in the\n", - "outskirts of the light profile, in this case the emission of the disk.\n", + "Now display the combined galaxy image with logarithmic colour scaling. This makes the extended, faint\n", + "light easier to see alongside the bright centre.\n", "\n", - "This is especially helpful to separate the bulge and disk profiles, which have different intensities and sizes." + "Compare the shape of the outskirts with the separate disc image. The disc\u2019s contribution should be easier\n", + "to recognise here, although each pixel still contains the sum of both components. Changing the colour\n", + "scale does not separate their light." ] }, { @@ -858,8 +900,8 @@ "metadata": {}, "source": [ "aplt.plot_array(\n", - " array=galaxy.image_2d_from(grid=grid),\n", - " title=\"Galaxy Bulge+Disk Image\",\n", + " array=image,\n", + " title=\"Galaxy Bulge and Disc Image (Log Scale)\",\n", " use_log10=True,\n", ")" ], @@ -870,34 +912,32 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Using the tools above, we can visualize each light profile's contribution in 1D.\n", + "A radial plot lets us compare the bulge and disc intensities directly, using the same axes.\n", "\n", - "1D plots show the intensity of the light profile as a function of distance from the profile's center. The bulge\n", - "and disk profiles in this example share the same `centre`, meaning that plotting them together on the same 1D plot\n", - "shows how they vary relative to one another.\n", + "Our two profiles share a centre at `(0.0, 0.0)` and have their major axes along x. We can therefore evaluate\n", + "both at the same positions along the positive x-axis.\n", "\n", - "If the `centre` of the profiles were different, when you make the 1D plot you would need to decide whether to plot the\n", - "profiles offset from one another or plot them both from zero." + "Look for the bulge\u2019s high central intensity and how its contribution changes relative to the disc as you\n", + "move outwards. These curves show intensity at each position, not the total light enclosed within that radius." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "grid_2d_projected = grid.grid_2d_radial_projected_from(\n", - " centre=galaxy.bulge.centre, angle=galaxy.bulge.angle()\n", - ")\n", - "bulge_image_1d = galaxy.bulge.image_2d_from(grid=grid_2d_projected)\n", + "radii = np.linspace(0.0, 5.0, 101)\n", "\n", - "grid_2d_projected = grid.grid_2d_radial_projected_from(\n", - " centre=galaxy.disk.centre, angle=galaxy.disk.angle()\n", + "grid_2d_projected = al.Grid2DIrregular(\n", + " np.column_stack((np.zeros_like(radii), radii))\n", ")\n", + "\n", + "bulge_image_1d = galaxy.bulge.image_2d_from(grid=grid_2d_projected)\n", "disk_image_1d = galaxy.disk.image_2d_from(grid=grid_2d_projected)\n", "\n", - "plt.plot(grid_2d_projected[:, 1], bulge_image_1d, label=\"Bulge\")\n", - "plt.plot(grid_2d_projected[:, 1], disk_image_1d, label=\"Disk\")\n", - "plt.xlabel(\"Radius (arcseconds)\")\n", - "plt.ylabel(\"Luminosity\")\n", + "plt.plot(radii, bulge_image_1d, label=\"Bulge\")\n", + "plt.plot(radii, disk_image_1d, label=\"Disc\")\n", + "plt.xlabel(\"Distance along major axis (arcseconds)\")\n", + "plt.ylabel(\"Intensity (arbitrary units)\")\n", "plt.legend()\n", "plt.show()\n", "plt.close()" @@ -909,12 +949,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can group multiple galaxies at the same redshift into a `Galaxies` object, which is created from a list of\n", - "individual galaxies.\n", + "Just as a `Galaxy` groups light profiles, a `Galaxies` object groups individual galaxies.\n", + "\n", + "Let\u2019s add a second galaxy, centred at `(0.2, 0.3)` arcseconds, and combine it with our bulge-and-disc galaxy.\n", + "Both have `redshift=0.5` in this example.\n", "\n", - "In a strong lens, we ultimately group together a foreground lens galaxy and a background source galaxy. For now, we\n", - "simply create a second galaxy and combine it with the original galaxy into a `Galaxies` object, to see how the light\n", - "of multiple galaxies is represented." + "Their light overlaps in the image. Here we are simply adding their light profiles; we are not calculating\n", + "gravitational lensing or simulating an interaction between the galaxies." ] }, { @@ -941,9 +982,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The `Galaxies` object has similar methods to those for light profiles and individual galaxies.\n", + "The `Galaxies` object provides the same `image_2d_from()` method we used for an individual galaxy.\n", "\n", - "For example, `image_2d_from` sums the images of all the galaxies." + "It calculates each galaxy\u2019s image on the supplied grid, then adds their intensities at every position.\n", + "The resulting image contains the light from the original bulge and disc together with the second galaxy\u2019s\n", + "S\u00e9rsic profile." ] }, { @@ -959,14 +1002,20 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can plot the combined image of all the galaxies, just like with other plotters." + "Plot the combined image of our two galaxies. Their centres are close together, so their light overlaps strongly.\n", + "\n", + "Compare this with the original bulge-and-disc galaxy image. The additional galaxy changes the brightness\n", + "distribution near the centre." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "aplt.plot_array(array=galaxies.image_2d_from(grid=grid), title=\"Image\")" + "aplt.plot_array(\n", + " array=image,\n", + " title=\"Combined Galaxy Image\",\n", + ")" ], "outputs": [], "execution_count": null @@ -975,14 +1024,19 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "A subplot of each individual galaxy image can also be created." + "To see the contribution from each galaxy, use `aplt.subplot_galaxy_images()`. Each panel shows one galaxy\n", + "from the collection, in the order we supplied them.\n", + "\n", + "The first contains our bulge and disc; the second contains the additional galaxy\u2019s single S\u00e9rsic profile.\n", + "Compare their positions and shapes. Each panel uses its own colour scale, so check the colour bars when\n", + "comparing brightness." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "aplt.subplot_galaxies(galaxies=galaxies, grid=grid)" + "aplt.subplot_galaxy_images(galaxies=galaxies, grid=grid)" ], "outputs": [], "execution_count": null @@ -991,17 +1045,21 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Because galaxy light distributions often follow a log10 pattern, plotting in log10 space helps reveal details in the\n", - "outskirts of the light profile.\n", + "Display the combined image with logarithmic colour scaling to make the faint, extended light easier to see.\n", "\n", - "This is especially helpful when visualizing how multiple galaxies overlap." + "The galaxies\u2019 light overlaps in the same pixels. Compare this view with the individual images to understand\n", + "how each contributes to the combined shape." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "aplt.plot_array(array=galaxies.image_2d_from(grid=grid), title=\"Image\", use_log10=True)" + "aplt.plot_array(\n", + " array=image,\n", + " title=\"Combined Galaxy Image (Log Scale)\",\n", + " use_log10=True,\n", + ")" ], "outputs": [], "execution_count": null @@ -1012,14 +1070,13 @@ "source": [ "__Units__\n", "\n", - "Earlier, we mentioned that a galaxy's `redshift` allows us to convert between arcseconds and kiloparsecs.\n", + "So far, we have described positions and sizes in arcseconds: angles measured on the sky. To express a\n", + "galaxy\u2019s size in kiloparsecs, we need its distance.\n", "\n", - "A redshift measures how much a galaxy's light is stretched by the Universe's expansion. A higher redshift means the\n", - "galaxy is further away, and its light has been stretched more. By knowing a galaxy's redshift, we can convert angular\n", - "distances (like arcseconds) to physical distances (like kiloparsecs).\n", + "A cosmological model relates the galaxy\u2019s redshift to the distance used for this conversion. Here we use\n", + "`Planck15`, a cosmology based on measurements from the Planck satellite.\n", "\n", - "To perform this conversion, we use a cosmological model that describes the Universe's expansion. Below, we use\n", - "the `Planck15` cosmology, which is based on observations from the Planck satellite." + "The code below calculates how many kiloparsecs correspond to one arcsecond at our galaxy\u2019s redshift of 0.5." ] }, { @@ -1028,10 +1085,11 @@ "source": [ "cosmology = al.cosmo.Planck15()\n", "\n", - "kpc_per_arcsec = cosmology.kpc_per_arcsec_from(redshift=galaxy.redshift)\n", + "kpc_per_arcsec = cosmology.kpc_per_arcsec_from(\n", + " redshift=galaxy.redshift\n", + ")\n", "\n", - "print(\"Kiloparsecs per Arcsecond:\")\n", - "print(kpc_per_arcsec)" + "print(\"Kiloparsecs per arcsecond:\", kpc_per_arcsec)" ], "outputs": [], "execution_count": null @@ -1040,17 +1098,25 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "This `kpc_per_arcsec` can be used as a conversion factor between arcseconds and kiloparsecs when plotting images of\n", - "galaxies.\n", + "Multiply an angular size by `kpc_per_arcsec` to express it in kiloparsecs.\n", + "\n", + "Our bulge has an effective radius of 1.0 arcsecond. The calculation below gives the physical size corresponding\n", + "to that radius at the galaxy\u2019s redshift, using the chosen cosmology.\n", "\n", - "We compute this value and plot the image, which by default is shown in units of arcseconds." + "This is the same circularised effective radius expressed in different units. The conversion does not change\n", + "the galaxy image or the profile parameters stored in `galaxy`." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "aplt.plot_array(array=galaxy.image_2d_from(grid=grid), title=\"Image\")" + "effective_radius_kpc = (\n", + " galaxy.bulge.effective_radius * kpc_per_arcsec\n", + ")\n", + "\n", + "print(\"Bulge effective radius (arcseconds):\", galaxy.bulge.effective_radius)\n", + "print(\"Bulge effective radius (kiloparsecs):\", effective_radius_kpc)" ], "outputs": [], "execution_count": null @@ -1061,55 +1127,57 @@ "source": [ "__Wrap Up__\n", "\n", - "In this tutorial, you've learnt the basic quantities used to describe the galaxies that make up a strong lens, before\n", - "we introduce any lensing calculations.\n", - "\n", - "Let's summarise what we've covered:\n", + "You have built galaxy images from light profiles and explored how their appearance depends on position,\n", + "orientation, size and brightness.\n", "\n", - "- **Grids**: A grid is a set of 2D $(y,x)$ coordinates that represent the positions where we measure the light of a\n", - "galaxy.\n", + "The main ideas are:\n", "\n", - "- **Geometry**: We showed how to shift, rotate, and convert grids to elliptical coordinates.\n", + "- **Grids:** `(y, x)` coordinates specify where we evaluate the light.\n", + "- **Geometry:** shifting and rotating coordinates lets us describe a profile relative to its own centre and orientation.\n", + "- **Light profiles:** a S\u00e9rsic profile assigns an intensity to each position.\n", + "- **Galaxies:** light profiles combine into a `Galaxy`, and individual galaxies combine into `Galaxies`.\n", + "- **Visualisation:** images show spatial structure, while radial plots let us compare intensity as a function of distance.\n", + "- **Units:** a redshift and a cosmological model let us convert angular sizes into physical sizes.\n", "\n", - "- **Light Profiles**: Light profiles are analytic functions that describe how a galaxy's light is distributed in\n", - "space. We used the `Sersic` profile to create images of galaxies.\n", - "\n", - "- **Galaxies**: Galaxies are collections of light profiles. We created galaxies with multiple light profiles, combined\n", - "them into a `Galaxies` object, and visualized their images.\n", - "\n", - "- **Units**: By assuming redshifts for galaxies we can convert their quantities from arcseconds to physical units like\n", - "kiloparsecs.\n", - "\n", - "In the next tutorial, we'll introduce the mass of a galaxy and perform our first lensing calculation, whereby the\n", - "light of a background source galaxy is deflected by the mass of a foreground lens galaxy.\n", + "**\ud83e\udd16 Ask AI:** In this tutorial, why do we rotate coordinates clockwise to evaluate a galaxy whose major axis\n", + "is oriented anticlockwise?\n", "\n", "__Advanced Topics__\n", "\n", - "The following advanced topics are not important for a new user learning the software for the first time. However,\n", - "once you are an expert user, the following guides and concepts are important for doing accurate strong lens analysis,\n", - "and thus may be things you want to commit to memory as future references.\n", + "The notes below give some additional context on brightness units and numerical accuracy. They are optional\n", + "on a first reading.\n", "\n", "__Other Unit Conversion__\n", "\n", - "Above, we used a redshift to convert between arcseconds and kiloparsecs. This is just one example of a unit conversion\n", - "that can be performed using a galaxy's redshift.\n", + "We used redshift and a cosmological model to convert angular sizes into physical sizes. Converting image\n", + "brightness into calibrated astronomical units is a different task.\n", "\n", - "There are many other unit conversions that can be performed, such as converting the units of a galaxy's image to what\n", - "Astronomers call an AB magnitude system, which is a system used to measure the brightness of galaxies.\n", + "Astronomers often express brightness using magnitudes, including the AB magnitude system. To calculate these\n", + "from an observed image, we need its flux calibration or an appropriate magnitude zero point. Redshift alone\n", + "is not enough, and the arbitrary intensity units used in this tutorial do not define an AB magnitude.\n", "\n", - "The `autolens_workspace/*/guides/units` module contains many examples of unit conversions and how to use them,\n", - "but they will not be covered in the *HowToLens* tutorials.\n", + "The workspace\u2019s [flux guide](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/units/flux.py)\n", + "gives examples of brightness conversions, while its\n", + "[cosmology guide](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/units/cosmology.py)\n", + "covers cosmological distance conversions.\n", "\n", "__Over Sampling__\n", "\n", - "Over sampling is a numerical technique where the images of light profiles and galaxies are evaluated\n", - "on a higher resolution grid than the image data to ensure the calculation is accurate.\n", + "A light profile can vary substantially across a pixel, especially near a bright galaxy centre. Evaluating\n", + "it only at the pixel centre may not represent the light across the whole pixel accurately.\n", + "\n", + "Over-sampling evaluates the profile at several positions within each pixel and combines those values.\n", + "This improves the numerical estimate without changing the image\u2019s pixel size.\n", + "\n", + "The library supports both uniform over-sampling and adaptive schemes that use finer sampling where it is\n", + "needed. Our manual calculation sampled pixel centres, whereas the library\u2019s image calculation uses the\n", + "grid\u2019s over-sampling settings.\n", "\n", - "For a new user, the details of over-sampling are not important, therefore just be aware that all calculations use an\n", - "adaptive over sampling scheme with high accuracy across all use cases.\n", + "Accuracy still depends on the profile and sampling choices. A useful check is to increase the sampling\n", + "and see whether the calculated image changes appreciably.\n", "\n", - "Once you are more experienced, you should read up on over-sampling in more detail via\n", - "the `autolens_workspace/*/guides/advanced/over_sampling.ipynb` notebook." + "The workspace\u2019s [over-sampling guide](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/advanced/over_sampling.py)\n", + "explains these settings and how to check their accuracy." ] } ], diff --git a/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb b/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb index 010efd3..94e4eff 100644 --- a/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb @@ -5,72 +5,75 @@ "metadata": {}, "source": [ "Tutorial 2: Ray Tracing\n", - "=======================\n", + "======================\n", "\n", - "Strong gravitational lensing occurs when the mass of a foreground galaxy (or galaxies) curves space-time around it,\n", - "causing light rays from a background source to appear deflected.\n", + "Strong gravitational lensing occurs when the mass of a foreground galaxy curves\n", + "space-time, bending the paths of light rays from a background source galaxy.\n", + "The source can then appear as arcs, a ring or multiple images.\n", "\n", - "The process of ray tracing calculates how much the path of each light ray is bent by the mass of the foreground galaxy.\n", - "It then traces the paths of these light rays back to the observer, allowing us to determine how the source appears\n", - "distorted. As a result, the images of the source may appear as arcs, multiple images, or other complex patterns.\n", + "In the previous tutorial, we used light profiles to describe how a galaxy's\n", + "brightness varies across an image. We now introduce **mass profiles**, which\n", + "describe how its mass is distributed. From a mass profile, we can calculate\n", + "the **deflection angles** that tell us how the galaxy bends light.\n", "\n", - "In the previous tutorial, we introduced **light profiles**, which are analytic functions that describe the distribution\n", - "of light from a galaxy. In this tutorial, we will focus on **mass profiles**, which are analytic functions that\n", - "describe the mass distribution within a galaxy. A key quantity derived from these profiles is the **deflection angle**,\n", - "which quantifies how light is deflected by the mass of the galaxy at any point in space.\n", + "These two ingredients let us construct a lensed image. The mass profile tells\n", + "us where each light ray came from in the source galaxy, and the source's light\n", + "profile tells us how bright that location is.\n", "\n", - "Grids were crucial in the previous tutorial, as they enabled us to compute the light profile of a galaxy at every\n", - "coordinate point. In ray tracing, grids are equally important because they are used to calculate the deflection\n", - "angles of light rays caused by a mass profile and to map the source's light rays back to the observer.\n", + "Let's revisit both views of strong lensing from the previous tutorial. The\n", + "schematic shows the geometry from the side: light travels from the source,\n", + "past the lens and towards the observer. It is not drawn to scale.\n", "\n", - "Let\u2019s revisit the schematic of strong lensing:\n", + "![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)\n", "\n", - "![Schematic of Gravitational Lensing](https://i.imgur.com/zB6tIdI.jpg)\n", + "The JWST image of the COSMOS-Web Ring shows the view on the sky. The bright\n", + "central galaxy is the lens, and the surrounding ring is light from the more\n", + "distant source galaxy.\n", "\n", - "As observers, we do not see the true appearance of the source (e.g., a round blob of light). Instead, we only\n", - "perceive its light after it has been deflected and lensed by the foreground galaxies. This resulting image is known\n", - "as the **observed image** or **image-plane image**, which we will produce through the ray-tracing process.\n", + "![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 schematic above uses the terms \"image-plane\" and \"source-plane.\" In the context of gravitational lensing, a \"plane\"\n", - "refers to a collection of galaxies located at the same redshift, meaning they are physically aligned parallel to one\n", - "another.\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", "\n", - "In this tutorial, we will create a strong lensing system consisting of planes similar to the one depicted above. While\n", - "a plane can contain multiple galaxies, we will focus on a simple scenario with just one lens galaxy and one source\n", - "galaxy.\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", - "Here is an overview of what we'll cover in this tutorial:\n", + "In our calculation, we follow the light paths backwards: we start with\n", + "positions in the image seen by the observer and trace rays back to positions\n", + "at the source.\n", "\n", - "- **Grid**: How the 2D grids that were important for evaluating light profiles are equally important\n", - " for ray-tracing calculations.\n", + "This process is called **ray tracing**. It allows us to work out what the\n", + "source's light looks like after gravitational lensing.\n", "\n", - "- **Mass Profiles**: Introduce mass profiles, which describe the mass distribution of galaxies and are used to\n", - " calculate deflection angles.\n", + "We describe the positions using two coordinate planes:\n", "\n", - "- **Ray Tracing Grids**: How to map the light rays from the image-plane to the source-plane using the\n", - " deflection angles and **lens equation**.\n", + "- The **image plane** contains the angular positions at which we see light\n", + " on the sky.\n", + "- The **source plane** contains the angular positions of the source before\n", + " its light is distorted by the lens.\n", "\n", - "- **Ray Tracing Images**: How to evaluate the lensed image of a source galaxy after it has been\n", - " gravitationally lensed.\n", + "For the lensing calculation, we also represent the foreground galaxy's mass\n", + "on a **lens plane**. The lens and source planes are imagined sheets\n", + "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", - "- **Galaxies**: How to include both light and mass profiles in a single `Galaxy` object, and therefore\n", - "construct realistic lens and source galaxies.\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", "\n", - "- **Tracer**: Introduce the `Tracer` object, which automates the ray-tracing process and allows us to compute\n", - " images of the entire lens system.\n", - "\n", - "- **Mappings**: Visualize how coordinates in the image-plane map to the source-plane by plotting the ray-traced grids.\n", + "The resulting **lensed image** shows how the foreground galaxy's gravity\n", + "distorts the appearance of the source.\n", "\n", "__Contents__\n", "\n", - "- **Grid:** In the previous tutorial, we created 2D grids of (y,x) coordinates and showed how shifting and.\n", - "- **Mass Profiles:** To perform lensing calculations, we use mass profiles available in the `mass_profile` module.\n", - "- **Ray Tracing Grids:** The lens equation uses deflection angles to map image-plane coordinates to the source-plane.\n", - "- **Ray Tracing Images:** Evaluating a source's light on the ray-traced grid produces its lensed image.\n", - "- **Galaxies:** A `Galaxy` can contain both light and mass profiles, forming realistic lens and source galaxies.\n", - "- **Tracer:** The `Tracer` object automates ray-tracing for a system of galaxies at different redshifts.\n", - "- **Mappings:** Every image-plane coordinate maps to a source-plane coordinate via the lens equation.\n", - "- **Wrap Up:** Summary of the script and next steps." + "- **Grid:** Set up the image-plane coordinates where we will calculate the light.\n", + "- **Mass Profiles:** Describe the lens galaxy's mass and calculate its deflection angles.\n", + "- **Ray Tracing Grids:** Use the lens equation to map image-plane coordinates to the source plane.\n", + "- **Mappings:** Visualise how image-plane positions map to source-plane positions.\n", + "- **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", + "- **Wrap Up:** Review what we have learned and the next steps." ] }, { @@ -123,6 +126,7 @@ "import matplotlib.pyplot as plt\n", "import autolens as al\n", "import autoarray as aa\n", + "import autoarray.plot as aaplt\n", "import autolens.plot as aplt\n" ], "outputs": [], @@ -134,23 +138,31 @@ "source": [ "__Grid__\n", "\n", - "In the previous tutorial, we created 2D grids of (y,x) coordinates and showed how shifting and rotating these grids \n", - "is crucial for evaluating the light profiles of galaxies.\n", + "In the previous tutorial, we evaluated light profiles on grids of (y,x)\n", + "coordinates. Each coordinate specified a position at which to calculate\n", + "the brightness.\n", + "\n", + "We begin in the same way here, creating a uniform grid called\n", + "`image_plane_grid`. Its coordinates represent positions on the sky where\n", + "we want to calculate the lensed image.\n", "\n", - "Grids are also essential for performing ray-tracing calculations. The coordinates in the grid are deflected by the \n", - "lens galaxy, and these deflected coordinates are used in ray-tracing calculations.\n", + "The grid has 101 rows and 101 columns, with adjacent pixel centres separated\n", + "by 0.1 arcseconds. As before, coordinates are measured relative to the centre\n", + "of the grid.\n", "\n", - "Now, let\u2019s create the grid for this tutorial, which we\u2019ll call the `image_plane_grid`. It represents the grid of \n", - "coordinates in the image plane, before the light is deflected by the lens galaxy. This grid is uniform, meaning \n", - "every coordinate is evenly spaced. However, this uniformity will change after ray-tracing, as the light rays are \n", - "mapped to the source plane." + "Ray tracing will map each of these image-plane coordinates to a position\n", + "in the source plane. Although our starting grid is uniform, the mapped\n", + "source-plane coordinates will generally not be evenly spaced." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "image_plane_grid = al.Grid2D.uniform(shape_native=(101, 101), pixel_scales=0.1)" + "\n", + "image_plane_grid = al.Grid2D.uniform(\n", + " shape_native=(101, 101), pixel_scales=0.1\n", + ")" ], "outputs": [], "execution_count": null @@ -161,26 +173,39 @@ "source": [ "__Mass Profiles__\n", "\n", - "To perform lensing calculations, we use mass profiles available in the `mass_profile` module (accessible via `al.mp`).\n", + "A mass profile is a mathematical description of how mass is distributed\n", + "within a galaxy. Just as a light profile lets us calculate brightness,\n", + "a mass profile lets us calculate how the galaxy deflects light.\n", + "\n", + "Mass profiles are available through `al.mp`. We will begin with\n", + "`IsothermalSph`, a spherical isothermal mass profile. This is a simple\n", + "model commonly used to illustrate galaxy-scale lensing.\n", "\n", - "A mass profile is an analytic function that describes the mass distribution within a galaxy. It is used to calculate \n", - "deflection angles and other quantities like surface density and gravitational potential.\n", + "For this profile, we specify two parameters:\n", "\n", - "In gravitational lensing, deflection angles describe how a mass bends light by curving space-time.\n", + "- `centre`: The (y,x) position of the mass profile's centre, in arcseconds.\n", + " We place it at (0.0, 0.0), the centre of our grid.\n", + "- `einstein_radius`: The angular scale of the lensing deflection, in\n", + " arcseconds. For this spherical profile, a point source exactly behind\n", + " the lens centre would form a ring at this radius.\n", "\n", - "We will start with a simple mass profile, `IsothermalSph`, which represents a spherically symmetric isothermal \n", - "mass distribution. This profile has two main properties: its center (the origin of the coordinate system) and its \n", - "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\n", + "distances, a larger Einstein radius corresponds to a more massive lens\n", + "within that radius.\n", + "\n", + "Printing the profile shows the parameters we have supplied." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "sis_mass_profile = al.mp.IsothermalSph(\n", - " centre=(0.0, 0.0), # The (y,x) arc-second coordinates of the profile's center.\n", - " einstein_radius=1.6, # The Einstein radius of the profile in arc-seconds.\n", + " centre=(0.0, 0.0), # The profile centre in (y,x) arcseconds.\n", + " einstein_radius=1.6, # The Einstein radius in arcseconds.\n", ")\n", + "\n", "print(sis_mass_profile)" ], "outputs": [], @@ -190,18 +215,28 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "In the previous tutorial, we used the `image_2d_from` method to compute the image of a light profile by evaluating \n", - "its intensity at each (y,x) coordinate on the grid.\n", + "In the previous tutorial, we called `image_2d_from` to evaluate a light\n", + "profile's intensity at every coordinate on a grid.\n", + "\n", + "For a mass profile, we call `deflections_yx_2d_from` to calculate the\n", + "deflection angles at those coordinates.\n", + "\n", + "Each position has two deflection components, ordered as (y,x), both\n", + "measured in arcseconds. Together, they describe the angular displacement\n", + "we will use to map that image-plane position to the source plane.\n", "\n", - "Mass profiles have a similar method called `deflections_yx_2d_from`, which calculates the deflection angles at \n", - "every (y,x) coordinate on the grid in units of arc-seconds." + "The following calculation gives us one deflection vector for every\n", + "coordinate in `image_plane_grid`." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "deflections = sis_mass_profile.deflections_yx_2d_from(grid=image_plane_grid)" + "\n", + "deflections = sis_mass_profile.deflections_yx_2d_from(\n", + " grid=image_plane_grid\n", + ")" ], "outputs": [], "execution_count": null @@ -210,23 +245,34 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Like grids and arrays, the deflection angles can be accessed using the `native` and `slim` attributes. These are \n", - "structured similarly to a `Grid2D` object:\n", + "As with the grids in the previous tutorial, we can access the deflections\n", + "using `native` and `slim`.\n", + "\n", + "- `native` preserves the image layout. Its shape is\n", + " (101, 101, 2): one pair of (y,x) deflection components for each pixel.\n", + "- `slim` lists the same pairs in pixel order. Its shape is\n", + " (10201, 2): one row per pixel, with two components in each row.\n", "\n", - "- **native**: A 2D array with shape \\([total_y_pixels, total_x_pixels, 2]\\), where the last dimension represents the \n", - " (y,x) deflection components.\n", - " \n", - "- **slim**: A 1D array with shape \\([total_y_pixels * total_x_pixels, 2]\\), where the coordinates are flattened \n", - " into a single list." + "The final dimension has length 2 because a deflection has both a y\n", + "component and an x component.\n", + "\n", + "Below, we print the deflection at the first pixel using both representations.\n", + "The two outputs should be identical. We then print the deflection at the\n", + "next pixel using `slim`." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(\"Deflection angles of pixel 0:\")\n", + "\n", + "print(\"Deflection at the first pixel, using native:\")\n", "print(deflections.native[0, 0])\n", - "print(\"Deflection angles of pixel 1:\")\n", + "\n", + "print(\"Deflection at the first pixel, using slim:\")\n", + "print(deflections.slim[0])\n", + "\n", + "print(\"Deflection at the next pixel, using slim:\")\n", "print(deflections.slim[1])" ], "outputs": [], @@ -236,20 +282,23 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "There is an important difference between a grid and deflection angles. A `Grid2D` is a set of coordinates, while \n", - "deflection angles are 2D vectors. This means that each deflection angle is defined at a specific (y,x) coordinate \n", - "but has two components: a y and an x value, which vary across the grid.\n", + "A grid tells us where we are evaluating the lensing calculation. A deflection\n", + "vector tells us the angular displacement associated with each of those\n", + "positions.\n", "\n", - "This is why the method is called `deflections_yx_2d_from`\u2014the `yx` signifies that these are 2D vectors with both \n", - "y and x components.\n", + "Both use pairs of numbers, but the pairs have different meanings: a grid\n", + "stores (y,x) positions, whereas the deflections store (y,x) components of\n", + "a displacement.\n", "\n", - "The deflection angles are stored in a `VectorYX2D` data structure:" + "PyAutoLens stores these deflections in a `VectorYX2D` object. This keeps\n", + "the vectors together with the grid of positions where they were calculated." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "print(type(deflections))" ], "outputs": [], @@ -259,18 +308,31 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "This structure includes a `grid`, which represents the `Grid2D` of coordinates where the deflection angles are \n", - "calculated (in this case, the `image_plane_grid` we defined earlier). It also has vector-specific methods, \n", - "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\n", + "calculated. Here, these are the coordinates of `image_plane_grid`.\n", + "\n", + "The `magnitudes` attribute gives the length of each deflection vector,\n", + "combining its two components:\n", + "\n", + "$\\lvert \\alpha \\rvert = \\sqrt{\\alpha_y^2 + \\alpha_x^2}$\n", + "\n", + "The magnitude is measured in arcseconds, just like the individual components.\n", + "\n", + "Below, we print the position of the first pixel and the magnitude of its\n", + "deflection. For our spherical isothermal profile, the deflection magnitude\n", + "away from the centre is equal to the Einstein radius, so we expect\n", + "approximately 1.6 arcseconds at this pixel." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(\"Deflection angle's `Grid2D` at pixel 0:\")\n", + "\n", + "print(\"Position of the first pixel (y,x), in arcseconds:\")\n", "print(deflections.grid.native[0, 0])\n", - "print(\"Deflection angle magnitude at pixel 0:\")\n", + "\n", + "print(\"Deflection magnitude at the first pixel, in arcseconds:\")\n", "print(deflections.magnitudes.native[0, 0])" ], "outputs": [], @@ -280,22 +342,43 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can use `aplt.plot_array` to visualize the deflection angles, which displays the y and x components separately. \n", + "We can see how the deflections vary across the image by plotting their\n", + "y and x components separately.\n", + "\n", + "For each component, we construct an `Array2D` using the image-plane grid's\n", + "mask. This places each value at the pixel where it was calculated.\n", "\n", - "On this plot, you\u2019ll see yellow and white lines called **critical curves**. These curves are important in lensing \n", - "and will be explained in detail in the next tutorial." + "The colours show the signed deflection component in arcseconds. In the\n", + "y-component plot, the sign changes across the horizontal line through the\n", + "lens centre. In the x-component plot, it changes across the vertical line.\n", + "\n", + "For this spherical profile, the components vary with direction even though\n", + "the total deflection magnitude is constant away from the centre. Compare\n", + "the two plots: their patterns should be related by a rotation." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "deflections = sis_mass_profile.deflections_yx_2d_from(grid=image_plane_grid)\n", - "deflections_y = aa.Array2D(values=deflections.slim[:, 0], mask=image_plane_grid.mask)\n", - "aplt.plot_array(array=deflections_y, title=\"Deflections Y\")\n", - "deflections = sis_mass_profile.deflections_yx_2d_from(grid=image_plane_grid)\n", - "deflections_x = aa.Array2D(values=deflections.slim[:, 1], mask=image_plane_grid.mask)\n", - "aplt.plot_array(array=deflections_x, title=\"Deflections X\")" + "\n", + "deflections_y = aa.Array2D(\n", + " values=deflections.slim[:, 0],\n", + " mask=image_plane_grid.mask,\n", + ")\n", + "aplt.plot_array(\n", + " array=deflections_y,\n", + " title=\"Y Deflection (arcseconds)\",\n", + ")\n", + "\n", + "deflections_x = aa.Array2D(\n", + " values=deflections.slim[:, 1],\n", + " mask=image_plane_grid.mask,\n", + ")\n", + "aplt.plot_array(\n", + " array=deflections_x,\n", + " title=\"X Deflection (arcseconds)\",\n", + ")" ], "outputs": [], "execution_count": null @@ -304,21 +387,47 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Mass profiles also have additional properties used in lensing calculations:\n", + "A mass profile also lets us calculate other quantities that describe\n", + "the lens and its effect on the source's appearance:\n", + "\n", + "- **Convergence** describes the projected mass per unit area, divided by\n", + " a reference surface density called the critical surface density.\n", + " This reference depends on the lens and source redshifts, which set\n", + " the relevant distances for a chosen cosmology. Convergence is\n", + " therefore dimensionless.\n", "\n", - "- **convergence**: Represents the surface mass density of the profile in dimensionless units.\n", - "- **potential**: Represents the \"lensing potential\" of the mass profile in dimensionless units.\n", - "- **magnification**: Indicates how much brighter light rays appear due to the focusing effect of lensing.\n", + "- **Lensing potential** is a mathematical function whose spatial variation\n", + " determines the deflection angles. Its gradient gives the deflection\n", + " vector. With our coordinates and deflections expressed in arcseconds,\n", + " the potential is expressed in arcseconds squared.\n", "\n", - "These quantities can be calculated using `*_from` methods and are returned as `Array2D` objects." + "- **Magnification** describes how lensing changes the apparent area of a\n", + " small source region. Lensing preserves surface brightness, but a larger\n", + " image covers more sky and therefore contains more total light. The\n", + " absolute magnification gives the local area and flux factor; its sign\n", + " records whether the image orientation is reversed.\n", + "\n", + "We will explore these quantities further as we develop the lensing\n", + "formalism. For now, we calculate them on our image-plane grid.\n", + "\n", + "Convergence and potential are calculated directly from the mass profile.\n", + "For magnification, we use `LensCalc`, which calculates it from the way\n", + "the deflections vary across the grid. Each result is an `Array2D`." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "convergence = sis_mass_profile.convergence_2d_from(grid=image_plane_grid)\n", - "potential_2d = sis_mass_profile.potential_2d_from(grid=image_plane_grid)\n", + "\n", + "convergence = sis_mass_profile.convergence_2d_from(\n", + " grid=image_plane_grid\n", + ")\n", + "\n", + "potential_2d = sis_mass_profile.potential_2d_from(\n", + " grid=image_plane_grid\n", + ")\n", + "\n", "magnification_2d = al.LensCalc.from_mass_obj(\n", " mass_obj=sis_mass_profile\n", ").magnification_2d_from(grid=image_plane_grid)" @@ -330,19 +439,37 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The same plotter API can be used to visualize these properties:" + "Let's plot the convergence and lensing potential.\n", + "\n", + "The convergence is largest near the centre and decreases outwards,\n", + "showing how the projected mass density falls with distance from the\n", + "centre of this profile.\n", + "\n", + "The spherical isothermal profile is singular at its exact centre:\n", + "its idealised density grows without bound there. The central pixel\n", + "therefore needs care when interpreting the numerical plot.\n", + "\n", + "The potential has a different pattern, increasing with distance from\n", + "the centre for this profile. It is not another image of the mass density.\n", + "Its spatial variation determines the deflections.\n", + "\n", + "Both plots should be circularly symmetric because we chose a spherical\n", + "mass profile." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "aplt.plot_array(\n", - " array=sis_mass_profile.convergence_2d_from(grid=image_plane_grid),\n", + " array=convergence,\n", " title=\"Convergence\",\n", ")\n", + "\n", "aplt.plot_array(\n", - " array=sis_mass_profile.potential_2d_from(grid=image_plane_grid), title=\"Potential\"\n", + " array=potential_2d,\n", + " title=\"Lensing Potential (arcseconds squared)\",\n", ")" ], "outputs": [], @@ -352,22 +479,39 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "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\n", + "from the mass profile's centre.\n", + "\n", + "Because our profile is spherical, the result is the same in every\n", + "direction. We will sample along the positive x direction, at radii\n", + "from 0.1 to 5.0 arcseconds. Starting away from zero avoids the\n", + "singularity at the centre of the isothermal profile.\n", + "\n", + "The convergence should decrease as we move outwards. For this profile,\n", + "doubling the radius halves the convergence." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "grid_2d_projected = image_plane_grid.grid_2d_radial_projected_from(\n", - " centre=sis_mass_profile.centre, angle=sis_mass_profile.angle()\n", + "\n", + "import numpy as np\n", + "\n", + "radii = np.linspace(0.1, 5.0, 100)\n", + "\n", + "radial_grid = al.Grid2DIrregular(\n", + " values=[\n", + " (sis_mass_profile.centre[0], sis_mass_profile.centre[1] + radius)\n", + " for radius in radii\n", + " ]\n", ")\n", "\n", - "convergence_1d = sis_mass_profile.convergence_2d_from(grid=grid_2d_projected)\n", + "convergence_1d = sis_mass_profile.convergence_2d_from(grid=radial_grid)\n", "\n", - "plt.plot(grid_2d_projected[:, 1], convergence_1d)\n", - "plt.xlabel(\"Radius (arcseconds)\")\n", - "plt.ylabel(\"Luminosity\")\n", + "plt.plot(radii, convergence_1d)\n", + "plt.xlabel(\"Radius from profile centre (arcseconds)\")\n", + "plt.ylabel(\"Convergence\")\n", "plt.show()\n", "plt.close()" ], @@ -378,21 +522,36 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "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\n", + "the variation farther out difficult to see.\n", + "\n", + "A logarithmic colour scale helps us display a wide range of positive\n", + "values. Equal steps in colour then represent equal ratios of values,\n", + "rather than equal differences.\n", + "\n", + "Below, we plot convergence and potential using logarithmic colour\n", + "scales. Compare these with the earlier plots: the underlying quantities\n", + "are unchanged, but different parts of their variation become easier\n", + "to distinguish.\n", + "\n", + "A logarithmic scale only represents positive values. The singular\n", + "centre of this idealised profile should still be treated with care." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "aplt.plot_array(\n", - " array=sis_mass_profile.convergence_2d_from(grid=image_plane_grid),\n", - " title=\"Convergence in Log10 Space\",\n", + " array=convergence,\n", + " title=\"Convergence (logarithmic colour scale)\",\n", " use_log10=True,\n", ")\n", + "\n", "aplt.plot_array(\n", - " array=sis_mass_profile.potential_2d_from(grid=image_plane_grid),\n", - " title=\"Potential in Log10 Space\",\n", + " array=potential_2d,\n", + " title=\"Lensing Potential (logarithmic colour scale)\",\n", " use_log10=True,\n", ")" ], @@ -405,25 +564,29 @@ "source": [ "__Ray Tracing Grids__\n", "\n", - "We now have all the tools we need to perform our first ray-tracing calculation.\n", - "\n", - "Ray tracing uses a mass profile's deflection angles to map coordinates from the image-plane (where we observe the\n", - "lensed source) to the source-plane (where the source truly is). This mapping is described by the **lens equation**:\n", + "We can now map image-plane coordinates to the source plane using\n", + "the **lens equation**:\n", "\n", "$\\beta = \\theta - \\alpha(\\theta)$\n", "\n", - "where $\\theta$ are the image-plane coordinates, $\\alpha(\\theta)$ are the deflection angles of the mass profile, and\n", - "$\\beta$ are the corresponding source-plane coordinates.\n", + "Here, $\\theta$ is an image-plane position, $\\alpha(\\theta)$ is its\n", + "deflection vector, and $\\beta$ is the corresponding source-plane\n", + "position. Each has (y,x) components measured in arcseconds.\n", + "\n", + "For example, at image-plane position (0.0, 2.0), the deflection is\n", + "(0.0, 1.6), giving source-plane position (0.0, 0.4) arcseconds.\n", "\n", - "We compute the deflection angles of our mass profile on the `image_plane_grid`, and then use the grid's\n", - "`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." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "deflections = sis_mass_profile.deflections_yx_2d_from(grid=image_plane_grid)\n", + "\n", + "deflections = sis_mass_profile.deflections_yx_2d_from(\n", + " grid=image_plane_grid\n", + ")\n", "\n", "source_plane_grid = image_plane_grid.grid_2d_via_deflection_grid_from(\n", " deflection_grid=deflections\n", @@ -436,19 +599,131 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Let's plot the image-plane grid and the ray-traced source-plane grid.\n", + "Let's plot the image-plane grid and its mapped source-plane coordinates.\n", + "\n", + "The image-plane grid is uniform, but the source-plane coordinates\n", + "are unevenly spaced. Each point still corresponds to one original\n", + "image-plane pixel.\n", + "\n", + "For our spherical isothermal profile, the deflection magnitude is\n", + "1.6 arcseconds everywhere away from the centre. The direction varies\n", + "across the grid, producing the pattern below; points nearer the\n", + "centre are not deflected more strongly." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "aplt.plot_grid(\n", + " grid=image_plane_grid,\n", + " title=\"Image Plane Grid\",\n", + ")\n", + "\n", + "aplt.plot_grid(\n", + " grid=source_plane_grid,\n", + " title=\"Source Plane Grid (Ray Traced)\",\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The source-plane grid covers a wide area, but many of its points\n", + "land close together near the centre. Zooming in helps us see\n", + "their spacing.\n", + "\n", + "This is related to magnification: a small region of the source\n", + "can appear over a much larger area in the image plane. When we\n", + "trace those image-plane points back, many therefore land within\n", + "that small source-plane region.\n", + "\n", + "We often zoom in when plotting source planes so that this central\n", + "detail is easier to see. The plot below shows the central\n", + "2-by-2 arcseconds. Only the displayed limits change; the grid\n", + "and ray-tracing calculation stay the same.\n", + "\n", + "For these grid displays, we use `autoarray.plot` (imported as `aaplt`),\n", + "which provides the `extent` and grouped `indexes` options." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "aaplt.plot_grid(\n", + " grid=source_plane_grid,\n", + " title=\"Source Plane (Zoomed In)\",\n", + " extent=(-1.0, 1.0, -1.0, 1.0),\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Mappings__\n", + "\n", + "Each image-plane coordinate maps to a source-plane coordinate.\n", + "We can show this by highlighting groups of points in matching colours.\n", + "\n", + "As in the previous tutorial, indexes refer to positions in the\n", + "grid's `slim` ordering. Each inner list below selects five points;\n", + "the plotting function gives each group a different colour.\n", + "\n", + "We use the same indexes in both panels because ray tracing preserves\n", + "the order of the points. Follow each coloured group from the image\n", + "plane to the source plane and look at how its spacing changes.\n", "\n", - "The image-plane grid is uniform, but the source-plane grid is distorted. This distortion is caused by the mass\n", - "profile's deflection angles, which bend the light rays as they pass the lens galaxy. The coordinates near the\n", - "center of the mass are deflected the most." + "These indexes are chosen for our 101-by-101 grid. Try selecting\n", + "different indexes to follow other parts of the grid.\n", + "\n", + "To inspect the central points more closely, try changing `extent`\n", + "in the source-plane plot to (-1.0, 1.0, -1.0, 1.0). The four values\n", + "set the minimum and maximum x coordinates, then the minimum and\n", + "maximum y coordinates. Restore the limits below to compare both\n", + "planes at the same scale." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "aplt.plot_grid(grid=image_plane_grid, title=\"Image Plane Grid\")\n", - "aplt.plot_grid(grid=source_plane_grid, title=\"Source Plane Grid (Ray Traced)\")" + "\n", + "indexes = [\n", + " [5118, 5119, 5120, 5121, 5122],\n", + " [3078, 3079, 3080, 3081, 3082],\n", + " [7098, 7099, 7100, 7101, 7102],\n", + "]\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(12, 5))\n", + "\n", + "aaplt.plot_grid(\n", + " grid=image_plane_grid,\n", + " indexes=indexes,\n", + " ax=axes[0],\n", + " title=\"Image Plane\",\n", + " extent=(-5.5, 5.5, -5.5, 5.5),\n", + ")\n", + "\n", + "aaplt.plot_grid(\n", + " grid=source_plane_grid,\n", + " indexes=indexes,\n", + " ax=axes[1],\n", + " title=\"Source Plane\",\n", + " extent=(-5.5, 5.5, -5.5, 5.5),\n", + ")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "plt.close(fig)" ], "outputs": [], "execution_count": null @@ -459,19 +734,29 @@ "source": [ "__Ray Tracing Images__\n", "\n", - "The source-plane grid tells us where each image-plane coordinate lands in the source-plane after being deflected.\n", + "The source-plane grid tells us where the light at each image-plane\n", + "position originated. To calculate its brightness, we evaluate a\n", + "source light profile at those mapped positions.\n", + "\n", + "We use an `ExponentialCore` light profile centred at (0.1, 0.1)\n", + "arcseconds in the source plane. This places the source slightly\n", + "away from exact alignment with the lens centre.\n", "\n", - "To compute the lensed image of a source galaxy, we place a light profile in the source-plane and evaluate its light\n", - "on the ray-traced `source_plane_grid`. Because many image-plane coordinates map to the same region of the\n", - "source-plane, the source appears multiply imaged, forming arcs or a complete Einstein ring.\n", + "Each calculated intensity remains associated with its original\n", + "image-plane pixel. The resulting array therefore describes the\n", + "lensed image seen on the sky, even though we evaluated the light\n", + "profile at source-plane coordinates.\n", "\n", - "Let's create a source light profile and compute its lensed image." + "Different parts of the image plane can map onto the same region\n", + "of the source. This is how one source galaxy can appear as\n", + "multiple images or extended arcs." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "source_light_profile = al.lp.ExponentialCore(\n", " centre=(0.1, 0.1),\n", " ell_comps=(0.0, 0.1),\n", @@ -479,7 +764,9 @@ " effective_radius=0.2,\n", ")\n", "\n", - "lensed_image = source_light_profile.image_2d_from(grid=source_plane_grid)" + "lensed_image = source_light_profile.image_2d_from(\n", + " grid=source_plane_grid\n", + ")" ], "outputs": [], "execution_count": null @@ -488,20 +775,32 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "When we plot this image, the source's light appears as a strongly lensed Einstein ring.\n", + "Let's plot the lensed source. Look for its light stretched around\n", + "the lens centre into a ring-like image.\n", + "\n", + "This image is calculated from our chosen mass and light profiles.\n", + "\n", + "Try changing the source profile's `centre` in the preceding cell:\n", + "\n", + "- Start with (0.0, 0.0) arcseconds to align the source with the lens.\n", + "- Then try (0.0, 0.5) arcseconds to move the source off-centre.\n", "\n", - "This is the **image-plane image** or **observed image** we discussed at the start of the tutorial: the appearance\n", - "of the source *after* its light has been deflected by the lens galaxy's mass.\n", + "After each change, rerun the source-profile and `lensed_image`\n", + "calculations, then plot the result below. Moving the source off-centre\n", + "should make the lensed light less evenly distributed around the lens.\n", "\n", - "*Exercise*: Try changing the `centre` of the source light profile. Observe how moving the source relative to the\n", - "lens galaxy changes the lensed image from a ring into arcs or multiple images." + "Restore `centre=(0.1, 0.1)` and rerun those cells before continuing." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "aplt.plot_array(array=lensed_image, title=\"Lensed Source Image\")" + "\n", + "aplt.plot_array(\n", + " array=lensed_image,\n", + " title=\"Lensed Source Image\",\n", + ")" ], "outputs": [], "execution_count": null @@ -512,19 +811,25 @@ "source": [ "__Galaxies__\n", "\n", - "In the previous tutorial we saw that a `Galaxy` can contain one or more light profiles. A `Galaxy` can also contain\n", - "mass profiles, and can contain both at the same time.\n", + "In the previous tutorial, we put light profiles inside `Galaxy`\n", + "objects. A galaxy can also contain mass profiles.\n", "\n", - "This lets us construct realistic lens and source galaxies:\n", + "Let's place our mass profile in a lens galaxy at redshift 0.5,\n", + "and our source light profile in a source galaxy at redshift 1.0.\n", "\n", - "- The **lens galaxy** has a mass profile (which deflects light) and typically a light profile (its own emission).\n", - "- 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\n", + "but contributes no light of its own to this example. The source\n", + "galaxy contains the light profile whose lensed image we have\n", + "just calculated.\n", + "\n", + "Printing the galaxies shows their redshifts and profiles." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "lens_galaxy = al.Galaxy(\n", " redshift=0.5,\n", " mass=sis_mass_profile,\n", @@ -547,17 +852,18 @@ "source": [ "__Tracer__\n", "\n", - "Performing the ray-tracing calculation manually, as we did above, becomes cumbersome once we have multiple galaxies\n", - "at multiple redshifts.\n", + "A `Tracer` brings our galaxies together and performs the ray tracing\n", + "for us.\n", "\n", - "The `Tracer` object automates the entire ray-tracing process. We create it from a list of galaxies, ordered by their\n", - "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\n", + "which galaxy is in front and which is behind." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "tracer = al.Tracer(galaxies=[lens_galaxy, source_galaxy])" ], "outputs": [], @@ -567,19 +873,31 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The `Tracer` has an `image_2d_from` method, just like light profiles and galaxies. It performs all the ray-tracing\n", - "for us and returns the image of the entire strong lens system.\n", + "Like a light profile or galaxy, a `Tracer` has an `image_2d_from`\n", + "method.\n", + "\n", + "We pass it the original image-plane grid. It calculates the\n", + "deflections, traces the grid to the source plane and evaluates\n", + "the source's light there.\n", + "\n", + "The plot should reproduce the lensed image we calculated manually,\n", + "because we supplied the same mass and light profiles.\n", "\n", - "This produces the same lensed Einstein ring we computed manually above, but in a single line of code." + "A tracer also includes any light emitted by the lens galaxy.\n", + "Here, there is none, so the image contains only the lensed source." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "image = tracer.image_2d_from(grid=image_plane_grid)\n", "\n", - "aplt.plot_array(array=image, title=\"Image of Strong Lens System via Tracer\")" + "aplt.plot_array(\n", + " array=image,\n", + " title=\"Lensed Image via Tracer\",\n", + ")" ], "outputs": [], "execution_count": null @@ -588,14 +906,26 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The `subplot_tracer` method plots a subplot of the most important quantities of the strong lens system, including\n", - "its image, convergence, potential and deflection angles." + "We can display several views of the lens system together using\n", + "`aplt.subplot_tracer`.\n", + "\n", + "Compare the lensed image with the source-plane image, which shows\n", + "the source light profile before lensing. The lens-light panel\n", + "contains no emission because our lens galaxy has no light profile.\n", + "\n", + "The remaining panels show convergence, potential, the two\n", + "deflection components and magnification. These describe the same\n", + "mass profile we examined earlier.\n", + "\n", + "**\ud83e\udd16 Ask AI:** How does moving the source away from alignment with the\n", + "lens change an Einstein ring into separate arcs or images?" ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "aplt.subplot_tracer(tracer=tracer, grid=image_plane_grid)" ], "outputs": [], @@ -605,20 +935,22 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Mappings__\n", - "\n", - "The `Tracer` also gives us access to the grids of every plane in the strong lens system, via the\n", - "`traced_grid_2d_list_from` method.\n", + "The `Tracer` can also return the grids used in its ray-tracing\n", + "calculation, through `traced_grid_2d_list_from`.\n", "\n", - "This returns a list, where the first entry is the image-plane grid and the second entry is the ray-traced\n", - "source-plane grid. These are the same two grids we computed manually earlier, but now produced by the tracer." + "For our two-galaxy system, the first entry is the original\n", + "image-plane grid and the second is the ray-traced source-plane\n", + "grid. These correspond to the two grids we calculated manually." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "traced_grid_list = tracer.traced_grid_2d_list_from(grid=image_plane_grid)\n", + "\n", + "traced_grid_list = tracer.traced_grid_2d_list_from(\n", + " grid=image_plane_grid\n", + ")\n", "\n", "image_plane_grid_traced = traced_grid_list[0]\n", "source_plane_grid_traced = traced_grid_list[1]" @@ -626,52 +958,31 @@ "outputs": [], "execution_count": null }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "By plotting the image-plane and source-plane grids together, we can visualize the **mappings** between them.\n", - "\n", - "Every coordinate in the image-plane maps to a coordinate in the source-plane via the lens equation. This mapping is\n", - "the heart of strong lens modeling: to fit a lens, we ray-trace the image-plane grid to the source-plane, evaluate\n", - "the source's light there, and compare the resulting lensed image to the observed data." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.plot_grid(grid=image_plane_grid_traced, title=\"Image Plane Grid\")\n", - "aplt.plot_grid(grid=source_plane_grid_traced, title=\"Source Plane Grid\")" - ], - "outputs": [], - "execution_count": null - }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Wrap Up__\n", "\n", - "In this tutorial, you performed your first lensing calculations. Let's summarise what we've learnt:\n", - "\n", - "- **Mass Profiles**: Mass profiles are analytic functions that describe the mass distribution of a galaxy. They are\n", - "used to compute deflection angles, as well as the convergence and gravitational potential.\n", - "\n", - "- **Ray Tracing Grids**: The lens equation, $\\beta = \\theta - \\alpha(\\theta)$, uses deflection angles to map\n", - "image-plane coordinates to the source-plane, producing a distorted ray-traced grid.\n", - "\n", - "- **Ray Tracing Images**: By evaluating a source galaxy's light on the ray-traced source-plane grid, we compute the\n", - "lensed image of the source, which appears as arcs or an Einstein ring.\n", - "\n", - "- **Galaxies**: A `Galaxy` can contain both light and mass profiles, allowing us to construct realistic lens and\n", - "source galaxies.\n", - "\n", - "- **Tracer**: The `Tracer` object automates the ray-tracing process for a system of galaxies at different redshifts,\n", - "computing the image of the entire strong lens system in a single line of code.\n", - "\n", - "In the next tutorial, we'll extend these ideas to more complex mass and light distributions, building towards the\n", - "realistic strong lens systems we observe in real data." + "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." ] } ], diff --git a/scripts/chapter_1_introduction/tutorial_0_visualization.py b/scripts/chapter_1_introduction/tutorial_0_visualization.py index 0dcf202..12ae756 100644 --- a/scripts/chapter_1_introduction/tutorial_0_visualization.py +++ b/scripts/chapter_1_introduction/tutorial_0_visualization.py @@ -1,19 +1,19 @@ """ Tutorial 0: Visualization -========================= +======================== -In this tutorial, we quickly cover visualization in **PyAutoLens** and make sure images display -clearly in your Jupyter notebook and on your computer screen. +Plot a simulated image with **PyAutoLens**, compare views of the dataset, and adjust the display so you +can inspect its structure. This tutorial introduces the plotting tools used throughout the course. __Contents__ -- **Directories:** **HowToLens** assumes the working directory is the `HowToLens` repository root on your hard-disk. -- **Dataset:** Load and plot the strong lens dataset. -- **Dataset Auto-Simulation:** Create the dataset via its simulator script if it is not on your hard-disk. -- **Subplots:** In addition to plotting individual figures, **PyAutoLens** can plot `subplots` which show multiple. -- **Plot Customization:** Does the figure display correctly on your computer screen? -- **Overlays:** Overlays such as critical curves and image positions are added using the `lines=` and `positions=`. -- **Wrap Up:** Summary of the script and next steps. +- **Directories:** Check where the tutorial looks for files. +- **Dataset:** Identify the simulated image we will use. +- **Dataset Auto-Simulation:** Generate the example if needed, load it and plot the image. +- **Subplots:** Compare several views of the dataset. +- **Plot Customization:** Adjust colour scaling and figure size. +- **Overlays:** Draw a model-derived curve on an unblurred lensed image. +- **Wrap Up:** Review the plotting tools and continue to Tutorial 1. """ @@ -24,38 +24,33 @@ """ __Directories__ -**HowToLens** assumes the working directory is the `HowToLens` repository root on your hard-disk. This setup -allows **PyAutoLens** to: +Run this tutorial from the `HowToLens` repository folder, which contains `config/`, `dataset/` and `scripts/`. +Relative paths in the tutorial are resolved from your current working directory. -- Load configuration settings from the config files in the `config/` folder. +The next cell prints that directory. Check that it points to your `HowToLens` folder before continuing. -- Load the example strong lens datasets in the `dataset/` folder. - -- Write the results of model-fits to your hard-disk in the `output/` folder. - -If you do not have a clone of **HowToLens** on your computer, you can download it here: +If you have not downloaded the tutorials, get them from [the HowToLens repository](https://github.com/PyAutoLabs/HowToLens). +""" +from pathlib import Path - https://github.com/PyAutoLabs/HowToLens +print(Path.cwd()) -If your working directory does not match this path on your computer, you can manually set it as follows (the -example below shows the path I would use on my laptop. The code is commented out so you do not use this path in -this tutorial! """ -# workspace_path = "/Users/Jammy/Code/PyAuto/HowToLens" -# #%cd $workspace_path -# print(f"Working Directory has been set to `{workspace_path}`") +If the directory is incorrect, replace the example path below with the location of your repository and uncomment +the two lines. Then rerun the cell above to check the directory. +""" +# import os +# os.chdir("/path/to/HowToLens") """ __Dataset__ -The `dataset_path` specifies where the dataset is located, which is the -directory `dataset/imaging/simple__no_lens_light` of the HowToLens repository. +We will use a simulated image of a gravitationally lensed galaxy. This example omits light from the foreground +lens galaxy so that we can focus on the lensed source. -The simulated images of strong lenses used throughout the **HowToLens** lectures are written to the `dataset` -directory at runtime by the simulator scripts in `scripts/simulator/`. +The following path identifies the dataset folder within `HowToLens`. If the data are missing, the next section +generates them. """ -from pathlib import Path - import autolens as al import autolens.plot as aplt @@ -64,20 +59,26 @@ """ __Dataset Auto-Simulation__ -If the dataset does not already exist on your system, it is created by running the corresponding -simulator script. This ensures every example script can be run without manually simulating data first. +The next cell runs the simulator if the example dataset needs to be generated. You do not need to run the +simulator separately. """ if al.util.dataset.should_simulate(str(dataset_path)): import subprocess import sys + # Use the same Python interpreter as this tutorial. subprocess.run( [sys.executable, "scripts/simulator/no_lens_light.py"], check=True, ) """ -We now load this dataset from .fits files and create an instance of an `Imaging` object. +We now load three FITS files into an `Imaging` object: the image, its noise map and the point-spread function +(PSF). The noise map describes the uncertainty in each pixel; the PSF describes how the image of a point source +is blurred. + +Each pixel spans 0.1 arcseconds on each side, matching the simulator settings. Loading these files does not +fit a model to the image. """ dataset = al.Imaging.from_fits( data_path=dataset_path / "data.fits", @@ -87,49 +88,73 @@ ) """ -We can plot an image with `aplt.plot_array()`, passing the data array and a title. +Plot the simulated image using `aplt.plot_array()`. Look for the background galaxy’s light distorted into bright +features around the centre of the lens. The foreground galaxy contributes no light in this example. + +The simulation includes blurring by the PSF and noise, so the image includes both instrumental blurring and random fluctuations. """ aplt.plot_array(array=dataset.data, title="Dataset Image") """ __Subplots__ -In addition to plotting individual figures, **PyAutoLens** can plot `subplots` which show multiple -views of the dataset at once. +A subplot brings several views of the dataset into one figure. The next cell displays the image, noise map, +PSF and signal-to-noise map, alongside additional diagnostic panels. -The `aplt.subplot_imaging_dataset()` function plots the data, noise-map and PSF together. +Compare the image with its logarithmic view, labelled “Data (log10)”. The different colour scaling helps +reveal faint structure alongside bright features; it does not change the underlying data. + +For now, focus on these image panels and the noise map. We will introduce the numerical settings shown in +the other panels as they become relevant. """ aplt.subplot_imaging_dataset(dataset=dataset) """ __Plot Customization__ -Does the figure display correctly on your computer screen? +Change a figure's appearance by passing options to `aplt.plot_array()`. Here we use a logarithmic colour +scale to make faint structure easier to see. We create a 7-by-7-inch figure with Matplotlib and pass its axes +to the plotting function. -If not, the default matplotlib settings can be customized via the config files in: +Compare this plot with the first image. Logarithmic scaling changes how positive pixel values map to colours; +it does not change the image or make faint features more statistically significant. +""" +import matplotlib.pyplot as plt - config/visualize/ +fig, ax = plt.subplots(figsize=(7, 7)) +aplt.plot_array( + array=dataset.data, + title="Dataset Image (Log10)", + use_log10=True, + ax=ax, +) +plt.show() +plt.close(fig) -Key config entries: +""" +Try changing `use_log10=True` to `False` and rerun the cell to return to a linear colour scale. To enlarge +the figure, change `figsize=(7, 7)` to `(9, 9)`. Restore the starting values to reproduce the plot above. - - `mat_wrap.yaml` -> Figure -> figure: -> figsize - - `mat_wrap.yaml` -> YLabel -> figure: -> fontsize - - `mat_wrap.yaml` -> XLabel -> figure: -> fontsize - - `mat_wrap.yaml` -> TickParams -> figure: -> labelsize - - `mat_wrap.yaml` -> YTicks -> figure: -> labelsize - - `mat_wrap.yaml` -> XTicks -> figure: -> labelsize +You can also set `colormap="gray"` to display the image in greyscale. For persistent defaults, explore +`config/visualize/general.yaml`; its `colormap` entry sets the default colour map and +`subplot_shape_to_figsize_factor` controls subplot sizes. The per-call options above are enough for this lesson. -For quick one-off adjustments you can pass `title=`, `colormap=`, and `use_log10=` directly: +**🤖 Ask AI:** Why can logarithmic colour scaling make faint structure easier to see without increasing its +signal-to-noise ratio? """ -aplt.plot_array(array=dataset.data, title="Dataset Image (Log10)", use_log10=True) """ __Overlays__ -Overlays such as critical curves and image positions are added using the `lines=` and `positions=` -keyword arguments. +Overlays place reference curves or positions on an image. The `lines=` argument draws curves, while +`positions=` marks coordinates. + +Here we create a new, illustrative lens model and plot its unblurred lensed image with a tangential critical curve. +This curve is calculated from the model; it is not a feature measured directly from the image. Later tutorials +explain its lensing meaning. -For example, we can compute the critical curves of a tracer and overlay them on the image. +This model differs from the one used to simulate the dataset above. We evaluate its image at fixed parameters, +without adding a PSF or noise and without fitting the dataset. Look for the curve drawn over the unblurred lensed image. """ grid = al.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.05) @@ -160,16 +185,8 @@ """ __Wrap Up__ -Throughout the lectures you'll see lots more visuals plotted on figures and subplots. - -The key plotting functions you'll use are: - - - `aplt.plot_array(array, title, ...)` — plot any 2D array. - - `aplt.plot_grid(grid, title, ...)` — plot a 2D grid of coordinates. - - `aplt.subplot_imaging_dataset(dataset)` — multi-panel dataset overview. - - `aplt.subplot_tracer(tracer, grid)` — multi-panel tracer overview. - - `aplt.subplot_fit_imaging(fit)` — multi-panel fit overview. +You have plotted an image, compared dataset panels and changed the display without changing the pixel values. +Use `aplt.plot_array()` for an individual image and `aplt.subplot_imaging_dataset()` for a dataset overview. -Great! Hopefully, visualization in **PyAutoLens** is displaying nicely for us to get on with the -**HowToLens** lecture series. +Next, open Tutorial 1: Grids and Galaxies to learn how coordinates and light profiles produce a galaxy image. """ diff --git a/scripts/chapter_1_introduction/tutorial_1_grids_and_galaxies.py b/scripts/chapter_1_introduction/tutorial_1_grids_and_galaxies.py index 352267c..85753e3 100644 --- a/scripts/chapter_1_introduction/tutorial_1_grids_and_galaxies.py +++ b/scripts/chapter_1_introduction/tutorial_1_grids_and_galaxies.py @@ -1,66 +1,70 @@ r""" HowToLens: Introduction -======================= +====================== -A strong gravitational lens is a system where two (or more) galaxies align perfectly down our line of sight from Earth -such that the foreground galaxy's mass curves space-time in on itself, such that the light of a background source galaxy -is deflected and magnified. This means we can see the background source galaxy multiple times, as multiple arcs or rings, -because multiple paths through the foreground galaxy's mass are taken by the source's light. +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. -Here is a schematic of a strong gravitational lens: +We call the foreground galaxy the **lens** and the background galaxy the **source**. The side-on illustration +below shows two paths by which light from the source can reach the observer. It illustrates the geometry; +it is not drawn to scale. -![Schematic of Gravitational Lensing](https://raw.githubusercontent.com/PyAutoLabs/PyAutoLens/main/docs/overview/images/overview_1_lensing/schematic.jpg) -**Credit: F. Courbin, S. G. Djorgovski, G. Meylan, et al., Caltech / EPFL / WMKO** -https://www.astro.caltech.edu/~george/qsolens/ +![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) -Today, Astronomers use computer software, statistical algorithms and image processing techniques analyse the light of -these strong gravitational lenses. They are used for a wide range of scientific studies, including studying dark matter -in the foreground lens galaxies, the morphology and structure of the background source galaxies, and even the expansion -of the Universe itself. +Looking towards the lens, we see the source’s distorted images around it. The JWST image below shows the +COSMOS-Web Ring: the bright central galaxy is the lens, and the surrounding ring is light from the more +distant source galaxy. -The **HowToLens** series of tutorials will teach you how to perform this analysis yourself, using the open-source -software package **PyAutoLens**. By the end of the **HowToLens** series, you'll be able to take an image of -strong lens and study it using the same techniques that professional astronomers use today. +![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) -Tutorial 1: Grids And Galaxies -============================== +Both figures label an **Extra Galaxy**. This is another galaxy visible near the ring in the image, distinct +from the main lens and the lensed source. Its light can overlap the region we want to model. Appearing nearby +on the sky does not by itself tell us whether it is at the same distance as the lens. -In this tutorial, we will introduce the first fundamental concepts and quantities used to study strong lenses. -These concepts will enable us to create images of galaxies and analyze how their light is distributed across space. -Additionally, we will explore how adjusting various properties of galaxies can alter their appearance. For instance, -we can change the size of a galaxy, rotate it, or modify its brightness. +For now, the strong lenses we consider in this chapter have one lens galaxy. Chapter 4 introduces systems +with additional galaxies and explains how to account for their light and, where relevant, their gravitational +effect on the source images. -To create these images, we first need to define 2D grids of \((y, x)\) coordinates. We will shift and rotate these -grids to manipulate the appearance of the galaxy in the generated images. The grid will serve as the input for light -profiles, which are analytic functions that describe the distribution of a galaxy's light. By evaluating these light -profiles on the grid, we can effectively generate images that represent the structure and characteristics of galaxies. +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). -This tutorial won't yet perform any lensing calculations, which are introduced in the next tutorial. +By modelling these images, astronomers can study the distribution of mass in the lens, including dark matter, +and reconstruct the source galaxy’s light. Some lens systems also allow measurements of the Universe’s expansion. -Here is an overview of what we'll cover in this tutorial: +**HowToLens** teaches you to build and fit these models using **PyAutoLens**. We begin with simple descriptions +of galaxy light, then introduce gravitational lensing and the statistical methods used to compare models with data. -- **Grids**: We'll create a uniform grid of $(y,x)$ coordinates and show how it can be used to measure the light of a galaxy. -- **Geometry**: We'll show how to shift and rotate a grid, and convert it to elliptical coordinates. -- **Light Profiles**: We'll introduce light profiles, analytic functions that describe how a galaxy's light is distributed. -- **Galaxies**: We'll create galaxies containing light profiles and show how to compute their image. -- **Units**: We'll show how to convert the units of a galaxy's image to physical units like kiloparsecs. +Tutorial 1: Grids and Galaxies +============================= +In this tutorial, we will build an image of a galaxy from light profiles and explore how its appearance changes when we +adjust its position, orientation, size and brightness. -The imports below are required to run the HowToLens tutorials in a Jupiter notebook. They also import the -`autolens` package and the `autolens.plot` module which are used throughout the tutorials. +We start with a grid of positions on the sky, written in `(y, x)` order. A **light profile** is a mathematical +function that describes how a galaxy’s light varies with position. It is a model: a simplified mathematical +description of the galaxy. Evaluating it on the grid gives us a **light-profile image**. Later, we will +include the telescope’s blurring to construct a **model image** that can be compared with observed data. + +To describe a profile centred and oriented anywhere in the image, we express the grid coordinates relative +to that profile. We will work through these coordinate transformations before using the library’s light +profiles and galaxy objects. + +The examples evaluate models with parameters that we choose. They do not yet fit a model to observed data. + +We introduce the deflection of light by gravity in the next tutorial. __Contents__ -- **Grids:** A `Grid2D` is a set of two-dimensional $(y,x)$ coordinates that represent points in space where we. -- **Geometry:** The above grid is centered on the origin (0.0", 0.0"). -- **Light Profiles:** Galaxies are collections of stars, gas, dust, and other astronomical objects that emit light. -- **One Dimension Projection:** We often want to calculative 1D quantities of a light profile, for example to plot how its light. -- **Galaxies:** Galaxies are collections of light profiles that represent a galaxy's luminous emission. -- **Units:** By assuming a redshift for a galaxy we can convert its quantities from arcseconds to kiloparsecs. -- **Wrap Up:** Summary of the script and next steps. -- **Advanced Topics:** Optional reference material for expert users, not needed on a first read. -- **Other Unit Conversion:** Other unit conversions a galaxy's redshift enables (e.g. AB magnitudes). -- **Over Sampling:** The adaptive over-sampling scheme used to evaluate light profiles accurately. +- **Grids:** Create image coordinates and inspect their native and slim representations. +- **Geometry:** Express coordinates relative to a profile’s centre, orientation and ellipticity. +- **Light Profiles:** Calculate Sérsic intensities and build light-profile images. +- **One Dimension Projection:** Sample intensity along a profile’s major axis. +- **Galaxies:** Combine light profiles and galaxies, and compare their contributions. +- **Units:** Convert angular sizes into physical sizes using a cosmology. +- **Wrap Up:** Review the main ideas. +- **Advanced Topics:** Optional notes on units and numerical accuracy. +- **Other Unit Conversion:** Understand what brightness calibration requires. +- **Over Sampling:** Improve the numerical calculation within each pixel. """ @@ -78,107 +82,121 @@ """ __Grids__ -A `Grid2D` is a set of two-dimensional $(y,x)$ coordinates that represent points in space where we evaluate the -light emitted by a galaxy. +To build a galaxy image, we need positions at which to evaluate its light profile. A `Grid2D` stores these +positions in `(y, x)` order. For a uniform image grid, each coordinate marks the centre of a pixel. -Each coordinate on the grid is referred to as a 'pixel'. This is because we use the grid to measure the brightness of a -galaxy at each of these coordinates, allowing us to create an image of the galaxy. +We express positions in **arcseconds**, a unit of angle equal to 1/3600 of a degree. This describes distances +across the sky rather than physical distances within the galaxy. -Grids are defined in units of 'arc-seconds' ("). An arc-second is a unit of angular measurement used by astronomers to -describe the apparent size of objects in the sky. +The grid below has 101 rows and 101 columns. Setting `pixel_scales=0.1` gives square pixels that span +0.1 arcseconds on each side. -The `pixel_scales` parameter sets how many arc-seconds each pixel represents. For example, if `pixel_scales=0.1`, -then each pixel covers 0.1" of the sky. - -We create a uniform 2D grid of 101 x 101 pixels with a pixel scale of 0.1", corresponding to an area -of 10.1" x 10.1", spanning from -5.05" to 5.05" in both the y and x directions. +The image covers 10.1 by 10.1 arcseconds, with edges at −5.05 and +5.05 arcseconds. The pixel centres run +from −5.0 to +5.0 arcseconds along each axis, with the central pixel at `(0.0, 0.0)`. """ grid = al.Grid2D.uniform( - shape_native=( - 101, - 101, - ), # The dimensions of the grid, which here is 101 x 101 pixels. - pixel_scales=0.1, # The conversion factor between pixel units and arc-seconds. + shape_native=(101, 101), + pixel_scales=0.1, ) """ -We can visualize this grid as a uniform grid of dots, each representing a coordinate where the light is measured. +Plot the grid to see where we will evaluate the light profile. Each dot marks a pixel centre, with neighbouring +dots separated by 0.1 arcseconds horizontally and vertically. + +This figure shows positions only. We have not yet assigned a brightness to any pixel. """ aplt.plot_grid(grid=grid, title="Uniform Grid of Coordinates") """ -Each coordinate in the grid corresponds to an arc-second position. Below, we print a few of these coordinates to see -the values. +We can inspect individual coordinates using `grid.native[row, column]`. Rows and columns are numbered from +zero, and each entry contains a `(y, x)` pair in arcseconds. + +The first three entries below lie along the top row: their y coordinate stays at +5.0 while x increases +from −5.0 in steps of 0.1. The final entry starts the next row, where y decreases to +4.9. """ -print("(y,x) pixel 0:") -print(grid.native[0, 0]) # The coordinate of the first pixel. -print("(y,x) pixel 1:") -print(grid.native[0, 1]) # The coordinate of the second pixel. -print("(y,x) pixel 2:") -print(grid.native[0, 2]) # The coordinate of the third pixel. -print("(y,x) pixel 100:") -print(grid.native[1, 0]) # The coordinate of the 100th pixel. -print("...") +print("Row 0, column 0 (y, x):", grid.native[0, 0]) +print("Row 0, column 1 (y, x):", grid.native[0, 1]) +print("Row 0, column 2 (y, x):", grid.native[0, 2]) +print("Row 1, column 0 (y, x):", grid.native[1, 0]) """ -Grids have two internal representations, `native` and `slim`: +The same grid coordinates can be arranged in two ways: -- `native`: A 2D array with shape [total_y_pixels, total_x_pixels, 2], where the 2 corresponds to the (y,x) coordinates. -- `slim`: A 1D array with shape [total_y_pixels * total_x_pixels, 2], where the coordinates are 'flattened' into a single list. +- **`native`** preserves the rows and columns of the image. Use `grid.native[row, column]` to select a pixel’s `(y, x)` coordinates. +- **`slim`** lists the coordinate pairs in row order. Use `grid.slim[index]` to select a pair from that list. -These formats are useful for different calculations and plotting. Here, we show the same coordinate using both formats. +These are different arrangements of the same positions, not different grids. The two expressions below +return the coordinates of the same pixel. """ -print("(y,x) pixel 0 (accessed via native):") -print(grid.native[0, 0]) -print("(y,x) pixel 0 (accessed via slim 1D):") -print(grid.slim[0]) +print("First coordinate via native:", grid.native[0, 0]) +print("First coordinate via slim:", grid.slim[0]) """ -We can also check the shapes of the `Grid2D` object in both `native` and `slim` formats. For this grid, -the `native` shape is (101, 101, 2) and the `slim` shape is (10201, 2). +For this unmasked grid, `native` has shape `(101, 101, 2)`: 101 rows, 101 columns and two values per pixel—the +y and x coordinates. + +The `slim` representation has shape `(10201, 2)`: one coordinate pair for each of the 101 × 101 pixels. +The final dimension remains two because each position still needs both y and x. + +Print the shapes below to check how the coordinates are arranged. """ -print(grid.native.shape) -print(grid.slim.shape) +print("Native shape:", grid.native.shape) +print("Slim shape:", grid.slim.shape) """ -For the HowToLens tutorials, you don't need to fully understand why grids have both native and slim representations. -Just note that both are used for calculations and plotting. +Try changing the grid definition above, then rerun the plotting and coordinate-inspection cells: + +- Keep `shape_native=(101, 101)` and change `pixel_scales` from `0.1` to `0.2`. The number of points stays the same, but their spacing doubles and the image covers 20.2 by 20.2 arcseconds. +- Restore `pixel_scales=0.1`, then change `shape_native` to `(51, 51)`. The spacing stays the same, but fewer pixels cover a smaller region: 5.1 by 5.1 arcseconds. -*Exercise*: Try creating grids with different shapes and pixel scales using the `al.Grid2D.uniform()` function above. -Observe how the grid coordinates change when you adjust `shape_native` and `pixel_scales`. +Compare the axis ranges in the plots and the printed array shapes. Changing pixel scale changes the angular +spacing; changing the number of pixels changes how many positions we sample. + +Before continuing, restore `shape_native=(101, 101)` and `pixel_scales=0.1`, then rerun the grid-definition cell. __Geometry__ -The above grid is centered on the origin (0.0", 0.0"). Sometimes, we need to shift the grid to be centered on a -specific point, like the center of a galaxy. +Our grid describes positions relative to the image centre, `(0.0, 0.0)`. To evaluate a galaxy’s light profile, +we first express those positions relative to the galaxy’s centre. + +For a galaxy centred at `(0.3, 0.5)` arcseconds, subtract 0.3 from every y coordinate and 0.5 from every +x coordinate. The galaxy’s centre then has coordinates `(0.0, 0.0)` in this new reference frame. -We can shift the grid to a new center, (y_c, x_c), by subtracting this center from each coordinate. +This changes how we describe the positions; it does not move the pixels on the sky. """ -centre = (0.3, 0.5) # Shifting the grid to be centered at y=0.3", x=0.5". +centre = (0.3, 0.5) -grid_shifted = grid -grid_shifted[:, 0] = grid_shifted[:, 0] - centre[0] # Shift in y-direction. -grid_shifted[:, 1] = grid_shifted[:, 1] - centre[1] # Shift in x-direction. +grid_shifted = grid.copy() # Preserve the original image coordinates. +grid_shifted[:, 0] = grid_shifted[:, 0] - centre[0] +grid_shifted[:, 1] = grid_shifted[:, 1] - centre[1] -print("(y,x) pixel 0 After Shift:") -print(grid_shifted.native[0, 0]) # The coordinate of the first pixel after shifting. +print("First coordinate relative to the galaxy centre:", grid_shifted.native[0, 0]) """ -The grid is now centered around (0.3", 0.5"). We can plot the shifted grid to see this change. +The first coordinate changes from `(5.0, -5.0)` to `(4.7, -5.5)` arcseconds. The grid’s spacing and shape +are unchanged, but its coordinates now describe offsets from the galaxy’s centre. + +In the plot below, the original image centre lies at `(-0.3, -0.5)`. The origin of this coordinate frame +represents the galaxy’s centre. -*Exercise*: Try shifting the grid to a different center, for example (0.0", 0.0") or (2.0", 3.0"). Observe how the -center of the grid changes when you adjust the `centre` variable. +Try setting `centre=(0.0, 0.0)` and rerunning the shift and plot cells: the coordinates should match the +original grid. Restore `centre=(0.3, 0.5)` and rerun both cells before continuing. """ -aplt.plot_grid(grid=grid_shifted, title="Grid Centered Around (0.3, 0.5)") +aplt.plot_grid( + grid=grid_shifted, + title="Coordinates Relative to the Galaxy Centre", +) -r""" -Next, we can rotate the grid by an angle `phi` (in degrees). The rotation is counter-clockwise from the positive x-axis. +""" +An elliptical light profile also has an orientation. Its **position angle** is measured anticlockwise +from the positive x-axis to its major axis. -To rotate the grid: +To express our coordinates in a frame aligned with that profile, we apply the inverse rotation. For a +position angle of 60 degrees, we rotate the coordinate values clockwise by 60 degrees. -1. Calculate the distance `radius` of each coordinate from the origin using $r = \sqrt{y^2 + x^2}$. -2. Determine the angle `theta` counter clockwise from the positive x-axis using $\theta = \arctan(y / x)$. -3. Adjust `theta` by the rotation angle and convert back to Cartesian coordinates via $y = r \sin(\theta)$ and $x = r \cos(\theta)$. +The code below finds each point’s distance and angle from the galaxy’s centre, subtracts the profile’s +position angle, and converts back to `(y, x)` coordinates. `np.arctan2(y, x)` determines the angle while +accounting for which quadrant contains the point. """ angle_degrees = 60.0 @@ -188,138 +206,161 @@ radius = np.sqrt(y**2 + x**2) theta = np.arctan2(y, x) - np.radians(angle_degrees) -grid_rotated = grid_shifted +grid_rotated = grid_shifted.copy() # Preserve the unrotated offsets. grid_rotated[:, 0] = radius * np.sin(theta) grid_rotated[:, 1] = radius * np.cos(theta) -print("(y,x) pixel 0 After Rotation:") -print(grid_rotated.native[0, 0]) # The coordinate of the first pixel after rotation. +print("First coordinate in the profile frame:", grid_rotated.native[0, 0]) """ -The grid has now been rotated 60 degrees counter-clockwise. We can plot it to see the change. +The coordinates now describe positions in the profile’s reference frame, with its major axis along x. +The transformation preserves each point’s distance from the galaxy’s centre. + +Plot the transformed grid below. Its orientation has changed because we rotated the coordinate values +clockwise by 60 degrees. -*Exercise*: Try rotating the grid by a different angle, for example 30 degrees or 90 degrees. Observe how the grid -changes when you adjust the `angle_degrees` variable. +Try setting `angle_degrees=0.0` and rerunning the rotation and plot cells. The result should match +`grid_shifted`. Then try `30.0` to see a smaller rotation. Restore `60.0` and rerun both cells before continuing. """ -aplt.plot_grid(grid=grid_rotated, title="Grid Rotated 60 Degrees") +aplt.plot_grid( + grid=grid_rotated, + title="Coordinates in the Profile Frame", +) r""" -Next, we convert the rotated grid to elliptical coordinates using: +We can now assign an **elliptical radius** to each position. Points with the same elliptical radius lie +on an ellipse centred on the galaxy. + +Let $q=b/a$ be the ratio of the ellipse’s minor axis to its major axis. A circle has $q=1$; smaller values +describe more elongated ellipses. In the profile frame, the major axis lies along x, and the elliptical radius is -$\eta = \sqrt{(x_r)^2 + (y_r)^2/q^2}$ +$\eta = \sqrt{x_r^2 + \left(\frac{y_r}{q}\right)^2}$. -Where `q` is the axis-ratio of the ellipse and `(x_r, y_r)` are the rotated coordinates. +Here, $y_r$ and $x_r$ are the shifted and rotated coordinates in arcseconds, so $\eta$ is also in arcseconds. -Elliptical coordinates are a system used to describe positions in relation to an ellipse rather than a circle. They -are particularly useful in astronomy when dealing with objects like galaxies, which often have elliptical shapes -due to their inclination or intrinsic shape. +For $q=0.5$, a point at `(y, x) = (0, 1)` has elliptical radius 1 arcsecond, while `(1, 0)` has elliptical +radius 2 arcseconds. Offsets along the minor axis therefore correspond to larger elliptical radii. -*Exercise*: Try converting the grid to elliptical coordinates using a different axis-ratio, for example 0.3 or 0.8. -What happens to the grid when you adjust the `axis_ratio` variable? +The code below calculates one radius per grid position. It does not move the grid points. Try +`axis_ratio=1.0` to recover ordinary distance from the centre, then restore `0.5` before continuing. """ axis_ratio = 0.5 -eta = np.sqrt((grid_rotated[:, 0]) ** 2 + (grid_rotated[:, 1]) ** 2 / axis_ratio**2) -r""" -Above, the angle $\phi$ (in degrees) was used to rotate the grid, and the axis-ratio $q$ was used to convert the grid -to elliptical coordinates. +y_rotated = grid_rotated[:, 0] +x_rotated = grid_rotated[:, 1] + +eta = np.sqrt(x_rotated**2 + (y_rotated / axis_ratio) ** 2) -From now on, we'll describe ellipticity using "elliptical components" $\epsilon_{1}$ and $\epsilon_{2}$, calculated -from $\phi$ and $q$: +print("First ten elliptical radii (arcseconds):", eta[:10]) -$\epsilon_{1} = \frac{1 - q}{1 + q} \sin(2\phi)$ -$\epsilon_{2} = \frac{1 - q}{1 + q} \cos(2\phi)$ +r""" +The axis ratio $q$ and position angle $\phi$ together describe the ellipse’s shape and orientation. +The library packages the same information into two **ellipticity components**, passed as `ell_comps`: -We'll refer to these as `ell_comps` in the code for brevity. +$\epsilon_y = \frac{1-q}{1+q}\sin(2\phi)$, +$\epsilon_x = \frac{1-q}{1+q}\cos(2\phi)$. -Future tutorials will explain why $\epsilon_{1}$ and $\epsilon_{2}$ are preferred over $q$ and $\phi$. +The component order is `(epsilon_y, epsilon_x)`. These are dimensionless shape parameters, not spatial coordinates. -*Exercise*: Try computing the elliptical components from the axis-ratio and angle above. What happens to the elliptical -components when you adjust the `axis_ratio` and `angle_degrees` variables? +The doubled angle reflects the symmetry of an ellipse: rotating it by 180 degrees leaves its appearance +unchanged. For a circle, $q=1$, both components are zero and the orientation has no effect. + +The code below converts our axis ratio of 0.5 and position angle of 60 degrees into approximately +`(0.289, -0.167)`. We convert degrees to radians because NumPy’s trigonometric functions expect radians. """ -fac = (1 - axis_ratio) / (1 + axis_ratio) -epsilon_y = fac * np.sin(2 * np.radians(angle_degrees)) -epsilon_x = fac * np.cos(2 * np.radians(angle_degrees)) +ellipticity = (1 - axis_ratio) / (1 + axis_ratio) +angle_radians = np.radians(angle_degrees) -ell_comps = (epsilon_y, epsilon_x) +epsilon_y = ellipticity * np.sin(2 * angle_radians) +epsilon_x = ellipticity * np.cos(2 * angle_radians) -print("Elliptical Components:") -print(ell_comps) +ell_comps = (epsilon_y, epsilon_x) +print("Ellipticity components:", ell_comps) r""" __Light Profiles__ -Galaxies are collections of stars, gas, dust, and other astronomical objects that emit light. Astronomers study this -light to understand various properties of galaxies. +We now have the geometry needed to describe an elliptical galaxy. A light profile assigns a brightness to +each position using its distance from the galaxy’s centre. + +A commonly used model is the **Sérsic profile**: -To model the light of a galaxy, we use light profiles, which are mathematical functions that describe how a galaxy's -light is distributed across space. By applying these light profiles to 2D grids of $(y, x)$ coordinates, we can -create images that represent a galaxy's luminous emission. +$I(r)=I_e\exp\left\{-k\left[\left(\frac{r}{R_e}\right)^{1/n}-1\right]\right\}$. -A commonly used light profile is the `Sersic` profile, which is widely adopted in astronomy for representing galaxy -light. The `Sersic` profile is defined by the equation: +Its parameters are: -$I_{\rm Ser} (\eta_{\rm l}) = I \exp \left\{ -k \left[ \left( \frac{\eta}{R} \right)^{\frac{1}{n}} - 1 \right] \right\}$ +- $I_e$: the intensity at the effective radius, which sets the brightness scale. +- $R_e$: the effective radius, which describes the galaxy’s size. +- $n$: the Sérsic index, which controls the radial shape of the profile. +- $k$: a value determined by $n$, chosen so that the effective radius encloses half the model’s total light. -In this equation: +To match the library’s convention, we use the **circularised radius** $r=\sqrt{q}\,\eta$. A circle of radius +$r$ has the same area as the ellipse with major-axis radius $\eta$ and axis ratio $q$. Accordingly, $R_e$ +is the circularised size of the half-light ellipse; it does not generally describe a circular aperture +containing half the light. - - $\eta$ represents the elliptical coordinates of the profile in arc-seconds (refer to earlier sections for elliptical coordinates). - - $I$ is the intensity normalization of the profile, given in arbitrary units, which controls the overall brightness of the Sersic profile. - - $R$ is the effective radius in arc-seconds, which determines the size of the profile. - - $n$ is the Sersic index, which defines how 'steep' the profile is, influencing the concentration of light. - - $k$ is a constant that ensures half the light of the profile lies within the radius $R$, where $k = 2n - \frac{1}{3}$. +For this worked calculation, we use the simple approximation $k\approx2n-1/3$. The half-light interpretation +is therefore approximate here; the library uses a more accurate expression. -We can evaluate this function using values for $(\eta, I, R, n)$ to calculate the intensity of the profile at -a particular elliptical coordinate. +The code below evaluates the profile at a circularised radius of 0.5 arcseconds, using $R_e=2.0$ arcseconds, +$n=1.0$, and an intensity scale of 1.0 in arbitrary units. """ -elliptical_coordinate = ( - 0.5 # The elliptical coordinate where we compute the intensity, in arc-seconds. -) -intensity = 1.0 # Intensity normalization of the profile in arbitrary units. -effective_radius = 2.0 # Effective radius of the profile in arc-seconds. -sersic_index = 1.0 # Sersic index of the profile. -k = 2 * sersic_index - ( - 1.0 / 3.0 -) # Calculating the constant k, note that this is an approximation. - -# Calculate the intensity of the Sersic profile at a specific elliptical coordinate. -sersic_value = np.exp( - -k * ((elliptical_coordinate / effective_radius) ** (1.0 / sersic_index) - 1.0) +radius = 0.5 # Circularised radius in arcseconds. +intensity = 1.0 +effective_radius = 2.0 +sersic_index = 1.0 + +k = 2 * sersic_index - 1 / 3 + +sersic_value = intensity * np.exp( + -k * ((radius / effective_radius) ** (1 / sersic_index) - 1) ) -print("Intensity of Sersic Light Profile at Elliptical Coordinate 0.5:") -print(sersic_value) +print("Intensity at radius 0.5 arcseconds:", sersic_value) """ -The calculation above gives the intensity of the Sersic profile at an elliptical coordinate of 0.5. +The result is approximately 3.49 in our chosen intensity units. It exceeds `intensity=1.0` because this +position lies inside the effective radius, where the profile is brighter. -To create a complete image of the Sersic profile, we can evaluate the intensity at every point in our grid of -elliptical coordinates. +To build an image, apply the same calculation at every grid position. First convert the elliptical radii +`eta` to circularised radii, then evaluate the Sérsic function for the whole array. """ -sersic_image = np.exp(-k * ((eta / effective_radius) ** (1.0 / sersic_index) - 1.0)) +circularised_radii = np.sqrt(axis_ratio) * eta + +sersic_image = intensity * np.exp( + -k * ((circularised_radii / effective_radius) ** (1 / sersic_index) - 1) +) """ -When we plot the resulting image, we can see how the properties of the grid affect its appearance: +Plot the resulting brightness values at their original image positions. Look for a galaxy centred at +`(0.3, 0.5)` arcseconds, with its major axis oriented 60 degrees anticlockwise from the positive x-axis +and an axis ratio of 0.5. - - The peak intensity is at the position (0.3", 0.5"), where we shifted the grid. - - The image is elongated along a 60° counter-clockwise angle, corresponding to the rotation of the grid. - - The image has an elliptical shape, consistent with the axis ratio of 0.5. +The clockwise coordinate transformation lets us evaluate this anticlockwise-oriented profile. We then +display the calculated brightnesses on the original image grid. -This demonstrates how the geometry of the grid directly influences the appearance of the light profile. +Try changing `intensity` from `1.0` to `2.0`, then rerun the intensity calculations and plot. Every calculated +intensity should double, although automatic colour scaling may make the image look unchanged. Check the +printed value and colour-bar labels. -*Exercise*: Try changing the values of `centre`, `ell_comps`, `effective_radius`, and `sersic_index` above. -Observe how these adjustments change the Sersic profile image. +Restore `intensity=1.0` and rerun those cells before continuing. """ aplt.plot_array( - array=aa.Array2D(values=sersic_image, mask=grid.mask), title="Sersic Image" + array=aa.Array2D(values=sersic_image, mask=grid.mask), + title="Sérsic Image", ) """ -Instead of manually handling these transformations, we can use `LightProfile` objects from the `light_profile` -module (`lp`) for faster and more efficient calculations. +We have worked through the geometry and intensity calculation explicitly. A `Sersic` light-profile object +brings these steps together: we supply its parameters, and the library evaluates the profile. -Below, we define a `Sersic` light profile using the `Sersic` object. We can print the profile to display its parameters. +The `lp` namespace contains the library’s light profiles. Below, we create a Sérsic profile centred at +`(0.0, 0.0)`, with ellipticity components `(0.0, 0.1)`. These describe a mildly elliptical profile whose +major axis lies along x. + +This is a different example from our manual calculation: its centre and ellipticity have changed. +The intensity, effective radius and Sérsic index retain their previous values. """ sersic_light_profile = al.lp.Sersic( centre=(0.0, 0.0), @@ -332,132 +373,133 @@ print(sersic_light_profile) """ -With this `Sersic` light profile, we can create an image by passing a grid to its `image_2d_from` method. +Pass the original image grid to `image_2d_from()`. The profile handles the shift into its own reference frame, +its orientation and the intensity calculation. + +Use `grid`, rather than `grid_shifted` or `grid_rotated`: those transformed coordinates were part of our +manual demonstration. -The calculation will internally handle all the coordinate transformations and intensity evaluations we performed -manually earlier, making it much simpler. +Look for a galaxy centred on the origin and elongated along x. Its appearance differs from the previous +image because we changed the profile parameters. The library also uses a more accurate Sérsic constant +and samples within pixels to improve the image calculation; the optional over-sampling section explains +this later. -The `Sersic` profile we created just above is different from the one we used to manually compute the image, -so the image will look different. However, the process is the same. +This evaluates the model we specified. It does not fit the model to data. """ image = sersic_light_profile.image_2d_from(grid=grid) -aplt.plot_array(array=image, title="Sersic Image via Light Profile") +aplt.plot_array(array=image, title="Sérsic Image via Light Profile") """ -The `image` is returned as an `Array2D` object. Similar to a `Grid2D`, it has two forms: +The result is an `Array2D`, which stores one intensity value per image pixel. Like the grid, it supports +`native` and `slim` representations: - - `native`: A 2D array with shape [total_y_image_pixels, total_x_image_pixels]. - - `slim`: A 1D array that flattens this data into shape [total_y_image_pixels * total_x_image_pixels]. +- `image.native` arranges the values into image rows and columns, with shape `(101, 101)`. +- `image.slim` lists the values in row order, with shape `(10201,)`. -The `native` form is often used for visualizations, while the `slim` form can be useful for certain calculations. -""" -print("Intensity of pixel 0:") -print(image.native[0, 0]) -print("Intensity of pixel 1:") -print(image.slim[1]) +Unlike grid coordinates, image intensities do not need a final dimension of size two: each pixel contains +a single value. +The two expressions below access the same pixel, so they should print the same intensity. """ -To visualize the light profile's image, we use `aplt.plot_array`. - -We provide it with the light profile and the grid, which are used to create and plot the image. -""" -aplt.plot_array( - array=sersic_light_profile.image_2d_from(grid=grid), title="Image via Light Profile" -) +print("First pixel via native:", image.native[0, 0]) +print("First pixel via slim:", image.slim[0]) """ __One Dimension Projection__ -We often want to calculative 1D quantities of a light profile, for example to plot how its light changes as -a function of radius. +A light-profile image shows the galaxy’s two-dimensional appearance. We can also inspect how its intensity +changes along a line through its centre. -To do this, we must still input a 2D grid into the `image_2d_from` method, therefore we create a project 2D -radial grid as follows which has shape [Number_of_1d_coordinates, 2] and where all [:,0] entries are the same. +We still supply `(y, x)` positions to `image_2d_from()`, but those positions now lie along a line rather than +filling an image. The four points below lie along the positive x-axis, at distances of 0, 1, 2 and 3 arcseconds +from the origin. -A simple example of such a grid is as follows with 4 1D coordinates is: +`Grid2DIrregular` stores a list of positions without requiring a rectangular pixel grid. """ grid_2d_projected = al.Grid2DIrregular( [ - [1.000000e-06, 1.000000e-06], - [1.000000e-06, 1.000001e00], - [1.000000e-06, 2.000001e00], - [1.000000e-06, 3.000001e00], + (0.0, 0.0), + (0.0, 1.0), + (0.0, 2.0), + (0.0, 3.0), ] ) """ -As in this example, we often already have a 2D grid we are using to calculate images of a ligth profile -and it would be convenient to simply create `grid_2d_projected` from that. - -For example, we may want the project grid which traces it major axis in uniform radial steps. +For a smoother curve, sample more positions along the profile’s major axis. The code below places 101 points +between the galaxy’s centre and a distance of 5 arcseconds. -This is easily computed using the `grid_2d_radial_project_from` function and passing the `centre` and `angle` -of a light profile we can make it align with the light profile itself. +The position angle determines the direction of this line. Multiplying each distance by its sine and cosine +gives the y and x offsets; adding the profile centre places the line correctly in the image. -Note how in this example the two galaxy bulges are not rotationally aligned but we aligned the projected -grid with the first galaxy. The centres are aligned, but if they were not that would cause similar -issues. +We then evaluate the light profile at these positions. This measures intensity along the major axis, +rather than averaging the image in circular rings. """ -grid_2d_projected = grid.grid_2d_radial_projected_from( - centre=sersic_light_profile.centre, angle=sersic_light_profile.angle() +radii = np.linspace(0.0, 5.0, 101) +angle_radians = np.radians(sersic_light_profile.angle()) + +grid_2d_projected = al.Grid2DIrregular( + np.column_stack( + ( + sersic_light_profile.centre[0] + radii * np.sin(angle_radians), + sersic_light_profile.centre[1] + radii * np.cos(angle_radians), + ) + ) ) image_1d = sersic_light_profile.image_2d_from(grid=grid_2d_projected) """ -We can now plot the 1D radial profile of the light profile. This profile shows how the intensity of the light -changes as a function of distance from the profile's center. This is a more informative way to visualize the light p -rofile's distribution. - -When we plot 1D quantities, we do not use built-in plotting functions as in 2D, but instead use standard -matplotlib functionality. +Plot intensity against distance from the galaxy’s centre. The curve should fall outwards as the profile +becomes fainter. -The reason is partly that 1D plotting is simple, but also because 1D plots have many different decisions -about what is plotted and how they are computed, meaning its better to give the user full control. +The horizontal axis is distance along the major axis in arcseconds, not the circularised radius used earlier. +The vertical axis is intensity in our chosen arbitrary units—not luminosity integrated over the galaxy. -**Exercise**: Try plotting the 1D radial profile of Sersic profiles with different effective radii and Sersic indices. -Does the 1D representation show more clearly how the light distribution changes with these parameters? +Try changing `effective_radius` in the `Sersic` definition from `2.0` to `1.0`. Recreate the profile, then rerun +the sampling and plotting cells. The profile should become more compact. Restore `effective_radius=2.0` +and rerun those cells before continuing. """ -plt.plot(grid_2d_projected[:, 1], image_1d) -plt.xlabel("Radius (arcseconds)") -plt.ylabel("Luminosity") +plt.plot(radii, image_1d) +plt.xlabel("Distance along major axis (arcseconds)") +plt.ylabel("Intensity (arbitrary units)") plt.show() plt.close() +""" +A galaxy’s bright centre and faint outskirts can span a wide range of intensities. On a linear colour scale, +the bright centre can dominate the image, making the outskirts difficult to see. -r""" -Since galaxy light distributions often cover a wide range of values, they are typically better visualized on a log10 -scale. This approach helps highlight details in the faint outskirts of a light profile. +Logarithmic colour scaling gives more of the colour range to faint emission. Equal colour intervals represent +equal ratios of intensity, rather than equal differences. -The `plot_array`/`subplot_\*` object has a `use_log10` option that applies this transformation automatically. Below, you can see -that the image plotted in log10 space reveals more details. +Plot the same light-profile image with `use_log10=True` and compare it with the earlier linear-scale plot. +Look for light extending beyond the bright centre that was difficult to distinguish before. The intensity +values have not changed; we have changed how they are displayed. """ aplt.plot_array( - array=sersic_light_profile.image_2d_from(grid=grid), - title="Sersic Image", + array=image, + title="Sérsic Light-Profile Image (Log Scale)", use_log10=True, ) """ __Galaxies__ -Now, let's introduce `Galaxy` objects, which are a key component in **PyAutoLens**. +Now, let’s introduce `Galaxy` objects. A light profile can represent a component of a galaxy, such as its +bulge or disc. By combining light profiles in a `Galaxy`, we can describe their light together. -A light profile represents a single feature of a galaxy, such as its bulge or disk. To model a complete galaxy, -we combine multiple light profiles into a `Galaxy` object. This allows us to create images that include different -components of a galaxy. - -In addition to light profiles, a `Galaxy` has a `redshift`, which indicates how far away it is from Earth. The redshift -is essential for performing unit conversions using cosmological calculations, such as converting arc-seconds into -kiloparsecs. (A kiloparsec is a distance unit in astronomy, equal to about 3.26 million light-years.) +A `Galaxy` also has a **redshift**, which describes how much the wavelengths of its light have increased. +Together with a cosmological model, this lets us convert angular sizes in arcseconds into physical sizes +in kiloparsecs. A kiloparsec is approximately 3,260 light-years. Redshifts are especially important in strong lensing, where the foreground lens galaxy and background source galaxy lie at two different redshifts. We are not yet performing any lensing calculations in this tutorial, so for now we simply use a single galaxy to build up intuition for the `Galaxy` object. -Let's start by creating a galaxy with two `Sersic` light profiles, which we will consider to represent a bulge and -disk component of the galaxy, the two most important structures seen in galaxies. +Let’s create a galaxy with two Sérsic light profiles representing a bulge and a disc. In this example, +the bulge is smaller and rounder, while the disc is more extended and flattened. """ bulge = al.lp.Sersic( centre=(0.0, 0.0), @@ -480,81 +522,89 @@ print(galaxy) """ -We can pass a 2D grid to a light profile to compute its image using the `image_2d_from` method. +We used `image_2d_from()` to calculate the image of a light profile. The same method works for a `Galaxy`: +it evaluates each light profile on the grid and adds their intensities together. -The same approach works for a `Galaxy` object: +The result is an `Array2D` containing the galaxy image. Below, we print the combined intensity in each of +the first three pixels of the top row. """ image = galaxy.image_2d_from(grid=grid) -print("Intensity of `Grid2D` pixel 0:") -print(image.native[0, 0]) -print("Intensity of `Grid2D` pixel 1:") -print(image.native[0, 1]) -print("Intensity of `Grid2D` pixel 2:") -print(image.native[0, 2]) -print("...") +print("Row 0, column 0 intensity:", image.native[0, 0]) +print("Row 0, column 1 intensity:", image.native[0, 1]) +print("Row 0, column 2 intensity:", image.native[0, 2]) """ -We can plot the galaxy's image, just like how we did for a light profile. +Let’s plot the galaxy image. Each pixel contains light from both the bulge and the disc. + +The bright central region should stand out most clearly. The disc contributes light too, but its emission +is spread over a larger area and can be difficult to distinguish on this linear colour scale. """ -aplt.plot_array(array=galaxy.image_2d_from(grid=grid), title="Galaxy Bulge+Disk Image") +aplt.plot_array( + array=image, + title="Galaxy Bulge and Disc Image", +) """ -The bulge dominates the center of the image, and is pretty much the only luminous emission we can see on a linear -scale. The disk's emission is present, but it is much fainter and spread over a larger area. +To see what each component contributes, plot the bulge and disc separately using +`aplt.subplot_galaxy_light_profiles()`. + +Look for the bulge’s concentrated centre and the disc’s broader, more flattened appearance. These are the +two light-profile images that add together to produce the galaxy image above. -We can confirm this using the `subplot_galaxy_light_profiles` method, which plots each individual light profile -separately. +Each panel chooses its own colour scale, so compare the colour-bar values as well as the colours when +judging their relative brightness. """ aplt.subplot_galaxy_light_profiles(galaxy=galaxy, grid=grid) """ -Because galaxy light distributions often follow a log10 pattern, plotting in log10 space helps reveal details in the -outskirts of the light profile, in this case the emission of the disk. +Now display the combined galaxy image with logarithmic colour scaling. This makes the extended, faint +light easier to see alongside the bright centre. -This is especially helpful to separate the bulge and disk profiles, which have different intensities and sizes. +Compare the shape of the outskirts with the separate disc image. The disc’s contribution should be easier +to recognise here, although each pixel still contains the sum of both components. Changing the colour +scale does not separate their light. """ aplt.plot_array( - array=galaxy.image_2d_from(grid=grid), - title="Galaxy Bulge+Disk Image", + array=image, + title="Galaxy Bulge and Disc Image (Log Scale)", use_log10=True, ) """ -Using the tools above, we can visualize each light profile's contribution in 1D. +A radial plot lets us compare the bulge and disc intensities directly, using the same axes. -1D plots show the intensity of the light profile as a function of distance from the profile's center. The bulge -and disk profiles in this example share the same `centre`, meaning that plotting them together on the same 1D plot -shows how they vary relative to one another. +Our two profiles share a centre at `(0.0, 0.0)` and have their major axes along x. We can therefore evaluate +both at the same positions along the positive x-axis. -If the `centre` of the profiles were different, when you make the 1D plot you would need to decide whether to plot the -profiles offset from one another or plot them both from zero. +Look for the bulge’s high central intensity and how its contribution changes relative to the disc as you +move outwards. These curves show intensity at each position, not the total light enclosed within that radius. """ -grid_2d_projected = grid.grid_2d_radial_projected_from( - centre=galaxy.bulge.centre, angle=galaxy.bulge.angle() -) -bulge_image_1d = galaxy.bulge.image_2d_from(grid=grid_2d_projected) +radii = np.linspace(0.0, 5.0, 101) -grid_2d_projected = grid.grid_2d_radial_projected_from( - centre=galaxy.disk.centre, angle=galaxy.disk.angle() +grid_2d_projected = al.Grid2DIrregular( + np.column_stack((np.zeros_like(radii), radii)) ) + +bulge_image_1d = galaxy.bulge.image_2d_from(grid=grid_2d_projected) disk_image_1d = galaxy.disk.image_2d_from(grid=grid_2d_projected) -plt.plot(grid_2d_projected[:, 1], bulge_image_1d, label="Bulge") -plt.plot(grid_2d_projected[:, 1], disk_image_1d, label="Disk") -plt.xlabel("Radius (arcseconds)") -plt.ylabel("Luminosity") +plt.plot(radii, bulge_image_1d, label="Bulge") +plt.plot(radii, disk_image_1d, label="Disc") +plt.xlabel("Distance along major axis (arcseconds)") +plt.ylabel("Intensity (arbitrary units)") plt.legend() plt.show() plt.close() """ -We can group multiple galaxies at the same redshift into a `Galaxies` object, which is created from a list of -individual galaxies. +Just as a `Galaxy` groups light profiles, a `Galaxies` object groups individual galaxies. + +Let’s add a second galaxy, centred at `(0.2, 0.3)` arcseconds, and combine it with our bulge-and-disc galaxy. +Both have `redshift=0.5` in this example. -In a strong lens, we ultimately group together a foreground lens galaxy and a background source galaxy. For now, we -simply create a second galaxy and combine it with the original galaxy into a `Galaxies` object, to see how the light -of multiple galaxies is represented. +Their light overlaps in the image. Here we are simply adding their light profiles; we are not calculating +gravitational lensing or simulating an interaction between the galaxies. """ extra_galaxy = al.Galaxy( redshift=0.5, @@ -570,107 +620,134 @@ galaxies = al.Galaxies(galaxies=[galaxy, extra_galaxy]) """ -The `Galaxies` object has similar methods to those for light profiles and individual galaxies. +The `Galaxies` object provides the same `image_2d_from()` method we used for an individual galaxy. -For example, `image_2d_from` sums the images of all the galaxies. +It calculates each galaxy’s image on the supplied grid, then adds their intensities at every position. +The resulting image contains the light from the original bulge and disc together with the second galaxy’s +Sérsic profile. """ image = galaxies.image_2d_from(grid=grid) """ -We can plot the combined image of all the galaxies, just like with other plotters. +Plot the combined image of our two galaxies. Their centres are close together, so their light overlaps strongly. + +Compare this with the original bulge-and-disc galaxy image. The additional galaxy changes the brightness +distribution near the centre. """ -aplt.plot_array(array=galaxies.image_2d_from(grid=grid), title="Image") +aplt.plot_array( + array=image, + title="Combined Galaxy Image", +) """ -A subplot of each individual galaxy image can also be created. +To see the contribution from each galaxy, use `aplt.subplot_galaxy_images()`. Each panel shows one galaxy +from the collection, in the order we supplied them. + +The first contains our bulge and disc; the second contains the additional galaxy’s single Sérsic profile. +Compare their positions and shapes. Each panel uses its own colour scale, so check the colour bars when +comparing brightness. """ -aplt.subplot_galaxies(galaxies=galaxies, grid=grid) +aplt.subplot_galaxy_images(galaxies=galaxies, grid=grid) """ -Because galaxy light distributions often follow a log10 pattern, plotting in log10 space helps reveal details in the -outskirts of the light profile. +Display the combined image with logarithmic colour scaling to make the faint, extended light easier to see. -This is especially helpful when visualizing how multiple galaxies overlap. +The galaxies’ light overlaps in the same pixels. Compare this view with the individual images to understand +how each contributes to the combined shape. """ -aplt.plot_array(array=galaxies.image_2d_from(grid=grid), title="Image", use_log10=True) +aplt.plot_array( + array=image, + title="Combined Galaxy Image (Log Scale)", + use_log10=True, +) """ __Units__ -Earlier, we mentioned that a galaxy's `redshift` allows us to convert between arcseconds and kiloparsecs. +So far, we have described positions and sizes in arcseconds: angles measured on the sky. To express a +galaxy’s size in kiloparsecs, we need its distance. -A redshift measures how much a galaxy's light is stretched by the Universe's expansion. A higher redshift means the -galaxy is further away, and its light has been stretched more. By knowing a galaxy's redshift, we can convert angular -distances (like arcseconds) to physical distances (like kiloparsecs). +A cosmological model relates the galaxy’s redshift to the distance used for this conversion. Here we use +`Planck15`, a cosmology based on measurements from the Planck satellite. -To perform this conversion, we use a cosmological model that describes the Universe's expansion. Below, we use -the `Planck15` cosmology, which is based on observations from the Planck satellite. +The code below calculates how many kiloparsecs correspond to one arcsecond at our galaxy’s redshift of 0.5. """ cosmology = al.cosmo.Planck15() -kpc_per_arcsec = cosmology.kpc_per_arcsec_from(redshift=galaxy.redshift) +kpc_per_arcsec = cosmology.kpc_per_arcsec_from( + redshift=galaxy.redshift +) -print("Kiloparsecs per Arcsecond:") -print(kpc_per_arcsec) +print("Kiloparsecs per arcsecond:", kpc_per_arcsec) """ -This `kpc_per_arcsec` can be used as a conversion factor between arcseconds and kiloparsecs when plotting images of -galaxies. +Multiply an angular size by `kpc_per_arcsec` to express it in kiloparsecs. -We compute this value and plot the image, which by default is shown in units of arcseconds. -""" -aplt.plot_array(array=galaxy.image_2d_from(grid=grid), title="Image") +Our bulge has an effective radius of 1.0 arcsecond. The calculation below gives the physical size corresponding +to that radius at the galaxy’s redshift, using the chosen cosmology. +This is the same circularised effective radius expressed in different units. The conversion does not change +the galaxy image or the profile parameters stored in `galaxy`. """ -__Wrap Up__ - -In this tutorial, you've learnt the basic quantities used to describe the galaxies that make up a strong lens, before -we introduce any lensing calculations. - -Let's summarise what we've covered: +effective_radius_kpc = ( + galaxy.bulge.effective_radius * kpc_per_arcsec +) -- **Grids**: A grid is a set of 2D $(y,x)$ coordinates that represent the positions where we measure the light of a -galaxy. +print("Bulge effective radius (arcseconds):", galaxy.bulge.effective_radius) +print("Bulge effective radius (kiloparsecs):", effective_radius_kpc) -- **Geometry**: We showed how to shift, rotate, and convert grids to elliptical coordinates. +""" +__Wrap Up__ -- **Light Profiles**: Light profiles are analytic functions that describe how a galaxy's light is distributed in -space. We used the `Sersic` profile to create images of galaxies. +You have built galaxy images from light profiles and explored how their appearance depends on position, +orientation, size and brightness. -- **Galaxies**: Galaxies are collections of light profiles. We created galaxies with multiple light profiles, combined -them into a `Galaxies` object, and visualized their images. +The main ideas are: -- **Units**: By assuming redshifts for galaxies we can convert their quantities from arcseconds to physical units like -kiloparsecs. +- **Grids:** `(y, x)` coordinates specify where we evaluate the light. +- **Geometry:** shifting and rotating coordinates lets us describe a profile relative to its own centre and orientation. +- **Light profiles:** a Sérsic profile assigns an intensity to each position. +- **Galaxies:** light profiles combine into a `Galaxy`, and individual galaxies combine into `Galaxies`. +- **Visualisation:** images show spatial structure, while radial plots let us compare intensity as a function of distance. +- **Units:** a redshift and a cosmological model let us convert angular sizes into physical sizes. -In the next tutorial, we'll introduce the mass of a galaxy and perform our first lensing calculation, whereby the -light of a background source galaxy is deflected by the mass of a foreground lens galaxy. +**🤖 Ask AI:** In this tutorial, why do we rotate coordinates clockwise to evaluate a galaxy whose major axis +is oriented anticlockwise? __Advanced Topics__ -The following advanced topics are not important for a new user learning the software for the first time. However, -once you are an expert user, the following guides and concepts are important for doing accurate strong lens analysis, -and thus may be things you want to commit to memory as future references. +The notes below give some additional context on brightness units and numerical accuracy. They are optional +on a first reading. __Other Unit Conversion__ -Above, we used a redshift to convert between arcseconds and kiloparsecs. This is just one example of a unit conversion -that can be performed using a galaxy's redshift. +We used redshift and a cosmological model to convert angular sizes into physical sizes. Converting image +brightness into calibrated astronomical units is a different task. -There are many other unit conversions that can be performed, such as converting the units of a galaxy's image to what -Astronomers call an AB magnitude system, which is a system used to measure the brightness of galaxies. +Astronomers often express brightness using magnitudes, including the AB magnitude system. To calculate these +from an observed image, we need its flux calibration or an appropriate magnitude zero point. Redshift alone +is not enough, and the arbitrary intensity units used in this tutorial do not define an AB magnitude. -The `autolens_workspace/*/guides/units` module contains many examples of unit conversions and how to use them, -but they will not be covered in the *HowToLens* tutorials. +The workspace’s [flux guide](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/units/flux.py) +gives examples of brightness conversions, while its +[cosmology guide](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/units/cosmology.py) +covers cosmological distance conversions. __Over Sampling__ -Over sampling is a numerical technique where the images of light profiles and galaxies are evaluated -on a higher resolution grid than the image data to ensure the calculation is accurate. +A light profile can vary substantially across a pixel, especially near a bright galaxy centre. Evaluating +it only at the pixel centre may not represent the light across the whole pixel accurately. + +Over-sampling evaluates the profile at several positions within each pixel and combines those values. +This improves the numerical estimate without changing the image’s pixel size. + +The library supports both uniform over-sampling and adaptive schemes that use finer sampling where it is +needed. Our manual calculation sampled pixel centres, whereas the library’s image calculation uses the +grid’s over-sampling settings. -For a new user, the details of over-sampling are not important, therefore just be aware that all calculations use an -adaptive over sampling scheme with high accuracy across all use cases. +Accuracy still depends on the profile and sampling choices. A useful check is to increase the sampling +and see whether the calculated image changes appreciably. -Once you are more experienced, you should read up on over-sampling in more detail via -the `autolens_workspace/*/guides/advanced/over_sampling.ipynb` notebook. +The workspace’s [over-sampling guide](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/advanced/over_sampling.py) +explains these settings and how to check their accuracy. """ diff --git a/scripts/chapter_1_introduction/tutorial_2_ray_tracing.py b/scripts/chapter_1_introduction/tutorial_2_ray_tracing.py index d0f7346..1334e3f 100644 --- a/scripts/chapter_1_introduction/tutorial_2_ray_tracing.py +++ b/scripts/chapter_1_introduction/tutorial_2_ray_tracing.py @@ -1,72 +1,74 @@ """ 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. As in the previous tutorial, we leave systems with additional +galaxies until Chapter 4 and use one lens galaxy and one source galaxy here. -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. +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. -- **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`. +- **Wrap Up:** Review what we have learned and the next steps. """ from autolens import jax_wrapper # Sets JAX environment before other imports @@ -76,202 +78,462 @@ import matplotlib.pyplot as plt import autolens as al import autoarray as aa +import autoarray.plot as aaplt import autolens.plot as aplt """ __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. """ -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. -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. +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. -In gravitational lensing, deflection angles describe how a mass bends light by curving space-time. +For this profile, we specify two parameters: -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). +- `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 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. """ + 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) """ -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. -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. +For a mass profile, we call `deflections_yx_2d_from` to calculate the +deflection angles at those coordinates. + +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`. """ -deflections = sis_mass_profile.deflections_yx_2d_from(grid=image_plane_grid) -r""" -Like grids and arrays, the deflection angles can be accessed using the `native` and `slim` attributes. These are -structured similarly to a `Grid2D` object: +deflections = sis_mass_profile.deflections_yx_2d_from( + grid=image_plane_grid +) + +""" +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. + +The final dimension has length 2 because a deflection has both a y +component and an x component. -- **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. +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`. """ -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]) """ -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. """ + print(type(deflections)) r""" -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. """ -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]) """ -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. + +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. -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. +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. """ -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)", +) """ -Mass profiles also have additional properties used in lensing calculations: +A mass profile also lets us calculate other quantities that describe +the lens and its effect on the source's appearance: -- **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. +- **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`. """ -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: +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. """ + 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)", ) """ -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. """ -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() """ -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. """ + 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, ) r""" __Ray Tracing Grids__ -We now have all the tools we need to perform our first ray-tracing calculation. - -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. """ -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. """ -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)", +) + +""" +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. +""" + +aaplt.plot_grid( + grid=source_plane_grid, + title="Source Plane (Zoomed In)", + extent=(-1.0, 1.0, -1.0, 1.0), +) + +""" +__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. +""" + +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) """ __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. """ + source_light_profile = al.lp.ExponentialCore( centre=(0.1, 0.1), ell_comps=(0.0, 0.1), @@ -279,30 +541,50 @@ 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. """ -aplt.plot_array(array=lensed_image, title="Lensed Source Image") + +aplt.plot_array( + array=lensed_image, + title="Lensed Source Image", +) """ __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. """ + lens_galaxy = al.Galaxy( redshift=0.5, mass=sis_mass_profile, @@ -319,74 +601,91 @@ """ __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. """ + 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. -This produces the same lensed Einstein ring we computed manually above, but in a single line of code. -""" -image = tracer.image_2d_from(grid=image_plane_grid) +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. -aplt.plot_array(array=image, title="Image of Strong Lens System via Tracer") +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. """ -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. -""" -aplt.subplot_tracer(tracer=tracer, grid=image_plane_grid) -""" -__Mappings__ +image = tracer.image_2d_from(grid=image_plane_grid) -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. +aplt.plot_array( + array=image, + title="Lensed Image via Tracer", +) -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. """ -traced_grid_list = tracer.traced_grid_2d_list_from(grid=image_plane_grid) +We can display several views of the lens system together using +`aplt.subplot_tracer`. -image_plane_grid_traced = traced_grid_list[0] -source_plane_grid_traced = traced_grid_list[1] +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. -""" -By plotting the image-plane and source-plane grids together, we can visualize the **mappings** between them. +The remaining panels show convergence, potential, the two +deflection components and magnification. These describe the same +mass profile we examined earlier. -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. +**🤖 Ask AI:** How does moving the source away from alignment with the +lens change an Einstein ring into separate arcs or images? """ -aplt.plot_grid(grid=image_plane_grid_traced, title="Image Plane Grid") -aplt.plot_grid(grid=source_plane_grid_traced, title="Source Plane Grid") - -r""" -__Wrap Up__ -In this tutorial, you performed your first lensing calculations. Let's summarise what we've learnt: +aplt.subplot_tracer(tracer=tracer, grid=image_plane_grid) -- **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. +""" +The `Tracer` can also return the grids used in its ray-tracing +calculation, through `traced_grid_2d_list_from`. -- **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 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. +""" -- **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. +traced_grid_list = tracer.traced_grid_2d_list_from( + grid=image_plane_grid +) -- **Galaxies**: A `Galaxy` can contain both light and mass profiles, allowing us to construct realistic lens and -source galaxies. +image_plane_grid_traced = traced_grid_list[0] +source_plane_grid_traced = traced_grid_list[1] -- **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. +r""" +__Wrap Up__ -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. +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. """ diff --git a/workspace_index.json b/workspace_index.json index 5a03a1e..7211da8 100644 --- a/workspace_index.json +++ b/workspace_index.json @@ -12,7 +12,7 @@ "cross_refs": [], "notebook": "notebooks/chapter_1_introduction/tutorial_0_visualization.ipynb", "path": "scripts/chapter_1_introduction/tutorial_0_visualization.py", - "summary": "In this tutorial, we quickly cover visualization in **PyAutoLens** and make sure images display clearly in your Jupyter notebook and on your computer screen.", + "summary": "Plot a simulated image with **PyAutoLens**, compare views of the dataset, and adjust the display so you can inspect its structure. This tutorial introduces the plotting tools used throughout the course.", "title": "Tutorial 0: Visualization" }, { @@ -29,11 +29,14 @@ "Over Sampling" ], "cross_refs": [ - "/guides/advanced/over_sampling.ipynb" + "//github.com/PyAutoLabs/autolens_assistant/blob/main/docs/colab/cosmos_web_ring_colab.py", + "//github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/advanced/over_sampling.py", + "//github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/units/cosmology.py", + "//github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/units/flux.py" ], "notebook": "notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb", "path": "scripts/chapter_1_introduction/tutorial_1_grids_and_galaxies.py", - "summary": "A strong gravitational lens is a system where two (or more) galaxies align perfectly down our line of sight from Earth such that the foreground galaxy's mass curves space-time in on itself, such that the light of a background source galaxy is deflected and magnified. This means we can see the background source galaxy multiple times, as multiple arcs or rings, because multiple paths through the foreground galaxy's mass are taken by the source's light.", + "summary": "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\u2019s gravity deflects the light, allowing it to reach us along different paths. This is strong gravitational lensing.", "title": "HowToLens: Introduction" }, { @@ -41,16 +44,18 @@ "Grid", "Mass Profiles", "Ray Tracing Grids", + "Mappings", "Ray Tracing Images", "Galaxies", "Tracer", - "Mappings", "Wrap Up" ], - "cross_refs": [], + "cross_refs": [ + "//github.com/PyAutoLabs/autolens_assistant/blob/main/docs/colab/cosmos_web_ring_colab.py" + ], "notebook": "notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb", "path": "scripts/chapter_1_introduction/tutorial_2_ray_tracing.py", - "summary": "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.", + "summary": "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.", "title": "Tutorial 2: Ray Tracing" }, { From 79da36398dce7957e3ecef3cc43b5524b0e398cb Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sat, 31 Oct 2026 12:40:47 +0000 Subject: [PATCH 2/2] fix: declare full mapping grid in the ray-tracing tutorial --- config/build/profile_smoke.yaml | 9 ++++----- llms-full.txt | 2 +- .../tutorial_2_ray_tracing.ipynb | 3 ++- .../chapter_1_introduction/tutorial_2_ray_tracing.py | 10 ++++++++++ workspace_index.json | 3 ++- 5 files changed, 19 insertions(+), 8 deletions(-) diff --git a/config/build/profile_smoke.yaml b/config/build/profile_smoke.yaml index 4845f7a..2bcf776 100644 --- a/config/build/profile_smoke.yaml +++ b/config/build/profile_smoke.yaml @@ -31,8 +31,7 @@ defaults: # copied in from that repo's profile_smoke.yaml. HowToLens contains only # chapter_*/tutorial_*.py, so none of them ever matched a file here. # Do not copy override patterns between repos; a pattern that matches nothing -# is silently inert, not an override. -overrides: - # Fixed slim indexes illustrate mappings on the lesson's 101x101 grid. - - pattern: "chapter_1_introduction/tutorial_2_ray_tracing.py" - unset: [PYAUTO_SMALL_DATASETS] +# is silently inert, not an override. The list is now empty, and `overrides: []` +# is written explicitly because env_config.py reads `.get("overrides", [])` — +# a bare `overrides:` key would load as None and raise on iteration. +overrides: [] diff --git a/llms-full.txt b/llms-full.txt index 4face2e..1fa8efd 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -14,7 +14,7 @@ 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 + - 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 - [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. diff --git a/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb b/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb index 94e4eff..6e74ea9 100644 --- a/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb @@ -73,7 +73,8 @@ "- **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", - "- **Wrap Up:** Review what we have learned and the next steps." + "- **Wrap Up:** Review what we have learned and the next steps.\n", + "- **Env:** Preserve the grid used by the mapping example." ] }, { diff --git a/scripts/chapter_1_introduction/tutorial_2_ray_tracing.py b/scripts/chapter_1_introduction/tutorial_2_ray_tracing.py index 1334e3f..1c67e30 100644 --- a/scripts/chapter_1_introduction/tutorial_2_ray_tracing.py +++ b/scripts/chapter_1_introduction/tutorial_2_ray_tracing.py @@ -69,6 +69,7 @@ - **Galaxies:** Combine light and mass profiles into lens and source galaxies. - **Tracer:** Perform the ray-tracing calculation using a `Tracer`. - **Wrap Up:** Review what we have learned and the next steps. +- **Env:** Preserve the grid used by the mapping example. """ from autolens import jax_wrapper # Sets JAX environment before other imports @@ -689,3 +690,12 @@ In Tutorial 3, we will build on this example and explore more of the ray-tracing calculation. """ + +""" +__Env__ + +Keep the full 101-by-101 grid during automated runs so that the +chosen mapping indexes refer to the same points as in the lesson. + +ENV: full_datasets +""" diff --git a/workspace_index.json b/workspace_index.json index 7211da8..689121d 100644 --- a/workspace_index.json +++ b/workspace_index.json @@ -48,7 +48,8 @@ "Ray Tracing Images", "Galaxies", "Tracer", - "Wrap Up" + "Wrap Up", + "Env" ], "cross_refs": [ "//github.com/PyAutoLabs/autolens_assistant/blob/main/docs/colab/cosmos_web_ring_colab.py"