diff --git a/.github/scripts/check_tutorials_complete.py b/.github/scripts/check_tutorials_complete.py index 670b8dd..d9458ef 100644 --- a/.github/scripts/check_tutorials_complete.py +++ b/.github/scripts/check_tutorials_complete.py @@ -11,7 +11,9 @@ section marker (``__Wrap Up__`` or ``__Summary__``). A truncated script never reaches its wrap-up, so the absence of the marker is a reliable signal that the script lost content. Deliberate "not written yet" stub tutorials still carry a -``__Wrap Up__`` section, so they pass. +``__Wrap Up__`` section, so they pass. Tutorial 6 of Chapter 1 deliberately +ends with ``__Likelihood Function__``; it must retain its closing Chapter 2 +transition in the final docstring. A second, cheaper guard flags any script whose final docstring block ends on a colon (``:``) — the classic "a plot/code block follows" promise left dangling @@ -46,9 +48,17 @@ def final_docstring(text: str) -> str | None: def check(path: Path) -> str | None: """Return a failure reason for a truncated-looking tutorial, else None.""" text = path.read_text(encoding="utf-8") - if not any(marker in text.lower() for marker in TERMINAL_MARKERS): - return "no __Wrap Up__/__Summary__ terminal section (looks truncated)" trailing = final_docstring(text) + likelihood_ending = ( + path.parts[-2:] == ("chapter_1_introduction", "tutorial_6_fitting.py") + and "__Likelihood Function__" in text + and trailing is not None + and "__Likelihood Function__" not in trailing + and "In Chapter 2," in trailing + and trailing.strip().endswith("systematically.") + ) + if not likelihood_ending and not any(marker in text.lower() for marker in TERMINAL_MARKERS): + return "no __Wrap Up__/__Summary__ terminal section (looks truncated)" if trailing is not None and trailing.strip().endswith(":"): return "final docstring ends on ':' (dangling promise of a following block)" return None @@ -67,7 +77,8 @@ def main(root: str) -> int: print(f" [FAIL] {f.relative_to(root)} — {reason}") print( "\nEach tutorial must end with a `__Wrap Up__` (or `__Summary__`) " - "section. If a script is genuinely truncated, restore its lost " + "section (or the approved Chapter 1 likelihood ending). " + "If a script is genuinely truncated, restore its lost " "content; if it is complete, add the terminal section." ) return 1 diff --git a/llms-full.txt b/llms-full.txt index 29df721..cf1054d 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -19,11 +19,11 @@ AUTO-GENERATED by PyAutoHands — do not edit by hand; regenerate with generate. - Contents: Initial Setup, Concise Code, Cosmological Distances, Convergence, Deflection Angles, The Lensing Potential, Shear and Magnification, Critical Curves and Caustics, Einstein Radius, Time Delays, Wrap Up, Env - [Tutorial 4: Point Sources](scripts/chapter_1_introduction/tutorial_4_point_sources.py): In the previous tutorials, we lensed extended galaxies, producing arcs and Einstein rings. We now turn to sources whose individual lensed images are too small for a telescope to resolve: **point sources**. - Contents: Initial Setup, Seeing the Compact Source, Point Sources, Point Source Tracer, The Lens Equation, Point Solver, Finding the Images, Multiple Images and Critical Curves, Magnifications, Interpreting Fluxes, Time Delays, Connecting Time Delays to the Images, Extended Versus Point Computations, Wrap Up -- [Tutorial 5: Data](scripts/chapter_1_introduction/tutorial_5_data.py): In the last tutorials, we use tracers to create images of strong lenses. However, those images don't accurately represent what we would observe through a telescope. - - Contents: Initial Setup, Optics Blurring, Poisson Noise, Background Sky, Simulator, Output, Point Source Data, Interferometer Data, Weak Lensing Data, Wrap Up -- [Tutorial 6: Fitting](scripts/chapter_1_introduction/tutorial_6_fitting.py): In previous tutorials, we used light profiles to create simulated images of a tracer and visualized how these images would appear when captured by a CCD detector on a telescope like the Hubble Space Telescope. - - Contents: Dataset, Dataset Auto-Simulation, Mask, Masked Grid, Fitting, Incorrect Fit, Model Fitting, Wrap Up -- [Tutorial 7: Summary](scripts/chapter_1_introduction/tutorial_7_summary.py): In this chapter, we have learnt that: +- [Tutorial 5: Data](scripts/chapter_1_introduction/tutorial_5_data.py): In the previous tutorials, we used tracers to create images of strong lenses. We will now use one of these images to simulate an observation through a telescope. + - Contents: Initial Setup, Optics Blurring, Poisson Noise, Background Sky, Simulator, Output, Point Source Data, Interferometer Data, Weak Lensing Data, Group and Cluster Lenses, Wrap Up +- [Tutorial 6: Fitting](scripts/chapter_1_introduction/tutorial_6_fitting.py): In the previous tutorial, we chose a lens and source, predicted their lensed image and simulated a telescope observation. We will now work in the other direction: starting with an image, we want to learn about the objects that produced it. + - Contents: Dataset, Dataset Auto-Simulation, Mask, Masked Grid, Fitting, Incorrect Fit, Model Fitting, Likelihood Function +- [Tutorial 7: Summary](scripts/chapter_1_introduction/tutorial_7_summary.py): In this chapter, we have built up the steps needed to describe a gravitational lens and compare its predicted image with an observation: - Contents: Start, Object Composition, Visualization, Code Design, Source Code, Wrap Up ## chapter_2_lens_modeling diff --git a/notebooks/chapter_1_introduction/tutorial_5_data.ipynb b/notebooks/chapter_1_introduction/tutorial_5_data.ipynb index 97a30d8..23bd35b 100644 --- a/notebooks/chapter_1_introduction/tutorial_5_data.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_5_data.ipynb @@ -7,43 +7,33 @@ "Tutorial 5: Data\n", "================\n", "\n", - "In the last tutorials, we use tracers to create images of strong lenses. However, those images don't accurately\n", - "represent what we would observe through a telescope.\n", + "In the previous tutorials, we used tracers to create images of strong lenses.\n", + "We will now use one of these images to simulate an observation through a telescope.\n", "\n", - "Real telescope images, like those taken with the Charge Coupled Device (CCD) imaging detectors on the Hubble Space\n", - "Telescope, include several factors that affect what we see:\n", + "A telescope spreads light over neighbouring pixels, making fine details less\n", + "sharp. Its detector collects light for a finite exposure time, and the number\n", + "of photons detected fluctuates from one observation to another. Light from the\n", + "background sky also contributes to the recorded image.\n", "\n", - "**Telescope Optics:** The optical components of the telescope can blur the light, influencing the image's sharpness.\n", + "We will introduce these effects separately so that you can see what each one\n", + "does, then combine them using PyAutoLens's `SimulatorImaging` object.\n", "\n", - "**Exposure Time:** The time the detector collects light, affecting the clarity of the image. Longer exposure times\n", - "gather more light, improving the signal-to-noise ratio and creating a clearer image.\n", - "\n", - "**Background Sky:** Light from the sky itself, such as distant stars or zodiacal light, adds additional noise to\n", - "the image.\n", - "\n", - "In this tutorial, we'll simulate a strong lens image by applying these real-world effects to the light and mass\n", - "profiles and images we created earlier.\n", - "\n", - "Here is an overview of what we'll cover in this tutorial:\n", - "\n", - "- **Optics Blurring:** We'll simulate how the telescope optics blur the galaxy's light, making the images appear blurred.\n", - "- **Poisson Noise:** We'll add Poisson noise to the image, simulating the randomness in the photon-to-electron conversion process on the CCD.\n", - "- **Background Sky:** We'll add a background sky to the image, simulating the light from the sky that adds noise to the image.\n", - "- **Simulator:** We'll use the `SimulatorImaging` object to simulate imaging data that includes all these effects.\n", - "- **Other Data Types:** We'll finish with a brief look at point-source, interferometer and weak lensing datasets.\n", + "Our example uses a charge-coupled device (CCD), a detector that records incoming\n", + "light as electrons collected in its pixels.\n", "\n", "__Contents__\n", "\n", - "- **Initial Setup:** To create our simulated strong lens image, we first need a 2D grid.\n", - "- **Optics Blurring:** All images captured using CCDs (like those on the Hubble Space Telescope or Euclid) experience some.\n", - "- **Poisson Noise:** In addition to the blurring caused by telescope optics, we also need to consider Poisson noise when.\n", - "- **Background Sky:** The final effect we will consider when simulating imaging data is the background sky.\n", - "- **Simulator:** The `SimulatorImaging` object lets us create simulated imaging data while including the effects of.\n", - "- **Output:** We will now save these simulated data to `.fits` files, the standard format used by astronomers for.\n", - "- **Point Source Data:** Collect image positions, fluxes and time delays with their uncertainties.\n", - "- **Interferometer Data:** Radio / sub-mm interferometers like ALMA observe visibilities in the uv-plane rather than images.\n", - "- **Weak Lensing Data:** Weak lensing datasets are catalogues of weakly sheared background galaxy ellipticities.\n", - "- **Wrap Up:** Summary of the script and next steps." + "- **Initial Setup:** Create the lensed image that we will use for the simulation.\n", + "- **Optics Blurring:** Describe the telescope's blurring with a point spread function.\n", + "- **Poisson Noise:** Simulate fluctuations in the number of electrons collected.\n", + "- **Background Sky:** Include sky light and the additional noise it produces.\n", + "- **Simulator:** Combine these effects into an imaging dataset.\n", + "- **Output:** Save the data, noise map and point spread function to FITS files.\n", + "- **Point Source Data:** Introduce measured positions, fluxes and time delays.\n", + "- **Interferometer Data:** Introduce measurements made by radio interferometers.\n", + "- **Weak Lensing Data:** Introduce catalogues of background galaxy shapes.\n", + "- **Group and Cluster Lenses:** Preview the larger lens systems studied in Chapter 4.\n", + "- **Wrap Up:** Review what we have learned." ] }, { @@ -108,8 +98,9 @@ "source": [ "__Initial Setup__\n", "\n", - "To create our simulated strong lens image, we first need a 2D grid. This grid will represent the coordinate space over \n", - "which we will simulate the strong lens's light distribution." + "We begin with a grid of 101 x 101 pixels, with each pixel spanning 0.1 arcseconds\n", + "on the sky. As in the earlier tutorials, the grid supplies the coordinates at\n", + "which we calculate the lensed image." ] }, { @@ -117,11 +108,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": [], @@ -131,12 +119,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Next, we define the properties of our strong lens. In this tutorial, we\u2019ll represent the lens with no luminous\n", - "emmission and an`Isothermal` mass profile. The source galaxy will be represented by a Sersic light profile.\n", + "Our lens galaxy has an `Isothermal` mass profile. We omit its light so that we\n", + "can focus on how the observation changes the appearance of the lensed source.\n", + "The source galaxy has a Sersic light profile.\n", + "\n", + "For this simulation, image values represent electrons per second in each pixel.\n", + "Multiplying a pixel's value by the exposure time will therefore give the\n", + "expected number of electrons collected in that pixel.\n", "\n", - "In the previous tutorial, the units of `intensity` were arbitrary. However, for this tutorial, where we simulate \n", - "realistic imaging data, the intensity must have specific units. We\u2019ll use units of electrons per second per pixel \n", - "($e- pix^-1 s^-1$), which is standard for CCD imaging data." + "We use the same units for the light profile's `intensity`, which sets its\n", + "brightness at the effective radius." ] }, { @@ -146,7 +138,9 @@ "lens_galaxy = al.Galaxy(\n", " redshift=0.5,\n", " mass=al.mp.Isothermal(\n", - " centre=(0.0, 0.0), einstein_radius=1.6, ell_comps=(0.17647, 0.0)\n", + " centre=(0.0, 0.0),\n", + " einstein_radius=1.6,\n", + " ell_comps=(0.17647, 0.0),\n", " ),\n", ")\n", "\n", @@ -155,7 +149,7 @@ " bulge=al.lp.Sersic(\n", " centre=(0.1, 0.1),\n", " ell_comps=(0.0, 0.111111),\n", - " intensity=1.0, # in units of e- pix^-1 s^-1\n", + " intensity=1.0, # Electrons per second per pixel.\n", " effective_radius=1.0,\n", " sersic_index=2.5,\n", " ),\n", @@ -170,7 +164,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Lets look at the tracer's image, which is the image we'll be simulating." + "First, let's look at the lensed image. The telescope's blurring, background sky\n", + "and random noise have not yet been included.\n", + "\n", + "Look at the sharpness of the arcs and the faint light around them. This is our\n", + "starting image for seeing how each observational effect changes their appearance." ] }, { @@ -178,7 +176,8 @@ "metadata": {}, "source": [ "aplt.plot_array(\n", - " array=tracer.image_2d_from(grid=grid), title=\"Tracer Image Before Simulating\"\n", + " array=tracer.image_2d_from(grid=grid),\n", + " title=\"Lensed Image Before Simulating the Observation\",\n", ")" ], "outputs": [], @@ -190,13 +189,20 @@ "source": [ "__Optics Blurring__\n", "\n", - "All images captured using CCDs (like those on the Hubble Space Telescope or Euclid) experience some level of blurring \n", - "due to the optics of the telescope. This blurring occurs because the optical system spreads out the light from each \n", - "point source (e.g., a star or a part of a galaxy).\n", + "A point source does not appear as a single perfectly sharp point in a telescope\n", + "image. The telescope spreads its light over a small region. The shape of this\n", + "response is called the point spread function, or PSF.\n", + "\n", + "An extended image is blurred in the same way: light from every position is\n", + "spread according to the PSF. We calculate this using an operation called\n", + "convolution.\n", + "\n", + "For our example, we will use a circular Gaussian PSF. Its `sigma` is\n", + "0.1 arcseconds, equal to one pixel on our grid. A larger sigma would spread the\n", + "light over a wider region.\n", "\n", - "The Point Spread Function (PSF) describes how the telescope blurs the image. It can be thought of as a 2D representation \n", - "of how a single point of light would appear in the image, spread out by the optics. In practice, the PSF is a 2D \n", - "convolution kernel that we apply to the image to simulate this blurring effect." + "The PSF is represented by an 11 x 11 array called a kernel. We normalise its\n", + "values to sum to one, so that it describes how light is redistributed." ] }, { @@ -204,10 +210,10 @@ "metadata": {}, "source": [ "psf = al.Convolver.from_gaussian(\n", - " shape_native=(11, 11), # The size of the PSF kernel, represented as an 11x11 grid.\n", - " sigma=0.1, # Controls the width of the Gaussian PSF, which determines the level of blurring.\n", - " pixel_scales=grid.pixel_scales, # Maintains consistency with the scale of the image grid.\n", - " normalize=True, # Normalizes the PSF kernel so that its values sum to 1.\n", + " shape_native=(11, 11),\n", + " sigma=0.1, # Arcseconds.\n", + " pixel_scales=grid.pixel_scales,\n", + " normalize=True,\n", ")" ], "outputs": [], @@ -217,9 +223,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can visualize the PSF to better understand how it will blur the galaxy's image. The PSF is essentially a small \n", - "image that represents the spreading out of light from a single point source. This kernel will be used to blur the \n", - "entire tracer image when we perform the convolution." + "Plotting the kernel shows how the light from a point source is distributed:\n", + "the central pixels receive the most light, with progressively less farther\n", + "from the centre." ] }, { @@ -235,16 +241,22 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The PSF is often more informative when plotted on a log10 scale. This approach allows us to clearly observe values \n", - "in its tail, which are much smaller than the central peak yet critical for many scientific analyses. The tail \n", - "values may significantly affect the spread and detail captured in the data." + "The PSF becomes much fainter away from its centre. On the previous plot's linear\n", + "colour scale, these faint outer regions can be difficult to see.\n", + "\n", + "A logarithmic colour scale makes them more visible. The kernel values are\n", + "unchanged; only the way we display them changes." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "aplt.plot_array(array=psf.kernel, title=\"PSF 2D Kernel (Log10)\", use_log10=True)" + "aplt.plot_array(\n", + " array=psf.kernel,\n", + " title=\"PSF 2D Kernel (Log10)\",\n", + " use_log10=True,\n", + ")" ], "outputs": [], "execution_count": null @@ -253,35 +265,37 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Next, we'll manually perform a 2D convolution of the PSF with the image of the galaxy. This convolution simulates the \n", - "blurring that occurs when the telescope optics spread out the galaxy's light.\n", + "We will now convolve the lensed image with the PSF to calculate how it appears\n", + "after the telescope has blurred it.\n", "\n", - "1. **Padding the Image**: Before convolution, we add padding (extra space with zero values) around the edges of the \n", - " image. This prevents unwanted edge effects when we perform the convolution, ensuring that the image's edges don't \n", - " become artificially altered by the process.\n", + "Light just outside the image can be spread into pixels near its edges. To\n", + "include this light, we first evaluate the tracer on a larger grid, extending\n", + "beyond the region we want to observe. This produces a padded image containing\n", + "the model's predicted light in the surrounding pixels.\n", "\n", - "2. **Convolution**: Using the `Convolver` object's `convolve` method, we apply the 2D PSF convolution to the padded \n", - " image. This step combines the PSF with the galaxy's light, simulating how the telescope spreads out the light.\n", - "\n", - "3. **Trimming the Image**: After convolution, we trim the padded areas back to their original size, obtaining a \n", - " convolved (blurred) image that matches the dimensions of the initial tracer image." + "We then convolve this larger image with the PSF and trim away the extra border.\n", + "The result has the same dimensions as our original image." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "image = tracer.image_2d_from(grid=grid) # The original unblurred image of the galaxy.\n", + "image = tracer.image_2d_from(grid=grid)\n", + "\n", "padded_image = tracer.padded_image_2d_from(\n", " grid=grid,\n", - " psf_shape_2d=psf.kernel.shape_native, # Adding padding based on the PSF size.\n", + " psf_shape_2d=psf.kernel.shape_native,\n", ")\n", + "\n", "convolved_image = psf.convolved_image_from(\n", - " image=padded_image, blurring_image=None\n", - ") # Applying the PSF convolution.\n", + " image=padded_image,\n", + " blurring_image=None,\n", + ")\n", + "\n", "blurred_image = convolved_image.trimmed_after_convolution_from(\n", " kernel_shape=psf.kernel.shape_native\n", - ") # Trimming back to the original size." + ")" ], "outputs": [], "execution_count": null @@ -290,8 +304,15 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can now plot the original and the blurred images side by side. This allows us to clearly see how the PSF \n", - "convolution affects the appearance of the galaxy, making the image appear softer and less sharp." + "Compare the lensed image before and after convolution. Look at the narrow\n", + "features in the arcs: the PSF spreads their light over neighbouring pixels,\n", + "making them less sharp. With our small PSF, the difference may be subtle.\n", + "\n", + "To make the effect easier to see, change `sigma` in the PSF definition from\n", + "0.1 to 0.2 arcseconds. Rerun the PSF definition, convolution and plots below.\n", + "You should see stronger blurring in the second image.\n", + "\n", + "Afterwards, restore `sigma=0.1` and rerun those cells before continuing." ] }, { @@ -300,57 +321,57 @@ "source": [ "aplt.plot_array(array=image, title=\"Tracer Image Before PSF\")\n", "\n", - "aplt.plot_array(array=blurred_image, title=\"Tracer Image After PSF\")\n" + "aplt.plot_array(array=blurred_image, title=\"Tracer Image After PSF\")" ], "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**🤖 Ask AI:** How does blurring by a telescope's PSF affect our ability to\n", + "distinguish two nearby features in a gravitationally lensed arc?" + ] + }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Poisson Noise__\n", "\n", - "In addition to the blurring caused by telescope optics, we also need to consider Poisson noise when simulating imaging \n", - "data.\n", - "\n", - "When a telescope captures an image of a galaxy, photons from the galaxy are collected by the telescope's mirror and \n", - "directed onto a CCD (Charge-Coupled Device). The CCD is made up of a silicon lattice (or another material) that \n", - "converts incoming photons into electrons. These electrons are then gathered into discrete squares, which form the \n", - "pixels of the final image.\n", + "Even if a galaxy's brightness remains constant, repeated observations do not\n", + "collect exactly the same number of photons in each pixel. Photon arrivals\n", + "fluctuate randomly, and the detector records these arrivals as electrons.\n", "\n", - "The process of converting photons into electrons is inherently random, following a Poisson distribution. This randomness \n", - "means that the number of electrons in each pixel can vary, even if the same number of photons hits the CCD. Therefore, \n", - "the electron count per pixel becomes a Poisson random variable. For our simulation, this means that the recorded \n", - "number of photons in each pixel will differ slightly from the true number due to this randomness.\n", + "For this simulation, we describe the number of electrons collected in each\n", + "pixel using a Poisson distribution. Its mean is the expected electron count.\n", + "Drawing a value from this distribution gives one possible observed count,\n", + "which can be above or below that expectation.\n", "\n", - "To replicate this effect in our simulation, we can add Poisson noise to the tracer image using NumPy\u2019s random module, \n", - "which generates values from a Poisson distribution.\n", + "Our blurred image gives the expected electron rate in each pixel. Multiplying\n", + "it by an exposure time of 300 seconds gives the expected counts for that\n", + "exposure. We use these counts as the means of the Poisson distributions.\n", "\n", - "It's important to note that the blurring caused by the telescope optics occurs before the photons reach the CCD. \n", - "Therefore, we need to add the Poisson noise after blurring the tracer image.\n", + "The telescope spreads the light before the detector collects it, so we draw\n", + "the counts from the blurred image.\n", "\n", - "We also need to consider the units of our image data. Let\u2019s assume that the tracer image is measured in units of \n", - "electrons per second ($e^- s^{-1}$), which is standard for CCD imaging data. To simulate the number of electrons \n", - "actually detected in each pixel, we multiply the image by the observation\u2019s exposure time. This conversion changes\n", - "the units to the total number of electrons collected per pixel over the entire exposure time.\n", - "\n", - "Once the image is converted, we add Poisson noise, simulating the randomness in the photon-to-electron conversion \n", - "process. After adding the noise, we convert the image back to units of electrons per second for analysis, as \n", - "this is the preferred unit for astronomers when studying their data." + "Finally, we divide the randomly drawn counts by the exposure time to return\n", + "the image to electrons per second per pixel." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "exposure_time = 300.0 # Units of seconds\n", - "blurred_image_counts = (\n", - " blurred_image * exposure_time\n", - ") # Convert to total electrons detected over the exposure time.\n", + "exposure_time = 300.0 # Seconds.\n", + "\n", + "blurred_image_counts = blurred_image * exposure_time\n", + "\n", "blurred_image_with_poisson_noise = (\n", - " np.random.poisson(blurred_image_counts, blurred_image_counts.shape) / exposure_time\n", - ") # Add Poisson noise and convert back to electrons per second." + " np.random.poisson(blurred_image_counts, blurred_image_counts.shape)\n", + " / exposure_time\n", + ")" ], "outputs": [], "execution_count": null @@ -359,7 +380,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Here is what the blurred image with Poisson noise looks like." + "Let's plot the resulting image. It contains the same lensed structure as\n", + "before, with random fluctuations around the expected brightness in each pixel.\n", + "These fluctuations may be difficult to distinguish at this display scale." ] }, { @@ -367,7 +390,10 @@ "metadata": {}, "source": [ "aplt.plot_array(\n", - " array=aa.Array2D(values=blurred_image_with_poisson_noise, mask=blurred_image.mask),\n", + " array=aa.Array2D(\n", + " values=blurred_image_with_poisson_noise,\n", + " mask=blurred_image.mask,\n", + " ),\n", " title=\"Image With Poisson Noise\",\n", ")" ], @@ -378,13 +404,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "It is challenging to see the Poisson noise directly in the image above, as it is often subtle. To make the noise more \n", - "visible, we can subtract the blurred image without Poisson noise from the one with noise.\n", + "We can isolate the fluctuations by subtracting the expected blurred image from\n", + "the simulated observation.\n", + "\n", + "This difference is called a noise realisation: one particular outcome of the\n", + "random process. Positive values indicate pixels that collected more electrons\n", + "than expected; negative values indicate pixels that collected fewer.\n", "\n", - "This subtraction yields the \"Poisson noise realization\" which highlights the variation in each pixel due to the Poisson \n", - "distribution of photons hitting the CCD. It represents the noise values that were added to each pixel. We call\n", - "it the realization because it is one possible outcome of the Poisson process, and the noise will be different each time\n", - "we simulate the image." + "Rerunning the Poisson draw produces a different realisation. We can calculate\n", + "the exact difference here because we know the image used to generate the\n", + "simulation. For a real observation, that underlying image is unknown." ] }, { @@ -407,23 +436,19 @@ "source": [ "__Background Sky__\n", "\n", - "The final effect we will consider when simulating imaging data is the background sky.\n", - "\n", - "In addition to light from the strong lens, the telescope also picks up light from the sky. This background sky light is \n", - "primarily due to two sources: zodiacal light, which is light scattered by interplanetary dust in the solar system, \n", - "and the unresolved emission from distant stars and galaxies.\n", + "The telescope collects light from the surrounding sky as well as from the\n", + "strong lens. Sources of this background include sunlight scattered by dust\n", + "in the Solar System, known as zodiacal light, and unresolved distant objects.\n", "\n", - "For our simulation, we'll assume that the background sky has a uniform brightness across the image, measured at \n", - "0.1 electrons per second per pixel. The background sky is added to the image before applying the PSF convolution \n", - "and adding Poisson noise. This is important because it means that the background contributes additional noise to the \n", - "image.\n", + "We will represent the background as a uniform brightness of 0.1 electrons\n", + "per second per pixel. We add this to the blurred lensed image before drawing\n", + "the Poisson counts, so that both the source and sky contribute to the noise.\n", "\n", - "The background sky introduces noise throughout the entire image, including areas where the strong lens is not present. \n", - "This is why CCD images often appear noisy, especially in regions far from where the strong lens signal is detected. \n", - "The sky noise can make it more challenging to observe faint details of the lens and source galaxies.\n", + "A uniform background remains uniform when convolved with a normalised PSF,\n", + "so we can add it after blurring the lensed image.\n", "\n", - "To simulate this, we add a constant background sky to the tracer image and then apply Poisson noise to create the \n", - "final simulated image as it would appear through a telescope." + "Even where the source contributes very little light, sky photons are still\n", + "collected. Their fluctuating counts make faint features harder to distinguish." ] }, { @@ -432,33 +457,66 @@ "source": [ "background_sky_level = 0.1\n", "\n", - "# Add background sky to the blurred tracer image.\n", "blurred_image_with_sky = blurred_image + background_sky_level\n", "blurred_image_with_sky_counts = blurred_image_with_sky * exposure_time\n", "\n", - "# Apply Poisson noise to the image with the background sky.\n", "blurred_image_with_sky_poisson_noise = (\n", " np.random.poisson(\n", - " blurred_image_with_sky_counts, blurred_image_with_sky_counts.shape\n", + " blurred_image_with_sky_counts,\n", + " blurred_image_with_sky_counts.shape,\n", " )\n", " / exposure_time\n", - ")\n", - "\n", - "# Visualize the image with background sky and Poisson noise.\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This image includes the mean sky brightness as well as the random fluctuations\n", + "in the collected counts. Regions away from the lensed source therefore have\n", + "a background level around which their pixel values fluctuate." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ "aplt.plot_array(\n", " array=aa.Array2D(\n", - " values=blurred_image_with_sky_poisson_noise, mask=blurred_image.mask\n", + " values=blurred_image_with_sky_poisson_noise,\n", + " mask=blurred_image.mask,\n", " ),\n", " title=\"Image With Background Sky\",\n", - ")\n", - "\n", - "# Create a noise map showing the differences between the blurred image with and without noise.\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Subtracting the expected source-plus-sky image isolates the noise realisation.\n", + "Look for fluctuations even in regions where the lensed source is faint:\n", + "the background sky contributes noise there too." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ "poisson_noise_realization = (\n", " blurred_image_with_sky_poisson_noise - blurred_image_with_sky\n", ")\n", "\n", "aplt.plot_array(\n", - " array=aa.Array2D(values=poisson_noise_realization, mask=blurred_image.mask),\n", + " array=aa.Array2D(\n", + " values=poisson_noise_realization,\n", + " mask=blurred_image.mask,\n", + " ),\n", " title=\"Poisson Noise Realization\",\n", ")" ], @@ -471,8 +529,19 @@ "source": [ "__Simulator__\n", "\n", - "The `SimulatorImaging` object lets us create simulated imaging data while including the effects of PSF blurring, \n", - "Poisson noise, and background sky all at once:" + "We have now built up the observation one step at a time. The `SimulatorImaging`\n", + "object combines these steps: it blurs the lensed image with the PSF, adds the\n", + "background sky and draws the Poisson counts for the chosen exposure time.\n", + "\n", + "By default, it also subtracts the mean background sky level from the resulting\n", + "image. This represents an observation whose background has been removed during\n", + "data processing.\n", + "\n", + "Subtracting the mean sky level does not remove the random fluctuations caused\n", + "by sky photons. That noise remains in the image.\n", + "\n", + "The simulator returns an `Imaging` dataset containing the simulated image,\n", + "the PSF and a noise map. We will inspect each of these below." ] }, { @@ -495,9 +564,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "By plotting the `data` from the dataset, we can see that it matches the image we simulated earlier. It includes \n", - "the effects of PSF blurring, Poisson noise, and noise from the background sky. This image is a realistic \n", - "approximation of what a telescope like the Hubble Space Telescope would capture." + "The dataset's `data` contains the simulated observation, in electrons per\n", + "second per pixel.\n", + "\n", + "It shows the same lensed structure as our manual simulation, but uses a new\n", + "noise realisation and has the mean sky level subtracted. Pixels far from the\n", + "source should therefore fluctuate around zero. Some can be negative: after\n", + "sky subtraction, a pixel that collected fewer sky photons than expected can\n", + "have a negative value.\n", + "\n", + "These negative values do not represent negative light. They arise from\n", + "subtracting the estimated background from a noisy measurement." ] }, { @@ -513,11 +590,22 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The dataset also includes the `psf` (Point Spread Function) used to blur the strong lens image.\n", + "**🤖 Ask AI:** Why does subtracting the mean background sky from an astronomical\n", + "image leave the sky's Poisson noise behind?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The dataset also stores the PSF used to simulate the observation.\n", + "\n", + "For real observations, we need an estimate of the PSF, which can come from\n", + "stars in the image or a model of the instrument.\n", "\n", - "For actual telescope data, the PSF is determined during data processing and is provided along with the observations. \n", - "It's crucial for accurately deconvolving the PSF from the strong lens image, allowing us to recover the true properties \n", - "of the strong lens. We'll explore this further in the next tutorial." + "When comparing a lens model with the data, we blur its predicted image using\n", + "this PSF. This lets us compare the model and observation at the same resolution.\n", + "The next tutorial will show this comparison in practice." ] }, { @@ -533,16 +621,29 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The dataset includes a `noise_map`, which represents the Root Mean Square (RMS) standard deviation of the noise \n", - "estimated for each pixel in the image. Higher noise values mean that the measurements in those pixels are \n", - "less certain, so those pixels are given less weight when analyzing the data.\n", + "The `noise_map` gives an estimated standard deviation for each pixel, in the\n", + "same units as the data. It describes the typical size of the random\n", + "fluctuations expected in that pixel.\n", + "\n", + "This is different from the noise realisation we plotted earlier. A realisation\n", + "records the particular positive or negative fluctuation drawn for each pixel;\n", + "the noise map describes the scale of those fluctuations.\n", "\n", - "This `noise_map` is different from the Poisson noise arrays we plotted earlier. The Poisson noise arrays show the \n", - "actual noise added to the image due to the random nature of photon-to-electron conversion on the CCD, as calculated \n", - "using the numpy random module. These noise values are theoretical and cannot be directly measured in real telescope data.\n", + "For Poisson counts, the standard deviation is the square root of the expected\n", + "number of counts. The simulator estimates this using the simulated counts\n", + "before sky subtraction, then divides by the exposure time to return to\n", + "electrons per second per pixel.\n", "\n", - "In contrast, the `noise_map` is our best estimate of the noise present in the image, derived from the data itself \n", - "and used in the fitting process." + "The noise map therefore includes contributions from both the source and sky,\n", + "even though the mean sky level has been removed from the data.\n", + "\n", + "Look for larger noise values in the bright arcs, where more photons are\n", + "collected, and a background noise level elsewhere. More collected photons\n", + "produce larger absolute count fluctuations, but smaller fluctuations relative\n", + "to their mean.\n", + "\n", + "In the next tutorial, the noise map will set the scale against which we judge\n", + "differences between the model image and the data." ] }, { @@ -558,22 +659,31 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The `signal-to-noise_map` shows the ratio of the signal in each pixel to the noise level in that pixel. It is \n", - "calculated by dividing the `data` by the `noise_map`.\n", + "The `signal_to_noise_map` compares each pixel's measured brightness with its\n", + "estimated noise level. It is calculated by dividing `data` by `noise_map`,\n", + "giving a dimensionless ratio.\n", + "\n", + "For example, a value of 5 means that the pixel's measured brightness is five\n", + "times its estimated noise standard deviation. Look for high values along the\n", + "bright arcs and lower values where the source is faint.\n", "\n", - "This ratio helps us understand how much of the observed signal is reliable compared to the noise, allowing us to \n", - "see where we can trust the detected signal from the strong lens and where the noise is more significant.\n", + "PyAutoLens sets negative ratios to zero in this map. The negative values in\n", + "the background-subtracted data are still present in `dataset.data`; this\n", + "operation only affects the signal-to-noise map.\n", "\n", - "In general, a signal-to-noise ratio greater than 3 indicates that the signal is likely real and not overwhelmed by \n", - "noise. For our datasets, the signal-to-noise ratio peaks at ~70, meaning we can trust the signal detected in the\n", - "image." + "A high value indicates that a pixel stands out relative to its estimated\n", + "noise. A single threshold does not, by itself, establish that a feature is\n", + "real: its spatial structure and the properties of the noise also matter." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "aplt.plot_array(array=dataset.signal_to_noise_map, title=\"Signal-To-Noise Map\")" + "aplt.plot_array(\n", + " array=dataset.signal_to_noise_map,\n", + " title=\"Signal-To-Noise Map\",\n", + ")" ], "outputs": [], "execution_count": null @@ -582,13 +692,18 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The `aplt.subplot_imaging_dataset` object can display all of these components together, making it a powerful tool for visualizing \n", - "simulated imaging data.\n", + "We can display the dataset's main components together using\n", + "`aplt.subplot_imaging_dataset`.\n", + "\n", + "Compare the data, noise map and signal-to-noise map. The bright arcs have\n", + "larger absolute noise than the faint background, but they also have a stronger\n", + "signal relative to that noise.\n", "\n", - "It also shows the Data and PSF on a logarithmic (log10) scale, which helps highlight the faint details in these \n", - "components.\n", + "The figure includes logarithmic views of the data and PSF to help show faint\n", + "structure. These change how the values are displayed, not the underlying data.\n", "\n", - "The \"Over Sampling\" plots on the bottom of the figures display advanced features that can be ignored for now." + "Any panels labelled \"Over Sample Size\" describe how finely the model is\n", + "evaluated within pixels. We can leave these numerical settings aside here." ] }, { @@ -606,13 +721,21 @@ "source": [ "__Output__\n", "\n", - "We will now save these simulated data to `.fits` files, the standard format used by astronomers for storing images.\n", - "Most imaging data from telescopes like the Hubble Space Telescope (HST) are stored in this format.\n", + "We will save the simulated imaging dataset in FITS format, which is widely\n", + "used in astronomy for images and related data.\n", + "\n", + "The files contain:\n", + "\n", + "- `data.fits`: the simulated image after subtraction of the mean sky level.\n", + "- `noise_map.fits`: the estimated noise standard deviation in each pixel.\n", + "- `psf.fits`: the PSF kernel used to blur the image.\n", "\n", - "The `dataset_path` specifies where the data will be saved, in this case the `dataset/imaging/howtolens/`\n", - "directory of the HowToLens repository (paths are relative to the repository root, from which scripts are run).\n", + "They are written to `dataset/imaging/howtolens/`, relative to the repository\n", + "root from which this script is run. The next tutorial will load these files\n", + "and compare the data with a lens model.\n", "\n", - "The files are named `data.fits`, `noise_map.fits`, and `psf.fits`, and will be used in the next tutorial." + "With `overwrite=True`, rerunning this cell replaces any existing files with\n", + "these names." ] }, { @@ -639,14 +762,24 @@ "source": [ "__Point Source Data__\n", "\n", - "In Tutorial 4, we predicted the positions of a point source's multiple images. For real observations, we measure\n", - "these positions from the telescope image, accounting for its blurring and the foreground galaxy's light. Each\n", - "position also has an uncertainty.\n", + "In Tutorial 4, we predicted the positions of a point source's multiple images.\n", + "For an observed lens, we can measure these positions from the telescope image,\n", + "accounting for the PSF and light from the foreground galaxy. Each measured\n", + "position has an uncertainty.\n", "\n", - "A `PointDataset` collects these measurements for lens modelling. The illustrative values below are rounded from\n", - "Tutorial 4's predictions, rather than measured from observations. We include positions in arcseconds, fluxes in\n", - "arbitrary units and time delays in days relative to the first image, with assumed uncertainties of 0.01 arcseconds,\n", - "about 10 per cent in flux and one day in delay." + "A `PointDataset` stores these measurements for analysis. It can also\n", + "include the images' fluxes and, for a variable source, the time delays between\n", + "them. Time delays are measured by monitoring how the source's variations\n", + "appear at different times in its multiple images.\n", + "\n", + "The example below uses values rounded from Tutorial 4's predictions, with\n", + "assumed measurement uncertainties. These are illustrative data, not\n", + "measurements from a real observation.\n", + "\n", + "Positions are in arcseconds, fluxes are in arbitrary units and time delays\n", + "are in days relative to the first image. We assume positional uncertainties\n", + "of 0.01 arcseconds, flux uncertainties of about 10 per cent and time-delay\n", + "uncertainties of one day." ] }, { @@ -677,39 +810,71 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The positions use `(y, x)` coordinates, and every list follows the same image order. Negative delays mean that\n", - "an image arrives before the first image. The name `point_0` matches the point-source component introduced in\n", - "Tutorial 4, connecting these measurements to that source when fitting a model.\n", + "We can also display the point-source dataset as a subplot. The positions panel\n", + "shows where the multiple images lie, while the flux panel compares their\n", + "brightnesses. The time delays remain available in the printed summary." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "aplt.subplot_point_dataset(dataset=point_dataset)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Inspect the printed dataset summary. Positions use `(y, x)` coordinates, and\n", + "the position, flux and time-delay lists all follow the same image order.\n", + "\n", + "The first image defines the zero of the time delays. A negative delay means\n", + "that the corresponding image arrives before this reference image. The zero\n", + "entry is a reference choice, not an independently measured delay.\n", "\n", - "Fluxes and time delays are optional: positions alone are enough to begin modelling. For more on loading and\n", - "fitting these datasets, continue to the workspace's\n", - "[point-source examples](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/point_source/start_here.py).\n", + "The name `point_0` identifies the source associated with these measurements,\n", + "matching the point-source component introduced in Tutorial 4.\n", "\n", + "Fluxes and time delays are optional: a dataset can contain only positions\n", + "and their uncertainties. For further examples of working with these data,\n", + "see the workspace's\n", + "[point-source examples](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/point_source/start_here.py)." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ "__Interferometer Data__\n", "\n", - "CCD imaging is not the only type of data used to study strong lenses. Radio and sub-mm interferometers, like the\n", - "Atacama Large Millimeter Array (ALMA) and the Jansky Very Large Array (JVLA), observe strong lenses at wavelengths\n", - "where a CCD cannot.\n", + "We can also observe strong lenses at radio and submillimetre wavelengths using\n", + "interferometers, such as the Atacama Large Millimeter/submillimeter Array\n", + "(ALMA) and the Jansky Very Large Array (JVLA).\n", + "\n", + "An interferometer combines signals from pairs of antennas. Each pair measures\n", + "a quantity called a visibility, which contains information about the sky's\n", + "brightness on a particular angular scale and orientation.\n", "\n", - "An interferometer does not observe an image of the lens. Each pair of antennas in the array measures a \"visibility\",\n", - "a Fourier component of the sky brightness, at a point in what is called the \"uv-plane\" set by the separation of the\n", - "two antennas. The dataset is therefore a set of complex visibilities in Fourier space, not a 2D image, and its\n", - "noise properties are very different from those of CCD data \u2014 there is no PSF convolution, Poisson noise or\n", - "background sky; instead each visibility has Gaussian noise.\n", + "Visibilities are complex numbers, with real and imaginary components. They\n", + "sample the Fourier transform of the sky brightness at coordinates in the\n", + "\"uv-plane\". These coordinates depend on the antennas' projected separation\n", + "and the observing wavelength.\n", "\n", - "One could Fourier transform the visibilities into an image (called a \"dirty image\") and fit that, but the transform\n", - "correlates the noise between pixels, making the fit statistically incorrect. **PyAutoLens** therefore fits lens\n", - "models directly in visibility space: the tracer's image is evaluated in real space on a grid (defined by a\n", - "real-space mask), Fourier transformed to the uv-plane and compared with the observed visibilities there.\n", + "An interferometer dataset therefore contains visibilities, their uncertainties\n", + "and their uv coordinates. In our simulated example, the noise in the real and\n", + "imaginary components is described by Gaussian distributions.\n", "\n", - "Below, we load a simulated interferometer dataset (creating it first via the `scripts/simulator/interferometer.py`\n", - "script if it does not exist on your hard-disk, using the same auto-simulation idiom as later tutorials) and plot\n", - "its dirty images \u2014 the closest an interferometer dataset comes to the CCD images we simulated above.\n", + "We can transform the sampled visibilities into a picture called a \"dirty\n", + "image\". Incomplete sampling produces an instrumental response called the\n", + "\"dirty beam\", which can introduce structure around bright emission. The\n", + "transformation also correlates the noise between image pixels.\n", "\n", - "HowToLens will not cover interferometry any further than this. The lecture series teaches lensing using CCD\n", - "imaging, and everything you learn transfers to visibility-space fitting. If you need to model interferometer data,\n", - "go to the `autolens_workspace/scripts/interferometer` package, which is the dedicated resource for uv-plane lens\n", - "modeling." + "Below, we load a simulated dataset, creating it first if needed, and display\n", + "its dirty-image diagnostics. The circular real-space mask defines the region\n", + "of sky used for these images." ] }, { @@ -746,28 +911,43 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Look for the lensed emission in the dirty image. Its appearance reflects both\n", + "the sky brightness and the interferometer's sampling, so surrounding structure\n", + "need not correspond to additional emission on the sky.\n", + "\n", + "The dataset retains the visibilities for analysis. For further examples of\n", + "working with these data, see the workspace's\n", + "[interferometer examples](https://github.com/PyAutoLabs/autolens_workspace/tree/main/scripts/interferometer)." + ] + }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Weak Lensing Data__\n", "\n", - "There is one more type of lensing data to glimpse before we move on: weak lensing.\n", + "Away from the prominent arcs and rings, gravitational lensing can produce\n", + "small, coherent changes in the apparent shapes of background galaxies. This\n", + "is the weak-lensing regime.\n", "\n", - "A weak lensing dataset looks nothing like the images above. Instead of the spectacular arcs and rings of strong\n", - "lensing, it is a *catalogue* of many background galaxies, each with a measured ellipticity \u2014 a shear \u2014 at its\n", - "(y, x) position on the sky. Each galaxy is only weakly sheared by the foreground mass, a distortion far too small\n", - "to see in any single galaxy, and the plot below shows this: a field of short line segments tracing the subtle,\n", - "coherent stretching of the background galaxy population, rather than any arc-like feature.\n", + "Galaxies already have different shapes and orientations before they are\n", + "lensed. An individual galaxy's measured ellipticity therefore does not tell\n", + "us the lensing distortion on its own. We use measurements from many galaxies\n", + "to identify the shared distortion, called shear.\n", "\n", - "We load a simulated weak lensing shear catalogue (again auto-simulating it, via `scripts/simulator/weak_lensing.py`,\n", - "if it is not on your hard-disk) and plot it, just so you have seen what this data looks like.\n", + "For analysis, these measurements can be collected into a catalogue containing\n", + "sky positions, estimates of the two shear components and their uncertainties.\n", "\n", - "That is deliberately all we will say for now \u2014 this glimpse is foreshadowing. Weak lensing gets a full treatment in\n", - "the final tutorial of chapter 4, which describes what these shear measurements are, why they are made far from the\n", - "lens centre and how they are fitted; until then, we defer all further description to that tutorial. For worked\n", - "modelling examples, see the workspace\n", - "[weak-lensing examples](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/start_here.py)." + "The simulated example below evaluates the shear around a cluster-scale lens\n", + "and adds random scatter to represent the variation in galaxies' intrinsic\n", + "shapes. It creates a noisy shear catalogue directly, rather than measuring\n", + "galaxy shapes from simulated telescope images.\n", + "\n", + "We load this catalogue, creating it first if needed, and plot its contents." ] }, { @@ -796,29 +976,135 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Wrap Up__\n", + "The short line segments represent the orientations and strengths of the noisy\n", + "shear estimates at the background galaxies' positions. Individual segments\n", + "can differ substantially from the underlying lensing pattern because of the\n", + "added shape noise.\n", "\n", - "In this tutorial, you learned how CCD imaging data of a lens is collected using real telescopes like the \n", - "Hubble Space Telescope, and how to simulate this data using the `SimulatorImaging` object.\n", + "Chapter 4 returns to weak lensing in more detail. For further examples of\n", + "working with these data, see the workspace's\n", + "[weak-lensing examples](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/start_here.py)." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Group and Cluster Lenses__\n", + "\n", + "Strong lensing also occurs around groups and clusters of galaxies. Their\n", + "member galaxies and shared dark matter contribute to the deflection of light,\n", + "producing lens systems that can extend over much larger angles on the sky.\n", "\n", - "Let's summarise what we've covered:\n", + "We will study these objects in Chapter 4. For now, let's look at the simulated\n", + "imaging datasets used in its group-scale and cluster-scale tutorials. As above,\n", + "each dataset is created if needed and displayed with its imaging subplot.\n", + "\n", + "The group example contains a central galaxy and two member galaxies, together\n", + "with a lensed background source. Compare the angular scale of its arcs with\n", + "our earlier galaxy-scale example." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "group_dataset_path = Path(\"dataset\") / \"group\" / \"simple\"\n", + "\n", + "if al.util.dataset.should_simulate(str(group_dataset_path)):\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.run(\n", + " [sys.executable, \"scripts/simulator/group.py\"],\n", + " check=True,\n", + " )\n", + "\n", + "group_dataset = al.Imaging.from_fits(\n", + " data_path=group_dataset_path / \"data.fits\",\n", + " noise_map_path=group_dataset_path / \"noise_map.fits\",\n", + " psf_path=group_dataset_path / \"psf.fits\",\n", + " pixel_scales=0.1,\n", + ")\n", + "\n", + "aplt.subplot_imaging_dataset(dataset=group_dataset, title_prefix=\"Group Lens\")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The cluster example contains more member galaxies, a cluster-scale dark matter\n", + "halo and two background sources at different redshifts. Look for the member\n", + "galaxies and lensed features across its wider field. Use the coordinate axes\n", + "to compare angular sizes, since the figures are displayed at similar sizes\n", + "on the page.\n", + "\n", + "Chapter 4's group-scale and cluster-scale tutorials return to these same\n", + "simulated systems and explain how to analyse them." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cluster_dataset_path = Path(\"dataset\") / \"cluster\" / \"simple\"\n", + "\n", + "if al.util.dataset.should_simulate(str(cluster_dataset_path)):\n", + " import os\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.run(\n", + " [sys.executable, \"scripts/simulator/cluster.py\"],\n", + " check=True,\n", + " # The tutorial plots the dataset below; skip the simulator's extra figures.\n", + " env={**os.environ, \"PYAUTO_FAST_PLOTS\": \"1\"},\n", + " )\n", + "\n", + "cluster_dataset = al.Imaging.from_fits(\n", + " data_path=cluster_dataset_path / \"data.fits\",\n", + " noise_map_path=cluster_dataset_path / \"noise_map.fits\",\n", + " psf_path=cluster_dataset_path / \"psf.fits\",\n", + " pixel_scales=0.2,\n", + ")\n", + "\n", + "aplt.subplot_imaging_dataset(dataset=cluster_dataset, title_prefix=\"Cluster Lens\")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Wrap Up__\n", "\n", - "- **Optics Blurring**: The optics of a telescope blur the light of the tracer, reducing the clarity and sharpness of\n", - "the images.\n", + "We began with a lensed image and turned it into a simulated telescope\n", + "observation. Along the way, we introduced:\n", "\n", - "- **Poisson Noise**: The process of converting photons to electrons on a CCD introduces Poisson noise, which is random \n", - "variability in the number of electrons collected in each pixel.\n", + "- **PSF blurring:** The telescope spreads light over neighbouring pixels.\n", + "- **Poisson noise:** The detected counts fluctuate around their expected values.\n", + "- **Background sky:** Sky photons contribute both a background level and noise.\n", + " Subtracting the mean background leaves its noise behind.\n", + "- **Imaging datasets:** The `SimulatorImaging` object returns the data, PSF and\n", + " noise map, which we saved to FITS files.\n", "\n", - "- **Background Sky**: Light from the sky is captured along with light from the lens, adding a layer of noise across \n", - "the entire image.\n", + "We also saw how other observations are represented for analysis:\n", "\n", - "- **Simulator**: The `SimulatorImaging` object enables us to simulate realistic imaging data by including all of \n", - "these effects together and contains the `data`, `psf`, and `noise_map` components.\n", + "- **Point sources:** Image positions and their uncertainties, with optional\n", + " fluxes and time delays.\n", + "- **Interferometry:** Complex visibilities, their uncertainties and uv coordinates.\n", + "- **Weak lensing:** A catalogue of positions, shear estimates and uncertainties.\n", "\n", - "- **Output**: We saved the simulated data to `.fits` files, the standard format used by astronomers for storing images.\n", + "Finally, we previewed the group-scale and cluster-scale lenses studied in\n", + "Chapter 4, displaying their imaging datasets alongside the galaxy-scale example.\n", "\n", - "- **Point Source Data**: A `PointDataset` collects image positions and their uncertainties, with optional fluxes\n", - "and time delays, ready for point-source modelling." + "The next tutorial returns to our simulated imaging dataset and examines how\n", + "to compare a predicted image with the data, taking account of the PSF and\n", + "noise map." ] } ], @@ -846,7 +1132,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_1_introduction/tutorial_5_data.ipynb in HowToLens).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoLens calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoLens docs (https://pyautolens.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` \u2014 image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* \u2014 pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* \u2014 if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual \u2014 what convergence is, why caustics matter, what\na critical curve traces \u2014 see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions \u2014\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch \u2014 quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch \u2014 single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly \u2014 build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch \u2014 multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI \u2014 extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) \u2014 multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) \u2014 for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot \u2014 how light deflects, how critical curves and\n caustics arise.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action \u2014 building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` \u2014 ray tracing, profiles, numpy\n arrays, visualization.\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth \u2014 or build a\ntraining set for neural-network classifiers \u2014 you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating \u2014 single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* \u2014 chooses the branch.\n- *\"What's the ground truth?\"* \u2014 lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* \u2014 pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch \u2014 galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid \u2014 defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer \u2014 lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_fits(\n data_path=dataset_path / \"data.fits\",\n noise_map_path=dataset_path / \"noise_map.fits\",\n psf_path=dataset_path / \"psf.fits\",\n overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot \u2014 saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` \u2014 `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch \u2014 many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch \u2014 interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n \u2192 [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour \u2014 see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates \u2014 the forward physics\n the simulator runs.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice \u2014 grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_1_introduction/tutorial_5_data.ipynb in HowToLens).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoLens calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoLens docs (https://pyautolens.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` — image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* — pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* — if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual — what convergence is, why caustics matter, what\na critical curve traces — see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions —\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch — quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch — single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly — build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch — multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI — extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) — multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) — for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot — how light deflects, how critical curves and\n caustics arise.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action — building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** — [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` — ray tracing, profiles, numpy\n arrays, visualization.\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth — or build a\ntraining set for neural-network classifiers — you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating — single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* — chooses the branch.\n- *\"What's the ground truth?\"* — lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* — pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch — galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid — defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer — lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_fits(\n data_path=dataset_path / \"data.fits\",\n noise_map_path=dataset_path / \"noise_map.fits\",\n psf_path=dataset_path / \"psf.fits\",\n overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot — saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` — `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch — many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch — interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n → [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour — see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates — the forward physics\n the simulator runs.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice — grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" @@ -854,4 +1140,4 @@ }, "nbformat": 4, "nbformat_minor": 4 -} \ No newline at end of file +} diff --git a/notebooks/chapter_1_introduction/tutorial_6_fitting.ipynb b/notebooks/chapter_1_introduction/tutorial_6_fitting.ipynb index 2906bcc..6564ed2 100644 --- a/notebooks/chapter_1_introduction/tutorial_6_fitting.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_6_fitting.ipynb @@ -7,45 +7,38 @@ "Tutorial 6: Fitting\n", "===================\n", "\n", - "In previous tutorials, we used light profiles to create simulated images of a tracer and visualized how these images\n", - "would appear when captured by a CCD detector on a telescope like the Hubble Space Telescope.\n", - "\n", - "However, this simulation process is the reverse of what astronomers typically do when analyzing real data. Usually,\n", - "astronomers start with an observation\u2014an actual image of a strong lens - and aim to infer detailed information about the\n", - "lens\u2019s properties, such as its mass and unlensed source properties.\n", - "\n", - "To achieve this, we must fit the observed image data with a model, identifying the combination of light and mass\n", - "profiles that best matches the lens's appearance in the image. In this tutorial, we'll illustrate this process using\n", - "the imaging data simulated in the previous tutorial. Our goal is to demonstrate how we can recover the parameters of\n", - "the light profiles that we used to create the original simulation, as a proof of concept for the fitting procedure.\n", - "\n", - "The process of fitting data introduces essential statistical concepts like the `model`, `residual_map`, `chi-squared`,\n", - "`likelihood`, and `noise_map`. These terms are crucial for understanding how fitting works, not only in astronomy but\n", - "also in any scientific field that involves data modeling. This tutorial will provide a detailed introduction to these\n", - "concepts and show how they are applied in practice to analyze astronomical data.\n", - "\n", - "Here is an overview of what we'll cover in this tutorial:\n", - "\n", - "- **Dataset**: Load the imaging dataset that we previously simulated, consisting of the image, noise map, and PSF.\n", - "- **Mask**: Apply a mask to the data, excluding regions with low signal-to-noise ratios from the analysis.\n", - "- **Masked Grid**: Create a masked grid, which contains only the coordinates of unmasked pixels, to evaluate the\n", - " galaxy's light profile in only unmasked regions.\n", - "- **Fitting**: Fit the data with a galaxy model, computing key quantities like the model image, residuals,\n", - " chi-squared, and log likelihood to assess the quality of the fit.\n", - "- **Bad Fits**: Demonstrate how even small deviations from the true parameters can significantly impact the fit.\n", - "- **Model Fitting**: Perform a basic model fit on a simple dataset, adjusting the model parameters to improve the\n", - " fit quality.\n", + "In the previous tutorial, we chose a lens and source, predicted their lensed\n", + "image and simulated a telescope observation. We will now work in the other\n", + "direction: starting with an image, we want to learn about the objects that\n", + "produced it.\n", + "\n", + "A lens model is a mathematical description of the lens and source. Its\n", + "parameters specify properties such as the lens's mass distribution and the\n", + "source's position, size and brightness.\n", + "\n", + "To assess a model, we calculate the image it predicts and compare that\n", + "prediction with the data. We account for the telescope's blurring and the\n", + "uncertainty in each pixel, so that differences are judged relative to the\n", + "noise.\n", + "\n", + "We will first evaluate a model using the parameters that generated our\n", + "simulated data. We will then change those parameters and inspect how the\n", + "agreement changes. Finally, you will try adjusting parameters yourself.\n", + "\n", + "This introduces model fitting: finding parameter values that describe the\n", + "data well. Creating a `FitImaging` object evaluates the parameters we supply;\n", + "it does not search for new values automatically.\n", "\n", "__Contents__\n", "\n", - "- **Dataset:** Load the imaging dataset that we previously simulated, consisting of the image, noise map, and PSF.\n", - "- **Dataset Auto-Simulation:** Create the dataset by running the tutorial 5 script if it is not on your hard-disk.\n", - "- **Mask:** Apply a mask to the data, excluding regions with low signal-to-noise ratios from the analysis.\n", - "- **Masked Grid:** In tutorials 1 and 2, we emphasized that the `Grid2D` object is crucial for evaluating a lens's.\n", - "- **Fitting:** Fit the lens model to the dataset and inspect the results.\n", - "- **Incorrect Fit:** In the previous section, we successfully created and fitted a lens model to the image data.\n", - "- **Model Fitting:** In the previous sections, we used the true model to fit the data, which resulted in a high log.\n", - "- **Wrap Up:** Summary of the script and next steps." + "- **Dataset:** Locate the imaging data saved in Tutorial 5.\n", + "- **Dataset Auto-Simulation:** Create the dataset if needed, then load it.\n", + "- **Mask:** Select the region of the image used in the comparison.\n", + "- **Masked Grid:** Inspect the coordinates of the selected pixels.\n", + "- **Fitting:** Compare a predicted image with the data and calculate fit statistics.\n", + "- **Incorrect Fit:** See how changing the source position affects the comparison.\n", + "- **Model Fitting:** Experiment with adjusting parameters yourself.\n", + "- **Likelihood Function:** Combine the calculation into a function of the model parameters." ] }, { @@ -109,14 +102,11 @@ "source": [ "__Dataset__\n", "\n", - "We begin by loading the imaging dataset that we will use for fitting in this tutorial. This dataset is identical to the \n", - "one we simulated in the previous tutorial, representing how a lens would appear if captured by a CCD camera.\n", + "We will use the simulated imaging dataset saved in Tutorial 5. It contains\n", + "the background-subtracted image, its noise map and the PSF.\n", "\n", - "In the previous tutorial, we saved this dataset as .fits files in the `dataset/imaging/howtolens` folder of the\n", - "HowToLens repository. The `.fits` format is commonly used in astronomy for storing image data along with metadata,\n", - "making it a standard for CCD imaging.\n", - "\n", - "The `dataset_path` below specifies where these files are located: `dataset/imaging/howtolens/`." + "The files are in `dataset/imaging/howtolens/`, relative to the repository root\n", + "from which this script is run." ] }, { @@ -134,9 +124,10 @@ "source": [ "__Dataset Auto-Simulation__\n", "\n", - "The `howtolens` dataset is the one built up and saved in tutorial 5 (`tutorial_5_data.py`). If it does\n", - "not already exist on your system, it is created by running that script. This ensures every example\n", - "script can be run without manually simulating data first." + "If the dataset is missing, the following code runs Tutorial 5 to create it.\n", + "If you have already run that tutorial, we load the saved files.\n", + "\n", + "The pixel scale is 0.1 arcseconds, matching the simulation." ] }, { @@ -166,18 +157,18 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The `Imaging` object contains three key components: `data`, `noise_map`, and `psf`:\n", + "Recall the three components of an imaging dataset:\n", "\n", - "- `data`: The actual image of the lens, which we will analyze.\n", + "- `data`: the measured brightness in each pixel.\n", + "- `noise_map`: the estimated noise standard deviation in each pixel.\n", + "- `psf`: the kernel describing how the telescope spreads light.\n", "\n", - "- `noise_map`: A map indicating the uncertainty or noise level in each pixel of the image, reflecting how much the \n", - " observed signal in each pixel might fluctuate due to instrumental or background noise.\n", - " \n", - "- `psf`: The Point Spread Function, which describes how a point source of light is spread out in the image by the \n", - " telescope's optics. It characterizes the blurring effect introduced by the instrument.\n", + "The data and noise map have the same units. The PSF kernel is normalised\n", + "to sum to one.\n", "\n", - "Let's print some values from these components and plot a summary of the dataset to refresh our understanding of the \n", - "imaging data." + "Below, we print the first value in each array and display the dataset.\n", + "The first image pixel and first noise-map pixel refer to the same sky\n", + "position; the first PSF value belongs to the separate, smaller kernel." ] }, { @@ -202,20 +193,20 @@ "source": [ "__Mask__\n", "\n", - "The signal-to-noise map of the image highlights areas where the signal (light from the lens and source galaxies)\n", - "is detected above the background noise. Values above 3.0 indicate regions where the light is detected with a \n", - "signal-to-noise ratio of at least 3, while values below 3.0 are dominated by noise, where the light is not \n", - "clearly distinguishable.\n", + "A mask selects which pixels we include when comparing the model with the data.\n", + "It can exclude unrelated objects, detector defects or regions outside the\n", + "area we want to analyse.\n", "\n", - "To ensure the fitting process focuses only on meaningful data, we typically mask out regions with low signal-to-noise \n", - "ratios, removing areas dominated by noise from the analysis. This allows the fitting process to concentrate on the \n", - "regions where the lens is clearly detected.\n", + "For this example, we keep a circular region with a radius of 3 arcseconds,\n", + "centred on the lens. This includes the lensed arcs and some surrounding sky.\n", "\n", - "Here, we create a `Mask2D` to exclude certain regions of the image from the analysis. The mask defines which parts of \n", - "the image will be used during the fitting process.\n", + "We do not select individual pixels according to their measured\n", + "signal-to-noise ratio. Faint pixels still contain useful information: a model\n", + "that predicts bright emission where little is observed should disagree with\n", + "those data. The noise map determines how strongly each pixel contributes to\n", + "the comparison.\n", "\n", - "For our simulated image, a circular 3\" mask centered at the center of the image is appropriate, since the simulated \n", - "lens was positioned at the center." + "In a `Mask2D`, `True` means excluded and `False` means included." ] }, { @@ -225,12 +216,12 @@ "mask = al.Mask2D.circular(\n", " shape_native=dataset.shape_native,\n", " pixel_scales=dataset.pixel_scales,\n", - " radius=3.0, # The circular mask's radius in arc-seconds\n", - " centre=(0.0, 0.0), # center of the image which is also the center of the lens\n", + " radius=3.0, # Arcseconds.\n", + " centre=(0.0, 0.0),\n", ")\n", "\n", - "print(mask) # 1 = True, meaning the pixel is masked. Edge pixels are indeed masked.\n", - "print(mask[48:53, 48:53]) # Central pixels are `False` and therefore unmasked." + "print(mask)\n", + "print(mask[48:53, 48:53])" ], "outputs": [], "execution_count": null @@ -239,20 +230,23 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can visualize the mask over the strong lens image using an `aplt.subplot_imaging_dataset`, which helps us adjust the mask as needed. \n", - "This is useful to ensure that the mask appropriately covers the lens and source light and does not exclude important \n", - "regions.\n", + "Before applying the mask, let's display its boundary over the full image.\n", + "The boundary marks the edge of the region we will include in the comparison.\n", "\n", - "To overlay objects like a mask onto a figure, we use the `lines=`/`positions=` overlays object. This tool allows us to add custom \n", - "visuals to any plot, providing flexibility in creating tailored visual representations." + "Check that the lensed arcs lie inside it and that some surrounding sky is\n", + "included. At this stage, we are only displaying the boundary; the dataset\n", + "has not yet been masked." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "\n", - "aplt.plot_array(array=dataset.data, title=\"Imaging Data With Mask\")" + "aplt.plot_array(\n", + " array=dataset.data,\n", + " mask=mask.derive_grid.edge,\n", + " title=\"Imaging Data With Mask Boundary\",\n", + ")" ], "outputs": [], "execution_count": null @@ -261,8 +255,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Once we are satisfied with the mask, we apply it to the imaging data using the `apply_mask()` method. This ensures \n", - "that only the unmasked regions are considered during the analysis." + "We now apply the mask to the dataset. Pixels outside the circular region\n", + "will be excluded when we compare the model with the data." ] }, { @@ -278,10 +272,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "When we plot the masked imaging data again, the mask is now automatically included in the plot, even though we did \n", - "not explicitly pass it using the `lines=`/`positions=` overlays object. The plot also zooms into the unmasked area, showing only the \n", - "region where we will focus our analysis. This is particularly helpful when working with large images, as it centers \n", - "the view on the regions where the strong lens's signal is detected." + "The plotted image now shows the selected region, with the view zoomed to\n", + "the unmasked area. The plotting function obtains the mask boundary from\n", + "the array itself." ] }, { @@ -297,8 +290,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The mask is now stored as an additional attribute of the `Imaging` object, meaning it remains attached to the \n", - "dataset. This makes it readily available when we pass the dataset to a `FitImaging` object for the fitting process." + "The mask is stored with the dataset, so later calculations can identify\n", + "which pixels to include." ] }, { @@ -315,31 +308,30 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "In earlier tutorials, we discussed how grids and arrays have `native` and `slim` representations:\n", - "\n", - "- `native`: Represents the original 2D shape of the data, maintaining the full pixel array of the image.\n", - "- `slim`: Represents a 1D array containing only the values from unmasked pixels, allowing for more efficient \n", - " processing when working with large images.\n", + "The masked data retain the `native` and `slim` representations introduced\n", + "earlier:\n", "\n", - "After applying the mask, the `native` and `slim` representations change as follows:\n", + "- `native` arranges the values in the original 2D image shape. Masked pixels\n", + " are filled with zeros.\n", + "- `slim` contains only the unmasked pixel values in a 1D array.\n", "\n", - "- `native`: The 2D array keeps its original shape, [total_y_pixels, total_x_pixels], but masked pixels (those where \n", - " the mask is True) are set to 0.0.\n", - "- `slim`: This now only contains the unmasked pixel values, reducing the array size \n", - " from [total_y_pixels * total_x_pixels] to just the number of unmasked pixels.\n", + "Those zeros in the native representation are placeholders. They do not mean\n", + "that zero light was measured outside the mask, and they do not contribute\n", + "to the comparison with the model.\n", "\n", - "Let's verify this by checking the shape of the data in its `slim` representation." + "Our original image has 101 x 101 pixels. The slim array is shorter because\n", + "we have selected only the circular region." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(\"Number of unmasked pixels:\")\n", + "print(\"Native image shape:\")\n", "print(dataset.data.native.shape)\n", - "print(\n", - " dataset.data.slim.shape\n", - ") # This should be lower than the total number of pixels, e.g., 100 x 100 = 10,000" + "\n", + "print(\"Slim image shape:\")\n", + "print(dataset.data.slim.shape)" ], "outputs": [], "execution_count": null @@ -348,15 +340,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The `mask` object also has a `pixels_in_mask` attribute, which gives the number of unmasked pixels. This should \n", - "match the size of the `slim` data structure." + "Despite its name, `pixels_in_mask` counts the unmasked pixels: those included\n", + "in the analysis. This number should match the length of the slim array." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(dataset.data.mask.pixels_in_mask)" + "print(\"Number of unmasked pixels:\")\n", + "print(dataset.mask.pixels_in_mask)" ], "outputs": [], "execution_count": null @@ -365,7 +358,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can use the `slim` attribute to print the first unmasked values from the image and noise map:" + "The image and noise map share the same mask and pixel ordering. Their first\n", + "slim entries therefore describe the measurement and uncertainty at the same\n", + "sky position." ] }, { @@ -374,6 +369,7 @@ "source": [ "print(\"First unmasked image value:\")\n", "print(dataset.data.slim[0])\n", + "\n", "print(\"First unmasked noise map value:\")\n", "print(dataset.noise_map.slim[0])" ], @@ -384,18 +380,21 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Additionally, we can verify that the `native` data structure has zeros at the edges where the mask is applied and \n", - "retains non-zero values in the central unmasked regions." + "In the native representation, the corner pixel is masked and therefore\n", + "contains a zero placeholder. The central pixel is unmasked and retains its\n", + "measured value." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(\"Example masked pixel in the image's native representation at its edge:\")\n", + "print(\"Masked corner pixel in the native image:\")\n", "print(dataset.data.native[0, 0])\n", - "print(\"Example unmasked pixel in the image's native representation at its center:\")\n", + "\n", "centre = tuple(s // 2 for s in dataset.data.shape_native)\n", + "\n", + "print(\"Unmasked central pixel in the native image:\")\n", "print(dataset.data.native[centre])" ], "outputs": [], @@ -407,15 +406,12 @@ "source": [ "__Masked Grid__\n", "\n", - "In tutorials 1 and 2, we emphasized that the `Grid2D` object is crucial for evaluating a lens's light profile. This grid \n", - "contains (y, x) coordinates for each pixel in the image and is used to ray-trace to the source plane and map out the \n", - "positions where the source galaxy's light is calculated.\n", - "\n", - "From a `Mask2D`, we derive a `masked_grid`, which consists only of the coordinates of unmasked pixels. This ensures \n", - "that light profile calculations focus exclusively on regions where the strong lens's light is detected, saving \n", - "computational time and improving efficiency.\n", + "To predict the image, we need the sky coordinates corresponding to the\n", + "selected pixels. We obtain these from the mask as a grid of `(y, x)`\n", + "coordinates.\n", "\n", - "Below, we plot the masked grid:" + "Each coordinate marks the centre of an unmasked pixel. Plotting the grid\n", + "shows the circular region that we selected." ] }, { @@ -433,18 +429,23 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "By plotting this masked grid over the lens image, we can see that the grid aligns with the unmasked pixels of the \n", - "image.\n", + "We can overlay these coordinates on the image to see where the selected\n", + "pixels lie. Each dot corresponds to one pixel whose measured brightness\n", + "will be compared with the model prediction.\n", "\n", - "This alignment **is crucial** for accurate fitting because it ensures that when we evaluate a strong lens's light \n", - "profile, the calculations occur only at positions where we have real data from." + "The grid, image and noise map use matching pixel ordering, so their slim\n", + "entries refer to the same positions." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "aplt.plot_array(array=dataset.data, title=\"Image Data With 2D Grid Overlaid\")" + "aplt.plot_array(\n", + " array=dataset.data,\n", + " grid=masked_grid,\n", + " title=\"Image Data With 2D Grid Overlaid\",\n", + ")" ], "outputs": [], "execution_count": null @@ -455,11 +456,16 @@ "source": [ "__Fitting__\n", "\n", - "Now that our data is masked, we are ready to proceed with the fitting process.\n", + "We will begin with the same lens and source parameters used to simulate the\n", + "data. This gives us a useful reference: we know the underlying model, so we\n", + "can see what agreement with a noisy observation should look like.\n", + "\n", + "We should not expect the predicted image to match every observed pixel\n", + "exactly. The data contain random noise, whereas our prediction describes\n", + "the expected brightness.\n", "\n", - "Fitting the data is done using the `Galaxy` and `Tracer objects that we introduced in previous tutorials. We will start by \n", - "setting up a `Tracer`` object, using the same galaxy configuration that we previously used to simulate the \n", - "imaging data. This setup will give us what is known as a 'perfect' fit, as the simulated and fitted models are identical." + "As before, the lens has an Isothermal mass profile and the source has a\n", + "Sersic light profile. The lens galaxy's light was omitted from this simulation." ] }, { @@ -469,7 +475,9 @@ "lens_galaxy = al.Galaxy(\n", " redshift=0.5,\n", " mass=al.mp.Isothermal(\n", - " centre=(0.0, 0.0), einstein_radius=1.6, ell_comps=(0.17647, 0.0)\n", + " centre=(0.0, 0.0),\n", + " einstein_radius=1.6,\n", + " ell_comps=(0.17647, 0.0),\n", " ),\n", ")\n", "\n", @@ -484,10 +492,7 @@ " ),\n", ")\n", "\n", - "\n", - "tracer = al.Tracer(galaxies=[lens_galaxy, source_galaxy])\n", - "\n", - "aplt.plot_array(array=tracer.image_2d_from(grid=dataset.grid), title=\"Image\")" + "tracer = al.Tracer(galaxies=[lens_galaxy, source_galaxy])" ], "outputs": [], "execution_count": null @@ -496,10 +501,12 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Next, let's plot the image of the tracer. This should look familiar, as it is the same image we saw in \n", - "previous tutorials. The difference now is that we use the dataset's `grid`, which corresponds to the `masked_grid` \n", - "we defined earlier. This means that the tracer image is only evaluated in the unmasked region, skipping calculations \n", - "in masked regions." + "First, we evaluate the tracer on the dataset's grid. This calculates the\n", + "lensed source image at the selected image-plane coordinates.\n", + "\n", + "The arcs should look familiar, but this image has not yet been blurred by\n", + "the telescope's PSF. We must include that blurring before comparing it with\n", + "the observed data." ] }, { @@ -507,7 +514,8 @@ "metadata": {}, "source": [ "aplt.plot_array(\n", - " array=tracer.image_2d_from(grid=dataset.grid), title=\"Tracer Image To Be Fitted\"\n", + " array=tracer.image_2d_from(grid=dataset.grid),\n", + " title=\"Lensed Image Before PSF Blurring\",\n", ")" ], "outputs": [], @@ -517,18 +525,15 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Now, we proceed to fit the image by passing both the `Imaging` and `Tracer` objects to a `FitImaging` object. \n", - "This object will compute key quantities that describe the fit\u2019s quality:\n", + "The `FitImaging` object brings together our dataset and tracer. It calculates\n", + "the predicted image with PSF blurring and compares it with the data.\n", "\n", - "`image`: Creates an image of the tracer using their image_2d_from() method.\n", - "`model_data`: Convolves the tracer image with the data's PSF to account for the effects of telescope optics.\n", - "`residual_map`: The difference between the model data and observed data.\n", - "`normalized_residual_map`: Residuals divided by noise values, giving units of noise.\n", - "`chi_squared_map`: Squares the normalized residuals.\n", - "`chi_squared` and `log_likelihood`: Sums the chi-squared values to compute chi_squared, and converts this into \n", - "a log_likelihood, which measures how well the model fits the data (higher values indicate a better fit).\n", + "We supply the parameter values through the tracer. Creating this object\n", + "evaluates that choice of parameters; it does not adjust them.\n", "\n", - "Let's create the fit and inspect each of these attributes:" + "We will inspect the predicted image first, then calculate the differences\n", + "between it and the data. These differences will form the basis of the\n", + "statistical quantities introduced below." ] }, { @@ -544,15 +549,22 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The `model_data` represents the tracer's image after accounting for effects like PSF convolution. \n", + "The fit's `model_data` is the predicted image after PSF convolution. It has\n", + "the same units as the observed data and can be compared with them pixel\n", + "by pixel.\n", + "\n", + "The mask selects which observed pixels enter the comparison, but light\n", + "outside its boundary can still be blurred into those pixels by the PSF.\n", + "`FitImaging` therefore also evaluates the surrounding light needed for\n", + "this convolution.\n", "\n", - "An important technical note is that when we mask data, we discussed above how the image of the tracer is not evaluated\n", - "outside the mask and is set to zero. This is a problem for PSF convolution, as the PSF blurs light from these regions\n", - "outside the mask but at its edge into the mask. They must be correctly evaluated to ensure the model image accurately\n", - "represents the image data.\n", + "This is the same principle as the padding in Tutorial 5: we must account\n", + "for light beyond the edge of the region whose blurred image we want.\n", "\n", - "The `FitImaging` object handles this internally, but evaluating the model image in the additional regions outside the mask\n", - "that are close enough to the mask edge to be blurred into the mask. " + "Below, compare the data and model image. Their arcs should have similar\n", + "positions, shapes and brightnesses. The model image is smooth, while the\n", + "data include noise. We do not add a new random noise realisation to the\n", + "model image when assessing the fit." ] }, { @@ -561,26 +573,7 @@ "source": [ "print(\"First model image pixel:\")\n", "print(fit.model_data.slim[0])\n", - "aplt.plot_array(array=fit.model_data, title=\"Model Image\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Even before computing other fit quantities, we can normally assess if the fit is going to be good by visually comparing\n", - "the `data` and `model_data` and assessing if they look similar.\n", "\n", - "In this example, the tracer used to fit the data are the same as the tracer used to simulate it, so the two\n", - "look very similar (the only difference is the noise in the image)." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ "aplt.plot_array(array=fit.data, title=\"Data\")\n", "aplt.plot_array(array=fit.model_data, title=\"Model Image\")" ], @@ -591,15 +584,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The `residual_map` is the different between the observed image and model image, showing where in the image the fit is\n", - "good (e.g. low residuals) and where it is bad (e.g. high residuals).\n", + "Subtracting the model image from the data gives the `residual_map`:\n", "\n", - "The expression for the residual map is simply:\n", + "\\[\n", + "\\text{residual} = \\text{data} - \\text{model\\_data}\n", + "\\]\n", "\n", - "\\[ \\text{residual} = \\text{data} - \\text{model\\_data} \\]\n", + "A positive residual means that the observed pixel is brighter than predicted.\n", + "A negative residual means that it is fainter.\n", "\n", - "The residual-map is plotted below, noting that all values are very close to zero because the fit is near perfect.\n", - "The only non-zero residuals are due to noise in the image." + "We calculate this difference explicitly below and compare its first value\n", + "with the value provided by `FitImaging`." ] }, { @@ -607,6 +602,7 @@ "metadata": {}, "source": [ "residual_map = dataset.data - fit.model_data\n", + "\n", "print(\"First residual-map pixel:\")\n", "print(residual_map.slim[0])\n", "\n", @@ -622,18 +618,44 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Are these residuals indicative of a good fit to the data? Without considering the noise in the data, it's difficult \n", - "to ascertain. That is, its hard to ascenrtain if a residual value is large or small because this depends on the\n", - "amount of noise in that pixel.\n", + "Because we used the parameters that generated the simulation, we expect\n", + "the residuals to be dominated by the noise in the data.\n", "\n", - "The `normalized_residual_map` divides the residual-map by the noise-map, giving the residual in units of the noise.\n", - "Its expression is:\n", + "Look for positive and negative fluctuations rather than coherent arc-shaped\n", + "features. The fluctuations can be larger in bright regions, where the\n", + "Poisson noise is larger.\n", "\n", - "\\[ \\text{normalized\\_residual} = \\frac{\\text{residual\\_map}}{\\text{noise\\_map}} = \\frac{\\text{data} - \\text{model\\_data}}{\\text{noise\\_map}} \\]\n", + "To judge whether a residual is large or small, we must compare it with\n", + "the noise expected in that pixel. This is our next step.\n", "\n", - "If you're familiar with the concept of standard deviations (sigma) in statistics, the normalized residual map represents \n", - "how many standard deviations the residual is from zero. For instance, a normalized residual of 2.0 (corresponding \n", - "to a 95% confidence interval) means that the probability of the model underestimating the data by that amount is only 5%." + "**🤖 Ask AI:** Why can a correct lens model leave larger absolute residuals\n", + "in bright arcs than in the faint background?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The size of a residual only becomes informative when compared with the\n", + "uncertainty in that pixel. A difference of 0.1 electrons per second could\n", + "be small in a noisy pixel but substantial in a precisely measured one.\n", + "\n", + "The `normalized_residual_map` divides each residual by its noise standard\n", + "deviation:\n", + "\n", + "\\[\n", + "r_i = \\frac{d_i - m_i}{\\sigma_i}\n", + "\\]\n", + "\n", + "Here, \\(d_i\\) is the observed value, \\(m_i\\) is the model prediction and\n", + "\\(\\sigma_i\\) is the noise-map value for pixel \\(i\\).\n", + "\n", + "A normalised residual of +2 means that the observation is two noise standard\n", + "deviations above the prediction. A value of -2 means that it is two standard\n", + "deviations below.\n", + "\n", + "For a suitable model and well-estimated noise, we expect fluctuations around\n", + "zero, typically of order one. We do not expect every pixel to be close to zero." ] }, { @@ -648,7 +670,10 @@ "print(\"First normalized residual-map pixel via fit:\")\n", "print(fit.normalized_residual_map.slim[0])\n", "\n", - "aplt.plot_array(array=fit.normalized_residual_map, title=\"Normalized Residual Map\")" + "aplt.plot_array(\n", + " array=fit.normalized_residual_map,\n", + " title=\"Normalized Residual Map\",\n", + ")" ], "outputs": [], "execution_count": null @@ -657,25 +682,29 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Next, we define the `chi_squared_map`, which is obtained by squaring the `normalized_residual_map` and serves as a \n", - "measure of goodness of fit.\n", + "Squaring the normalised residuals gives the `chi_squared_map`:\n", "\n", - "The chi-squared map is calculated as:\n", + "\\[\n", + "\\chi_i^2 = \\left(\\frac{d_i - m_i}{\\sigma_i}\\right)^2\n", + "\\]\n", "\n", - "\\[ \\chi^2 = \\left(\\frac{\\text{data} - \\text{model\\_data}}{\\text{noise\\_map}}\\right)^2 \\]\n", + "Each value measures one pixel's contribution to the overall disagreement.\n", + "The values are non-negative: residuals of +2 and -2 both contribute 4.\n", "\n", - "Squaring the normalized residual map ensures all values are positive. For instance, both a normalized residual of -0.2 \n", - "and 0.2 would square to 0.04, indicating the same quality of fit in terms of `chi_squared`.\n", + "Look for pixels with large contributions and whether they form a coherent\n", + "pattern. A few large values can occur through noise, especially when an image\n", + "contains many pixels.\n", "\n", - "As seen from the normalized residual map, it's evident that the model provides a good fit to the data, in this\n", - "case because the chi-squared values are close to zero." + "For our reference model, the contributions should average approximately one,\n", + "rather than all being close to zero." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "chi_squared_map = (normalized_residual_map) ** 2\n", + "chi_squared_map = normalized_residual_map**2\n", + "\n", "print(\"First chi-squared pixel:\")\n", "print(chi_squared_map.slim[0])\n", "\n", @@ -691,26 +720,27 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Now, we consolidate all the information in our `chi_squared_map` into a single measure of goodness-of-fit \n", - "called `chi_squared`. \n", + "We sum the contributions from all \\(N\\) unmasked pixels to obtain one number,\n", + "the total `chi_squared`:\n", "\n", - "It is defined as the sum of all values in the `chi_squared_map` and is computed as:\n", - "\n", - "\\[ \\chi^2 = \\sum \\left(\\frac{\\text{data} - \\text{model\\_data}}{\\text{noise\\_map}}\\right)^2 \\]\n", + "\\[\n", + "\\chi^2 = \\sum_{i=1}^{N}\n", + "\\left(\\frac{d_i - m_i}{\\sigma_i}\\right)^2\n", + "\\]\n", "\n", - "This summing process highlights why ensuring all values in the chi-squared map are positive is crucial. If we \n", - "didn't square the values (making them positive), positive and negative residuals would cancel each other out, \n", - "leading to an inaccurate assessment of the model's fit to the data.\n", + "Squaring before summing prevents positive and negative residuals from\n", + "cancelling. Large differences relative to the noise contribute strongly.\n", "\n", - "The lower the `chi_squared`, the fewer residuals exist between the model's fit and the data, indicating a better \n", - "overall fit!" + "When comparing parameter choices using the same data, mask and noise map,\n", + "a lower chi-squared means smaller overall noise-weighted differences." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "chi_squared = np.sum(chi_squared_map)\n", + "chi_squared = np.sum(chi_squared_map.slim)\n", + "\n", "print(\"Chi-squared = \", chi_squared)\n", "print(\"Chi-squared via fit = \", fit.chi_squared)" ], @@ -721,23 +751,34 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The reduced chi-squared is the `chi_squared` value divided by the number of data points (e.g., the number of pixels\n", - "in the mask). \n", + "Dividing the total chi-squared by the number of unmasked pixels gives the\n", + "average contribution per pixel:\n", + "\n", + "\\[\n", + "\\frac{\\chi^2}{N}\n", + "\\]\n", + "\n", + "For the parameters that generated our simulation, we expect this to be\n", + "approximately one if the noise estimates describe the fluctuations well.\n", + "Individual pixels can contribute much more or much less than one.\n", "\n", - "This quantity offers an intuitive measure of the goodness-of-fit, as it normalizes the `chi_squared` value by the\n", - "number of data points. That is, a reduced chi-squared of 1.0 indicates that the model provides a good fit to the data,\n", - "because every data point is fitted with a chi-squared value of 1.0.\n", + "A substantially larger value can indicate a mismatch between the model and\n", + "data, underestimated noise, or both. A substantially smaller value can\n", + "indicate overestimated noise; it does not automatically establish overfitting.\n", "\n", - "A reduced chi-squared value significantly greater than 1.0 indicates that the model is not a good fit to the data,\n", - "whereas a value significantly less than 1.0 suggests that the model is overfitting the data." + "You may also encounter the term \"reduced chi-squared\". This divides chi-squared\n", + "by the number of degrees of freedom, often \\(N-p\\) when \\(p\\) independent\n", + "parameters have been estimated from the data. Here, we are simply inspecting\n", + "the average per pixel for a specified model." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "reduced_chi_squared = chi_squared / dataset.mask.pixels_in_mask\n", - "print(\"Reduced Chi-squared = \", reduced_chi_squared)" + "chi_squared_per_pixel = chi_squared / dataset.mask.pixels_in_mask\n", + "\n", + "print(\"Chi-squared per pixel = \", chi_squared_per_pixel)" ], "outputs": [], "execution_count": null @@ -746,27 +787,54 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Another quantity that contributes to our final assessment of the goodness-of-fit is the `noise_normalization`.\n", + "To turn this comparison into a likelihood, we need a statistical description\n", + "of the noise.\n", + "\n", + "We will treat each pixel's measurement as an independent Gaussian random\n", + "variable, centred on the model prediction \\(m_i\\), with standard deviation\n", + "\\(\\sigma_i\\). This is an approximation to the Poisson counts used in our\n", + "simulation, appropriate when the expected counts are sufficiently large.\n", + "\n", + "The probability density for a pixel value is then:\n", + "\n", + "\\[\n", + "p(d_i \\mid m_i, \\sigma_i)\n", + "=\n", + "\\frac{1}{\\sqrt{2\\pi\\sigma_i^2}}\n", + "\\exp\\left[-\\frac{1}{2}\n", + "\\left(\\frac{d_i-m_i}{\\sigma_i}\\right)^2\\right]\n", + "\\]\n", + "\n", + "The exponential penalises predictions far from the observed value. The factor\n", + "in front normalises the Gaussian so that its density integrates to one.\n", "\n", - "The `noise_normalization` is computed by summing, over every pixel, the logarithm of 2 pi times the squared noise value:\n", + "For independent pixels, we multiply these densities. Taking the natural\n", + "logarithm turns that product into a sum:\n", "\n", "\\[\n", - "\\text{{noise\\_normalization}} = \\sum \\log(2 \\pi \\text{{noise\\_map}}^2)\n", + "\\log \\mathcal{L}\n", + "=\n", + "-\\frac{1}{2}\n", + "\\left[\n", + "\\chi^2 + \\sum_{i=1}^{N}\\log(2\\pi\\sigma_i^2)\n", + "\\right]\n", "\\]\n", "\n", - "This quantity is fixed because the noise-map remains constant throughout the fitting process. Despite this, \n", - "including the `noise_normalization` is considered good practice due to its statistical significance.\n", + "The second term is called `noise_normalization` in PyAutoLens. It is part of\n", + "the probability density, not a test of whether the noise is Gaussian.\n", "\n", - "Understanding the exact meaning of `noise_normalization` isn't critical for our primary goal of successfully \n", - "fitting a model to a dataset. Essentially, it provides a measure of how well the noise properties of our data align \n", - "with a Gaussian distribution." + "For our fixed dataset, mask and noise map, this term stays constant as we\n", + "change the lens and source parameters." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "noise_normalization = np.sum(np.log(2 * np.pi * dataset.noise_map**2))\n", + "noise_normalization = np.sum(\n", + " np.log(2 * np.pi * dataset.noise_map.slim**2)\n", + ")\n", + "\n", "print(\"Noise Normalization = \", noise_normalization)\n", "print(\"Noise Normalization via fit = \", fit.noise_normalization)" ], @@ -777,16 +845,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "From the `chi_squared` and `noise_normalization`, we can define a final goodness-of-fit measure known as \n", - "the `log_likelihood`. \n", - "\n", - "This measure is calculated by taking the sum of the `chi_squared` and `noise_normalization`, and then multiplying the \n", - "result by -0.5:\n", - "\n", - "\\[ \\text{log\\_likelihood} = -0.5 \\times \\left( \\chi^2 + \\text{noise\\_normalization} \\right) \\]\n", + "We can now calculate the log likelihood and compare it with the value\n", + "returned by `FitImaging`.\n", "\n", - "Don't worry about why we multiply by -0.5; it's a standard practice in statistics to ensure the log likelihood is\n", - "defined correctly." + "The factor of -0.5 follows from the Gaussian expression above. With the\n", + "noise normalisation fixed, reducing chi-squared increases the log likelihood." ] }, { @@ -794,6 +857,7 @@ "metadata": {}, "source": [ "log_likelihood = -0.5 * (chi_squared + noise_normalization)\n", + "\n", "print(\"Log Likelihood = \", log_likelihood)\n", "print(\"Log Likelihood via fit = \", fit.log_likelihood)" ], @@ -804,42 +868,28 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "In the previous discussion, we noted that a lower \\(\\chi^2\\) value indicates a better fit of the model to the \n", - "observed data. \n", - "\n", - "When we calculate the log likelihood, we take the \\(\\chi^2\\) value and multiply it by -0.5. This means that a \n", - "higher log likelihood corresponds to a better model fit. Our goal when fitting models to data is to maximize the \n", - "log likelihood.\n", - "\n", - "The **reduced \\(\\chi^2\\)** value provides an intuitive measure of goodness-of-fit. Values close to 1.0 suggest a \n", - "good fit, while values below or above 1.0 indicate potential underfitting or overfitting of the data, respectively. \n", - "In contrast, the log likelihood values can be less intuitive. For instance, a log likelihood value printed above \n", - "might be around 5300.\n", + "For the same dataset, mask and noise assumptions, a higher log likelihood\n", + "indicates better agreement between the predicted image and the data.\n", "\n", - "However, log likelihoods become more meaningful when we compare them. For example, if we have two models, one with \n", - "a log likelihood of 5300 and the other with 5310 we can conclude that the first model fits the data better \n", - "because it has a higher log likelihood by 10.0. \n", + "For example, a log likelihood of 5310 is higher than 5300, so the former\n", + "parameter choice provides the better fit under those assumptions.\n", "\n", - "In fact, the difference in log likelihood between models can often be associated with a probability indicating how \n", - "much better one model fits the data compared to another. This can be expressed in terms of standard deviations (sigma). \n", + "The absolute value is not a probability that the model is correct. Nor does\n", + "a difference in log likelihood have a universal conversion into a number\n", + "of standard deviations.\n", "\n", - "As a rule of thumb:\n", + "We should also inspect where the model disagrees with the data. The subplot\n", + "below brings together the data, model image and residual diagnostics, along\n", + "with views of the source.\n", "\n", - "- A difference in log likelihood of **2.5** suggests that one model is preferred at the **2.0 sigma** level.\n", - "- A difference in log likelihood of **5.0** indicates a preference at the **3.0 sigma** level.\n", - "- A difference in log likelihood of **10.0** suggests a preference at the **5.0 sigma** level.\n", - "\n", - "All these metrics can be visualized together using the `aplt.subplot_fit_imaging` object, which offers a comprehensive \n", - "overview of the fit quality. It also shows separate model images for the lens and source galaxies, and the appearance\n", - "of the source galaxy in the image and source planes." + "Look for residuals consistent with noise rather than coherent features\n", + "tracing the lensed arcs." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "fit = al.FitImaging(dataset=dataset, tracer=tracer)\n", - "\n", "aplt.subplot_fit_imaging(fit=fit)" ], "outputs": [], @@ -849,36 +899,26 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "If you're familiar with model-fitting, you've likely encountered terms like 'residuals', 'chi-squared', \n", - "and 'log_likelihood' before. \n", + "__Incorrect Fit__\n", "\n", - "These metrics are standard ways to quantify the quality of a model fit. They are applicable not only to 1D data but \n", - "also to more complex data structures like 2D images, 3D data cubes, or any other multidimensional datasets.\n", + "We will now change the source position while keeping the lens mass and all\n", + "other source properties fixed.\n", "\n", - "__Incorrect Fit__\n", + "The original source centre was `(0.1, 0.1)` arcseconds. We move it to\n", + "`(0.15, 0.15)`, a displacement of 0.05 arcseconds in each source-plane\n", + "coordinate.\n", "\n", - "In the previous section, we successfully created and fitted a lens model to the image data, resulting in an \n", - "excellent fit. The residual map and chi-squared map showed no significant discrepancies, indicating that the \n", - "strong lens's light was accurately captured by our model. This optimal solution translates to one of the highest log \n", - "likelihood values possible, reflecting a good match between the model and the observed data.\n", + "Although 0.05 arcseconds is half our image pixel scale, lensing maps this\n", + "source-plane displacement into changes in the positions and shapes of the\n", + "observed arcs. It does not simply move every image by half a pixel.\n", "\n", - "Now, let's modify our lens model to create a fit that is close to the correct solution but slightly off. \n", - "Specifically, we will slightly offset the center of the source galaxy by half a pixel (0.05\") in both the x and y \n", - "directions. This change will allow us to observe how even small deviations from the true parameters can impact the \n", - "quality of the fit." + "The original `fit` remains our reference comparison." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "lens_galaxy = al.Galaxy(\n", - " redshift=0.5,\n", - " mass=al.mp.Isothermal(\n", - " centre=(0.0, 0.0), einstein_radius=1.6, ell_comps=(0.17647, 0.0)\n", - " ),\n", - ")\n", - "\n", "source_galaxy = al.Galaxy(\n", " redshift=1.0,\n", " bulge=al.lp.Sersic(\n", @@ -890,10 +930,12 @@ " ),\n", ")\n", "\n", - "\n", "tracer = al.Tracer(galaxies=[lens_galaxy, source_galaxy])\n", "\n", - "aplt.plot_array(array=tracer.image_2d_from(grid=dataset.grid), title=\"Image\")" + "aplt.plot_array(\n", + " array=tracer.image_2d_from(grid=dataset.grid),\n", + " title=\"Lensed Image With Shifted Source\",\n", + ")" ], "outputs": [], "execution_count": null @@ -902,9 +944,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "After implementing this slight adjustment, we can now plot the fit. In doing so, we observe that residuals have \n", - "emerged at the multiple images of the lensed source, which indicates a mismatch between our model and the data. \n", - "Consequently, this discrepancy results in increased chi-squared values, which in turn affects our log likelihood." + "We evaluate this new tracer against the same dataset and inspect the fit.\n", + "\n", + "Look for coherent positive and negative residuals around the arcs. These\n", + "indicate regions where the shifted source predicts too little or too much\n", + "light, rather than just random fluctuations about the observation." ] }, { @@ -922,17 +966,23 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Next, we can compare the log likelihood of our current model to the log likelihood value we computed previously." + "Compare the log likelihood with our reference value. We expect the shifted\n", + "source to give a lower value because its predicted image disagrees with\n", + "the data more strongly." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(\"Previous Likelihood:\")\n", + "print(\"Reference log likelihood:\")\n", "print(fit.log_likelihood)\n", - "print(\"New Likelihood:\")\n", - "print(fit_bad.log_likelihood)" + "\n", + "print(\"Shifted-source log likelihood:\")\n", + "print(fit_bad.log_likelihood)\n", + "\n", + "print(\"Change from reference:\")\n", + "print(fit_bad.log_likelihood - fit.log_likelihood)" ], "outputs": [], "execution_count": null @@ -941,24 +991,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "As expected, we observe that the log likelihood has decreased! This decline confirms that our new model is indeed a \n", - "worse fit to the data compared to the original model.\n", + "Next, move the source centre to `(0.5, 0.5)` arcseconds. All other parameters\n", + "remain unchanged.\n", "\n", - "Now, let\u2019s change our lens model once more, this time setting it to a position that is far from the true parameters. \n", - "We will offset the source's center significantly to see how this extreme deviation affects the fit quality." + "This is a much larger displacement from the original `(0.1, 0.1)` position.\n", + "Compare the predicted arcs and residuals with the previous two examples." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "lens_galaxy = al.Galaxy(\n", - " redshift=0.5,\n", - " mass=al.mp.Isothermal(\n", - " centre=(0.0, 0.0), einstein_radius=1.6, ell_comps=(0.17647, 0.0)\n", - " ),\n", - ")\n", - "\n", "source_galaxy = al.Galaxy(\n", " redshift=1.0,\n", " bulge=al.lp.Sersic(\n", @@ -970,7 +1013,6 @@ " ),\n", ")\n", "\n", - "\n", "tracer = al.Tracer(galaxies=[lens_galaxy, source_galaxy])\n", "\n", "fit_very_bad = al.FitImaging(dataset=dataset, tracer=tracer)\n", @@ -984,44 +1026,65 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "It is now evident that this model provides a terrible fit to the data. The tracer does not resemble a plausible\n", - "representation of our simulated strong lens dataset, which we already anticipated given that we generated the data ourselves!\n", + "Print the three log likelihoods together and compare their ordering with\n", + "what you saw in the residual plots.\n", "\n", - "As expected, the log likelihood has dropped dramatically with this poorly fitting model." + "For this example, the larger source displacement should produce the strongest\n", + "disagreement and the lowest log likelihood." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(\"Previous Likelihoods:\")\n", + "print(\"Reference source centre (0.1, 0.1):\")\n", "print(fit.log_likelihood)\n", + "\n", + "print(\"Source centre (0.15, 0.15):\")\n", "print(fit_bad.log_likelihood)\n", - "print(\"New Likelihood:\")\n", + "\n", + "print(\"Source centre (0.5, 0.5):\")\n", "print(fit_very_bad.log_likelihood)" ], "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We have evaluated three choices of parameters, rather than searched for\n", + "the best-fitting values.\n", + "\n", + "The parameters used to generate the simulation provide a useful reference,\n", + "but they need not give the highest possible likelihood for one noisy\n", + "observation. Small parameter changes can sometimes improve agreement with\n", + "that particular noise realisation.\n", + "\n", + "To restore the original comparison, rerun the first tracer and `FitImaging`\n", + "cells in the Fitting section.\n", + "\n", + "**🤖 Ask AI:** Why might the parameters that maximise the likelihood of a\n", + "noisy simulated image differ slightly from those used to generate it?" + ] + }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Model Fitting__\n", "\n", - "In the previous sections, we used the true model to fit the data, which resulted in a high log likelihood and minimal \n", - "residuals. We also demonstrated how even small deviations from the true parameters can significantly degrade the fit \n", - "quality, reducing the log likelihood.\n", + "So far, we have compared parameter choices with a known reference model.\n", + "For a real observation, we do not know the lens and source parameters in\n", + "advance. Finding values that describe the data well is the task of model\n", + "fitting.\n", "\n", - "In practice, however, we don't know the \"true\" model. For example, we might have an image of a strong lens observed with \n", - "the Hubble Space Telescope, but the values for parameters like its `einstein_radius` and others are \n", - "unknown. The process of determining the best-fit model is called model fitting, and it is the main topic of\n", - "Chapter 2 of **HowToLens**.\n", + "Let's try this manually using a new simulated dataset. It contains an\n", + "`IsothermalSph` lens mass profile and an `ExponentialCoreSph` source light\n", + "profile, with no light from the lens galaxy.\n", "\n", - "To conclude this section, let's perform a basic, hands-on model fit to develop some intuition about how we can find \n", - "the best-fit model. We'll start by loading a simple dataset that was simulated without any lens light, using \n", - "an `IsothermalSph` lens mass profile and `ExponentialCoreSph` source light profile, but the true parameters of these \n", - "profiles are unknown." + "For this exercise, treat the parameters used to generate the data as unknown.\n", + "We load the image and apply a circular mask as before." ] }, { @@ -1064,33 +1127,25 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Now, you'll try to determine the best-fit model for this image, corresponding to the parameters used to simulate the \n", - "dataset.\n", - "\n", - "We'll use the simplest possible approach: try different combinations of light and mass profile parameters and adjust \n", - "them based on how well each model fits the data. You\u2019ll quickly find that certain parameters produce a much better fit \n", - "than others. For example, determining the correct values of the `centre` should not take too long.\n", + "The parameters below are a starting guess. Run the cell and inspect the\n", + "predicted image, residuals and log likelihood.\n", "\n", - "Pay attention to the `log_likelihood` and the `residual_map` as you adjust the parameters. These will guide you in \n", - "determining if your model is providing a good fit to the data. Aim to increase the log likelihood and reduce the \n", - "residuals.\n", - "\n", - "Keep experimenting with different values for a while, seeing how small you can make the residuals and how high you \n", - "can push the log likelihood. Eventually, you\u2019ll likely reach a point where further improvements become difficult, \n", - "even after trying many different parameter values. This is a good point to stop and reflect on your first experience \n", - "with model fitting." + "The lens and source centres are `(y, x)` coordinates in arcseconds.\n", + "The Einstein radius, effective radius and break radius are also in\n", + "arcseconds. The source intensity uses the image's units of electrons\n", + "per second per pixel." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "\n", "lens_galaxy = al.Galaxy(\n", " redshift=0.5,\n", " mass=al.mp.IsothermalSph(\n", - " centre=(1.0, 1.0), einstein_radius=1.0\n", - " ), # These are the lens parameters you need to adjust\n", + " centre=(1.0, 1.0),\n", + " einstein_radius=1.0,\n", + " ),\n", ")\n", "\n", "source_galaxy = al.Galaxy(\n", @@ -1099,7 +1154,7 @@ " centre=(1.0, 1.0),\n", " intensity=1.0,\n", " effective_radius=1.0,\n", - " radius_break=0.025, # These are the source parameters you need to adjust\n", + " radius_break=0.025,\n", " ),\n", ")\n", "\n", @@ -1110,7 +1165,158 @@ "aplt.subplot_fit_imaging(fit=fit)\n", "\n", "print(\"Log Likelihood:\")\n", - "print(fit.log_likelihood)\n" + "print(fit.log_likelihood)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Try changing one parameter at a time and rerunning the cell above. Record\n", + "the log likelihood for each choice and use the residual plots to understand\n", + "what changed.\n", + "\n", + "Start with the lens centre. Try `(0.5, 0.5)` and `(0.0, 0.0)` instead of\n", + "`(1.0, 1.0)`. This changes the location about which the lens deflects light.\n", + "\n", + "Next, try changing the source centre in the same way. This changes how the\n", + "source is positioned behind the lens and therefore the arrangement of its\n", + "multiple images.\n", + "\n", + "You can then explore:\n", + "\n", + "- `einstein_radius`: try 1.3 and 1.6 arcseconds instead of 1.0. This changes\n", + " the characteristic angular scale of the lensing.\n", + "- `effective_radius`: try 0.5 and 0.2 arcseconds instead of 1.0. This changes\n", + " the source size and the extent of its lensed features.\n", + "- `intensity`: try 0.5 and 0.2 instead of 1.0. With the other parameters\n", + " fixed, this scales the predicted brightness.\n", + "\n", + "Keep `radius_break=0.025` and both redshifts fixed for this exercise.\n", + "\n", + "Retain changes that improve the log likelihood, but continue inspecting\n", + "the residuals. The parameters interact, so a useful change at one stage\n", + "may need revisiting after another parameter changes.\n", + "\n", + "To restore the original starting point, set both centres to `(1.0, 1.0)`,\n", + "and set `einstein_radius`, `effective_radius` and `intensity` to 1.0, then\n", + "rerun the cell." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You have now performed a simple manual search: choose parameters, predict\n", + "an image, compare it with the data, then use that comparison to choose\n", + "another set of parameters.\n", + "\n", + "The aim is not to make every residual vanish. A suitable prediction should\n", + "leave fluctuations consistent with the noise, without substantial coherent\n", + "structure.\n", + "\n", + "Nor does finding a good-looking result establish that it is the best possible\n", + "solution or tell us the uncertainty in its parameters. Several parameter\n", + "combinations may describe the data similarly well.\n", + "\n", + "Manual exploration becomes difficult as the number of parameters grows.\n", + "Chapter 2 introduces methods that explore parameter choices systematically\n", + "and quantify what we can infer from the data.\n", + "\n", + "**🤖 Ask AI:** How could changing both the source size and its intensity\n", + "make it difficult to determine either parameter by adjusting them manually?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Likelihood Function__\n", + "\n", + "Everything we have learned can now be put into a single sequence:\n", + "\n", + "1. Choose the lens and source parameters.\n", + "2. Construct their profiles and ray-trace the source to predict a lensed image.\n", + "3. Convolve that image with the telescope's PSF.\n", + "4. Subtract the prediction from the observed data.\n", + "5. Divide the residuals by the noise standard deviations and sum their squares.\n", + "6. Include the Gaussian normalisation to calculate the log likelihood.\n", + "\n", + "For a fixed dataset, this sequence defines a function of the model parameters:\n", + "the likelihood function. We usually work with its natural logarithm, the\n", + "log-likelihood function.\n", + "\n", + "Writing the parameters collectively as \\(\\boldsymbol{\\theta}\\), we have:\n", + "\n", + "\\[\n", + "\\log \\mathcal{L}(\\boldsymbol{\\theta})\n", + "=\n", + "-\\frac{1}{2}\n", + "\\sum_{i=1}^{N}\n", + "\\left[\n", + "\\frac{(d_i-m_i(\\boldsymbol{\\theta}))^2}{\\sigma_i^2}\n", + "+\n", + "\\log(2\\pi\\sigma_i^2)\n", + "\\right]\n", + "\\]\n", + "\n", + "The data, mask, PSF and noise map remain fixed. Changing the parameters changes\n", + "the predicted image \\(m_i(\\boldsymbol{\\theta})\\), and therefore the value\n", + "returned by the function.\n", + "\n", + "The function below implements this sequence for our exercise. `FitImaging`\n", + "handles the image prediction and PSF convolution, including light that blurs\n", + "across the mask boundary. We then write out the statistical calculation\n", + "explicitly using the unmasked pixels.\n", + "\n", + "The redshifts and source break radius remain fixed, as in the exercise." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def log_likelihood_function(\n", + " dataset,\n", + " lens_centre,\n", + " einstein_radius,\n", + " source_centre,\n", + " intensity,\n", + " effective_radius,\n", + "):\n", + " lens_galaxy = al.Galaxy(\n", + " redshift=0.5,\n", + " mass=al.mp.IsothermalSph(\n", + " centre=lens_centre,\n", + " einstein_radius=einstein_radius,\n", + " ),\n", + " )\n", + "\n", + " source_galaxy = al.Galaxy(\n", + " redshift=1.0,\n", + " bulge=al.lp.ExponentialCoreSph(\n", + " centre=source_centre,\n", + " intensity=intensity,\n", + " effective_radius=effective_radius,\n", + " radius_break=0.025,\n", + " ),\n", + " )\n", + "\n", + " tracer = al.Tracer(galaxies=[lens_galaxy, source_galaxy])\n", + " fit = al.FitImaging(dataset=dataset, tracer=tracer)\n", + "\n", + " model_image = fit.model_data.slim\n", + " residuals = dataset.data.slim - model_image\n", + " normalized_residuals = residuals / dataset.noise_map.slim\n", + "\n", + " chi_squared = np.sum(normalized_residuals**2)\n", + " noise_normalization = np.sum(\n", + " np.log(2 * np.pi * dataset.noise_map.slim**2)\n", + " )\n", + "\n", + " return -0.5 * (chi_squared + noise_normalization)\n" ], "outputs": [], "execution_count": null @@ -1119,40 +1325,65 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Manually guessing model parameters repeatedly is a very inefficient and slow way to find the best fit. If the model \n", - "were more complex\u2014say, if the source galaxy had additional light profile components beyond just its `bulge` (like a \n", - "second `Sersic` profile representing a `disk`)\u2014the model would become so intricate that this manual approach \n", - "would be practically impossible. This is definitely not how model fitting is done in practice.\n", - "\n", - "However, this exercise has given you a basic intuition for how model fitting works. The statistical inference tools \n", - "that are actually used for model fitting will be introduced in Chapter 2. Interestingly, these tools are not entirely \n", - "different from the approach you just tried. Essentially, they also involve iteratively testing models until those \n", - "with high log likelihoods are found. The key difference is that a computer can perform this process thousands of \n", - "times, and it does so in a much more efficient and strategic way.\n", - "\n", - "__Wrap Up__\n", - "\n", - "In this tutorial, you have learned how to fit a lens model to imaging data, a fundamental process in astronomy\n", - "and statistical inference. \n", - "\n", - "Let's summarise what we have covered:\n", - "\n", - "- **Dataset**: We loaded the imaging dataset that we previously simulated, consisting of the tracer image, noise map,\n", - " and PSF.\n", - " \n", - "- **Mask**: We applied a circular mask to the data, excluding regions with low signal-to-noise ratios from the analysis.\n", - "\n", - "- **Masked Grid**: We created a masked grid, which contains only the coordinates of unmasked pixels, to evaluate the\n", - " tracer's light profile.\n", - " \n", - "- **Fitting**: We fitted the data with a lens model, computing key quantities like the model image, residuals,\n", - " chi-squared, and log likelihood to assess the quality of the fit.\n", - " \n", - "- **Bad Fits**: We demonstrated how even small deviations from the true parameters can significantly impact the fit\n", - " quality, leading to decreased log likelihood values.\n", - " \n", - "- **Model Fitting**: We performed a basic model fit on a simple dataset, adjusting the model parameters to improve the\n", - " fit quality. " + "Evaluate the function using your current exercise parameters. Its result\n", + "should agree with the log likelihood from the corresponding `FitImaging`\n", + "object." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "exercise_log_likelihood = log_likelihood_function(\n", + " dataset=dataset,\n", + " lens_centre=lens_galaxy.mass.centre,\n", + " einstein_radius=lens_galaxy.mass.einstein_radius,\n", + " source_centre=source_galaxy.bulge.centre,\n", + " intensity=source_galaxy.bulge.intensity,\n", + " effective_radius=source_galaxy.bulge.effective_radius,\n", + ")\n", + "\n", + "print(\"Log likelihood from our function:\")\n", + "print(exercise_log_likelihood)\n", + "\n", + "print(\"Log likelihood from FitImaging:\")\n", + "print(fit.log_likelihood)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Each call evaluates one choice of parameters and returns one number. It does\n", + "not search for better parameters, and it does not generate new random noise.\n", + "\n", + "The notion of a likelihood function is central to Chapter 2. The search\n", + "methods introduced there repeatedly supply different parameter choices to\n", + "this function and use the returned likelihoods to explore which choices\n", + "describe the data well. Understanding this sequence is therefore the\n", + "foundation for understanding how automated lens modelling works.\n", + "\n", + "The interferometer, point-source, weak-lensing, group-scale and cluster-scale\n", + "examples shown in Tutorial 5 each have their own bespoke likelihood\n", + "functions, tailored to their measurements and analysis. They follow the\n", + "same principle: predict the observables from a set of parameters, then compare\n", + "those predictions with the data using the appropriate uncertainties.\n", + "\n", + "The `autolens_workspace` provides step-by-step guides to every likelihood\n", + "function in PyAutoLens. These unpack the calculations for different dataset\n", + "types and analysis methods, just as we have done here.\n", + "\n", + "For the imaging calculation introduced in this tutorial, see the workspace's\n", + "[imaging likelihood-function guide](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/likelihood_function.py).\n", + "The corresponding sections of the workspace provide guides for the other\n", + "likelihood functions.\n", + "\n", + "You have now followed the full path from a lens and source description to a\n", + "quantitative comparison with an observation. In Chapter 2, we will use this\n", + "likelihood function to move from trying parameters by hand to exploring them\n", + "systematically." ] } ], @@ -1180,7 +1411,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_1_introduction/tutorial_6_fitting.ipynb in HowToLens).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoLens calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoLens docs (https://pyautolens.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` \u2014 image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* \u2014 pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* \u2014 if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual \u2014 what convergence is, why caustics matter, what\na critical curve traces \u2014 see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions \u2014\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` \u2014 see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch \u2014 quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch \u2014 single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly \u2014 build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch \u2014 multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI \u2014 extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) \u2014 multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) \u2014 usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) \u2014 fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) \u2014 for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot \u2014 how light deflects, how critical curves and\n caustics arise.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action \u2014 building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` \u2014 ray tracing, profiles, numpy\n arrays, visualization.\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth \u2014 or build a\ntraining set for neural-network classifiers \u2014 you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating \u2014 single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* \u2014 chooses the branch.\n- *\"What's the ground truth?\"* \u2014 lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* \u2014 pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch \u2014 galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid \u2014 defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer \u2014 lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_fits(\n data_path=dataset_path / \"data.fits\",\n noise_map_path=dataset_path / \"noise_map.fits\",\n psf_path=dataset_path / \"psf.fits\",\n overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot \u2014 saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` \u2014 `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch \u2014 many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch \u2014 interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n \u2192 [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour \u2014 see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates \u2014 the forward physics\n the simulator runs.\n- **General reference** \u2014 [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice \u2014 grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_1_introduction/tutorial_6_fitting.ipynb in HowToLens).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoLens calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoLens docs (https://pyautolens.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_plot_tracer\n\n---\nname: al_plot_tracer\ndescription: Plot ray-tracing visuals from a `Tracer` — image-plane and source-plane galaxy images, deflection vector field, convergence and potential maps, critical curves and caustics, magnification map. Use after `al_load_results` has handed you a Tracer, or right after building one in `al_simulate_dataset`. For *fit*-derived plots (residuals, model image with PSF) see `al_plot_fit_residuals`.\n---\n\n# Plotting a Tracer\n\nA `Tracer` knows how to ray-trace grids of (y, x) coordinates through one or more\nlens planes. From it you can extract everything that depends only on the *model*,\nwithout needing the data: critical curves, caustics, deflection fields, convergence\nmaps, magnification maps, and per-galaxy images on the image and source planes.\n\nThis skill produces those plots for the user's tracer. For fit-vs-data diagnostics\nthat depend on the dataset (residuals, normalised residuals, chi-squared), use\n[`al_plot_fit_residuals`](./al_plot_fit_residuals.md) instead.\n\nCanonical references: `autolens_workspace:scripts/guides/plot/plotters.py`\nand `visuals.py`.\n\n## Ask\n\n- *\"Which plot do you want?\"* — pick from: image-plane subplot, source-plane subplot,\n deflection field, convergence, potential, magnification, critical curves +\n caustics overlay. Each lives in a different branch.\n- *\"On what grid?\"* — if you have a dataset, use `dataset.grid`. Otherwise build a\n `al.Grid2D.uniform(...)` of your choice.\n\nFor the physics behind each visual — what convergence is, why caustics matter, what\na critical curve traces — see\n[`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md).\n\n## Saving plots\n\nIn `2026.5.21+` `autolens.plot` is a flat module of free functions —\nthe previous object-oriented plotter/configuration classes\nare gone. Each plotting function takes `output_path` / `output_filename` /\n`output_format` kwargs directly. Define your destination once and reuse it:\n\n```python\nfrom pathlib import Path\nimport autolens.plot as aplt\n\nPLOT_DIR = Path(\"scripts/scratch\") / \"\" # pick a meaningful slug\nPLOT_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nAfter running, the agent quotes `PLOT_DIR.resolve()` and offers\n`open ` — see `_style.md` \"Plot output and path announcement\". The\nfunction-style plot API is documented in\n[`wiki/core/api/plotting.md`](../wiki/core/api/plotting.md).\n\n## Branch — quick subplots\n\n```python\n# Assume `tracer` and `grid` exist (e.g. from al_load_results + al_prepare_imaging_data).\naplt.subplot_tracer(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # 2x3: image, source, convergence, potential, deflection y, deflection x\n\naplt.subplot_galaxies_images(\n tracer=tracer, grid=grid,\n output_path=str(PLOT_DIR), output_format=\"png\",\n) # per-galaxy image-plane images\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nSource: `PyAutoLens:autolens/lens/plot/tracer_plots.py`.\n\n## Branch — single quantity at high resolution\n\n`MassProfilePlotter`-style figures are now built by extracting the array from\nthe profile (or the tracer) and passing it to `aplt.plot_array`:\n\n```python\n# Per-quantity overlays on a single mass profile\nmass = tracer.galaxies[0].mass\naplt.plot_array(array=mass.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=mass.potential_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"potential\",\n output_format=\"png\")\n\n# Or the whole tracer:\naplt.plot_array(array=tracer.convergence_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_convergence\",\n output_format=\"png\", use_log10=True)\naplt.plot_array(array=tracer.image_2d_from(grid=grid),\n output_path=str(PLOT_DIR), output_filename=\"tracer_image\",\n output_format=\"png\")\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\n`tracer.deflections_yx_2d_from(grid=grid)` returns a `VectorYX2D`; access the\ntwo components and plot separately, or use `aplt.subplot_tracer` to get the\ncombined figure. `Tracer` does not surface magnification, critical curves, or\ncaustics directly — build the magnification map from the deflection Jacobian\n(see [`wiki/core/concepts/lensing_basics.md`](../wiki/core/concepts/lensing_basics.md)).\n\n## Branch — multi-plane systems (>2 redshifts)\n\nWhen the `Tracer` has more than two lens planes (e.g. cluster lenses), the source\nplane is the *final* plane. There is no dedicated plane plotter in the flat function\nAPI — extract each intermediate plane's galaxies via `tracer.planes[i]`, evaluate\ntheir images on the traced grid for that plane, and pass the arrays to\n`aplt.plot_array`. See `PyAutoLens:autolens/lens/plot/`.\n\n[`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) — multi-plane ray tracing\nexplanation.\n\n## Combine\n\n- [`al_load_results`](./al_load_results.md) — usually how you get the `Tracer` you're\n plotting.\n- [`al_plot_fit_residuals`](./al_plot_fit_residuals.md) — fit quality plots.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) — for\n pixelised sources, the reconstruction is a `FitImaging` property.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Ray tracing and deflection\n angles](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_2_ray_tracing.ipynb):\n the physics under every tracer plot — how light deflects, how critical curves and\n caustics arise.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n the `Tracer` object in action — building one, evaluating it on a grid, plotting\n the result.\n- **Experienced PyAutoLens user** — [workspace/lens: guides/tracer.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/tracer.py):\n full pattern for inspecting an inferred `Tracer` — ray tracing, profiles, numpy\n arrays, visualization.\n\n## Skill: al_simulate_dataset\n\n---\nname: al_simulate_dataset\ndescription: Synthesise a strong-lens imaging or interferometer dataset from a ground-truth Tracer (lens + source galaxies, redshifts, light + mass profiles). Writes data / noise / PSF FITS files plus a tracer.json to a dataset folder. Use when the user wants a controlled test dataset, a training sample for an ML pipeline, or a sanity check that a model can recover known inputs. For modelling an *existing* dataset see `al_prepare_imaging_data` instead.\n---\n\n# Simulating a strong-lens dataset\n\nWhen you want to validate a modelling pipeline against a known truth — or build a\ntraining set for neural-network classifiers — you synthesise a dataset from a\nground-truth `Tracer`. The simulator ray-traces the source through the lens galaxy's\nmass, applies the PSF, adds Poisson + background noise, and writes the result to\nFITS.\n\nThe canonical example is `autolens_workspace:scripts/imaging/simulator.py`. This\nskill produces the equivalent for your specific model.\n\n## Ask\n\n- *\"What kind of lens are you simulating — single galaxy-scale, group, cluster?\n Imaging or interferometer?\"* — chooses the branch.\n- *\"What's the ground truth?\"* — lens redshift, source redshift, mass profile (SIE? +\n external shear?), lens light (Sersic?), source light (Sersic? compact?).\n- *\"What instrument are you mimicking?\"* — pixel scale, FoV, PSF FWHM, exposure\n time / background level.\n\n## Branch — galaxy-scale imaging\n\n```python\n# scripts/simulate_imaging.py\nfrom autonerves import jax_wrapper\nfrom pathlib import Path\nimport autolens as al\nimport autolens.plot as aplt\n\ndataset_path = Path(\"dataset/imaging/synthetic_galaxy_lens\")\ndataset_path.mkdir(parents=True, exist_ok=True)\n\n# 1. Grid — defines the simulated image's shape and pixel scale.\ngrid = al.Grid2D.uniform(shape_native=(150, 150), pixel_scales=0.06)\nover_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)]\n)\ngrid = grid.apply_over_sampling(over_sample_size=over_sample_size)\n\n# 2. Ground-truth Tracer — lens galaxy (light + mass) + source galaxy (light).\nlens = al.Galaxy(\n redshift=0.5,\n bulge=al.lp.Sersic(centre=(0.0, 0.0), ell_comps=(0.1, 0.0), intensity=4.0,\n effective_radius=0.8, sersic_index=2.5),\n mass=al.mp.Isothermal(centre=(0.0, 0.0), ell_comps=(0.1, 0.05), einstein_radius=1.2),\n)\nfield = al.MassField(redshift=0.5, shear=al.mp.ExternalShear(gamma_1=0.05, gamma_2=0.0))\nsource = al.Galaxy(\n redshift=1.0,\n bulge=al.lp.SersicCore(centre=(0.1, 0.1), ell_comps=(0.0, 0.0), intensity=0.3,\n effective_radius=0.1, sersic_index=1.0, radius_break=0.025),\n)\ntracer = al.Tracer(galaxies=[lens, source], fields=[field])\n\n# 3. PSF + simulator. Match your target instrument (HST/JWST/Euclid have different\n# PSF FWHM and pixel scale).\npsf = al.Convolver.from_gaussian(shape_native=(11, 11), sigma=0.05,\n pixel_scales=grid.pixel_scales)\n\nsimulator = al.SimulatorImaging(\n exposure_time=300.0,\n psf=psf,\n background_sky_level=0.1,\n add_poisson_noise_to_data=True,\n)\n\ndataset = simulator.via_tracer_from(tracer=tracer, grid=grid)\n\n# 4. Persist.\ndataset.output_to_fits(\n data_path=dataset_path / \"data.fits\",\n noise_map_path=dataset_path / \"noise_map.fits\",\n psf_path=dataset_path / \"psf.fits\",\n overwrite=True,\n)\n\n# Save the ground truth so we can verify recovery later.\nal.output_to_json(obj=tracer, file_path=dataset_path / \"tracer.json\")\n\n# 5. Preview plot — saved to scripts/scratch// for inspection.\nplot_dir = Path(\"scripts/scratch\") / dataset_path.name\nplot_dir.mkdir(parents=True, exist_ok=True)\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=str(plot_dir),\n output_filename=\"simulated_dataset\",\n output_format=\"png\",\n)\n\nprint(f\"FITS written to: {dataset_path.resolve()}\")\nprint(f\"Preview plot saved to: {plot_dir.resolve()}\")\n```\n\nSource citations:\n- `PyAutoLens:autolens/imaging/simulator.py` — `SimulatorImaging.via_tracer_from`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — Sersic profile.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — Isothermal SIE.\n\nRead [`wiki/core/concepts/tracer.md`](../wiki/core/concepts/tracer.md) for how the `Tracer`\nray-traces source positions through the mass model, and\n[`wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md) /\n[`wiki/core/api/mass_profile_catalog.md`](../wiki/core/api/mass_profile_catalog.md) for the\nfull menu of profiles you can swap in.\n\n## Branch — many simulated datasets (training sample)\n\nFor ML training sets, wrap the above in a loop, vary the ground-truth parameters per\niteration, and write each into its own `dataset_/` subfolder. The pattern is in\n`autolens_workspace:scripts/imaging/simulator_sample.py`.\n\n## Branch — interferometer\n\nSubstitute `al.Grid2D.uniform` with a `uv_wavelengths` array of (u, v) coordinates from\nyour interferometer, and use `al.SimulatorInterferometer` instead of\n`SimulatorImaging`. The `Tracer` build is identical. See\n`PyAutoLens:autolens/interferometer/simulator.py` and\n`autolens_workspace:scripts/interferometer/simulator.py`.\n\n## Combine\n\nAfter simulating:\n\n- Fit the simulated dataset with [`al_build_imaging_model`](./al_build_imaging_model.md)\n → [`al_run_search`](./al_run_search.md). Compare the recovered posterior to the\n ground-truth `tracer.json` to verify your pipeline.\n- Generate a sample of N datasets and use the database utilities in PyAutoFit to query\n aggregate behaviour — see `PyAutoFit:autofit/aggregator/`.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Critical curves, caustics, cosmological\n coordinates](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_3_more_ray_tracing.ipynb):\n ray-tracing through to caustics and physical (kpc) coordinates — the forward physics\n the simulator runs.\n- **General reference** — [RTD: Start here](https://pyautolens.readthedocs.io/en/latest/overview/overview_1_start_here.html):\n core PyAutoLens concepts in practice — grids, profiles, ray-tracing with `Tracer`.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/simulators/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/simulators/start_here.py):\n canonical instrument-realistic simulation when no real data are on hand.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" @@ -1188,4 +1419,4 @@ }, "nbformat": 4, "nbformat_minor": 4 -} \ No newline at end of file +} diff --git a/notebooks/chapter_1_introduction/tutorial_7_summary.ipynb b/notebooks/chapter_1_introduction/tutorial_7_summary.ipynb index a075690..629e538 100644 --- a/notebooks/chapter_1_introduction/tutorial_7_summary.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_7_summary.ipynb @@ -7,28 +7,28 @@ "Tutorial 7: Summary\n", "===================\n", "\n", - "In this chapter, we have learnt that:\n", + "In this chapter, we have built up the steps needed to describe a gravitational lens and compare its predicted image with an observation:\n", "\n", - " 1) **PyAutoLens** uses Cartesian `Grid2D`'s of $(y,x)$ coordinates to perform ray-tracing.\n", - " 2) These grids are combined with light and mass profiles to compute images, deflection angles and other quantities.\n", - " 3) Profiles are grouped together to make galaxies.\n", - " 4) Collections of galaxies (at the same redshift) form a plane.\n", - " 5) A `Tracer` can make an image-plane + source-plane strong lens system.\n", - " 6) The Universe's cosmology can be input into this `Tracer` to convert its units to kiloparsecs.\n", - " 7) The tracer's image can be used to simulate strong lens `Imaging` like it was observed with a real telescope.\n", - " 8) This data can be fitted, so to as quantify how well a model strong lens system represents the observed image.\n", + "1. A `Grid2D` provides the $(y,x)$ coordinates where we evaluate light and mass profiles.\n", + "2. Light profiles describe a galaxy's surface brightness, while mass profiles describe its gravitational lensing effects.\n", + "3. A `Galaxy` groups these profiles together at a specified redshift.\n", + "4. A `Tracer` groups galaxies into redshift planes and traces light between them.\n", + "5. The redshifts and cosmology connect angular quantities with physical distances.\n", + "6. A simulated imaging observation combines the predicted image with a telescope's PSF, exposure time and noise.\n", + "7. Comparing a predicted image with observed data gives residuals, a chi-squared and a log likelihood.\n", + "8. Putting this calculation into a likelihood function lets us evaluate different choices of model parameters.\n", "\n", - "In this summary, we'll go over all the different Python objects introduced throughout this chapter and consider how\n", - "they come together as one.\n", + "This final tutorial brings those ideas together. We will revisit how profiles, galaxies and planes fit inside a tracer,\n", + "and use that structure to plot individual components of a lensed source.\n", "\n", "__Contents__\n", "\n", - "- **Start:** Below, we do all the steps we have learned this chapter, making profiles, galaxies, a tracer, etc.\n", - "- **Object Composition:** Lets now consider how all of the objects we've covered throughout this chapter (`LightProfile`'s.\n", - "- **Visualization:** Furthermore, using the `MatPLot2D` and `lines=`/`positions=` overlays objects we can visualize any.\n", - "- **Code Design:** To end, I want to quickly talk about the **PyAutoLens** code-design and structure, which was really.\n", - "- **Source Code:** If you do enjoy code, variables, functions, and parameters, you may want to dig deeper into the.\n", - "- **Wrap Up:** Summary of the script and next steps." + "- **Start:** Build a lens and a source with two light profiles.\n", + "- **Object Composition:** Access the galaxies and profiles inside a tracer.\n", + "- **Visualization:** Add critical curves to the lensed image.\n", + "- **Code Design:** Connect the structure of the code with the physical system.\n", + "- **Source Code:** Find the projects that provide these tools.\n", + "- **Wrap Up:** Prepare for automated lens modelling in Chapter 2." ] }, { @@ -78,7 +78,6 @@ "\n", "from autolens import setup_notebook; setup_notebook()\n", "\n", - "from pathlib import Path\n", "import autolens as al\n", "import autolens.plot as aplt" ], @@ -91,10 +90,14 @@ "source": [ "__Start__\n", "\n", - "Below, we do all the steps we have learned this chapter, making profiles, galaxies, a tracer, etc. \n", + "We begin with a lens galaxy containing an elliptical mass profile and a source galaxy containing two light profiles,\n", + "named `bulge` and `disk`.\n", "\n", - "Note that in this tutorial, we omit the lens galaxy's light and include two light profiles in the source representing a\n", - "`bulge` and `disk`." + "The source profiles share a centre and ellipticity, but have different Sérsic indices. This gives them different radial\n", + "brightness distributions. We omit the lens galaxy's light, so the image produced by this tracer contains only the lensed\n", + "source.\n", + "\n", + "These are specified profiles and parameter values, just as in our earlier examples." ] }, { @@ -139,32 +142,43 @@ "source": [ "__Object Composition__\n", "\n", - "Lets now consider how all of the objects we've covered throughout this chapter (`LightProfile`'s, `MassProfile`'s,\n", - "`Galaxy`'s, `Plane`'s, `Tracer`'s) come together.\n", + "The tracer retains the galaxies and profiles we used to construct it. We can access them by stepping through this\n", + "structure.\n", + "\n", + "`tracer.planes[0]` contains the galaxies at the lens redshift, while `tracer.planes[1]` contains those at the source\n", + "redshift. Each plane contains one galaxy in this example, so `[0]` selects that galaxy.\n", "\n", - "The `Tracer`, which contains planes of `Galaxies`, which contains the `Galaxy`'s which contains the `Profile`'s:" + "We can then use the component names we supplied, such as `.mass`, `.bulge` and `.disk`, to access a particular profile.\n", + "The printed output below follows this sequence from the complete tracer down to its individual profiles." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "print(\"Tracer:\")\n", "print(tracer)\n", - "print()\n", - "print(tracer.planes[0])\n", - "print()\n", - "print(tracer.planes[1])\n", - "print()\n", + "\n", + "print(\"Lens plane:\")\n", "print(tracer.planes[0])\n", - "print()\n", + "\n", + "print(\"Source plane:\")\n", "print(tracer.planes[1])\n", - "print()\n", + "\n", + "print(\"Lens galaxy:\")\n", + "print(tracer.planes[0][0])\n", + "\n", + "print(\"Source galaxy:\")\n", + "print(tracer.planes[1][0])\n", + "\n", + "print(\"Lens mass profile:\")\n", "print(tracer.planes[0][0].mass)\n", - "print()\n", + "\n", + "print(\"Source bulge:\")\n", "print(tracer.planes[1][0].bulge)\n", - "print()\n", - "print(tracer.planes[1][0].disk)\n", - "print()" + "\n", + "print(\"Source disk:\")\n", + "print(tracer.planes[1][0].disk)" ], "outputs": [], "execution_count": null @@ -173,20 +187,23 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Once we have a tracer we can therefore use any of the plotting function objects throughout this chapter to plot\n", - "any specific aspect, whether it be a profile, galaxy, galaxies or tracer. \n", + "First, plot the complete lensed image. The tracer evaluates both source light profiles at the ray-traced coordinates\n", + "and adds their contributions.\n", "\n", - "For example, if we want to plot the image of the source galaxy's bulge and disk, we can do this in a variety of \n", - "different ways." + "We also keep the source-plane coordinates for the next plots. Each coordinate tells us where a ray from an image-plane\n", + "pixel reaches the source plane." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "aplt.plot_array(array=tracer.image_2d_from(grid=grid), title=\"Image\")\n", + "aplt.plot_array(\n", + " array=tracer.image_2d_from(grid=grid),\n", + " title=\"Lensed Source: Bulge + Disk\",\n", + ")\n", "\n", - "source_plane_grid = tracer.traced_grid_2d_list_from(grid=grid)[1]\n" + "source_plane_grid = tracer.traced_grid_2d_list_from(grid=grid)[1]" ], "outputs": [], "execution_count": null @@ -195,13 +212,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Understanding how these objects decompose into the different components of a strong lens is important for general \n", - "**PyAutoLens** use.\n", + "We can now evaluate each source profile separately at those same ray-traced coordinates.\n", "\n", - "As the strong lens systems that we analyse become more complex, it is useful to know how to decompose their light \n", - "profiles, mass profiles, galaxies and planes to extract different pieces of information about the strong lens. For \n", - "example, we made our source-galaxy above with two light profiles, a `bulge` and `disk`. We can plot the lensed image of \n", - "each component individually, now that we know how to break-up the different components of the tracer." + "These plots show the individual **lensed** contributions of the bulge and disk. Although we evaluate their brightness\n", + "at source-plane coordinates, the resulting values remain arranged according to the original image-plane pixels.\n", + "\n", + "Compare the distribution of light in the two images. Their different Sérsic indices change how concentrated the light\n", + "is and how it extends away from the centre. Adding these two images gives the complete lensed source image above.\n", + "\n", + "This is a decomposition of our specified source description. We have not inferred separate bulge and disk components\n", + "from observed data." ] }, { @@ -210,47 +230,52 @@ "source": [ "aplt.plot_array(\n", " array=tracer.planes[1][0].bulge.image_2d_from(grid=source_plane_grid),\n", - " title=\"Bulge Image\",\n", + " title=\"Lensed Bulge\",\n", ")\n", "\n", "aplt.plot_array(\n", " array=tracer.planes[1][0].disk.image_2d_from(grid=source_plane_grid),\n", - " title=\"Disk Image\",\n", + " title=\"Lensed Disk\",\n", ")" ], "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**🤖 Ask AI:** Why does evaluating a source light profile on ray-traced source-plane coordinates produce a lensed image,\n", + "whereas evaluating it on a uniform source-plane grid produces an unlensed image?" + ] + }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Visualization__\n", "\n", - "Furthermore, using the `MatPLot2D` and `lines=`/`positions=` overlays objects we can visualize any aspect we're interested \n", - "in and fully customize the figure. \n", + "We can combine the lensed image with other quantities calculated from the same tracer.\n", "\n", - "Before beginning chapter 2 of **HowToLens**, you should checkout the package `autolens_workspace/plot`. This provides a \n", - "full API reference of every plotting option in **PyAutoLens**, allowing you to create your own fully customized \n", - "figures of strong lenses with minimal effort!" + "Here, we overlay the tangential critical curves introduced earlier in the chapter. Compare their position with the\n", + "bright arcs in the lensed image. The curves depend on the lensing mass distribution and redshifts, while the appearance\n", + "of the arcs also depends on the source's position and light profiles.\n", + "\n", + "The `lines=` argument adds these curves to the image. The plotting examples in `autolens_workspace/plot` show how to\n", + "customise figures and add other overlays as you need them." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "\n", "tangential_critical_curve_list = al.LensCalc.from_tracer(\n", " tracer=tracer\n", ").tangential_critical_curve_list_from(grid=grid)\n", - "radial_critical_curve_list = al.LensCalc.from_tracer(\n", - " tracer=tracer\n", - ").radial_critical_curve_list_from(grid=grid)\n", - "\n", "\n", "aplt.plot_array(\n", " array=tracer.image_2d_from(grid=grid),\n", - " title=\"Tracer Image with Critical Curves\",\n", + " title=\"Lensed Source\\nTangential Critical Curves\",\n", " lines=tangential_critical_curve_list,\n", ")" ], @@ -261,56 +286,66 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "And, we're done, not just with the tutorial, but the chapter!\n", - "\n", "__Code Design__\n", "\n", - "To end, I want to quickly talk about the **PyAutoLens** code-design and structure, which was really the main topic of\n", - "this tutorial.\n", + "The structure we have just explored reflects the physical description of a lens system: profiles belong to galaxies,\n", + "galaxies occupy redshift planes, and a tracer calculates how light travels between those planes.\n", "\n", - "Throughout this chapter, we never talk about anything like it was code. We didn`t refer to 'variables', 'parameters`' \n", - "'functions' or 'dictionaries', did we? Instead, we talked about 'galaxies', 'planes' a 'Tracer', etc. We discussed \n", - "the objects that we, as scientists, think about when we consider a strong lens system.\n", + "This is an example of *object-oriented design*. Each object brings together information about something, such as a\n", + "galaxy, and operations we can perform with it, such as calculating its image.\n", "\n", - "Software that abstracts the underlying code in this way follows an `object-oriented design`, and it is our hope \n", - "with **PyAutoLens** that we've made its interface (often called the API for short) very intuitive, whether you were\n", - "previous familiar with gravitational lensing or a complete newcomer!\n", + "We have used Python variables, parameters and functions throughout this chapter, but their names and organisation let\n", + "us express those operations in familiar scientific terms. For example, `source.bulge` identifies a particular light\n", + "component, while `tracer.image_2d_from(grid=grid)` calculates the image of the complete system.\n", "\n", + "As your analyses become more complex, this same structure lets you add components and inspect their individual\n", + "contributions." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ "__Source Code__\n", "\n", - "If you do enjoy code, variables, functions, and parameters, you may want to dig deeper into the **PyAutoLens** source \n", - "code at some point in the future. Firstly, you should note that all of the code we discuss throughout the **HowToLens** \n", - "lectures is not contained in just one project (e.g. the **PyAutoLens** GitHub repository) but in fact four repositories:\n", + "The tools used in **HowToLens** are provided by four related projects:\n", "\n", - "**PyAutoFit** - Everything required for lens modeling (the topic of chapter 2): https://github.com/PyAutoLabs/PyAutoFit\n", + "- **[PyAutoFit](https://github.com/PyAutoLabs/PyAutoFit)** provides tools for defining models, searching their parameter spaces and analysing inference results. We will use these ideas in Chapter 2.\n", + "- **[PyAutoArray](https://github.com/PyAutoLabs/PyAutoArray)** provides arrays, grids, masks and tools for handling astronomical datasets.\n", + "- **[PyAutoGalaxy](https://github.com/PyAutoLabs/PyAutoGalaxy)** provides light profiles, mass profiles and galaxies.\n", + "- **[PyAutoLens](https://github.com/PyAutoLabs/PyAutoLens)** brings these components together for gravitational lensing, including ray tracing and comparisons with lensing observations.\n", "\n", - "**PyAutoArray** - Handles all data structures and Astronomy dataset objects: https://github.com/PyAutoLabs/PyAutoArray\n", + "You access much of this functionality through `import autolens as al`, so you do not need to work with each repository\n", + "separately to follow the tutorials.\n", "\n", - "**PyAutoGalaxy** - Contains the light profiles, mass profiles and galaxies: https://github.com/PyAutoLabs/PyAutoGalaxy\n", - "\n", - "**PyAutoLens** - Everything strong lensing: https://github.com/PyAutoLabs/PyAutoLens\n", - "\n", - "Instructions on how to build these projects from source are provided here:\n", - "\n", - "https://pyautolens.readthedocs.io/en/latest/installation/source.html\n", - "\n", - "We take a lot of pride in our source code, so I can promise you its well written, well documented and thoroughly \n", - "tested (check out the `test` directory if you're curious how to test code well!).\n", + "If you want to understand how a calculation is implemented, you can explore the source code and its accompanying tests.\n", + "Start with a familiar operation, such as calculating a light-profile image, and follow how its inputs become an output.\n", "\n", + "[Installation from source](https://pyautolens.readthedocs.io/en/latest/installation/source.html) is described in the\n", + "documentation. This is useful if you want to modify or contribute to the libraries; it is optional for continuing\n", + "**HowToLens**." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ "__Wrap Up__\n", "\n", - "You`ve learn a lot in this chapter, but what you have not learnt is how to 'model' a real strong gravitational lens.\n", + "You have now followed the path from a mathematical description of a lens system to a predicted observation and a\n", + "likelihood function that measures its agreement with data.\n", "\n", - "In the real world, we have no idea what the 'correct' combination of light profiles, mass profiles and galaxies are \n", - "that will give a good fit to a lens. Lens modeling is the process of finding the lens model which provides a good fit \n", - "and it is the topic of chapter 2 of **HowToLens**.\n", + "In our simulations, we chose the parameters that generated the observation. For a real lens, those parameters are\n", + "unknown. We must explore which choices describe the data well and what uncertainty remains.\n", "\n", - "Finally, if you enjoyed doing the **HowToLens** tutorials please git us a star on the **PyAutoLens** GitHub\n", - "repository: \n", + "In Tutorial 6, you began this process by changing parameters by hand. Chapter 2 introduces automated lens modelling:\n", + "a search repeatedly evaluates the likelihood function for different parameter choices, helping us infer the properties\n", + "of the lens and source.\n", "\n", - " https://github.com/PyAutoLabs/PyAutoLens\n", + "The profiles, galaxies, tracers and dataset calculations you have learnt here remain the foundation of that process.\n", "\n", - "Even the smallest bit of exposure via a GitHub star can help our project grow!" + "If you have found **HowToLens** useful, you can support the project by starring the\n", + "[PyAutoLens GitHub repository](https://github.com/PyAutoLabs/PyAutoLens)." ] } ], @@ -346,4 +381,4 @@ }, "nbformat": 4, "nbformat_minor": 4 -} \ No newline at end of file +} diff --git a/scripts/chapter_1_introduction/tutorial_5_data.py b/scripts/chapter_1_introduction/tutorial_5_data.py index 0b01c4b..55d81e1 100644 --- a/scripts/chapter_1_introduction/tutorial_5_data.py +++ b/scripts/chapter_1_introduction/tutorial_5_data.py @@ -2,43 +2,33 @@ Tutorial 5: Data ================ -In the last tutorials, we use tracers to create images of strong lenses. However, those images don't accurately -represent what we would observe through a telescope. +In the previous tutorials, we used tracers to create images of strong lenses. +We will now use one of these images to simulate an observation through a telescope. -Real telescope images, like those taken with the Charge Coupled Device (CCD) imaging detectors on the Hubble Space -Telescope, include several factors that affect what we see: +A telescope spreads light over neighbouring pixels, making fine details less +sharp. Its detector collects light for a finite exposure time, and the number +of photons detected fluctuates from one observation to another. Light from the +background sky also contributes to the recorded image. -**Telescope Optics:** The optical components of the telescope can blur the light, influencing the image's sharpness. +We will introduce these effects separately so that you can see what each one +does, then combine them using PyAutoLens's `SimulatorImaging` object. -**Exposure Time:** The time the detector collects light, affecting the clarity of the image. Longer exposure times -gather more light, improving the signal-to-noise ratio and creating a clearer image. - -**Background Sky:** Light from the sky itself, such as distant stars or zodiacal light, adds additional noise to -the image. - -In this tutorial, we'll simulate a strong lens image by applying these real-world effects to the light and mass -profiles and images we created earlier. - -Here is an overview of what we'll cover in this tutorial: - -- **Optics Blurring:** We'll simulate how the telescope optics blur the galaxy's light, making the images appear blurred. -- **Poisson Noise:** We'll add Poisson noise to the image, simulating the randomness in the photon-to-electron conversion process on the CCD. -- **Background Sky:** We'll add a background sky to the image, simulating the light from the sky that adds noise to the image. -- **Simulator:** We'll use the `SimulatorImaging` object to simulate imaging data that includes all these effects. -- **Other Data Types:** We'll finish with a brief look at point-source, interferometer and weak lensing datasets. +Our example uses a charge-coupled device (CCD), a detector that records incoming +light as electrons collected in its pixels. __Contents__ -- **Initial Setup:** To create our simulated strong lens image, we first need a 2D grid. -- **Optics Blurring:** All images captured using CCDs (like those on the Hubble Space Telescope or Euclid) experience some. -- **Poisson Noise:** In addition to the blurring caused by telescope optics, we also need to consider Poisson noise when. -- **Background Sky:** The final effect we will consider when simulating imaging data is the background sky. -- **Simulator:** The `SimulatorImaging` object lets us create simulated imaging data while including the effects of. -- **Output:** We will now save these simulated data to `.fits` files, the standard format used by astronomers for. -- **Point Source Data:** Collect image positions, fluxes and time delays with their uncertainties. -- **Interferometer Data:** Radio / sub-mm interferometers like ALMA observe visibilities in the uv-plane rather than images. -- **Weak Lensing Data:** Weak lensing datasets are catalogues of weakly sheared background galaxy ellipticities. -- **Wrap Up:** Summary of the script and next steps. +- **Initial Setup:** Create the lensed image that we will use for the simulation. +- **Optics Blurring:** Describe the telescope's blurring with a point spread function. +- **Poisson Noise:** Simulate fluctuations in the number of electrons collected. +- **Background Sky:** Include sky light and the additional noise it produces. +- **Simulator:** Combine these effects into an imaging dataset. +- **Output:** Save the data, noise map and point spread function to FITS files. +- **Point Source Data:** Introduce measured positions, fluxes and time delays. +- **Interferometer Data:** Introduce measurements made by radio interferometers. +- **Weak Lensing Data:** Introduce catalogues of background galaxy shapes. +- **Group and Cluster Lenses:** Preview the larger lens systems studied in Chapter 4. +- **Wrap Up:** Review what we have learned. """ @@ -55,29 +45,33 @@ """ __Initial Setup__ -To create our simulated strong lens image, we first need a 2D grid. This grid will represent the coordinate space over -which we will simulate the strong lens's light distribution. +We begin with a grid of 101 x 101 pixels, with each pixel spanning 0.1 arcseconds +on the sky. As in the earlier tutorials, the grid supplies the coordinates at +which we calculate the lensed image. """ 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, ) """ -Next, we define the properties of our strong lens. In this tutorial, we’ll represent the lens with no luminous -emmission and an`Isothermal` mass profile. The source galaxy will be represented by a Sersic light profile. +Our lens galaxy has an `Isothermal` mass profile. We omit its light so that we +can focus on how the observation changes the appearance of the lensed source. +The source galaxy has a Sersic light profile. + +For this simulation, image values represent electrons per second in each pixel. +Multiplying a pixel's value by the exposure time will therefore give the +expected number of electrons collected in that pixel. -In the previous tutorial, the units of `intensity` were arbitrary. However, for this tutorial, where we simulate -realistic imaging data, the intensity must have specific units. We’ll use units of electrons per second per pixel -($e- pix^-1 s^-1$), which is standard for CCD imaging data. +We use the same units for the light profile's `intensity`, which sets its +brightness at the effective radius. """ lens_galaxy = al.Galaxy( redshift=0.5, mass=al.mp.Isothermal( - centre=(0.0, 0.0), einstein_radius=1.6, ell_comps=(0.17647, 0.0) + centre=(0.0, 0.0), + einstein_radius=1.6, + ell_comps=(0.17647, 0.0), ), ) @@ -86,7 +80,7 @@ bulge=al.lp.Sersic( centre=(0.1, 0.1), ell_comps=(0.0, 0.111111), - intensity=1.0, # in units of e- pix^-1 s^-1 + intensity=1.0, # Electrons per second per pixel. effective_radius=1.0, sersic_index=2.5, ), @@ -95,135 +89,165 @@ tracer = al.Tracer(galaxies=[lens_galaxy, source_galaxy]) """ -Lets look at the tracer's image, which is the image we'll be simulating. +First, let's look at the lensed image. The telescope's blurring, background sky +and random noise have not yet been included. +Look at the sharpness of the arcs and the faint light around them. This is our +starting image for seeing how each observational effect changes their appearance. """ aplt.plot_array( - array=tracer.image_2d_from(grid=grid), title="Tracer Image Before Simulating" + array=tracer.image_2d_from(grid=grid), + title="Lensed Image Before Simulating the Observation", ) """ __Optics Blurring__ -All images captured using CCDs (like those on the Hubble Space Telescope or Euclid) experience some level of blurring -due to the optics of the telescope. This blurring occurs because the optical system spreads out the light from each -point source (e.g., a star or a part of a galaxy). +A point source does not appear as a single perfectly sharp point in a telescope +image. The telescope spreads its light over a small region. The shape of this +response is called the point spread function, or PSF. + +An extended image is blurred in the same way: light from every position is +spread according to the PSF. We calculate this using an operation called +convolution. -The Point Spread Function (PSF) describes how the telescope blurs the image. It can be thought of as a 2D representation -of how a single point of light would appear in the image, spread out by the optics. In practice, the PSF is a 2D -convolution kernel that we apply to the image to simulate this blurring effect. +For our example, we will use a circular Gaussian PSF. Its `sigma` is +0.1 arcseconds, equal to one pixel on our grid. A larger sigma would spread the +light over a wider region. + +The PSF is represented by an 11 x 11 array called a kernel. We normalise its +values to sum to one, so that it describes how light is redistributed. """ psf = al.Convolver.from_gaussian( - shape_native=(11, 11), # The size of the PSF kernel, represented as an 11x11 grid. - sigma=0.1, # Controls the width of the Gaussian PSF, which determines the level of blurring. - pixel_scales=grid.pixel_scales, # Maintains consistency with the scale of the image grid. - normalize=True, # Normalizes the PSF kernel so that its values sum to 1. + shape_native=(11, 11), + sigma=0.1, # Arcseconds. + pixel_scales=grid.pixel_scales, + normalize=True, ) """ -We can visualize the PSF to better understand how it will blur the galaxy's image. The PSF is essentially a small -image that represents the spreading out of light from a single point source. This kernel will be used to blur the -entire tracer image when we perform the convolution. +Plotting the kernel shows how the light from a point source is distributed: +the central pixels receive the most light, with progressively less farther +from the centre. """ aplt.plot_array(array=psf.kernel, title="PSF 2D Kernel") """ -The PSF is often more informative when plotted on a log10 scale. This approach allows us to clearly observe values -in its tail, which are much smaller than the central peak yet critical for many scientific analyses. The tail -values may significantly affect the spread and detail captured in the data. -""" -aplt.plot_array(array=psf.kernel, title="PSF 2D Kernel (Log10)", use_log10=True) +The PSF becomes much fainter away from its centre. On the previous plot's linear +colour scale, these faint outer regions can be difficult to see. +A logarithmic colour scale makes them more visible. The kernel values are +unchanged; only the way we display them changes. """ -Next, we'll manually perform a 2D convolution of the PSF with the image of the galaxy. This convolution simulates the -blurring that occurs when the telescope optics spread out the galaxy's light. +aplt.plot_array( + array=psf.kernel, + title="PSF 2D Kernel (Log10)", + use_log10=True, +) -1. **Padding the Image**: Before convolution, we add padding (extra space with zero values) around the edges of the - image. This prevents unwanted edge effects when we perform the convolution, ensuring that the image's edges don't - become artificially altered by the process. +""" +We will now convolve the lensed image with the PSF to calculate how it appears +after the telescope has blurred it. -2. **Convolution**: Using the `Convolver` object's `convolve` method, we apply the 2D PSF convolution to the padded - image. This step combines the PSF with the galaxy's light, simulating how the telescope spreads out the light. +Light just outside the image can be spread into pixels near its edges. To +include this light, we first evaluate the tracer on a larger grid, extending +beyond the region we want to observe. This produces a padded image containing +the model's predicted light in the surrounding pixels. -3. **Trimming the Image**: After convolution, we trim the padded areas back to their original size, obtaining a - convolved (blurred) image that matches the dimensions of the initial tracer image. +We then convolve this larger image with the PSF and trim away the extra border. +The result has the same dimensions as our original image. """ -image = tracer.image_2d_from(grid=grid) # The original unblurred image of the galaxy. +image = tracer.image_2d_from(grid=grid) + padded_image = tracer.padded_image_2d_from( grid=grid, - psf_shape_2d=psf.kernel.shape_native, # Adding padding based on the PSF size. + psf_shape_2d=psf.kernel.shape_native, ) + convolved_image = psf.convolved_image_from( - image=padded_image, blurring_image=None -) # Applying the PSF convolution. + image=padded_image, + blurring_image=None, +) + blurred_image = convolved_image.trimmed_after_convolution_from( kernel_shape=psf.kernel.shape_native -) # Trimming back to the original size. +) """ -We can now plot the original and the blurred images side by side. This allows us to clearly see how the PSF -convolution affects the appearance of the galaxy, making the image appear softer and less sharp. +Compare the lensed image before and after convolution. Look at the narrow +features in the arcs: the PSF spreads their light over neighbouring pixels, +making them less sharp. With our small PSF, the difference may be subtle. + +To make the effect easier to see, change `sigma` in the PSF definition from +0.1 to 0.2 arcseconds. Rerun the PSF definition, convolution and plots below. +You should see stronger blurring in the second image. + +Afterwards, restore `sigma=0.1` and rerun those cells before continuing. """ aplt.plot_array(array=image, title="Tracer Image Before PSF") aplt.plot_array(array=blurred_image, title="Tracer Image After PSF") +""" +**🤖 Ask AI:** How does blurring by a telescope's PSF affect our ability to +distinguish two nearby features in a gravitationally lensed arc? +""" """ __Poisson Noise__ -In addition to the blurring caused by telescope optics, we also need to consider Poisson noise when simulating imaging -data. +Even if a galaxy's brightness remains constant, repeated observations do not +collect exactly the same number of photons in each pixel. Photon arrivals +fluctuate randomly, and the detector records these arrivals as electrons. -When a telescope captures an image of a galaxy, photons from the galaxy are collected by the telescope's mirror and -directed onto a CCD (Charge-Coupled Device). The CCD is made up of a silicon lattice (or another material) that -converts incoming photons into electrons. These electrons are then gathered into discrete squares, which form the -pixels of the final image. +For this simulation, we describe the number of electrons collected in each +pixel using a Poisson distribution. Its mean is the expected electron count. +Drawing a value from this distribution gives one possible observed count, +which can be above or below that expectation. -The process of converting photons into electrons is inherently random, following a Poisson distribution. This randomness -means that the number of electrons in each pixel can vary, even if the same number of photons hits the CCD. Therefore, -the electron count per pixel becomes a Poisson random variable. For our simulation, this means that the recorded -number of photons in each pixel will differ slightly from the true number due to this randomness. +Our blurred image gives the expected electron rate in each pixel. Multiplying +it by an exposure time of 300 seconds gives the expected counts for that +exposure. We use these counts as the means of the Poisson distributions. -To replicate this effect in our simulation, we can add Poisson noise to the tracer image using NumPy’s random module, -which generates values from a Poisson distribution. +The telescope spreads the light before the detector collects it, so we draw +the counts from the blurred image. -It's important to note that the blurring caused by the telescope optics occurs before the photons reach the CCD. -Therefore, we need to add the Poisson noise after blurring the tracer image. +Finally, we divide the randomly drawn counts by the exposure time to return +the image to electrons per second per pixel. +""" +exposure_time = 300.0 # Seconds. -We also need to consider the units of our image data. Let’s assume that the tracer image is measured in units of -electrons per second ($e^- s^{-1}$), which is standard for CCD imaging data. To simulate the number of electrons -actually detected in each pixel, we multiply the image by the observation’s exposure time. This conversion changes -the units to the total number of electrons collected per pixel over the entire exposure time. +blurred_image_counts = blurred_image * exposure_time -Once the image is converted, we add Poisson noise, simulating the randomness in the photon-to-electron conversion -process. After adding the noise, we convert the image back to units of electrons per second for analysis, as -this is the preferred unit for astronomers when studying their data. -""" -exposure_time = 300.0 # Units of seconds -blurred_image_counts = ( - blurred_image * exposure_time -) # Convert to total electrons detected over the exposure time. blurred_image_with_poisson_noise = ( - np.random.poisson(blurred_image_counts, blurred_image_counts.shape) / exposure_time -) # Add Poisson noise and convert back to electrons per second. + np.random.poisson(blurred_image_counts, blurred_image_counts.shape) + / exposure_time +) """ -Here is what the blurred image with Poisson noise looks like. +Let's plot the resulting image. It contains the same lensed structure as +before, with random fluctuations around the expected brightness in each pixel. +These fluctuations may be difficult to distinguish at this display scale. """ aplt.plot_array( - array=aa.Array2D(values=blurred_image_with_poisson_noise, mask=blurred_image.mask), + array=aa.Array2D( + values=blurred_image_with_poisson_noise, + mask=blurred_image.mask, + ), title="Image With Poisson Noise", ) """ -It is challenging to see the Poisson noise directly in the image above, as it is often subtle. To make the noise more -visible, we can subtract the blurred image without Poisson noise from the one with noise. +We can isolate the fluctuations by subtracting the expected blurred image from +the simulated observation. -This subtraction yields the "Poisson noise realization" which highlights the variation in each pixel due to the Poisson -distribution of photons hitting the CCD. It represents the noise values that were added to each pixel. We call -it the realization because it is one possible outcome of the Poisson process, and the noise will be different each time -we simulate the image. +This difference is called a noise realisation: one particular outcome of the +random process. Positive values indicate pixels that collected more electrons +than expected; negative values indicate pixels that collected fewer. + +Rerunning the Poisson draw produces a different realisation. We can calculate +the exact difference here because we know the image used to generate the +simulation. For a real observation, that underlying image is unknown. """ poisson_noise_realization = blurred_image_with_poisson_noise - blurred_image @@ -235,61 +259,79 @@ """ __Background Sky__ -The final effect we will consider when simulating imaging data is the background sky. - -In addition to light from the strong lens, the telescope also picks up light from the sky. This background sky light is -primarily due to two sources: zodiacal light, which is light scattered by interplanetary dust in the solar system, -and the unresolved emission from distant stars and galaxies. +The telescope collects light from the surrounding sky as well as from the +strong lens. Sources of this background include sunlight scattered by dust +in the Solar System, known as zodiacal light, and unresolved distant objects. -For our simulation, we'll assume that the background sky has a uniform brightness across the image, measured at -0.1 electrons per second per pixel. The background sky is added to the image before applying the PSF convolution -and adding Poisson noise. This is important because it means that the background contributes additional noise to the -image. +We will represent the background as a uniform brightness of 0.1 electrons +per second per pixel. We add this to the blurred lensed image before drawing +the Poisson counts, so that both the source and sky contribute to the noise. -The background sky introduces noise throughout the entire image, including areas where the strong lens is not present. -This is why CCD images often appear noisy, especially in regions far from where the strong lens signal is detected. -The sky noise can make it more challenging to observe faint details of the lens and source galaxies. +A uniform background remains uniform when convolved with a normalised PSF, +so we can add it after blurring the lensed image. -To simulate this, we add a constant background sky to the tracer image and then apply Poisson noise to create the -final simulated image as it would appear through a telescope. +Even where the source contributes very little light, sky photons are still +collected. Their fluctuating counts make faint features harder to distinguish. """ background_sky_level = 0.1 -# Add background sky to the blurred tracer image. blurred_image_with_sky = blurred_image + background_sky_level blurred_image_with_sky_counts = blurred_image_with_sky * exposure_time -# Apply Poisson noise to the image with the background sky. blurred_image_with_sky_poisson_noise = ( np.random.poisson( - blurred_image_with_sky_counts, blurred_image_with_sky_counts.shape + blurred_image_with_sky_counts, + blurred_image_with_sky_counts.shape, ) / exposure_time ) -# Visualize the image with background sky and Poisson noise. +""" +This image includes the mean sky brightness as well as the random fluctuations +in the collected counts. Regions away from the lensed source therefore have +a background level around which their pixel values fluctuate. +""" aplt.plot_array( array=aa.Array2D( - values=blurred_image_with_sky_poisson_noise, mask=blurred_image.mask + values=blurred_image_with_sky_poisson_noise, + mask=blurred_image.mask, ), title="Image With Background Sky", ) -# Create a noise map showing the differences between the blurred image with and without noise. +""" +Subtracting the expected source-plus-sky image isolates the noise realisation. +Look for fluctuations even in regions where the lensed source is faint: +the background sky contributes noise there too. +""" poisson_noise_realization = ( blurred_image_with_sky_poisson_noise - blurred_image_with_sky ) aplt.plot_array( - array=aa.Array2D(values=poisson_noise_realization, mask=blurred_image.mask), + array=aa.Array2D( + values=poisson_noise_realization, + mask=blurred_image.mask, + ), title="Poisson Noise Realization", ) """ __Simulator__ -The `SimulatorImaging` object lets us create simulated imaging data while including the effects of PSF blurring, -Poisson noise, and background sky all at once: +We have now built up the observation one step at a time. The `SimulatorImaging` +object combines these steps: it blurs the lensed image with the PSF, adds the +background sky and draws the Poisson counts for the chosen exposure time. + +By default, it also subtracts the mean background sky level from the resulting +image. This represents an observation whose background has been removed during +data processing. + +Subtracting the mean sky level does not remove the random fluctuations caused +by sky photons. That noise remains in the image. + +The simulator returns an `Imaging` dataset containing the simulated image, +the PSF and a noise map. We will inspect each of these below. """ simulator = al.SimulatorImaging( exposure_time=300.0, @@ -301,69 +343,120 @@ dataset = simulator.via_tracer_from(tracer=tracer, grid=grid) """ -By plotting the `data` from the dataset, we can see that it matches the image we simulated earlier. It includes -the effects of PSF blurring, Poisson noise, and noise from the background sky. This image is a realistic -approximation of what a telescope like the Hubble Space Telescope would capture. +The dataset's `data` contains the simulated observation, in electrons per +second per pixel. + +It shows the same lensed structure as our manual simulation, but uses a new +noise realisation and has the mean sky level subtracted. Pixels far from the +source should therefore fluctuate around zero. Some can be negative: after +sky subtraction, a pixel that collected fewer sky photons than expected can +have a negative value. + +These negative values do not represent negative light. They arise from +subtracting the estimated background from a noisy measurement. """ aplt.plot_array(array=dataset.data, title="Simulated Imaging Data") """ -The dataset also includes the `psf` (Point Spread Function) used to blur the strong lens image. +**🤖 Ask AI:** Why does subtracting the mean background sky from an astronomical +image leave the sky's Poisson noise behind? +""" -For actual telescope data, the PSF is determined during data processing and is provided along with the observations. -It's crucial for accurately deconvolving the PSF from the strong lens image, allowing us to recover the true properties -of the strong lens. We'll explore this further in the next tutorial. +""" +The dataset also stores the PSF used to simulate the observation. + +For real observations, we need an estimate of the PSF, which can come from +stars in the image or a model of the instrument. + +When comparing a lens model with the data, we blur its predicted image using +this PSF. This lets us compare the model and observation at the same resolution. +The next tutorial will show this comparison in practice. """ aplt.plot_array(array=dataset.psf.kernel, title="Simulated PSF") """ -The dataset includes a `noise_map`, which represents the Root Mean Square (RMS) standard deviation of the noise -estimated for each pixel in the image. Higher noise values mean that the measurements in those pixels are -less certain, so those pixels are given less weight when analyzing the data. +The `noise_map` gives an estimated standard deviation for each pixel, in the +same units as the data. It describes the typical size of the random +fluctuations expected in that pixel. + +This is different from the noise realisation we plotted earlier. A realisation +records the particular positive or negative fluctuation drawn for each pixel; +the noise map describes the scale of those fluctuations. + +For Poisson counts, the standard deviation is the square root of the expected +number of counts. The simulator estimates this using the simulated counts +before sky subtraction, then divides by the exposure time to return to +electrons per second per pixel. -This `noise_map` is different from the Poisson noise arrays we plotted earlier. The Poisson noise arrays show the -actual noise added to the image due to the random nature of photon-to-electron conversion on the CCD, as calculated -using the numpy random module. These noise values are theoretical and cannot be directly measured in real telescope data. +The noise map therefore includes contributions from both the source and sky, +even though the mean sky level has been removed from the data. -In contrast, the `noise_map` is our best estimate of the noise present in the image, derived from the data itself -and used in the fitting process. +Look for larger noise values in the bright arcs, where more photons are +collected, and a background noise level elsewhere. More collected photons +produce larger absolute count fluctuations, but smaller fluctuations relative +to their mean. + +In the next tutorial, the noise map will set the scale against which we judge +differences between the model image and the data. """ aplt.plot_array(array=dataset.noise_map, title="Simulated Noise Map") """ -The `signal-to-noise_map` shows the ratio of the signal in each pixel to the noise level in that pixel. It is -calculated by dividing the `data` by the `noise_map`. +The `signal_to_noise_map` compares each pixel's measured brightness with its +estimated noise level. It is calculated by dividing `data` by `noise_map`, +giving a dimensionless ratio. + +For example, a value of 5 means that the pixel's measured brightness is five +times its estimated noise standard deviation. Look for high values along the +bright arcs and lower values where the source is faint. -This ratio helps us understand how much of the observed signal is reliable compared to the noise, allowing us to -see where we can trust the detected signal from the strong lens and where the noise is more significant. +PyAutoLens sets negative ratios to zero in this map. The negative values in +the background-subtracted data are still present in `dataset.data`; this +operation only affects the signal-to-noise map. -In general, a signal-to-noise ratio greater than 3 indicates that the signal is likely real and not overwhelmed by -noise. For our datasets, the signal-to-noise ratio peaks at ~70, meaning we can trust the signal detected in the -image. +A high value indicates that a pixel stands out relative to its estimated +noise. A single threshold does not, by itself, establish that a feature is +real: its spatial structure and the properties of the noise also matter. """ -aplt.plot_array(array=dataset.signal_to_noise_map, title="Signal-To-Noise Map") +aplt.plot_array( + array=dataset.signal_to_noise_map, + title="Signal-To-Noise Map", +) """ -The `aplt.subplot_imaging_dataset` object can display all of these components together, making it a powerful tool for visualizing -simulated imaging data. +We can display the dataset's main components together using +`aplt.subplot_imaging_dataset`. + +Compare the data, noise map and signal-to-noise map. The bright arcs have +larger absolute noise than the faint background, but they also have a stronger +signal relative to that noise. -It also shows the Data and PSF on a logarithmic (log10) scale, which helps highlight the faint details in these -components. +The figure includes logarithmic views of the data and PSF to help show faint +structure. These change how the values are displayed, not the underlying data. -The "Over Sampling" plots on the bottom of the figures display advanced features that can be ignored for now. +Any panels labelled "Over Sample Size" describe how finely the model is +evaluated within pixels. We can leave these numerical settings aside here. """ aplt.subplot_imaging_dataset(dataset=dataset) """ __Output__ -We will now save these simulated data to `.fits` files, the standard format used by astronomers for storing images. -Most imaging data from telescopes like the Hubble Space Telescope (HST) are stored in this format. +We will save the simulated imaging dataset in FITS format, which is widely +used in astronomy for images and related data. + +The files contain: -The `dataset_path` specifies where the data will be saved, in this case the `dataset/imaging/howtolens/` -directory of the HowToLens repository (paths are relative to the repository root, from which scripts are run). +- `data.fits`: the simulated image after subtraction of the mean sky level. +- `noise_map.fits`: the estimated noise standard deviation in each pixel. +- `psf.fits`: the PSF kernel used to blur the image. -The files are named `data.fits`, `noise_map.fits`, and `psf.fits`, and will be used in the next tutorial. +They are written to `dataset/imaging/howtolens/`, relative to the repository +root from which this script is run. The next tutorial will load these files +and compare the data with a lens model. + +With `overwrite=True`, rerunning this cell replaces any existing files with +these names. """ dataset_path = Path("dataset") / "imaging" / "howtolens" print("Dataset Path: ", dataset_path) @@ -379,14 +472,24 @@ """ __Point Source Data__ -In Tutorial 4, we predicted the positions of a point source's multiple images. For real observations, we measure -these positions from the telescope image, accounting for its blurring and the foreground galaxy's light. Each -position also has an uncertainty. +In Tutorial 4, we predicted the positions of a point source's multiple images. +For an observed lens, we can measure these positions from the telescope image, +accounting for the PSF and light from the foreground galaxy. Each measured +position has an uncertainty. + +A `PointDataset` stores these measurements for analysis. It can also +include the images' fluxes and, for a variable source, the time delays between +them. Time delays are measured by monitoring how the source's variations +appear at different times in its multiple images. -A `PointDataset` collects these measurements for lens modelling. The illustrative values below are rounded from -Tutorial 4's predictions, rather than measured from observations. We include positions in arcseconds, fluxes in -arbitrary units and time delays in days relative to the first image, with assumed uncertainties of 0.01 arcseconds, -about 10 per cent in flux and one day in delay. +The example below uses values rounded from Tutorial 4's predictions, with +assumed measurement uncertainties. These are illustrative data, not +measurements from a real observation. + +Positions are in arcseconds, fluxes are in arbitrary units and time delays +are in days relative to the first image. We assume positional uncertainties +of 0.01 arcseconds, flux uncertainties of about 10 per cent and time-delay +uncertainties of one day. """ point_dataset = al.PointDataset( name="point_0", @@ -406,39 +509,57 @@ print(point_dataset.info) """ -The positions use `(y, x)` coordinates, and every list follows the same image order. Negative delays mean that -an image arrives before the first image. The name `point_0` matches the point-source component introduced in -Tutorial 4, connecting these measurements to that source when fitting a model. +We can also display the point-source dataset as a subplot. The positions panel +shows where the multiple images lie, while the flux panel compares their +brightnesses. The time delays remain available in the printed summary. +""" +aplt.subplot_point_dataset(dataset=point_dataset) + +""" +Inspect the printed dataset summary. Positions use `(y, x)` coordinates, and +the position, flux and time-delay lists all follow the same image order. + +The first image defines the zero of the time delays. A negative delay means +that the corresponding image arrives before this reference image. The zero +entry is a reference choice, not an independently measured delay. -Fluxes and time delays are optional: positions alone are enough to begin modelling. For more on loading and -fitting these datasets, continue to the workspace's +The name `point_0` identifies the source associated with these measurements, +matching the point-source component introduced in Tutorial 4. + +Fluxes and time delays are optional: a dataset can contain only positions +and their uncertainties. For further examples of working with these data, +see the workspace's [point-source examples](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/point_source/start_here.py). +""" +""" __Interferometer Data__ -CCD imaging is not the only type of data used to study strong lenses. Radio and sub-mm interferometers, like the -Atacama Large Millimeter Array (ALMA) and the Jansky Very Large Array (JVLA), observe strong lenses at wavelengths -where a CCD cannot. +We can also observe strong lenses at radio and submillimetre wavelengths using +interferometers, such as the Atacama Large Millimeter/submillimeter Array +(ALMA) and the Jansky Very Large Array (JVLA). + +An interferometer combines signals from pairs of antennas. Each pair measures +a quantity called a visibility, which contains information about the sky's +brightness on a particular angular scale and orientation. -An interferometer does not observe an image of the lens. Each pair of antennas in the array measures a "visibility", -a Fourier component of the sky brightness, at a point in what is called the "uv-plane" set by the separation of the -two antennas. The dataset is therefore a set of complex visibilities in Fourier space, not a 2D image, and its -noise properties are very different from those of CCD data — there is no PSF convolution, Poisson noise or -background sky; instead each visibility has Gaussian noise. +Visibilities are complex numbers, with real and imaginary components. They +sample the Fourier transform of the sky brightness at coordinates in the +"uv-plane". These coordinates depend on the antennas' projected separation +and the observing wavelength. -One could Fourier transform the visibilities into an image (called a "dirty image") and fit that, but the transform -correlates the noise between pixels, making the fit statistically incorrect. **PyAutoLens** therefore fits lens -models directly in visibility space: the tracer's image is evaluated in real space on a grid (defined by a -real-space mask), Fourier transformed to the uv-plane and compared with the observed visibilities there. +An interferometer dataset therefore contains visibilities, their uncertainties +and their uv coordinates. In our simulated example, the noise in the real and +imaginary components is described by Gaussian distributions. -Below, we load a simulated interferometer dataset (creating it first via the `scripts/simulator/interferometer.py` -script if it does not exist on your hard-disk, using the same auto-simulation idiom as later tutorials) and plot -its dirty images — the closest an interferometer dataset comes to the CCD images we simulated above. +We can transform the sampled visibilities into a picture called a "dirty +image". Incomplete sampling produces an instrumental response called the +"dirty beam", which can introduce structure around bright emission. The +transformation also correlates the noise between image pixels. -HowToLens will not cover interferometry any further than this. The lecture series teaches lensing using CCD -imaging, and everything you learn transfers to visibility-space fitting. If you need to model interferometer data, -go to the `autolens_workspace/scripts/interferometer` package, which is the dedicated resource for uv-plane lens -modeling. +Below, we load a simulated dataset, creating it first if needed, and display +its dirty-image diagnostics. The circular real-space mask defines the region +of sky used for these images. """ dataset_path = Path("dataset") / "interferometer" / "simple" @@ -467,25 +588,37 @@ aplt.subplot_interferometer_dirty_images(dataset=dataset) +""" +Look for the lensed emission in the dirty image. Its appearance reflects both +the sky brightness and the interferometer's sampling, so surrounding structure +need not correspond to additional emission on the sky. + +The dataset retains the visibilities for analysis. For further examples of +working with these data, see the workspace's +[interferometer examples](https://github.com/PyAutoLabs/autolens_workspace/tree/main/scripts/interferometer). +""" + """ __Weak Lensing Data__ -There is one more type of lensing data to glimpse before we move on: weak lensing. +Away from the prominent arcs and rings, gravitational lensing can produce +small, coherent changes in the apparent shapes of background galaxies. This +is the weak-lensing regime. -A weak lensing dataset looks nothing like the images above. Instead of the spectacular arcs and rings of strong -lensing, it is a *catalogue* of many background galaxies, each with a measured ellipticity — a shear — at its -(y, x) position on the sky. Each galaxy is only weakly sheared by the foreground mass, a distortion far too small -to see in any single galaxy, and the plot below shows this: a field of short line segments tracing the subtle, -coherent stretching of the background galaxy population, rather than any arc-like feature. +Galaxies already have different shapes and orientations before they are +lensed. An individual galaxy's measured ellipticity therefore does not tell +us the lensing distortion on its own. We use measurements from many galaxies +to identify the shared distortion, called shear. -We load a simulated weak lensing shear catalogue (again auto-simulating it, via `scripts/simulator/weak_lensing.py`, -if it is not on your hard-disk) and plot it, just so you have seen what this data looks like. +For analysis, these measurements can be collected into a catalogue containing +sky positions, estimates of the two shear components and their uncertainties. -That is deliberately all we will say for now — this glimpse is foreshadowing. Weak lensing gets a full treatment in -the final tutorial of chapter 4, which describes what these shear measurements are, why they are made far from the -lens centre and how they are fitted; until then, we defer all further description to that tutorial. For worked -modelling examples, see the workspace -[weak-lensing examples](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/start_here.py). +The simulated example below evaluates the shear around a cluster-scale lens +and adds random scatter to represent the variation in galaxies' intrinsic +shapes. It creates a noisy shear catalogue directly, rather than measuring +galaxy shapes from simulated telescope images. + +We load this catalogue, creating it first if needed, and plot its contents. """ dataset_path = Path("dataset") / "weak_lensing" / "simple" @@ -503,27 +636,108 @@ aplt.subplot_weak_dataset(dataset=dataset) """ -__Wrap Up__ +The short line segments represent the orientations and strengths of the noisy +shear estimates at the background galaxies' positions. Individual segments +can differ substantially from the underlying lensing pattern because of the +added shape noise. -In this tutorial, you learned how CCD imaging data of a lens is collected using real telescopes like the -Hubble Space Telescope, and how to simulate this data using the `SimulatorImaging` object. +Chapter 4 returns to weak lensing in more detail. For further examples of +working with these data, see the workspace's +[weak-lensing examples](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/start_here.py). +""" -Let's summarise what we've covered: +""" +__Group and Cluster Lenses__ + +Strong lensing also occurs around groups and clusters of galaxies. Their +member galaxies and shared dark matter contribute to the deflection of light, +producing lens systems that can extend over much larger angles on the sky. + +We will study these objects in Chapter 4. For now, let's look at the simulated +imaging datasets used in its group-scale and cluster-scale tutorials. As above, +each dataset is created if needed and displayed with its imaging subplot. + +The group example contains a central galaxy and two member galaxies, together +with a lensed background source. Compare the angular scale of its arcs with +our earlier galaxy-scale example. +""" +group_dataset_path = Path("dataset") / "group" / "simple" + +if al.util.dataset.should_simulate(str(group_dataset_path)): + import subprocess + import sys + + subprocess.run( + [sys.executable, "scripts/simulator/group.py"], + check=True, + ) + +group_dataset = al.Imaging.from_fits( + data_path=group_dataset_path / "data.fits", + noise_map_path=group_dataset_path / "noise_map.fits", + psf_path=group_dataset_path / "psf.fits", + pixel_scales=0.1, +) + +aplt.subplot_imaging_dataset(dataset=group_dataset, title_prefix="Group Lens") + +""" +The cluster example contains more member galaxies, a cluster-scale dark matter +halo and two background sources at different redshifts. Look for the member +galaxies and lensed features across its wider field. Use the coordinate axes +to compare angular sizes, since the figures are displayed at similar sizes +on the page. + +Chapter 4's group-scale and cluster-scale tutorials return to these same +simulated systems and explain how to analyse them. +""" +cluster_dataset_path = Path("dataset") / "cluster" / "simple" + +if al.util.dataset.should_simulate(str(cluster_dataset_path)): + import os + import subprocess + import sys + + subprocess.run( + [sys.executable, "scripts/simulator/cluster.py"], + check=True, + # The tutorial plots the dataset below; skip the simulator's extra figures. + env={**os.environ, "PYAUTO_FAST_PLOTS": "1"}, + ) + +cluster_dataset = al.Imaging.from_fits( + data_path=cluster_dataset_path / "data.fits", + noise_map_path=cluster_dataset_path / "noise_map.fits", + psf_path=cluster_dataset_path / "psf.fits", + pixel_scales=0.2, +) + +aplt.subplot_imaging_dataset(dataset=cluster_dataset, title_prefix="Cluster Lens") + +""" +__Wrap Up__ -- **Optics Blurring**: The optics of a telescope blur the light of the tracer, reducing the clarity and sharpness of -the images. +We began with a lensed image and turned it into a simulated telescope +observation. Along the way, we introduced: -- **Poisson Noise**: The process of converting photons to electrons on a CCD introduces Poisson noise, which is random -variability in the number of electrons collected in each pixel. +- **PSF blurring:** The telescope spreads light over neighbouring pixels. +- **Poisson noise:** The detected counts fluctuate around their expected values. +- **Background sky:** Sky photons contribute both a background level and noise. + Subtracting the mean background leaves its noise behind. +- **Imaging datasets:** The `SimulatorImaging` object returns the data, PSF and + noise map, which we saved to FITS files. -- **Background Sky**: Light from the sky is captured along with light from the lens, adding a layer of noise across -the entire image. +We also saw how other observations are represented for analysis: -- **Simulator**: The `SimulatorImaging` object enables us to simulate realistic imaging data by including all of -these effects together and contains the `data`, `psf`, and `noise_map` components. +- **Point sources:** Image positions and their uncertainties, with optional + fluxes and time delays. +- **Interferometry:** Complex visibilities, their uncertainties and uv coordinates. +- **Weak lensing:** A catalogue of positions, shear estimates and uncertainties. -- **Output**: We saved the simulated data to `.fits` files, the standard format used by astronomers for storing images. +Finally, we previewed the group-scale and cluster-scale lenses studied in +Chapter 4, displaying their imaging datasets alongside the galaxy-scale example. -- **Point Source Data**: A `PointDataset` collects image positions and their uncertainties, with optional fluxes -and time delays, ready for point-source modelling. +The next tutorial returns to our simulated imaging dataset and examines how +to compare a predicted image with the data, taking account of the PSF and +noise map. """ diff --git a/scripts/chapter_1_introduction/tutorial_6_fitting.py b/scripts/chapter_1_introduction/tutorial_6_fitting.py index 376ea4e..6f57aed 100644 --- a/scripts/chapter_1_introduction/tutorial_6_fitting.py +++ b/scripts/chapter_1_introduction/tutorial_6_fitting.py @@ -2,46 +2,38 @@ Tutorial 6: Fitting =================== -In previous tutorials, we used light profiles to create simulated images of a tracer and visualized how these images -would appear when captured by a CCD detector on a telescope like the Hubble Space Telescope. - -However, this simulation process is the reverse of what astronomers typically do when analyzing real data. Usually, -astronomers start with an observation—an actual image of a strong lens - and aim to infer detailed information about the -lens’s properties, such as its mass and unlensed source properties. - -To achieve this, we must fit the observed image data with a model, identifying the combination of light and mass -profiles that best matches the lens's appearance in the image. In this tutorial, we'll illustrate this process using -the imaging data simulated in the previous tutorial. Our goal is to demonstrate how we can recover the parameters of -the light profiles that we used to create the original simulation, as a proof of concept for the fitting procedure. - -The process of fitting data introduces essential statistical concepts like the `model`, `residual_map`, `chi-squared`, -`likelihood`, and `noise_map`. These terms are crucial for understanding how fitting works, not only in astronomy but -also in any scientific field that involves data modeling. This tutorial will provide a detailed introduction to these -concepts and show how they are applied in practice to analyze astronomical data. - -Here is an overview of what we'll cover in this tutorial: - -- **Dataset**: Load the imaging dataset that we previously simulated, consisting of the image, noise map, and PSF. -- **Mask**: Apply a mask to the data, excluding regions with low signal-to-noise ratios from the analysis. -- **Masked Grid**: Create a masked grid, which contains only the coordinates of unmasked pixels, to evaluate the - galaxy's light profile in only unmasked regions. -- **Fitting**: Fit the data with a galaxy model, computing key quantities like the model image, residuals, - chi-squared, and log likelihood to assess the quality of the fit. -- **Bad Fits**: Demonstrate how even small deviations from the true parameters can significantly impact the fit. -- **Model Fitting**: Perform a basic model fit on a simple dataset, adjusting the model parameters to improve the - fit quality. +In the previous tutorial, we chose a lens and source, predicted their lensed +image and simulated a telescope observation. We will now work in the other +direction: starting with an image, we want to learn about the objects that +produced it. -__Contents__ +A lens model is a mathematical description of the lens and source. Its +parameters specify properties such as the lens's mass distribution and the +source's position, size and brightness. + +To assess a model, we calculate the image it predicts and compare that +prediction with the data. We account for the telescope's blurring and the +uncertainty in each pixel, so that differences are judged relative to the +noise. + +We will first evaluate a model using the parameters that generated our +simulated data. We will then change those parameters and inspect how the +agreement changes. Finally, you will try adjusting parameters yourself. -- **Dataset:** Load the imaging dataset that we previously simulated, consisting of the image, noise map, and PSF. -- **Dataset Auto-Simulation:** Create the dataset by running the tutorial 5 script if it is not on your hard-disk. -- **Mask:** Apply a mask to the data, excluding regions with low signal-to-noise ratios from the analysis. -- **Masked Grid:** In tutorials 1 and 2, we emphasized that the `Grid2D` object is crucial for evaluating a lens's. -- **Fitting:** Fit the lens model to the dataset and inspect the results. -- **Incorrect Fit:** In the previous section, we successfully created and fitted a lens model to the image data. -- **Model Fitting:** In the previous sections, we used the true model to fit the data, which resulted in a high log. -- **Wrap Up:** Summary of the script and next steps. +This introduces model fitting: finding parameter values that describe the +data well. Creating a `FitImaging` object evaluates the parameters we supply; +it does not search for new values automatically. + +__Contents__ +- **Dataset:** Locate the imaging data saved in Tutorial 5. +- **Dataset Auto-Simulation:** Create the dataset if needed, then load it. +- **Mask:** Select the region of the image used in the comparison. +- **Masked Grid:** Inspect the coordinates of the selected pixels. +- **Fitting:** Compare a predicted image with the data and calculate fit statistics. +- **Incorrect Fit:** See how changing the source position affects the comparison. +- **Model Fitting:** Experiment with adjusting parameters yourself. +- **Likelihood Function:** Combine the calculation into a function of the model parameters. """ from autolens import jax_wrapper # Sets JAX environment before other imports @@ -56,23 +48,21 @@ """ __Dataset__ -We begin by loading the imaging dataset that we will use for fitting in this tutorial. This dataset is identical to the -one we simulated in the previous tutorial, representing how a lens would appear if captured by a CCD camera. +We will use the simulated imaging dataset saved in Tutorial 5. It contains +the background-subtracted image, its noise map and the PSF. -In the previous tutorial, we saved this dataset as .fits files in the `dataset/imaging/howtolens` folder of the -HowToLens repository. The `.fits` format is commonly used in astronomy for storing image data along with metadata, -making it a standard for CCD imaging. - -The `dataset_path` below specifies where these files are located: `dataset/imaging/howtolens/`. +The files are in `dataset/imaging/howtolens/`, relative to the repository root +from which this script is run. """ dataset_path = Path("dataset") / "imaging" / "howtolens" """ __Dataset Auto-Simulation__ -The `howtolens` dataset is the one built up and saved in tutorial 5 (`tutorial_5_data.py`). If it does -not already exist on your system, it is created by running that script. This ensures every example -script can be run without manually simulating data first. +If the dataset is missing, the following code runs Tutorial 5 to create it. +If you have already run that tutorial, we load the saved files. + +The pixel scale is 0.1 arcseconds, matching the simulation. """ if al.util.dataset.should_simulate(str(dataset_path)): import subprocess @@ -91,18 +81,18 @@ ) """ -The `Imaging` object contains three key components: `data`, `noise_map`, and `psf`: +Recall the three components of an imaging dataset: -- `data`: The actual image of the lens, which we will analyze. +- `data`: the measured brightness in each pixel. +- `noise_map`: the estimated noise standard deviation in each pixel. +- `psf`: the kernel describing how the telescope spreads light. -- `noise_map`: A map indicating the uncertainty or noise level in each pixel of the image, reflecting how much the - observed signal in each pixel might fluctuate due to instrumental or background noise. - -- `psf`: The Point Spread Function, which describes how a point source of light is spread out in the image by the - telescope's optics. It characterizes the blurring effect introduced by the instrument. +The data and noise map have the same units. The PSF kernel is normalised +to sum to one. -Let's print some values from these components and plot a summary of the dataset to refresh our understanding of the -imaging data. +Below, we print the first value in each array and display the dataset. +The first image pixel and first noise-map pixel refer to the same sky +position; the first PSF value belongs to the separate, smaller kernel. """ print("Value of first pixel in imaging data:") print(dataset.data.native[0, 0]) @@ -116,148 +106,165 @@ """ __Mask__ -The signal-to-noise map of the image highlights areas where the signal (light from the lens and source galaxies) -is detected above the background noise. Values above 3.0 indicate regions where the light is detected with a -signal-to-noise ratio of at least 3, while values below 3.0 are dominated by noise, where the light is not -clearly distinguishable. +A mask selects which pixels we include when comparing the model with the data. +It can exclude unrelated objects, detector defects or regions outside the +area we want to analyse. -To ensure the fitting process focuses only on meaningful data, we typically mask out regions with low signal-to-noise -ratios, removing areas dominated by noise from the analysis. This allows the fitting process to concentrate on the -regions where the lens is clearly detected. +For this example, we keep a circular region with a radius of 3 arcseconds, +centred on the lens. This includes the lensed arcs and some surrounding sky. -Here, we create a `Mask2D` to exclude certain regions of the image from the analysis. The mask defines which parts of -the image will be used during the fitting process. +We do not select individual pixels according to their measured +signal-to-noise ratio. Faint pixels still contain useful information: a model +that predicts bright emission where little is observed should disagree with +those data. The noise map determines how strongly each pixel contributes to +the comparison. -For our simulated image, a circular 3" mask centered at the center of the image is appropriate, since the simulated -lens was positioned at the center. +In a `Mask2D`, `True` means excluded and `False` means included. """ mask = al.Mask2D.circular( shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, - radius=3.0, # The circular mask's radius in arc-seconds - centre=(0.0, 0.0), # center of the image which is also the center of the lens + radius=3.0, # Arcseconds. + centre=(0.0, 0.0), ) -print(mask) # 1 = True, meaning the pixel is masked. Edge pixels are indeed masked. -print(mask[48:53, 48:53]) # Central pixels are `False` and therefore unmasked. +print(mask) +print(mask[48:53, 48:53]) """ -We can visualize the mask over the strong lens image using an `aplt.subplot_imaging_dataset`, which helps us adjust the mask as needed. -This is useful to ensure that the mask appropriately covers the lens and source light and does not exclude important -regions. +Before applying the mask, let's display its boundary over the full image. +The boundary marks the edge of the region we will include in the comparison. -To overlay objects like a mask onto a figure, we use the `lines=`/`positions=` overlays object. This tool allows us to add custom -visuals to any plot, providing flexibility in creating tailored visual representations. +Check that the lensed arcs lie inside it and that some surrounding sky is +included. At this stage, we are only displaying the boundary; the dataset +has not yet been masked. """ - -aplt.plot_array(array=dataset.data, title="Imaging Data With Mask") +aplt.plot_array( + array=dataset.data, + mask=mask.derive_grid.edge, + title="Imaging Data With Mask Boundary", +) """ -Once we are satisfied with the mask, we apply it to the imaging data using the `apply_mask()` method. This ensures -that only the unmasked regions are considered during the analysis. +We now apply the mask to the dataset. Pixels outside the circular region +will be excluded when we compare the model with the data. """ dataset = dataset.apply_mask(mask=mask) """ -When we plot the masked imaging data again, the mask is now automatically included in the plot, even though we did -not explicitly pass it using the `lines=`/`positions=` overlays object. The plot also zooms into the unmasked area, showing only the -region where we will focus our analysis. This is particularly helpful when working with large images, as it centers -the view on the regions where the strong lens's signal is detected. +The plotted image now shows the selected region, with the view zoomed to +the unmasked area. The plotting function obtains the mask boundary from +the array itself. """ aplt.plot_array(array=dataset.data, title="Masked Imaging Data") """ -The mask is now stored as an additional attribute of the `Imaging` object, meaning it remains attached to the -dataset. This makes it readily available when we pass the dataset to a `FitImaging` object for the fitting process. +The mask is stored with the dataset, so later calculations can identify +which pixels to include. """ print("Mask2D:") print(dataset.mask) """ -In earlier tutorials, we discussed how grids and arrays have `native` and `slim` representations: +The masked data retain the `native` and `slim` representations introduced +earlier: -- `native`: Represents the original 2D shape of the data, maintaining the full pixel array of the image. -- `slim`: Represents a 1D array containing only the values from unmasked pixels, allowing for more efficient - processing when working with large images. +- `native` arranges the values in the original 2D image shape. Masked pixels + are filled with zeros. +- `slim` contains only the unmasked pixel values in a 1D array. -After applying the mask, the `native` and `slim` representations change as follows: +Those zeros in the native representation are placeholders. They do not mean +that zero light was measured outside the mask, and they do not contribute +to the comparison with the model. -- `native`: The 2D array keeps its original shape, [total_y_pixels, total_x_pixels], but masked pixels (those where - the mask is True) are set to 0.0. -- `slim`: This now only contains the unmasked pixel values, reducing the array size - from [total_y_pixels * total_x_pixels] to just the number of unmasked pixels. - -Let's verify this by checking the shape of the data in its `slim` representation. +Our original image has 101 x 101 pixels. The slim array is shorter because +we have selected only the circular region. """ -print("Number of unmasked pixels:") +print("Native image shape:") print(dataset.data.native.shape) -print( - dataset.data.slim.shape -) # This should be lower than the total number of pixels, e.g., 100 x 100 = 10,000 + +print("Slim image shape:") +print(dataset.data.slim.shape) """ -The `mask` object also has a `pixels_in_mask` attribute, which gives the number of unmasked pixels. This should -match the size of the `slim` data structure. +Despite its name, `pixels_in_mask` counts the unmasked pixels: those included +in the analysis. This number should match the length of the slim array. """ -print(dataset.data.mask.pixels_in_mask) +print("Number of unmasked pixels:") +print(dataset.mask.pixels_in_mask) """ -We can use the `slim` attribute to print the first unmasked values from the image and noise map: +The image and noise map share the same mask and pixel ordering. Their first +slim entries therefore describe the measurement and uncertainty at the same +sky position. """ print("First unmasked image value:") print(dataset.data.slim[0]) + print("First unmasked noise map value:") print(dataset.noise_map.slim[0]) """ -Additionally, we can verify that the `native` data structure has zeros at the edges where the mask is applied and -retains non-zero values in the central unmasked regions. +In the native representation, the corner pixel is masked and therefore +contains a zero placeholder. The central pixel is unmasked and retains its +measured value. """ -print("Example masked pixel in the image's native representation at its edge:") +print("Masked corner pixel in the native image:") print(dataset.data.native[0, 0]) -print("Example unmasked pixel in the image's native representation at its center:") + centre = tuple(s // 2 for s in dataset.data.shape_native) + +print("Unmasked central pixel in the native image:") print(dataset.data.native[centre]) """ __Masked Grid__ -In tutorials 1 and 2, we emphasized that the `Grid2D` object is crucial for evaluating a lens's light profile. This grid -contains (y, x) coordinates for each pixel in the image and is used to ray-trace to the source plane and map out the -positions where the source galaxy's light is calculated. - -From a `Mask2D`, we derive a `masked_grid`, which consists only of the coordinates of unmasked pixels. This ensures -that light profile calculations focus exclusively on regions where the strong lens's light is detected, saving -computational time and improving efficiency. +To predict the image, we need the sky coordinates corresponding to the +selected pixels. We obtain these from the mask as a grid of `(y, x)` +coordinates. -Below, we plot the masked grid: +Each coordinate marks the centre of an unmasked pixel. Plotting the grid +shows the circular region that we selected. """ masked_grid = mask.derive_grid.unmasked aplt.plot_grid(grid=masked_grid, title="Masked Grid2D") """ -By plotting this masked grid over the lens image, we can see that the grid aligns with the unmasked pixels of the -image. +We can overlay these coordinates on the image to see where the selected +pixels lie. Each dot corresponds to one pixel whose measured brightness +will be compared with the model prediction. -This alignment **is crucial** for accurate fitting because it ensures that when we evaluate a strong lens's light -profile, the calculations occur only at positions where we have real data from. +The grid, image and noise map use matching pixel ordering, so their slim +entries refer to the same positions. """ -aplt.plot_array(array=dataset.data, title="Image Data With 2D Grid Overlaid") +aplt.plot_array( + array=dataset.data, + grid=masked_grid, + title="Image Data With 2D Grid Overlaid", +) """ __Fitting__ -Now that our data is masked, we are ready to proceed with the fitting process. +We will begin with the same lens and source parameters used to simulate the +data. This gives us a useful reference: we know the underlying model, so we +can see what agreement with a noisy observation should look like. -Fitting the data is done using the `Galaxy` and `Tracer objects that we introduced in previous tutorials. We will start by -setting up a `Tracer`` object, using the same galaxy configuration that we previously used to simulate the -imaging data. This setup will give us what is known as a 'perfect' fit, as the simulated and fitted models are identical. +We should not expect the predicted image to match every observed pixel +exactly. The data contain random noise, whereas our prediction describes +the expected brightness. + +As before, the lens has an Isothermal mass profile and the source has a +Sersic light profile. The lens galaxy's light was omitted from this simulation. """ lens_galaxy = al.Galaxy( redshift=0.5, mass=al.mp.Isothermal( - centre=(0.0, 0.0), einstein_radius=1.6, ell_comps=(0.17647, 0.0) + centre=(0.0, 0.0), + einstein_radius=1.6, + ell_comps=(0.17647, 0.0), ), ) @@ -272,74 +279,73 @@ ), ) - tracer = al.Tracer(galaxies=[lens_galaxy, source_galaxy]) -aplt.plot_array(array=tracer.image_2d_from(grid=dataset.grid), title="Image") - """ -Next, let's plot the image of the tracer. This should look familiar, as it is the same image we saw in -previous tutorials. The difference now is that we use the dataset's `grid`, which corresponds to the `masked_grid` -we defined earlier. This means that the tracer image is only evaluated in the unmasked region, skipping calculations -in masked regions. +First, we evaluate the tracer on the dataset's grid. This calculates the +lensed source image at the selected image-plane coordinates. + +The arcs should look familiar, but this image has not yet been blurred by +the telescope's PSF. We must include that blurring before comparing it with +the observed data. """ aplt.plot_array( - array=tracer.image_2d_from(grid=dataset.grid), title="Tracer Image To Be Fitted" + array=tracer.image_2d_from(grid=dataset.grid), + title="Lensed Image Before PSF Blurring", ) """ -Now, we proceed to fit the image by passing both the `Imaging` and `Tracer` objects to a `FitImaging` object. -This object will compute key quantities that describe the fit’s quality: +The `FitImaging` object brings together our dataset and tracer. It calculates +the predicted image with PSF blurring and compares it with the data. -`image`: Creates an image of the tracer using their image_2d_from() method. -`model_data`: Convolves the tracer image with the data's PSF to account for the effects of telescope optics. -`residual_map`: The difference between the model data and observed data. -`normalized_residual_map`: Residuals divided by noise values, giving units of noise. -`chi_squared_map`: Squares the normalized residuals. -`chi_squared` and `log_likelihood`: Sums the chi-squared values to compute chi_squared, and converts this into -a log_likelihood, which measures how well the model fits the data (higher values indicate a better fit). +We supply the parameter values through the tracer. Creating this object +evaluates that choice of parameters; it does not adjust them. -Let's create the fit and inspect each of these attributes: +We will inspect the predicted image first, then calculate the differences +between it and the data. These differences will form the basis of the +statistical quantities introduced below. """ fit = al.FitImaging(dataset=dataset, tracer=tracer) """ -The `model_data` represents the tracer's image after accounting for effects like PSF convolution. +The fit's `model_data` is the predicted image after PSF convolution. It has +the same units as the observed data and can be compared with them pixel +by pixel. + +The mask selects which observed pixels enter the comparison, but light +outside its boundary can still be blurred into those pixels by the PSF. +`FitImaging` therefore also evaluates the surrounding light needed for +this convolution. -An important technical note is that when we mask data, we discussed above how the image of the tracer is not evaluated -outside the mask and is set to zero. This is a problem for PSF convolution, as the PSF blurs light from these regions -outside the mask but at its edge into the mask. They must be correctly evaluated to ensure the model image accurately -represents the image data. +This is the same principle as the padding in Tutorial 5: we must account +for light beyond the edge of the region whose blurred image we want. -The `FitImaging` object handles this internally, but evaluating the model image in the additional regions outside the mask -that are close enough to the mask edge to be blurred into the mask. +Below, compare the data and model image. Their arcs should have similar +positions, shapes and brightnesses. The model image is smooth, while the +data include noise. We do not add a new random noise realisation to the +model image when assessing the fit. """ print("First model image pixel:") print(fit.model_data.slim[0]) -aplt.plot_array(array=fit.model_data, title="Model Image") - -""" -Even before computing other fit quantities, we can normally assess if the fit is going to be good by visually comparing -the `data` and `model_data` and assessing if they look similar. -In this example, the tracer used to fit the data are the same as the tracer used to simulate it, so the two -look very similar (the only difference is the noise in the image). -""" aplt.plot_array(array=fit.data, title="Data") aplt.plot_array(array=fit.model_data, title="Model Image") r""" -The `residual_map` is the different between the observed image and model image, showing where in the image the fit is -good (e.g. low residuals) and where it is bad (e.g. high residuals). +Subtracting the model image from the data gives the `residual_map`: -The expression for the residual map is simply: +\[ +\text{residual} = \text{data} - \text{model\_data} +\] -\[ \text{residual} = \text{data} - \text{model\_data} \] +A positive residual means that the observed pixel is brighter than predicted. +A negative residual means that it is fainter. -The residual-map is plotted below, noting that all values are very close to zero because the fit is near perfect. -The only non-zero residuals are due to noise in the image. +We calculate this difference explicitly below and compare its first value +with the value provided by `FitImaging`. """ residual_map = dataset.data - fit.model_data + print("First residual-map pixel:") print(residual_map.slim[0]) @@ -348,19 +354,42 @@ aplt.plot_array(array=fit.residual_map, title="Residual Map") +""" +Because we used the parameters that generated the simulation, we expect +the residuals to be dominated by the noise in the data. + +Look for positive and negative fluctuations rather than coherent arc-shaped +features. The fluctuations can be larger in bright regions, where the +Poisson noise is larger. + +To judge whether a residual is large or small, we must compare it with +the noise expected in that pixel. This is our next step. + +**🤖 Ask AI:** Why can a correct lens model leave larger absolute residuals +in bright arcs than in the faint background? +""" + r""" -Are these residuals indicative of a good fit to the data? Without considering the noise in the data, it's difficult -to ascertain. That is, its hard to ascenrtain if a residual value is large or small because this depends on the -amount of noise in that pixel. +The size of a residual only becomes informative when compared with the +uncertainty in that pixel. A difference of 0.1 electrons per second could +be small in a noisy pixel but substantial in a precisely measured one. -The `normalized_residual_map` divides the residual-map by the noise-map, giving the residual in units of the noise. -Its expression is: +The `normalized_residual_map` divides each residual by its noise standard +deviation: -\[ \text{normalized\_residual} = \frac{\text{residual\_map}}{\text{noise\_map}} = \frac{\text{data} - \text{model\_data}}{\text{noise\_map}} \] +\[ +r_i = \frac{d_i - m_i}{\sigma_i} +\] + +Here, \(d_i\) is the observed value, \(m_i\) is the model prediction and +\(\sigma_i\) is the noise-map value for pixel \(i\). + +A normalised residual of +2 means that the observation is two noise standard +deviations above the prediction. A value of -2 means that it is two standard +deviations below. -If you're familiar with the concept of standard deviations (sigma) in statistics, the normalized residual map represents -how many standard deviations the residual is from zero. For instance, a normalized residual of 2.0 (corresponding -to a 95% confidence interval) means that the probability of the model underestimating the data by that amount is only 5%. +For a suitable model and well-estimated noise, we expect fluctuations around +zero, typically of order one. We do not expect every pixel to be close to zero. """ normalized_residual_map = residual_map / dataset.noise_map @@ -370,23 +399,30 @@ print("First normalized residual-map pixel via fit:") print(fit.normalized_residual_map.slim[0]) -aplt.plot_array(array=fit.normalized_residual_map, title="Normalized Residual Map") +aplt.plot_array( + array=fit.normalized_residual_map, + title="Normalized Residual Map", +) r""" -Next, we define the `chi_squared_map`, which is obtained by squaring the `normalized_residual_map` and serves as a -measure of goodness of fit. +Squaring the normalised residuals gives the `chi_squared_map`: -The chi-squared map is calculated as: +\[ +\chi_i^2 = \left(\frac{d_i - m_i}{\sigma_i}\right)^2 +\] -\[ \chi^2 = \left(\frac{\text{data} - \text{model\_data}}{\text{noise\_map}}\right)^2 \] +Each value measures one pixel's contribution to the overall disagreement. +The values are non-negative: residuals of +2 and -2 both contribute 4. -Squaring the normalized residual map ensures all values are positive. For instance, both a normalized residual of -0.2 -and 0.2 would square to 0.04, indicating the same quality of fit in terms of `chi_squared`. +Look for pixels with large contributions and whether they form a coherent +pattern. A few large values can occur through noise, especially when an image +contains many pixels. -As seen from the normalized residual map, it's evident that the model provides a good fit to the data, in this -case because the chi-squared values are close to zero. +For our reference model, the contributions should average approximately one, +rather than all being close to zero. """ -chi_squared_map = (normalized_residual_map) ** 2 +chi_squared_map = normalized_residual_map**2 + print("First chi-squared pixel:") print(chi_squared_map.slim[0]) @@ -396,134 +432,145 @@ aplt.plot_array(array=fit.chi_squared_map, title="Chi Squared Map") r""" -Now, we consolidate all the information in our `chi_squared_map` into a single measure of goodness-of-fit -called `chi_squared`. +We sum the contributions from all \(N\) unmasked pixels to obtain one number, +the total `chi_squared`: -It is defined as the sum of all values in the `chi_squared_map` and is computed as: - -\[ \chi^2 = \sum \left(\frac{\text{data} - \text{model\_data}}{\text{noise\_map}}\right)^2 \] +\[ +\chi^2 = \sum_{i=1}^{N} +\left(\frac{d_i - m_i}{\sigma_i}\right)^2 +\] -This summing process highlights why ensuring all values in the chi-squared map are positive is crucial. If we -didn't square the values (making them positive), positive and negative residuals would cancel each other out, -leading to an inaccurate assessment of the model's fit to the data. +Squaring before summing prevents positive and negative residuals from +cancelling. Large differences relative to the noise contribute strongly. -The lower the `chi_squared`, the fewer residuals exist between the model's fit and the data, indicating a better -overall fit! +When comparing parameter choices using the same data, mask and noise map, +a lower chi-squared means smaller overall noise-weighted differences. """ -chi_squared = np.sum(chi_squared_map) +chi_squared = np.sum(chi_squared_map.slim) + print("Chi-squared = ", chi_squared) print("Chi-squared via fit = ", fit.chi_squared) -""" -The reduced chi-squared is the `chi_squared` value divided by the number of data points (e.g., the number of pixels -in the mask). +r""" +Dividing the total chi-squared by the number of unmasked pixels gives the +average contribution per pixel: -This quantity offers an intuitive measure of the goodness-of-fit, as it normalizes the `chi_squared` value by the -number of data points. That is, a reduced chi-squared of 1.0 indicates that the model provides a good fit to the data, -because every data point is fitted with a chi-squared value of 1.0. +\[ +\frac{\chi^2}{N} +\] + +For the parameters that generated our simulation, we expect this to be +approximately one if the noise estimates describe the fluctuations well. +Individual pixels can contribute much more or much less than one. -A reduced chi-squared value significantly greater than 1.0 indicates that the model is not a good fit to the data, -whereas a value significantly less than 1.0 suggests that the model is overfitting the data. +A substantially larger value can indicate a mismatch between the model and +data, underestimated noise, or both. A substantially smaller value can +indicate overestimated noise; it does not automatically establish overfitting. + +You may also encounter the term "reduced chi-squared". This divides chi-squared +by the number of degrees of freedom, often \(N-p\) when \(p\) independent +parameters have been estimated from the data. Here, we are simply inspecting +the average per pixel for a specified model. """ -reduced_chi_squared = chi_squared / dataset.mask.pixels_in_mask -print("Reduced Chi-squared = ", reduced_chi_squared) +chi_squared_per_pixel = chi_squared / dataset.mask.pixels_in_mask + +print("Chi-squared per pixel = ", chi_squared_per_pixel) r""" -Another quantity that contributes to our final assessment of the goodness-of-fit is the `noise_normalization`. +To turn this comparison into a likelihood, we need a statistical description +of the noise. -The `noise_normalization` is computed by summing, over every pixel, the logarithm of 2 pi times the squared noise value: +We will treat each pixel's measurement as an independent Gaussian random +variable, centred on the model prediction \(m_i\), with standard deviation +\(\sigma_i\). This is an approximation to the Poisson counts used in our +simulation, appropriate when the expected counts are sufficiently large. + +The probability density for a pixel value is then: + +\[ +p(d_i \mid m_i, \sigma_i) += +\frac{1}{\sqrt{2\pi\sigma_i^2}} +\exp\left[-\frac{1}{2} +\left(\frac{d_i-m_i}{\sigma_i}\right)^2\right] +\] + +The exponential penalises predictions far from the observed value. The factor +in front normalises the Gaussian so that its density integrates to one. + +For independent pixels, we multiply these densities. Taking the natural +logarithm turns that product into a sum: \[ -\text{{noise\_normalization}} = \sum \log(2 \pi \text{{noise\_map}}^2) +\log \mathcal{L} += +-\frac{1}{2} +\left[ +\chi^2 + \sum_{i=1}^{N}\log(2\pi\sigma_i^2) +\right] \] -This quantity is fixed because the noise-map remains constant throughout the fitting process. Despite this, -including the `noise_normalization` is considered good practice due to its statistical significance. +The second term is called `noise_normalization` in PyAutoLens. It is part of +the probability density, not a test of whether the noise is Gaussian. -Understanding the exact meaning of `noise_normalization` isn't critical for our primary goal of successfully -fitting a model to a dataset. Essentially, it provides a measure of how well the noise properties of our data align -with a Gaussian distribution. +For our fixed dataset, mask and noise map, this term stays constant as we +change the lens and source parameters. """ -noise_normalization = np.sum(np.log(2 * np.pi * dataset.noise_map**2)) +noise_normalization = np.sum( + np.log(2 * np.pi * dataset.noise_map.slim**2) +) + print("Noise Normalization = ", noise_normalization) print("Noise Normalization via fit = ", fit.noise_normalization) -r""" -From the `chi_squared` and `noise_normalization`, we can define a final goodness-of-fit measure known as -the `log_likelihood`. - -This measure is calculated by taking the sum of the `chi_squared` and `noise_normalization`, and then multiplying the -result by -0.5: - -\[ \text{log\_likelihood} = -0.5 \times \left( \chi^2 + \text{noise\_normalization} \right) \] +""" +We can now calculate the log likelihood and compare it with the value +returned by `FitImaging`. -Don't worry about why we multiply by -0.5; it's a standard practice in statistics to ensure the log likelihood is -defined correctly. +The factor of -0.5 follows from the Gaussian expression above. With the +noise normalisation fixed, reducing chi-squared increases the log likelihood. """ log_likelihood = -0.5 * (chi_squared + noise_normalization) + print("Log Likelihood = ", log_likelihood) print("Log Likelihood via fit = ", fit.log_likelihood) -r""" -In the previous discussion, we noted that a lower \(\chi^2\) value indicates a better fit of the model to the -observed data. - -When we calculate the log likelihood, we take the \(\chi^2\) value and multiply it by -0.5. This means that a -higher log likelihood corresponds to a better model fit. Our goal when fitting models to data is to maximize the -log likelihood. - -The **reduced \(\chi^2\)** value provides an intuitive measure of goodness-of-fit. Values close to 1.0 suggest a -good fit, while values below or above 1.0 indicate potential underfitting or overfitting of the data, respectively. -In contrast, the log likelihood values can be less intuitive. For instance, a log likelihood value printed above -might be around 5300. - -However, log likelihoods become more meaningful when we compare them. For example, if we have two models, one with -a log likelihood of 5300 and the other with 5310 we can conclude that the first model fits the data better -because it has a higher log likelihood by 10.0. +""" +For the same dataset, mask and noise assumptions, a higher log likelihood +indicates better agreement between the predicted image and the data. -In fact, the difference in log likelihood between models can often be associated with a probability indicating how -much better one model fits the data compared to another. This can be expressed in terms of standard deviations (sigma). +For example, a log likelihood of 5310 is higher than 5300, so the former +parameter choice provides the better fit under those assumptions. -As a rule of thumb: +The absolute value is not a probability that the model is correct. Nor does +a difference in log likelihood have a universal conversion into a number +of standard deviations. -- A difference in log likelihood of **2.5** suggests that one model is preferred at the **2.0 sigma** level. -- A difference in log likelihood of **5.0** indicates a preference at the **3.0 sigma** level. -- A difference in log likelihood of **10.0** suggests a preference at the **5.0 sigma** level. +We should also inspect where the model disagrees with the data. The subplot +below brings together the data, model image and residual diagnostics, along +with views of the source. -All these metrics can be visualized together using the `aplt.subplot_fit_imaging` object, which offers a comprehensive -overview of the fit quality. It also shows separate model images for the lens and source galaxies, and the appearance -of the source galaxy in the image and source planes. +Look for residuals consistent with noise rather than coherent features +tracing the lensed arcs. """ -fit = al.FitImaging(dataset=dataset, tracer=tracer) - aplt.subplot_fit_imaging(fit=fit) """ -If you're familiar with model-fitting, you've likely encountered terms like 'residuals', 'chi-squared', -and 'log_likelihood' before. +__Incorrect Fit__ -These metrics are standard ways to quantify the quality of a model fit. They are applicable not only to 1D data but -also to more complex data structures like 2D images, 3D data cubes, or any other multidimensional datasets. +We will now change the source position while keeping the lens mass and all +other source properties fixed. -__Incorrect Fit__ +The original source centre was `(0.1, 0.1)` arcseconds. We move it to +`(0.15, 0.15)`, a displacement of 0.05 arcseconds in each source-plane +coordinate. -In the previous section, we successfully created and fitted a lens model to the image data, resulting in an -excellent fit. The residual map and chi-squared map showed no significant discrepancies, indicating that the -strong lens's light was accurately captured by our model. This optimal solution translates to one of the highest log -likelihood values possible, reflecting a good match between the model and the observed data. +Although 0.05 arcseconds is half our image pixel scale, lensing maps this +source-plane displacement into changes in the positions and shapes of the +observed arcs. It does not simply move every image by half a pixel. -Now, let's modify our lens model to create a fit that is close to the correct solution but slightly off. -Specifically, we will slightly offset the center of the source galaxy by half a pixel (0.05") in both the x and y -directions. This change will allow us to observe how even small deviations from the true parameters can impact the -quality of the fit. +The original `fit` remains our reference comparison. """ -lens_galaxy = al.Galaxy( - redshift=0.5, - mass=al.mp.Isothermal( - centre=(0.0, 0.0), einstein_radius=1.6, ell_comps=(0.17647, 0.0) - ), -) - source_galaxy = al.Galaxy( redshift=1.0, bulge=al.lp.Sersic( @@ -535,42 +582,45 @@ ), ) - tracer = al.Tracer(galaxies=[lens_galaxy, source_galaxy]) -aplt.plot_array(array=tracer.image_2d_from(grid=dataset.grid), title="Image") +aplt.plot_array( + array=tracer.image_2d_from(grid=dataset.grid), + title="Lensed Image With Shifted Source", +) """ -After implementing this slight adjustment, we can now plot the fit. In doing so, we observe that residuals have -emerged at the multiple images of the lensed source, which indicates a mismatch between our model and the data. -Consequently, this discrepancy results in increased chi-squared values, which in turn affects our log likelihood. +We evaluate this new tracer against the same dataset and inspect the fit. + +Look for coherent positive and negative residuals around the arcs. These +indicate regions where the shifted source predicts too little or too much +light, rather than just random fluctuations about the observation. """ fit_bad = al.FitImaging(dataset=dataset, tracer=tracer) aplt.subplot_fit_imaging(fit=fit_bad) """ -Next, we can compare the log likelihood of our current model to the log likelihood value we computed previously. +Compare the log likelihood with our reference value. We expect the shifted +source to give a lower value because its predicted image disagrees with +the data more strongly. """ -print("Previous Likelihood:") +print("Reference log likelihood:") print(fit.log_likelihood) -print("New Likelihood:") + +print("Shifted-source log likelihood:") print(fit_bad.log_likelihood) -""" -As expected, we observe that the log likelihood has decreased! This decline confirms that our new model is indeed a -worse fit to the data compared to the original model. +print("Change from reference:") +print(fit_bad.log_likelihood - fit.log_likelihood) -Now, let’s change our lens model once more, this time setting it to a position that is far from the true parameters. -We will offset the source's center significantly to see how this extreme deviation affects the fit quality. """ -lens_galaxy = al.Galaxy( - redshift=0.5, - mass=al.mp.Isothermal( - centre=(0.0, 0.0), einstein_radius=1.6, ell_comps=(0.17647, 0.0) - ), -) +Next, move the source centre to `(0.5, 0.5)` arcseconds. All other parameters +remain unchanged. +This is a much larger displacement from the original `(0.1, 0.1)` position. +Compare the predicted arcs and residuals with the previous two examples. +""" source_galaxy = al.Galaxy( redshift=1.0, bulge=al.lp.Sersic( @@ -582,7 +632,6 @@ ), ) - tracer = al.Tracer(galaxies=[lens_galaxy, source_galaxy]) fit_very_bad = al.FitImaging(dataset=dataset, tracer=tracer) @@ -590,33 +639,51 @@ aplt.subplot_fit_imaging(fit=fit_very_bad) """ -It is now evident that this model provides a terrible fit to the data. The tracer does not resemble a plausible -representation of our simulated strong lens dataset, which we already anticipated given that we generated the data ourselves! +Print the three log likelihoods together and compare their ordering with +what you saw in the residual plots. -As expected, the log likelihood has dropped dramatically with this poorly fitting model. +For this example, the larger source displacement should produce the strongest +disagreement and the lowest log likelihood. """ -print("Previous Likelihoods:") +print("Reference source centre (0.1, 0.1):") print(fit.log_likelihood) + +print("Source centre (0.15, 0.15):") print(fit_bad.log_likelihood) -print("New Likelihood:") + +print("Source centre (0.5, 0.5):") print(fit_very_bad.log_likelihood) +""" +We have evaluated three choices of parameters, rather than searched for +the best-fitting values. + +The parameters used to generate the simulation provide a useful reference, +but they need not give the highest possible likelihood for one noisy +observation. Small parameter changes can sometimes improve agreement with +that particular noise realisation. + +To restore the original comparison, rerun the first tracer and `FitImaging` +cells in the Fitting section. + +**🤖 Ask AI:** Why might the parameters that maximise the likelihood of a +noisy simulated image differ slightly from those used to generate it? +""" + """ __Model Fitting__ -In the previous sections, we used the true model to fit the data, which resulted in a high log likelihood and minimal -residuals. We also demonstrated how even small deviations from the true parameters can significantly degrade the fit -quality, reducing the log likelihood. +So far, we have compared parameter choices with a known reference model. +For a real observation, we do not know the lens and source parameters in +advance. Finding values that describe the data well is the task of model +fitting. -In practice, however, we don't know the "true" model. For example, we might have an image of a strong lens observed with -the Hubble Space Telescope, but the values for parameters like its `einstein_radius` and others are -unknown. The process of determining the best-fit model is called model fitting, and it is the main topic of -Chapter 2 of **HowToLens**. +Let's try this manually using a new simulated dataset. It contains an +`IsothermalSph` lens mass profile and an `ExponentialCoreSph` source light +profile, with no light from the lens galaxy. -To conclude this section, let's perform a basic, hands-on model fit to develop some intuition about how we can find -the best-fit model. We'll start by loading a simple dataset that was simulated without any lens light, using -an `IsothermalSph` lens mass profile and `ExponentialCoreSph` source light profile, but the true parameters of these -profiles are unknown. +For this exercise, treat the parameters used to generate the data as unknown. +We load the image and apply a circular mask as before. """ dataset_name = "simple__no_lens_light__mass_sis" dataset_path = Path("dataset") / "imaging" / dataset_name @@ -648,28 +715,20 @@ aplt.subplot_imaging_dataset(dataset=dataset) """ -Now, you'll try to determine the best-fit model for this image, corresponding to the parameters used to simulate the -dataset. - -We'll use the simplest possible approach: try different combinations of light and mass profile parameters and adjust -them based on how well each model fits the data. You’ll quickly find that certain parameters produce a much better fit -than others. For example, determining the correct values of the `centre` should not take too long. - -Pay attention to the `log_likelihood` and the `residual_map` as you adjust the parameters. These will guide you in -determining if your model is providing a good fit to the data. Aim to increase the log likelihood and reduce the -residuals. +The parameters below are a starting guess. Run the cell and inspect the +predicted image, residuals and log likelihood. -Keep experimenting with different values for a while, seeing how small you can make the residuals and how high you -can push the log likelihood. Eventually, you’ll likely reach a point where further improvements become difficult, -even after trying many different parameter values. This is a good point to stop and reflect on your first experience -with model fitting. +The lens and source centres are `(y, x)` coordinates in arcseconds. +The Einstein radius, effective radius and break radius are also in +arcseconds. The source intensity uses the image's units of electrons +per second per pixel. """ - lens_galaxy = al.Galaxy( redshift=0.5, mass=al.mp.IsothermalSph( - centre=(1.0, 1.0), einstein_radius=1.0 - ), # These are the lens parameters you need to adjust + centre=(1.0, 1.0), + einstein_radius=1.0, + ), ) source_galaxy = al.Galaxy( @@ -678,7 +737,7 @@ centre=(1.0, 1.0), intensity=1.0, effective_radius=1.0, - radius_break=0.025, # These are the source parameters you need to adjust + radius_break=0.025, ), ) @@ -691,40 +750,188 @@ print("Log Likelihood:") print(fit.log_likelihood) +""" +Try changing one parameter at a time and rerunning the cell above. Record +the log likelihood for each choice and use the residual plots to understand +what changed. + +Start with the lens centre. Try `(0.5, 0.5)` and `(0.0, 0.0)` instead of +`(1.0, 1.0)`. This changes the location about which the lens deflects light. + +Next, try changing the source centre in the same way. This changes how the +source is positioned behind the lens and therefore the arrangement of its +multiple images. + +You can then explore: + +- `einstein_radius`: try 1.3 and 1.6 arcseconds instead of 1.0. This changes + the characteristic angular scale of the lensing. +- `effective_radius`: try 0.5 and 0.2 arcseconds instead of 1.0. This changes + the source size and the extent of its lensed features. +- `intensity`: try 0.5 and 0.2 instead of 1.0. With the other parameters + fixed, this scales the predicted brightness. + +Keep `radius_break=0.025` and both redshifts fixed for this exercise. + +Retain changes that improve the log likelihood, but continue inspecting +the residuals. The parameters interact, so a useful change at one stage +may need revisiting after another parameter changes. + +To restore the original starting point, set both centres to `(1.0, 1.0)`, +and set `einstein_radius`, `effective_radius` and `intensity` to 1.0, then +rerun the cell. +""" + +""" +You have now performed a simple manual search: choose parameters, predict +an image, compare it with the data, then use that comparison to choose +another set of parameters. + +The aim is not to make every residual vanish. A suitable prediction should +leave fluctuations consistent with the noise, without substantial coherent +structure. + +Nor does finding a good-looking result establish that it is the best possible +solution or tell us the uncertainty in its parameters. Several parameter +combinations may describe the data similarly well. + +Manual exploration becomes difficult as the number of parameters grows. +Chapter 2 introduces methods that explore parameter choices systematically +and quantify what we can infer from the data. + +**🤖 Ask AI:** How could changing both the source size and its intensity +make it difficult to determine either parameter by adjusting them manually? +""" + +r""" +__Likelihood Function__ + +Everything we have learned can now be put into a single sequence: + +1. Choose the lens and source parameters. +2. Construct their profiles and ray-trace the source to predict a lensed image. +3. Convolve that image with the telescope's PSF. +4. Subtract the prediction from the observed data. +5. Divide the residuals by the noise standard deviations and sum their squares. +6. Include the Gaussian normalisation to calculate the log likelihood. + +For a fixed dataset, this sequence defines a function of the model parameters: +the likelihood function. We usually work with its natural logarithm, the +log-likelihood function. + +Writing the parameters collectively as \(\boldsymbol{\theta}\), we have: + +\[ +\log \mathcal{L}(\boldsymbol{\theta}) += +-\frac{1}{2} +\sum_{i=1}^{N} +\left[ +\frac{(d_i-m_i(\boldsymbol{\theta}))^2}{\sigma_i^2} ++ +\log(2\pi\sigma_i^2) +\right] +\] + +The data, mask, PSF and noise map remain fixed. Changing the parameters changes +the predicted image \(m_i(\boldsymbol{\theta})\), and therefore the value +returned by the function. + +The function below implements this sequence for our exercise. `FitImaging` +handles the image prediction and PSF convolution, including light that blurs +across the mask boundary. We then write out the statistical calculation +explicitly using the unmasked pixels. + +The redshifts and source break radius remain fixed, as in the exercise. +""" +def log_likelihood_function( + dataset, + lens_centre, + einstein_radius, + source_centre, + intensity, + effective_radius, +): + lens_galaxy = al.Galaxy( + redshift=0.5, + mass=al.mp.IsothermalSph( + centre=lens_centre, + einstein_radius=einstein_radius, + ), + ) + + source_galaxy = al.Galaxy( + redshift=1.0, + bulge=al.lp.ExponentialCoreSph( + centre=source_centre, + intensity=intensity, + effective_radius=effective_radius, + radius_break=0.025, + ), + ) + + tracer = al.Tracer(galaxies=[lens_galaxy, source_galaxy]) + fit = al.FitImaging(dataset=dataset, tracer=tracer) + + model_image = fit.model_data.slim + residuals = dataset.data.slim - model_image + normalized_residuals = residuals / dataset.noise_map.slim + + chi_squared = np.sum(normalized_residuals**2) + noise_normalization = np.sum( + np.log(2 * np.pi * dataset.noise_map.slim**2) + ) + + return -0.5 * (chi_squared + noise_normalization) + """ -Manually guessing model parameters repeatedly is a very inefficient and slow way to find the best fit. If the model -were more complex—say, if the source galaxy had additional light profile components beyond just its `bulge` (like a -second `Sersic` profile representing a `disk`)—the model would become so intricate that this manual approach -would be practically impossible. This is definitely not how model fitting is done in practice. +Evaluate the function using your current exercise parameters. Its result +should agree with the log likelihood from the corresponding `FitImaging` +object. +""" +exercise_log_likelihood = log_likelihood_function( + dataset=dataset, + lens_centre=lens_galaxy.mass.centre, + einstein_radius=lens_galaxy.mass.einstein_radius, + source_centre=source_galaxy.bulge.centre, + intensity=source_galaxy.bulge.intensity, + effective_radius=source_galaxy.bulge.effective_radius, +) -However, this exercise has given you a basic intuition for how model fitting works. The statistical inference tools -that are actually used for model fitting will be introduced in Chapter 2. Interestingly, these tools are not entirely -different from the approach you just tried. Essentially, they also involve iteratively testing models until those -with high log likelihoods are found. The key difference is that a computer can perform this process thousands of -times, and it does so in a much more efficient and strategic way. +print("Log likelihood from our function:") +print(exercise_log_likelihood) + +print("Log likelihood from FitImaging:") +print(fit.log_likelihood) + +""" +Each call evaluates one choice of parameters and returns one number. It does +not search for better parameters, and it does not generate new random noise. -__Wrap Up__ +The notion of a likelihood function is central to Chapter 2. The search +methods introduced there repeatedly supply different parameter choices to +this function and use the returned likelihoods to explore which choices +describe the data well. Understanding this sequence is therefore the +foundation for understanding how automated lens modelling works. -In this tutorial, you have learned how to fit a lens model to imaging data, a fundamental process in astronomy -and statistical inference. +The interferometer, point-source, weak-lensing, group-scale and cluster-scale +examples shown in Tutorial 5 each have their own bespoke likelihood +functions, tailored to their measurements and analysis. They follow the +same principle: predict the observables from a set of parameters, then compare +those predictions with the data using the appropriate uncertainties. -Let's summarise what we have covered: +The `autolens_workspace` provides step-by-step guides to every likelihood +function in PyAutoLens. These unpack the calculations for different dataset +types and analysis methods, just as we have done here. -- **Dataset**: We loaded the imaging dataset that we previously simulated, consisting of the tracer image, noise map, - and PSF. - -- **Mask**: We applied a circular mask to the data, excluding regions with low signal-to-noise ratios from the analysis. +For the imaging calculation introduced in this tutorial, see the workspace's +[imaging likelihood-function guide](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/likelihood_function.py). +The corresponding sections of the workspace provide guides for the other +likelihood functions. -- **Masked Grid**: We created a masked grid, which contains only the coordinates of unmasked pixels, to evaluate the - tracer's light profile. - -- **Fitting**: We fitted the data with a lens model, computing key quantities like the model image, residuals, - chi-squared, and log likelihood to assess the quality of the fit. - -- **Bad Fits**: We demonstrated how even small deviations from the true parameters can significantly impact the fit - quality, leading to decreased log likelihood values. - -- **Model Fitting**: We performed a basic model fit on a simple dataset, adjusting the model parameters to improve the - fit quality. +You have now followed the full path from a lens and source description to a +quantitative comparison with an observation. In Chapter 2, we will use this +likelihood function to move from trying parameters by hand to exploring them +systematically. """ diff --git a/scripts/chapter_1_introduction/tutorial_7_summary.py b/scripts/chapter_1_introduction/tutorial_7_summary.py index 30ed86c..9d4142c 100644 --- a/scripts/chapter_1_introduction/tutorial_7_summary.py +++ b/scripts/chapter_1_introduction/tutorial_7_summary.py @@ -2,28 +2,28 @@ Tutorial 7: Summary =================== -In this chapter, we have learnt that: +In this chapter, we have built up the steps needed to describe a gravitational lens and compare its predicted image with an observation: - 1) **PyAutoLens** uses Cartesian `Grid2D`'s of $(y,x)$ coordinates to perform ray-tracing. - 2) These grids are combined with light and mass profiles to compute images, deflection angles and other quantities. - 3) Profiles are grouped together to make galaxies. - 4) Collections of galaxies (at the same redshift) form a plane. - 5) A `Tracer` can make an image-plane + source-plane strong lens system. - 6) The Universe's cosmology can be input into this `Tracer` to convert its units to kiloparsecs. - 7) The tracer's image can be used to simulate strong lens `Imaging` like it was observed with a real telescope. - 8) This data can be fitted, so to as quantify how well a model strong lens system represents the observed image. +1. A `Grid2D` provides the $(y,x)$ coordinates where we evaluate light and mass profiles. +2. Light profiles describe a galaxy's surface brightness, while mass profiles describe its gravitational lensing effects. +3. A `Galaxy` groups these profiles together at a specified redshift. +4. A `Tracer` groups galaxies into redshift planes and traces light between them. +5. The redshifts and cosmology connect angular quantities with physical distances. +6. A simulated imaging observation combines the predicted image with a telescope's PSF, exposure time and noise. +7. Comparing a predicted image with observed data gives residuals, a chi-squared and a log likelihood. +8. Putting this calculation into a likelihood function lets us evaluate different choices of model parameters. -In this summary, we'll go over all the different Python objects introduced throughout this chapter and consider how -they come together as one. +This final tutorial brings those ideas together. We will revisit how profiles, galaxies and planes fit inside a tracer, +and use that structure to plot individual components of a lensed source. __Contents__ -- **Start:** Below, we do all the steps we have learned this chapter, making profiles, galaxies, a tracer, etc. -- **Object Composition:** Lets now consider how all of the objects we've covered throughout this chapter (`LightProfile`'s. -- **Visualization:** Furthermore, using the `MatPLot2D` and `lines=`/`positions=` overlays objects we can visualize any. -- **Code Design:** To end, I want to quickly talk about the **PyAutoLens** code-design and structure, which was really. -- **Source Code:** If you do enjoy code, variables, functions, and parameters, you may want to dig deeper into the. -- **Wrap Up:** Summary of the script and next steps. +- **Start:** Build a lens and a source with two light profiles. +- **Object Composition:** Access the galaxies and profiles inside a tracer. +- **Visualization:** Add critical curves to the lensed image. +- **Code Design:** Connect the structure of the code with the physical system. +- **Source Code:** Find the projects that provide these tools. +- **Wrap Up:** Prepare for automated lens modelling in Chapter 2. """ @@ -31,17 +31,20 @@ # from autolens import setup_notebook; setup_notebook() -from pathlib import Path import autolens as al import autolens.plot as aplt """ __Start__ -Below, we do all the steps we have learned this chapter, making profiles, galaxies, a tracer, etc. +We begin with a lens galaxy containing an elliptical mass profile and a source galaxy containing two light profiles, +named `bulge` and `disk`. -Note that in this tutorial, we omit the lens galaxy's light and include two light profiles in the source representing a -`bulge` and `disk`. +The source profiles share a centre and ellipticity, but have different Sérsic indices. This gives them different radial +brightness distributions. We omit the lens galaxy's light, so the image produced by this tracer contains only the lensed +source. + +These are specified profiles and parameter values, just as in our earlier examples. """ grid = al.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.05) @@ -75,133 +78,155 @@ """ __Object Composition__ -Lets now consider how all of the objects we've covered throughout this chapter (`LightProfile`'s, `MassProfile`'s, -`Galaxy`'s, `Plane`'s, `Tracer`'s) come together. +The tracer retains the galaxies and profiles we used to construct it. We can access them by stepping through this +structure. + +`tracer.planes[0]` contains the galaxies at the lens redshift, while `tracer.planes[1]` contains those at the source +redshift. Each plane contains one galaxy in this example, so `[0]` selects that galaxy. -The `Tracer`, which contains planes of `Galaxies`, which contains the `Galaxy`'s which contains the `Profile`'s: +We can then use the component names we supplied, such as `.mass`, `.bulge` and `.disk`, to access a particular profile. +The printed output below follows this sequence from the complete tracer down to its individual profiles. """ +print("Tracer:") print(tracer) -print() -print(tracer.planes[0]) -print() -print(tracer.planes[1]) -print() + +print("Lens plane:") print(tracer.planes[0]) -print() + +print("Source plane:") print(tracer.planes[1]) -print() + +print("Lens galaxy:") +print(tracer.planes[0][0]) + +print("Source galaxy:") +print(tracer.planes[1][0]) + +print("Lens mass profile:") print(tracer.planes[0][0].mass) -print() + +print("Source bulge:") print(tracer.planes[1][0].bulge) -print() + +print("Source disk:") print(tracer.planes[1][0].disk) -print() """ -Once we have a tracer we can therefore use any of the plotting function objects throughout this chapter to plot -any specific aspect, whether it be a profile, galaxy, galaxies or tracer. +First, plot the complete lensed image. The tracer evaluates both source light profiles at the ray-traced coordinates +and adds their contributions. -For example, if we want to plot the image of the source galaxy's bulge and disk, we can do this in a variety of -different ways. +We also keep the source-plane coordinates for the next plots. Each coordinate tells us where a ray from an image-plane +pixel reaches the source plane. """ -aplt.plot_array(array=tracer.image_2d_from(grid=grid), title="Image") +aplt.plot_array( + array=tracer.image_2d_from(grid=grid), + title="Lensed Source: Bulge + Disk", +) source_plane_grid = tracer.traced_grid_2d_list_from(grid=grid)[1] - """ -Understanding how these objects decompose into the different components of a strong lens is important for general -**PyAutoLens** use. +We can now evaluate each source profile separately at those same ray-traced coordinates. + +These plots show the individual **lensed** contributions of the bulge and disk. Although we evaluate their brightness +at source-plane coordinates, the resulting values remain arranged according to the original image-plane pixels. + +Compare the distribution of light in the two images. Their different Sérsic indices change how concentrated the light +is and how it extends away from the centre. Adding these two images gives the complete lensed source image above. -As the strong lens systems that we analyse become more complex, it is useful to know how to decompose their light -profiles, mass profiles, galaxies and planes to extract different pieces of information about the strong lens. For -example, we made our source-galaxy above with two light profiles, a `bulge` and `disk`. We can plot the lensed image of -each component individually, now that we know how to break-up the different components of the tracer. +This is a decomposition of our specified source description. We have not inferred separate bulge and disk components +from observed data. """ aplt.plot_array( array=tracer.planes[1][0].bulge.image_2d_from(grid=source_plane_grid), - title="Bulge Image", + title="Lensed Bulge", ) aplt.plot_array( array=tracer.planes[1][0].disk.image_2d_from(grid=source_plane_grid), - title="Disk Image", + title="Lensed Disk", ) +""" +**🤖 Ask AI:** Why does evaluating a source light profile on ray-traced source-plane coordinates produce a lensed image, +whereas evaluating it on a uniform source-plane grid produces an unlensed image? +""" + """ __Visualization__ -Furthermore, using the `MatPLot2D` and `lines=`/`positions=` overlays objects we can visualize any aspect we're interested -in and fully customize the figure. +We can combine the lensed image with other quantities calculated from the same tracer. -Before beginning chapter 2 of **HowToLens**, you should checkout the package `autolens_workspace/plot`. This provides a -full API reference of every plotting option in **PyAutoLens**, allowing you to create your own fully customized -figures of strong lenses with minimal effort! -""" +Here, we overlay the tangential critical curves introduced earlier in the chapter. Compare their position with the +bright arcs in the lensed image. The curves depend on the lensing mass distribution and redshifts, while the appearance +of the arcs also depends on the source's position and light profiles. +The `lines=` argument adds these curves to the image. The plotting examples in `autolens_workspace/plot` show how to +customise figures and add other overlays as you need them. +""" tangential_critical_curve_list = al.LensCalc.from_tracer( tracer=tracer ).tangential_critical_curve_list_from(grid=grid) -radial_critical_curve_list = al.LensCalc.from_tracer( - tracer=tracer -).radial_critical_curve_list_from(grid=grid) - aplt.plot_array( array=tracer.image_2d_from(grid=grid), - title="Tracer Image with Critical Curves", + title="Lensed Source\nTangential Critical Curves", lines=tangential_critical_curve_list, ) """ -And, we're done, not just with the tutorial, but the chapter! - __Code Design__ -To end, I want to quickly talk about the **PyAutoLens** code-design and structure, which was really the main topic of -this tutorial. +The structure we have just explored reflects the physical description of a lens system: profiles belong to galaxies, +galaxies occupy redshift planes, and a tracer calculates how light travels between those planes. -Throughout this chapter, we never talk about anything like it was code. We didn`t refer to 'variables', 'parameters`' -'functions' or 'dictionaries', did we? Instead, we talked about 'galaxies', 'planes' a 'Tracer', etc. We discussed -the objects that we, as scientists, think about when we consider a strong lens system. +This is an example of *object-oriented design*. Each object brings together information about something, such as a +galaxy, and operations we can perform with it, such as calculating its image. -Software that abstracts the underlying code in this way follows an `object-oriented design`, and it is our hope -with **PyAutoLens** that we've made its interface (often called the API for short) very intuitive, whether you were -previous familiar with gravitational lensing or a complete newcomer! +We have used Python variables, parameters and functions throughout this chapter, but their names and organisation let +us express those operations in familiar scientific terms. For example, `source.bulge` identifies a particular light +component, while `tracer.image_2d_from(grid=grid)` calculates the image of the complete system. -__Source Code__ - -If you do enjoy code, variables, functions, and parameters, you may want to dig deeper into the **PyAutoLens** source -code at some point in the future. Firstly, you should note that all of the code we discuss throughout the **HowToLens** -lectures is not contained in just one project (e.g. the **PyAutoLens** GitHub repository) but in fact four repositories: - -**PyAutoFit** - Everything required for lens modeling (the topic of chapter 2): https://github.com/PyAutoLabs/PyAutoFit +As your analyses become more complex, this same structure lets you add components and inspect their individual +contributions. +""" -**PyAutoArray** - Handles all data structures and Astronomy dataset objects: https://github.com/PyAutoLabs/PyAutoArray +""" +__Source Code__ -**PyAutoGalaxy** - Contains the light profiles, mass profiles and galaxies: https://github.com/PyAutoLabs/PyAutoGalaxy +The tools used in **HowToLens** are provided by four related projects: -**PyAutoLens** - Everything strong lensing: https://github.com/PyAutoLabs/PyAutoLens +- **[PyAutoFit](https://github.com/PyAutoLabs/PyAutoFit)** provides tools for defining models, searching their parameter spaces and analysing inference results. We will use these ideas in Chapter 2. +- **[PyAutoArray](https://github.com/PyAutoLabs/PyAutoArray)** provides arrays, grids, masks and tools for handling astronomical datasets. +- **[PyAutoGalaxy](https://github.com/PyAutoLabs/PyAutoGalaxy)** provides light profiles, mass profiles and galaxies. +- **[PyAutoLens](https://github.com/PyAutoLabs/PyAutoLens)** brings these components together for gravitational lensing, including ray tracing and comparisons with lensing observations. -Instructions on how to build these projects from source are provided here: +You access much of this functionality through `import autolens as al`, so you do not need to work with each repository +separately to follow the tutorials. -https://pyautolens.readthedocs.io/en/latest/installation/source.html +If you want to understand how a calculation is implemented, you can explore the source code and its accompanying tests. +Start with a familiar operation, such as calculating a light-profile image, and follow how its inputs become an output. -We take a lot of pride in our source code, so I can promise you its well written, well documented and thoroughly -tested (check out the `test` directory if you're curious how to test code well!). +[Installation from source](https://pyautolens.readthedocs.io/en/latest/installation/source.html) is described in the +documentation. This is useful if you want to modify or contribute to the libraries; it is optional for continuing +**HowToLens**. +""" +""" __Wrap Up__ -You`ve learn a lot in this chapter, but what you have not learnt is how to 'model' a real strong gravitational lens. +You have now followed the path from a mathematical description of a lens system to a predicted observation and a +likelihood function that measures its agreement with data. -In the real world, we have no idea what the 'correct' combination of light profiles, mass profiles and galaxies are -that will give a good fit to a lens. Lens modeling is the process of finding the lens model which provides a good fit -and it is the topic of chapter 2 of **HowToLens**. +In our simulations, we chose the parameters that generated the observation. For a real lens, those parameters are +unknown. We must explore which choices describe the data well and what uncertainty remains. -Finally, if you enjoyed doing the **HowToLens** tutorials please git us a star on the **PyAutoLens** GitHub -repository: +In Tutorial 6, you began this process by changing parameters by hand. Chapter 2 introduces automated lens modelling: +a search repeatedly evaluates the likelihood function for different parameter choices, helping us infer the properties +of the lens and source. - https://github.com/PyAutoLabs/PyAutoLens +The profiles, galaxies, tracers and dataset calculations you have learnt here remain the foundation of that process. -Even the smallest bit of exposure via a GitHub star can help our project grow! +If you have found **HowToLens** useful, you can support the project by starring the +[PyAutoLens GitHub repository](https://github.com/PyAutoLabs/PyAutoLens). """ diff --git a/workspace_index.json b/workspace_index.json index ef81a78..2f87252 100644 --- a/workspace_index.json +++ b/workspace_index.json @@ -119,17 +119,16 @@ "Point Source Data", "Interferometer Data", "Weak Lensing Data", + "Group and Cluster Lenses", "Wrap Up" ], "cross_refs": [ "//github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/point_source/start_here.py", - "//github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/start_here.py", - "scripts/simulator/interferometer.py", - "scripts/simulator/weak_lensing.py" + "//github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/start_here.py" ], "notebook": "notebooks/chapter_1_introduction/tutorial_5_data.ipynb", "path": "scripts/chapter_1_introduction/tutorial_5_data.py", - "summary": "In the last tutorials, we use tracers to create images of strong lenses. However, those images don't accurately represent what we would observe through a telescope.", + "summary": "In the previous tutorials, we used tracers to create images of strong lenses. We will now use one of these images to simulate an observation through a telescope.", "title": "Tutorial 5: Data" }, { @@ -141,14 +140,14 @@ "Fitting", "Incorrect Fit", "Model Fitting", - "Wrap Up" + "Likelihood Function" ], "cross_refs": [ - "tutorial_5_data.py" + "//github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/likelihood_function.py" ], "notebook": "notebooks/chapter_1_introduction/tutorial_6_fitting.ipynb", "path": "scripts/chapter_1_introduction/tutorial_6_fitting.py", - "summary": "In previous tutorials, we used light profiles to create simulated images of a tracer and visualized how these images would appear when captured by a CCD detector on a telescope like the Hubble Space Telescope.", + "summary": "In the previous tutorial, we chose a lens and source, predicted their lensed image and simulated a telescope observation. We will now work in the other direction: starting with an image, we want to learn about the objects that produced it.", "title": "Tutorial 6: Fitting" }, { @@ -163,7 +162,7 @@ "cross_refs": [], "notebook": "notebooks/chapter_1_introduction/tutorial_7_summary.ipynb", "path": "scripts/chapter_1_introduction/tutorial_7_summary.py", - "summary": "In this chapter, we have learnt that:", + "summary": "In this chapter, we have built up the steps needed to describe a gravitational lens and compare its predicted image with an observation:", "title": "Tutorial 7: Summary" }, {