diff --git a/llms-full.txt b/llms-full.txt index 679fbb6..a09955d 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -68,17 +68,17 @@ AUTO-GENERATED by PyAutoHands — do not edit by hand; regenerate with generate. ## chapter_4_scaling_up_lensing -- [Tutorial 1: Extra Galaxies](scripts/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.py): Welcome to chapter 4 of **HowToLens**, where we scale up lens modeling beyond a single lens galaxy. +- [Tutorial 1: Extra Galaxies](scripts/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.py): Welcome to chapter 4 of **HowToLens**, where we scale up lens modeling beyond a single dominant lens galaxy. - Contents: Initial Setup, Light Versus Mass, Mask, Approach 1 Noise Scaling, Noise Scaling Fit, Approach 2 Extra Galaxies Model, Extra Galaxy Centres, Extra Galaxies Fit, Which Approach When, Wrap Up -- [Tutorial 2: Multi-Galaxy Lenses](scripts/chapter_4_scaling_up_lensing/tutorial_2_multi_galaxy.py): In the previous tutorial, we learned how to deal with extra galaxies near a strong lens — nuisance objects whose light contaminates the data but which play no meaningful role in the lensing itself. We removed their emission from the analysis, or gave them a heavily restricted model, and the single dominant lens galaxy remained the star of the show. +- [Tutorial 2: Multi-Galaxy Lenses](scripts/chapter_4_scaling_up_lensing/tutorial_2_multi_galaxy.py): In the previous tutorial, we modeled a system with one dominant lens galaxy and a smaller nearby galaxy. We saw that the extra galaxy's light and gravitational deflections required separate consideration. - Contents: Initial Setup, Mask, Over Sampling, Model, Fixing the Mass Centres, Model Fit, Result, Mass Degeneracies, No Shared Halo, Three Lens Galaxies, Wrap Up -- [Tutorial 3: Scaling Relations](scripts/chapter_4_scaling_up_lensing/tutorial_3_scaling_relation.py): The previous tutorial ended on a warning: every deflector we add to a lens model brings its own free parameters. Two galaxies were manageable, but each one cost us a mass profile's worth of dimensions, and the arithmetic only gets worse. A group-scale lens may have ten member galaxies, a cluster hundreds. If every member keeps its own free mass, the parameter space explodes — a 100-galaxy cluster with 5 free mass parameters per galaxy is a 500-dimensional model, which no non-linear search can sample and no dataset can constrain anyway. +- [Tutorial 3: Scaling Relations](scripts/chapter_4_scaling_up_lensing/tutorial_3_scaling_relation.py): In the previous tutorial, we saw how adding significant deflectors increases both the number of parameters and the degeneracies between galaxy masses. Independently fitting the mass of every member becomes increasingly demanding for groups and clusters. - Contents: Mass Follows Light, Initial Setup, Mask, Measured Luminosities, The Anchor, Over Sampling, Light Via MGE, Scaling Relation, Model, Parameter Counts, Scaling To Many Galaxies, Model Fit, Results, Limitations, Lens Environments, Wrap Up -- [Tutorial 4: Group Scale](scripts/chapter_4_scaling_up_lensing/tutorial_4_group_scale.py): In the previous tutorials we took our first steps beyond the single lens galaxy: we included extra galaxies near the lens in the model, we modeled systems where two or more galaxies of comparable mass share the lensing, and we introduced scaling relations, which tie the mass of a galaxy to its light so that adding more galaxies to a model does not mean adding more free parameters. - - Contents: Initial Setup, Mask, Galaxy Centres, The dPIE Profile, Fitting a Group, A Group Halo?, Model Fit, Scaling Relation Members, The Group Scale Sweet Spot, Wrap Up -- [Tutorial 5: Cluster Scale](scripts/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.py): Throughout this chapter we have been climbing a ladder of scale: from a single lens galaxy with an extra galaxy nearby, to multi-galaxy lenses, to galaxy groups whose members share a common dark matter halo. +- [Tutorial 4: Group Scale](scripts/chapter_4_scaling_up_lensing/tutorial_4_group_scale.py): The previous tutorials introduced nearby galaxies, multiple significant deflectors and scaling relations. We now combine these ideas to model a **group-scale lens**. + - Contents: Initial Setup, Mask, Galaxy Centres, The dPIE Profile, Fitting a Group, A Group Halo?, Model Fit, Fit With a Shared NFW Dark Matter Halo, Bayesian Model Comparison, Scaling Relation Members, The Group Scale Sweet Spot, Wrap Up +- [Tutorial 5: Cluster Scale](scripts/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.py): We now extend the tools developed for galaxies and groups to **galaxy clusters**. - Contents: Multi-Plane Ray Tracing, Dataset, Point Source Modeling, Point Datasets, The CSV Interface, Point Solver, Model, Analysis + Factor Graph, Search, Model Fit, Results, Customization, Wrap Up -- [Tutorial 6: Weak Lensing](scripts/chapter_4_scaling_up_lensing/tutorial_6_weak_lensing.py): Every tutorial in this series so far — indeed, every fit performed in all four chapters of **HowToLens** — has been a *strong* lensing analysis. Strong lensing occurs when a background galaxy lies so close (in projection) to a foreground mass that its light is bent into multiple images, arcs or a complete Einstein ring. These dramatic features are what we simulated, fitted and modeled, from the single galaxy-scale lenses of chapters 1 and 2 up to the group-scale and cluster-scale systems earlier in this chapter. +- [Tutorial 6: Weak Lensing](scripts/chapter_4_scaling_up_lensing/tutorial_6_weak_lensing.py): Our modeling tutorials have concentrated on **strong lensing**: the multiple images, arcs and Einstein rings produced by galaxy, group and cluster lenses. - Contents: Shear Catalogues, Mass Scales, Ray Tracing, Source Galaxy Positions, Simulate, Visualize, Mass Map, Fitting, Model Fit, Result, Joint Strong and Weak Lensing, Wrap Up ## chapter_optional diff --git a/notebooks/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.ipynb b/notebooks/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.ipynb index 46b0203..42a45c6 100644 --- a/notebooks/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.ipynb +++ b/notebooks/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.ipynb @@ -7,41 +7,30 @@ "Tutorial 1: Extra Galaxies\n", "==========================\n", "\n", - "Welcome to chapter 4 of **HowToLens**, where we scale up lens modeling beyond a single lens galaxy.\n", + "Welcome to chapter 4 of **HowToLens**, where we scale up lens modeling beyond a single dominant lens galaxy.\n", "\n", - "In chapters 1 to 3, every strong lens we studied had the same simple anatomy: one lens galaxy, whose light and mass\n", - "we modeled, and one background source galaxy, whose lensed emission we fitted. This is the cleanest possible lensing\n", - "configuration, and it was the right place to learn the fundamentals of ray-tracing, non-linear searches and\n", - "pixelized source reconstructions.\n", + "In chapters 2 and 3, we focused on modeling systems with one main lens galaxy and one background source galaxy.\n", + "These examples introduced non-linear searches, lens modeling and pixelized source reconstructions.\n", "\n", - "Real strong lenses are rarely this tidy. Galaxies live in crowded fields: a lens galaxy may have a faint companion a\n", - "few arc-seconds away, sit in a small group of comparably massive galaxies, or be embedded in a cluster containing\n", - "hundreds of members and a vast dark matter halo. The science of strong lensing scales up through this hierarchy, and\n", - "so must our modeling:\n", + "In chapter 1, we also saw that lensing occurs in more complex systems, including groups and clusters of galaxies.\n", + "We now explore how to build and fit models of these systems, starting with a nearby galaxy that complicates an\n", + "otherwise familiar galaxy-scale lens.\n", "\n", - "- **Extra galaxies (this tutorial)**: a single dominant lens galaxy, with one or more nearby interloper galaxies\n", - " whose light and mass may contaminate the analysis.\n", + "This chapter introduces:\n", "\n", - "- **Multi-galaxy lenses (next tutorial)**: systems where two or more galaxies are co-equal lenses, and no single\n", - " galaxy can be called \"the\" lens.\n", + "- **Extra galaxies:** nearby galaxies whose light or mass may affect our analysis.\n", + "- **Multi-galaxy lenses:** systems where two or more galaxies contribute substantially to the lensing.\n", + "- **Scaling relations:** linking the mass properties of many galaxies to their luminosities, reducing the number\n", + " of free parameters.\n", + "- **Group and cluster scales:** modeling member galaxies together with a shared dark matter halo.\n", + "- **Weak lensing:** using the small distortions of background galaxies to constrain foreground mass beyond the\n", + " strongly lensed region.\n", "\n", - "- **Scaling relations**: modeling many galaxies at once by tying their properties to their luminosity, so that\n", - " adding galaxies does not add free parameters.\n", + "Many of these modeling techniques also apply to studies of galaxy morphology without lensing. **PyAutoGalaxy**\n", + "provides the same tools for fitting galaxy light and composing models of multiple galaxies, without ray-tracing.\n", "\n", - "- **Group and cluster scales**: lenses whose deflectors are entire groups or clusters of galaxies, including a\n", - " shared dark matter halo.\n", - "\n", - "- **Weak lensing**: the statistical distortion of many background galaxies by foreground mass, extending lensing\n", - " beyond the strong regime entirely.\n", - "\n", - "Much of the methodology in this chapter is not specific to lensing. Fitting the light of extra galaxies, modeling\n", - "blended multi-galaxy fields and composing models via scaling relations are equally important for non-lensing galaxy\n", - "studies, and **PyAutoGalaxy** provides the same API for these tasks applied to galaxy morphology (without the\n", - "ray-tracing).\n", - "\n", - "In this first tutorial, we take the first step up in scale: a galaxy-scale lens with one extra galaxy nearby. We\n", - "will learn how to decide whether the extra galaxy matters, and the two approaches to dealing with it when it does:\n", - "removing its light from the data, or including it in the lens model.\n", + "In this tutorial, we consider one extra galaxy near a dominant lens galaxy. We will distinguish the effects of its\n", + "light and mass, then compare excluding its light from the fit with explicitly including the galaxy in our model.\n", "\n", "__Contents__\n", "\n", @@ -118,15 +107,17 @@ "source": [ "__Initial Setup__\n", "\n", - "Lets load the `Imaging` dataset we'll fit in this tutorial. It is similar to the `lens_sersic` dataset used\n", - "throughout chapter 2, where:\n", + "Let's load the `Imaging` dataset we will fit in this tutorial. It is similar to the `lens_sersic` dataset used in\n", + "chapter 2:\n", + "\n", + "- The lens galaxy's light follows a `Sersic` profile.\n", + "- Its mass follows an `Isothermal` profile, with a separate `ExternalShear` field.\n", + "- The source galaxy's light follows a `SersicCore` profile.\n", "\n", - " - The lens galaxy's light is an `Sersic`.\n", - " - The lens system uses an `Isothermal` galaxy mass profile and a separate `ExternalShear` field.\n", - " - The source galaxy's light is an `SersicCore`.\n", + "This dataset also contains an extra galaxy a few arcseconds from the main lens. Its light follows an\n", + "`ExponentialSph` profile and its mass follows an `IsothermalSph` profile.\n", "\n", - "However, there is one addition: an extra galaxy, with its own light (an `ExponentialSph`) and its own\n", - "mass (an `IsothermalSph`), located a few arc-seconds from the lens galaxy." + "Both its emission and its gravitational deflections are therefore present in the simulated data." ] }, { @@ -176,12 +167,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "When we plot the dataset, the familiar sight of a lens galaxy surrounded by a lensed source's ring of emission is\n", - "joined by a blob of light in the upper-right of the image.\n", + "Plotting the dataset shows the familiar lens galaxy and lensed source emission, together with an extra galaxy\n", + "nearby.\n", "\n", - "This is the extra galaxy. It is not part of the strong lens system we are studying: it is an interloper, a galaxy\n", - "that happens to lie close to the lens on the sky. Interlopers like this are extremely common in real imaging of\n", - "strong lenses, and every lens modeler has to decide what to do about them." + "We call this an **extra galaxy** because the main lens remains the dominant deflector. This does not mean the extra\n", + "galaxy has no lensing effect: its mass also deflects the source's light.\n", + "\n", + "Nearby galaxies are common in observations of strong lenses. Before fitting the data, we must decide whether their\n", + "light, their mass, or both need to be accounted for." ] }, { @@ -199,36 +192,40 @@ "source": [ "__Light Versus Mass__\n", "\n", - "The decision of what to do about an extra galaxy hinges on one question, asked twice:\n", + "An extra galaxy raises two separate questions.\n", "\n", - "**Does its light affect the analysis?** The extra galaxy's emission may extend into the region of the image we fit.\n", - "If it does, and we fit a model containing only the lens and source, the model has no component that can produce\n", - "this emission. The fit will respond by distorting the lens light, source light or mass model to soak it up,\n", - "biasing every parameter we infer.\n", + "**Does its light affect the analysis?** If its emission falls within the region we fit, a model containing only the\n", + "main lens and source may try to reproduce that light using the wrong components. This can distort the inferred\n", + "lens light, source reconstruction or mass model.\n", "\n", - "**Does its mass affect the analysis?** The extra galaxy's mass deflects light rays, just like the lens galaxy's\n", - "mass does. If the galaxy is close (in projection) to the lensed source's light, its deflections measurably perturb\n", - "the ray-tracing. A model without this mass will compensate by biasing the main lens galaxy's mass parameters, for\n", - "example its `einstein_radius` or `ell_comps`.\n", + "**Does its mass affect the analysis?** The extra galaxy also deflects the source's light. Whether we need to model\n", + "these deflections depends on its mass, position and redshift, together with the precision of the data and the\n", + "measurements we want to make.\n", "\n", - "These two effects are dealt with separately, which gives us two approaches:\n", + "Removing the extra galaxy's light from the fit does not remove its gravitational effect. Likewise, including its\n", + "mass does not account for its emission.\n", "\n", - "- **Approach 1 (remove its light)**: If only the light matters, we can remove the extra galaxy's emission from the\n", - " fit entirely, without adding anything to the model. The mass is ignored.\n", + "We will compare two approaches:\n", "\n", - "- **Approach 2 (model it explicitly)**: If the mass matters (or the light blends too closely with the lensed source\n", - " to cleanly remove), we include the extra galaxy in the lens model, with its own light and / or mass profiles.\n", + "- **Noise scaling:** use the method introduced in chapter 2 to prevent the extra galaxy's light from meaningfully\n", + " constraining the fit. In this first example, we also omit its mass, allowing us to explore the limitation of\n", + " that choice.\n", + "- **Explicit modeling:** include the extra galaxy's light and mass profiles, fitting its emission and accounting\n", + " for its deflections.\n", "\n", - "We will now perform both, and at the end of the tutorial discuss when each is appropriate.\n", + "These are not the only combinations. We can also noise-scale the light while retaining a mass profile, or model\n", + "the light while omitting the mass when its lensing effect is negligible.\n", "\n", "__Mask__\n", "\n", - "We first define the circular mask used to fit the data. In chapter 2 we typically used a 2.6\" - 3.0\" mask, which\n", - "tightly contained the lens and lensed source.\n", + "We use a circular mask with a radius of 4.0\", which includes the main lens, the lensed source emission and the\n", + "extra galaxy.\n", + "\n", + "Keeping the extra galaxy inside the mask lets us compare noise scaling and explicit modeling using the same\n", + "overall fitting region.\n", "\n", - "Here, we use a larger 4.0\" mask, so that the region containing the extra galaxy is included in the fit. If we\n", - "simply shrank the mask to exclude the extra galaxy, we would also throw away pixels containing lensed source\n", - "emission, and the mask's hard edge could still cut through the extra galaxy's light." + "For other datasets, a smaller mask may exclude an unwanted galaxy. This is appropriate only if it retains the\n", + "lensed emission we want to analyze and avoids significant contamination from the extra galaxy's light." ] }, { @@ -250,8 +247,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Plotting the masked dataset confirms the extra galaxy's emission is inside the mask, and will therefore impact the\n", - "model-fit unless we do something about it." + "Plotting the masked dataset confirms that the extra galaxy's emission lies within the fitting region. We must\n", + "therefore account for its light, either by noise scaling the affected pixels or by modeling the emission explicitly." ] }, { @@ -269,23 +266,18 @@ "source": [ "__Approach 1 Noise Scaling__\n", "\n", - "Our first approach removes the extra galaxy's light from the fit.\n", - "\n", - "The most obvious way to do this would be to mask the extra galaxy's pixels, removing them from the fit entirely.\n", - "However, removing pixels changes the fit in subtle ways: their coordinates are no longer used in the ray-tracing,\n", - "and for certain models (e.g. the pixelized source reconstructions of chapter 3) removing interior pixels creates\n", - "discontinuities in the pixelization that introduce unexpected systematics.\n", + "We first use the noise-scaling method introduced in chapter 2. Recall that this sets selected data values to zero\n", + "and increases their noise values, giving those pixels negligible weight when constraining the model while\n", + "retaining them in the dataset's geometry.\n", "\n", - "Instead, we use **noise scaling**: the pixels stay in the fit, but their data values are set to zero and their\n", - "noise-map values are increased to very large values. A pixel with enormous noise contributes negligibly to the\n", - "likelihood, so the extra galaxy's light cannot influence the model, while the pixels themselves remain part of the\n", - "fit's geometry.\n", + "Here, we apply it to the region containing the extra galaxy's light. Any lensed source emission within that region\n", + "will also lose its constraining power, so we should avoid this approach where the extra galaxy and source are\n", + "strongly blended.\n", "\n", - "To do this we need a mask of the extra galaxy's region. For real data, you would create this yourself by\n", - "inspecting the image (the workspace's `data_preparation` package includes a GUI for drawing it); for this simulated\n", - "dataset the simulator script has already output a `mask_extra_galaxies.fits` circle covering the extra galaxy.\n", + "For this simulated dataset, the simulator provides a `mask_extra_galaxies.fits` file identifying the extra galaxy's\n", + "region. For real observations, we would define this region by inspecting the image.\n", "\n", - "We reload the dataset first, because noise scaling must be applied before the circular mask." + "We reload the original dataset, apply noise scaling, and then apply the same 4.0\" circular mask." ] }, { @@ -322,8 +314,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Plotting the dataset shows the extra galaxy's emission has vanished: its data values are zero and the\n", - "signal-to-noise of its pixels is effectively zero, so the fit will simply ignore that region of the image." + "The subplot shows that the selected region now has zero data values and effectively zero signal-to-noise. Its\n", + "pixels therefore contribute negligibly to constraining the fit.\n", + "\n", + "This excludes the extra galaxy's light from the analysis, but its mass has still deflected the source light\n", + "recorded elsewhere in the image. Noise scaling does not undo those deflections." ] }, { @@ -341,9 +336,14 @@ "source": [ "__Noise Scaling Fit__\n", "\n", - "We now fit this noise-scaled dataset with a lens model that does **not** include the extra galaxy. The model is the\n", - "same one we used in chapter 2's linear profiles tutorial: a linear `Sersic` lens bulge, an `Isothermal` plus\n", - "`ExternalShear` mass model and a linear `SersicCore` source." + "We now fit the noise-scaled dataset using the familiar model from chapter 2: a linear `Sersic` lens light profile,\n", + "an `Isothermal` lens mass profile, a separate `ExternalShear` field and a linear `SersicCore` source light profile.\n", + "\n", + "This model contains no extra galaxy. Its light has been handled by noise scaling, but its mass is deliberately\n", + "omitted.\n", + "\n", + "The fit therefore illustrates an important distinction: excluding contaminating light does not necessarily make a\n", + "single-galaxy mass model adequate." ] }, { @@ -378,14 +378,15 @@ "analysis = al.AnalysisImaging(dataset=dataset)\n", "\n", "print(\n", - " \"The non-linear search has begun running - checkout the output/howtolens/chapter_4/tutorial_1_extra_galaxies_noise_scaling\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell with progress once search has completed - this could take some time!\"\n", + " \"The non-linear search has begun. Check the \"\n", + " \"output/howtolens/chapter_4/tutorial_1_extra_galaxies_noise_scaling \"\n", + " \"folder for results and visualizations as the search progresses. \"\n", + " \"This cell will finish when the search completes.\"\n", ")\n", "\n", "result_noise_scaling = search.fit(model=model, analysis=analysis)\n", "\n", - "print(\"The search has finished run - you may now continue the notebook.\")" + "print(\"The search has finished \u2014 you may now continue the notebook.\")" ], "outputs": [], "execution_count": null @@ -394,13 +395,18 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Plotting the maximum log likelihood fit shows the lens and source are fitted well, with the noise-scaled region\n", - "contributing nothing to the residuals.\n", + "Inspect the maximum log likelihood fit below, paying particular attention to the residuals and normalized\n", + "residuals around the lensed source.\n", + "\n", + "The noise-scaled pixels have negligible weight in the fit. Their raw residuals need not be zero, because the model\n", + "can still predict emission there.\n", "\n", - "The extra galaxy's light has been dealt with. However, note what this approach did **not** do: the extra galaxy's\n", - "mass is completely absent from the model. Its deflection of the source's light rays is unaccounted for, and the\n", - "inferred lens mass model will have absorbed that perturbation as best it can. For an extra galaxy that is small\n", - "and / or far from the lensed emission this bias is negligible; for one that is massive and close, it is not." + "Elsewhere, the model must reproduce source emission that was lensed by both the main lens and the extra galaxy,\n", + "even though it includes only the main lens mass and external shear. These components may absorb some of the\n", + "missing perturbation, potentially shifting the inferred parameters.\n", + "\n", + "A visually satisfactory fit therefore does not establish that the extra galaxy's mass can safely be ignored.\n", + "Next, we include it explicitly so that we can compare the results." ] }, { @@ -418,11 +424,11 @@ "source": [ "__Approach 2 Extra Galaxies Model__\n", "\n", - "Our second approach includes the extra galaxy in the lens model, fitting its light (so we no longer need to remove\n", - "it from the data) and its mass (so its deflections are included in the ray-tracing).\n", + "We now include the extra galaxy's light and mass in the model. Its light profile accounts for its emission, while\n", + "its mass profile contributes to the deflections of the background source.\n", "\n", - "We reload the dataset and apply the 4.0\" circular mask, but this time we do **not** apply noise scaling, because\n", - "the extra galaxy's emission is now something the model itself will fit." + "We reload the original dataset and apply the same 4.0\" circular mask. This time, we do not apply noise scaling,\n", + "because we want to fit the extra galaxy's light." ] }, { @@ -453,21 +459,30 @@ "source": [ "__Extra Galaxy Centres__\n", "\n", - "To include the extra galaxy in the model, we input the centre of its light, as observed in the image.\n", + "We first load the extra galaxy's observed light centre.\n", + "\n", + "Allowing its light and mass centres to vary freely would introduce additional parameters and give the search more\n", + "opportunities to find unwanted solutions. For example, its light profile might fit part of a lensed arc, or its\n", + "mass profile might move towards the main lens and contribute to that galaxy's mass distribution.\n", + "\n", + "Measuring galaxy light centres first and then fixing them in the model is a common workflow throughout\n", + "extra-galaxy modeling. It becomes especially useful for the more complex multi-galaxy, group and cluster systems\n", + "we encounter later in this chapter, where allowing every centre to vary would introduce many additional parameters.\n", "\n", - "In principle, we could add the extra galaxy to the model with a completely free centre, and let the non-linear\n", - "search figure out where it is. In practice this is a bad idea: the extra parameters make parameter space more\n", - "complex, and fits commonly go wrong in characteristic ways. For example, the extra galaxy's light profile may\n", - "wander off and fit one of the lensed source's multiple images instead of the interloper, or its mass profile may\n", - "recentre itself onto the main lens galaxy and act as part of its mass distribution.\n", + "Typically, we inspect the image and record each galaxy's light centre using a GUI, a source-detection tool or a\n", + "preliminary light-profile fit. We then use these measured positions as fixed centres for its light and mass\n", + "profiles in the lens model. The workspace's data-preparation tools support this workflow; here, we load the\n", + "positions supplied by the simulator.\n", "\n", - "Fixing each extra galaxy's light and mass centres to its observed light centre removes these failure modes and\n", - "keeps the model as simple as possible. The observed centre is an excellent estimate of the true centre, because\n", - "(unlike the lensed source) the extra galaxy's light is not distorted by lensing.\n", + "Fixing centres is therefore a practical modeling choice used in many analyses, rather than just a simplification\n", + "for this tutorial. It keeps galaxies anchored to their observed positions and reduces the freedom for their\n", + "profiles to fit unrelated emission or move towards the main lens.\n", "\n", - "For real data you would measure these centres from the image (the workspace's `data_preparation` package shows\n", - "how, including a GUI for marking them); for this simulated dataset the simulator has output them to a .json file,\n", - "which we load below." + "This still assumes that each mass profile is centred on the observed light. Where positional uncertainties or\n", + "possible light-mass offsets matter scientifically, we can relax that assumption using informative priors.\n", + "\n", + "In this example, the extra galaxy is at the main lens's redshift, so its light is not lensed by the main lens.\n", + "This need not be true of every galaxy projected nearby on the sky." ] }, { @@ -489,7 +504,8 @@ "source": [ "__Extra Galaxies Model Composition__\n", "\n", - "We compose the main lens and source model exactly as before." + "We compose the main lens and source model exactly as before. Keeping these components unchanged makes it easier\n", + "to assess the effect of adding the extra galaxy." ] }, { @@ -515,25 +531,27 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We now compose the model of the extra galaxy, using the dedicated `extra_galaxies` modeling API.\n", + "We now build the extra galaxy using the `extra_galaxies` modeling API.\n", + "\n", + "For each observed centre, we create a galaxy containing:\n", "\n", - "For each extra galaxy centre (there is only one here, but the loop below scales to any number) we create a `Galaxy`\n", - "model with:\n", + "- A linear `ExponentialSph` light profile. Its centre is fixed, leaving `effective_radius` as one free non-linear\n", + " parameter. Its intensity is solved for during the linear inversion.\n", + "- An `IsothermalSph` mass profile. Its centre is also fixed, leaving `einstein_radius` as one free non-linear\n", + " parameter.\n", "\n", - " - A linear `ExponentialSph` light profile, with its `centre` fixed to the observed centre [1 free\n", - " parameter: `effective_radius`, as the `intensity` is solved for by the linear inversion].\n", + "The spherical profiles and fixed centres keep this model compact: the extra galaxy adds just two non-linear\n", + "parameters.\n", "\n", - " - An `IsothermalSph` mass profile, with its `centre` fixed to the observed centre [1 free\n", - " parameter: `einstein_radius`].\n", + "We assign its Einstein radius a uniform prior between 0.0\" and 0.5\", appropriate for the small companion in this\n", + "simulated example. For real data, this range should reflect what we know about the galaxy, and we should check\n", + "whether the inferred value approaches either prior boundary.\n", "\n", - "Extra galaxy mass profiles can wander to unphysically high `einstein_radius` values, degrading the fit, so we set\n", - "a `UniformPrior` with an upper limit of 0.5\" to prevent this. The extra galaxy is much less massive than the main\n", - "lens (whose `einstein_radius` is around 1.6\"), so this prior comfortably contains all plausible solutions.\n", + "We place the extra galaxies in an `af.Collection` and pass it through the overall model's `extra_galaxies` input,\n", + "alongside the main lens and source.\n", "\n", - "The extra galaxies are grouped into their own `af.Collection`, which is passed to the overall model via its\n", - "`extra_galaxies` input, alongside the `galaxies` collection containing the lens and source. This is the same\n", - "API used throughout the `autolens_workspace` for extra galaxies, and it is how **PyAutoLens** knows to include\n", - "these galaxies in the ray-tracing without treating them as the main lens or source." + "Here, the extra galaxy has redshift 0.5, matching the main lens. A galaxy at a different redshift would require\n", + "its appropriate redshift in the model." ] }, { @@ -580,8 +598,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The `info` attribute confirms the model includes the extra galaxy, with its fixed centres and its\n", - "free `effective_radius` and `einstein_radius` parameters." + "The `info` attribute shows the extra galaxy's fixed centres and the priors on its two free non-linear parameters:\n", + "`effective_radius` and `einstein_radius`.\n", + "\n", + "Its light-profile intensity is determined by the linear inversion during each likelihood evaluation, rather than\n", + "sampled by the non-linear search." ] }, { @@ -597,16 +618,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The same model can also be visualized as a figure, making its structure easier to understand at a glance.\n", + "The model can also be visualized as a figure, showing how its components and parameters are organized.\n", "\n", - "The figure shows how the model is organized: which parameters belong to each component, and whether they are free,\n", - "fixed, shared, linked by an expression, solved during the fit, or not configured. `model.info` provides the\n", - "corresponding numerical details, including the prior assigned to each free parameter and the value of each fixed\n", - "parameter.\n", + "Notice that the extra galaxy's light and mass centres are fixed to its measured position. This is the workflow\n", + "we will reuse as we introduce larger populations of galaxies: measure their positions first, then keep those\n", + "positions fixed while fitting their other properties.\n", "\n", - "The extra galaxy is part of the model and part of the ray-tracing, but it is neither the lens nor the source.\n", - "Its centres are fixed to the values we measured from the data and its light is linear, so an entire extra galaxy\n", - "costs just two more free parameters than the same lens-and-source model without it." + "Here, spherical profiles and a linearly solved light intensity mean the extra galaxy adds only two non-linear\n", + "parameters. The figure shows this structure, while `model.info` gives the numerical values and priors." ] }, { @@ -624,8 +643,14 @@ "source": [ "__Extra Galaxies Fit__\n", "\n", - "We fit this model with the same search set up as before. The model has only two more free parameters than the\n", - "noise-scaling fit, thanks to the fixed centres and linear light profile, so the fit remains fast." + "We fit the model using the same search settings as before.\n", + "\n", + "The extra galaxy adds only two non-linear parameters, keeping the increase in search dimensionality small.\n", + "Nevertheless, fitting time also depends on degeneracies between components and the cost of each likelihood\n", + "evaluation.\n", + "\n", + "This fit uses the original, unscaled data, so the extra galaxy's light now contributes to constraining the model\n", + "alongside the main lens and source." ] }, { @@ -644,14 +669,14 @@ "analysis = al.AnalysisImaging(dataset=dataset)\n", "\n", "print(\n", - " \"The non-linear search has begun running - checkout the output/howtolens/chapter_4/tutorial_1_extra_galaxies_model\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell with progress once search has completed - this could take some time!\"\n", + " \"The non-linear search has begun. Check the output/howtolens/chapter_4/tutorial_1_extra_galaxies_model\"\n", + " \" folder for results and visualizations as the search progresses.\"\n", + " \" This cell will finish when the search completes.\"\n", ")\n", "\n", "result_extra_galaxies = search.fit(model=model, analysis=analysis)\n", "\n", - "print(\"The search has finished run - you may now continue the notebook.\")" + "print(\"The search has finished \u2014 you may now continue the notebook.\")" ], "outputs": [], "execution_count": null @@ -660,8 +685,15 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Plotting the maximum log likelihood fit shows the extra galaxy's emission is now fitted by its own light profile,\n", - "and its mass has contributed deflections to the ray-tracing of the source." + "Inspect the maximum log likelihood fit below. The extra galaxy's emission is now represented by its own light\n", + "profile, and its mass contributes to the ray-tracing of the background source.\n", + "\n", + "Compare the residuals around the extra galaxy and the lensed arcs with the earlier fit. Also compare the inferred\n", + "main-lens parameters: accounting for the extra galaxy's mass may change them even if both fits appear visually\n", + "satisfactory.\n", + "\n", + "The two fits use different noise maps and different sets of informative pixels. Their raw likelihood or Bayesian\n", + "evidence values should therefore not be interpreted as a straightforward model comparison." ] }, { @@ -677,8 +709,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The result's `info` shows the inferred `einstein_radius` of the extra galaxy, quantifying how much lensing power\n", - "the interloper contributes to the system." + "The result's `info` summarizes the inferred parameters and their uncertainties, including the extra galaxy's\n", + "`einstein_radius`.\n", + "\n", + "Inspect its uncertainty and whether it lies close to a prior boundary. Including a mass profile does not\n", + "guarantee that the data tightly constrain its normalization.\n", + "\n", + "The inferred Einstein radius describes the lensing strength of the adopted `IsothermalSph` profile; it is not a\n", + "direct measurement of the galaxy's total mass." ] }, { @@ -696,51 +734,47 @@ "source": [ "__Which Approach When__\n", "\n", - "We have seen the two extremes of dealing with an extra galaxy. Choosing between them comes back to the\n", - "light-versus-mass question at the start of this tutorial, which in practice is settled by three properties of the\n", - "interloper:\n", - "\n", - "- **Distance from the lensed emission**: An extra galaxy whose light is well separated from the lensed source (as\n", - " in this tutorial) can be cleanly noise-scaled away. If its light blends into the source's arcs, noise scaling\n", - " would also delete source emission we need, and the light must be modeled instead.\n", + "Choosing how to handle an extra galaxy returns us to two separate questions: does its light affect the fit,\n", + "and do its gravitational deflections matter for the measurements we want to make?\n", "\n", - "- **Brightness**: A faint interloper whose emission barely rises above the noise can often be ignored entirely, or\n", - " noise-scaled with no consequence. A bright one must be removed or modeled, or it will bias the fit.\n", + "**Consider the light first.** If its emission is outside the fitting region or negligible compared with the noise,\n", + "we may not need a light profile. If it contaminates pixels we would otherwise fit, we can noise-scale those pixels\n", + "or model the emission explicitly.\n", "\n", - "- **Mass and proximity to the lens**: The mass matters when the extra galaxy is massive enough, and close enough\n", - " (in projection) to the lensed source's light, for its deflections to measurably perturb the ray-tracing. A rough\n", - " rule of thumb is to compare its expected Einstein radius to the astrometric precision of the data: a small galaxy\n", - " several arc-seconds from the arcs can have its mass safely ignored, whereas one abutting the Einstein ring\n", - " cannot. When in doubt, fit both approaches and compare the inferred lens models: if the main lens's mass\n", - " parameters shift appreciably, the extra galaxy's mass matters.\n", + "Noise scaling is useful when we can exclude the contaminated region without losing important source information.\n", + "If the extra galaxy overlaps the lensed arcs, explicitly modeling its light lets us retain those pixels, although\n", + "the accuracy of its light profile then matters.\n", "\n", - "Intermediate options also exist and are fully supported by the API: you can noise-scale the light but still include\n", - "the mass profile in the model, or model the light but omit the mass. The `extra_galaxies` collection simply\n", - "contains whatever profiles you give it.\n", + "**Consider the mass separately.** Its importance depends on its mass, redshift and position relative to the lensed\n", + "images, as well as the precision of the data and the scientific question. Neither faintness nor separation alone\n", + "guarantees that its deflections are negligible.\n", "\n", - "__Wrap Up__\n", - "\n", - "In this tutorial, we took the first step up in scale from the single lens galaxy of chapters 1 to 3, and learnt:\n", + "To investigate its effect, compare models with and without the extra mass profile while keeping the data\n", + "treatment and other modeling choices consistent. Inspect changes in the residuals and inferred parameters\n", + "relative to their uncertainties. A small change is useful evidence of robustness within the models tested,\n", + "rather than proof that every possible perturbation is negligible.\n", "\n", - "1. Real lenses live in crowded fields, and interloping extra galaxies are the first complication real data throws\n", - " at us.\n", + "The API supports each combination: model both light and mass, model only the light, or noise-scale the light while\n", + "retaining a mass profile.\n", "\n", - "2. Whether an extra galaxy matters hinges on two separate questions: does its **light** contaminate the region of\n", - " the image we fit, and does its **mass** perturb the ray-tracing of the source?\n", + "__Wrap Up__\n", "\n", - "3. Noise scaling removes an extra galaxy's light from the fit without adding model complexity, by zeroing its data\n", - " and inflating its noise, but leaves its mass unaccounted for.\n", + "In this tutorial, we learned:\n", "\n", - "4. The `extra_galaxies` modeling API includes extra galaxies in the model with their own light and mass profiles,\n", - " with their centres fixed to the observed light centres to keep parameter space simple and well behaved.\n", + "1. An extra galaxy's light and mass affect the analysis in different ways and should be considered separately.\n", + "2. Noise scaling, introduced in chapter 2, can exclude contaminating light from constraining the fit, but does not\n", + " remove the galaxy's gravitational effect.\n", + "3. The `extra_galaxies` collection lets us include the light and mass profiles needed for each galaxy.\n", + "4. Measuring light centres first and fixing them in the model is a common practical workflow. It becomes\n", + " increasingly useful as the number of galaxies grows.\n", + "5. The appropriate treatment depends on the data and scientific goal, and should be checked through fit\n", + " diagnostics and comparisons between consistent modeling choices.\n", "\n", - "5. Which approach is appropriate depends on the interloper's distance from the lensed emission, its brightness,\n", - " and its mass's proximity to the lens.\n", + "Here, one galaxy remained the dominant lens, with a smaller nearby galaxy adding a complication.\n", "\n", - "Throughout, the extra galaxy was a nuisance: something to remove or account for, so that our analysis of the\n", - "main lens remained accurate. In the next tutorial we meet systems where that framing breaks down entirely, because\n", - "a second galaxy is not a nuisance but a co-equal lens, with light and mass comparable to the first. There, no\n", - "single galaxy is \"the\" lens, and the model must treat them all on an equal footing." + "In the next tutorial, we consider systems where two or more galaxies contribute substantially to the lensing.\n", + "We will build models containing multiple main deflectors and explore the degeneracies between their mass\n", + "distributions." ] } ], @@ -768,7 +802,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_4_scaling_up_lensing/tutorial_1_extra_galaxies.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_group_lensing\n\n---\nname: al_group_lensing\ndescription: Model a group-scale strong lens — one or two main lens galaxies plus a population of companion (\"extra\") galaxies whose light + mass must also be modelled. Two strategies: (a) free per-companion profiles for small N, (b) \"scaling-relation\" galaxies tied to a luminosity-to-mass relation for larger N. Pairs with `al_cluster_csv_api` (when N is large enough that inline Python composition becomes unwieldy). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Group-scale lensing — companion galaxies and scaling relations\n\nA galaxy-scale model assumes one dominant lens. A group-scale lens has\nmultiple deflectors: a primary galaxy plus companions whose mass cannot be\nignored. With ~3–10 companions you can give each its own light + mass\nprofile (free). Past that, parameter count explodes and you instead tie\neach companion's mass to its observed luminosity via a scaling relation.\n\nWorkspace path: `autolens_workspace:scripts/group/start_here.py` and\n`scripts/group/features/scaling_relation/modeling.py`.\n\n## Ask\n\n- *\"How many lens galaxies — main + how many companions?\"* This picks the\n branch.\n- *\"Do you have light + position measurements for the companions, or just\n positions?\"* Scaling relations need a measured luminosity per\n companion.\n- *\"Source — single or multiple?\"* Group lenses sometimes have multiple\n background sources at different redshifts.\n- *\"Parametric or pixelised source?\"* Same trade-off as galaxy-scale.\n\n## Branch — small N: free per-companion mass profiles\n\n> TODO: recipe. Pattern: each companion gets its own `Galaxy` with light\n> + mass; centres are fixed from imaging measurements; mass-profile\n> normalisations are free. Bundle into a single `af.Collection`.\n\n## Branch — large N: scaling-relation companions\n\n> TODO: recipe. Pattern: a single set of shared scaling-relation\n> parameters (slope, normalisation, scatter) governs the mass of every\n> companion as a function of its measured luminosity. See\n> `PyAutoGalaxy:autogalaxy/galaxy/...` for the scaling-relation\n> machinery.\n\n## Branch — group with extra + scaling galaxies together\n\nSome companions are bright enough to deserve free mass; the rest follow\nthe scaling relation. Composed in one model.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_cluster_csv_api`](./al_cluster_csv_api.md) — for very large N\n (cluster-scale), spreadsheet-driven composition.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) — group SLaM\n variant exists in the workspace.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n — pixelised sources are common in group lenses.\n\n## Further reading\n\n- **Student / new to lensing** — _ (no direct HowToLens chapter; group\n lensing is an advanced topic).\n- **General reference** — [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n group lensing in the feature tour.\n- **Experienced PyAutoLens user** — [workspace/lens: group/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/group/start_here.py):\n the canonical group fit — extra galaxies, scaling relations, group\n SLaM.\n\nSee also [`wiki/core/concepts/group_and_cluster_lensing.md`](../wiki/core/concepts/group_and_cluster_lensing.md)\nfor the physics (group mass scale, cluster member kinematics, the\nextra-galaxy vs. scaling-relation choice).\n\n## Skill: al_build_imaging_model\n\n---\nname: al_build_imaging_model\ndescription: Compose a strong-lens model for imaging data — galaxies with light + mass profiles, prior customisation, and an `al.AnalysisImaging` ready to hand to a non-linear search. Writes a runnable Python script in scripts/. Pairs with `al_prepare_imaging_data` (which loads + masks the dataset) and `al_run_search` (which executes the fit). For visibility-plane data see `al_build_interferometer_model`.\n---\n\n# Composing an imaging lens model\n\nThe model is the PyAuto\\* representation of *what kind of lens you think this is* — how\nmany galaxies, at what redshifts, with what light and mass parameterisations, with\nwhich parameters free and which fixed. Building one is the step between \"I have a\nloaded `Imaging` dataset\" and \"I'm running a non-linear search\".\n\nThe canonical example is `autolens_workspace:scripts/imaging/modeling.py`. This skill\ngenerates the equivalent for the user's lens.\n\nThis skill assumes the imaging data is already preprocessing-ready. For real\nobservational data, confirm first that the user has **inspected `dataset.png`** and\nthought through mask extent, contaminating objects, and any regions to exclude — in\nparticular that any **extra galaxies** have been handled (noise-scaled via a\n`mask_extra_galaxies.fits`, or excluded by shrinking the circular mask). If not, route\nthem back to [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) before building the\nmodel — don't compose a model over data with an unaddressed contaminant.\n\n## Ask\n\n- *\"If this is real observational data, have you inspected `dataset.png`, decided the\n mask extent, and handled any extra galaxies (noise-scaled a `mask_extra_galaxies.fits`,\n or shrunk the mask to exclude them)?\"* — if not, stop and do that in\n [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) first.\n- *\"How many galaxies in the model — single galaxy-scale, multi-galaxy (2+ co-dominant, no host halo), group (2–10, optional group halo), cluster?\"* —\n this is the only structural choice. Skill below assumes galaxy-scale; bootstrap a\n variant for groups/clusters via `_bootstrap_skill` if needed.\n- *\"What's the lens light parameterisation — a single Sersic, MGE (multi-Gaussian\n expansion), bulge + disk, or no lens light at all (mass-only)?\"*\n- *\"What's the lens mass — Isothermal (SIE) + ExternalShear is the standard starting\n point; PowerLaw or NFW for total or dark-matter-only models.\"*\n- *\"What's the source — parametric Sersic, MGE, or pixelised inversion?\"* — pixelised\n needs a different `Analysis` wiring; see [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md).\n- *\"What are the lens and source redshifts?\"* — needed for distance ratios; even a\n ballpark value works for relative-comparison runs.\n\n## Branch — galaxy-scale, Sersic light + SIE mass + Sersic source\n\nThe minimum viable model. Save to `scripts/build_model.py`:\n\n```python\n# scripts/build_model.py\nfrom autonerves import jax_wrapper\nimport autofit as af\nimport autolens as al\n\n# Lens light — a Sersic for the bulge.\nlens_bulge = af.Model(al.lp.Sersic)\n\n# Lens mass — SIE plus a separate external field.\nlens_mass = af.Model(al.mp.Isothermal)\nlens_shear = af.Model(al.mp.ExternalShear)\n\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=lens_bulge,\n mass=lens_mass,\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=lens_shear)\n\n# Source light — a single Sersic.\nsource = af.Model(\n al.Galaxy,\n redshift=1.0,\n bulge=af.Model(al.lp.SersicCore),\n)\n\n# Compose into a Collection.\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# Optional: customise priors. E.g. tighten the lens centre.\nlens_mass.centre.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\nlens_mass.centre.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n\n# On real data, bound the Einstein radius from the ring you can see in the image\n# (the default prior is uniform over 0-8\"). A maximum-likelihood optimiser such as\n# MultiStartProdigy otherwise finds degenerate basins where theta_E exceeds the mask,\n# the \"source\" lands on a neighbouring galaxy and the ring is left in the residuals\n# (this is exactly what happened on the bundled COSMOS-Web Ring: theta_E 2.4\" vs 0.8\").\nlens_mass.einstein_radius = af.UniformPrior(lower_limit=0.3, upper_limit=1.5)\n\nprint(model.info)\n```\n\nSource citations:\n- `PyAutoGalaxy:autogalaxy/galaxy/galaxy.py` — `Galaxy`.\n- `PyAutoGalaxy:autogalaxy/galaxy/mass_field.py` — `MassField`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` — `Sersic`, `SersicCore`.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` — `Isothermal`.\n- `PyAutoFit:autofit/mapper/prior_model/prior_model.py` — `af.Model`.\n- `PyAutoFit:autofit/mapper/prior_model/collection.py` — `af.Collection`.\n\nWiki:\n- [`wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md) — what each\n light profile represents and when to pick which.\n- [`wiki/core/concepts/mass_profiles.md`](../wiki/core/concepts/mass_profiles.md) — same for mass.\n- [`wiki/core/concepts/galaxy_and_plane.md`](../wiki/core/concepts/galaxy_and_plane.md) — how\n galaxies, redshifts, and the `Tracer` fit together.\n\n## Branch — linear (MGE) lens light\n\nFor complex lens galaxy morphologies, replace the single Sersic bulge with a Multi-\nGaussian Expansion of *linear* light profiles. Linear profiles have their\n*intensities* solved analytically inside the fit, so the search only varies\nshape parameters — far fewer dimensions, much better convergence.\n\n```python\nn_gaussians = 30\ngaussian_per_basis = [\n af.Model(al.lp_linear.Gaussian) for _ in range(n_gaussians)\n]\n# Tie centres + ellipticities across the basis; let only sigma + intensity vary.\nfor g in gaussian_per_basis[1:]:\n g.centre = gaussian_per_basis[0].centre\n g.ell_comps = gaussian_per_basis[0].ell_comps\n\nlens_bulge = af.Model(al.lp_basis.Basis, profile_list=gaussian_per_basis)\n```\n\nSee `PyAutoGalaxy:autogalaxy/profiles/light/linear/` for the linear-profile classes.\n\n## Branch — pixelised source\n\nFor sources with complex morphology (lensed arcs, multiple components), reconstruct\nthe source on a pixel grid rather than as a parametric Sersic. The model wiring is\ndifferent: the source `Galaxy` carries a `Pixelization`, and the `Analysis` needs a\npositions likelihood penalty to keep the inversion well-posed.\n\nSee [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) for\nthe full pattern.\n\n## Wrap with an analysis\n\nOnce the model is built, wrap your loaded `dataset` (from `al_prepare_imaging_data`)\nin an analysis object:\n\n```python\nanalysis = al.AnalysisImaging(dataset=dataset)\n```\n\nSource: `PyAutoLens:autolens/imaging/model/analysis.py`.\n\n`analysis` + `model` are the two inputs to the non-linear search. Pass them to\n[`al_run_search`](./al_run_search.md).\n\n## Combine\n\nNatural next steps:\n\n- [`al_configure_search`](./al_configure_search.md) — pick Nautilus (default), Dynesty,\n Emcee, or another search; tune live points / walkers.\n- [`al_run_search`](./al_run_search.md) — `search.fit(model=model, analysis=analysis)`.\n- [`al_chain_searches`](./al_chain_searches.md) — chain a fast Sersic source fit into\n a slower pixelised one, inheriting priors.\n\n## Further reading\n\n- **Student / new to lensing** — [HowToLens: Non-linear searches and parameter\n inference](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb):\n how non-linear searches find a best-fit model — parameter spaces, likelihoods,\n priors. The statistical foundation under model composition.\n- **General reference** — [RTD: Model cookbook](https://pyautolens.readthedocs.io/en/latest/general/model_cookbook.html):\n systematic reference for building lens models with `Model` and `Collection` —\n two-component to multi-galaxy, prior customisation, parameter pairing, MGE.\n- **Experienced PyAutoLens user** — [workspace/lens: imaging/modeling/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling/start_here.py):\n the canonical imaging-modeling script — light-profile choice (Sersic vs. MGE),\n non-linear-search configuration, JAX/GPU fitting.\n" + "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_4_scaling_up_lensing/tutorial_1_extra_galaxies.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_group_lensing\n\n---\nname: al_group_lensing\ndescription: Model a group-scale strong lens \u2014 one or two main lens galaxies plus a population of companion (\"extra\") galaxies whose light + mass must also be modelled. Two strategies: (a) free per-companion profiles for small N, (b) \"scaling-relation\" galaxies tied to a luminosity-to-mass relation for larger N. Pairs with `al_cluster_csv_api` (when N is large enough that inline Python composition becomes unwieldy). Writes a runnable Python script in scripts/. **Status: stub.**\n---\n\n# Group-scale lensing \u2014 companion galaxies and scaling relations\n\nA galaxy-scale model assumes one dominant lens. A group-scale lens has\nmultiple deflectors: a primary galaxy plus companions whose mass cannot be\nignored. With ~3\u201310 companions you can give each its own light + mass\nprofile (free). Past that, parameter count explodes and you instead tie\neach companion's mass to its observed luminosity via a scaling relation.\n\nWorkspace path: `autolens_workspace:scripts/group/start_here.py` and\n`scripts/group/features/scaling_relation/modeling.py`.\n\n## Ask\n\n- *\"How many lens galaxies \u2014 main + how many companions?\"* This picks the\n branch.\n- *\"Do you have light + position measurements for the companions, or just\n positions?\"* Scaling relations need a measured luminosity per\n companion.\n- *\"Source \u2014 single or multiple?\"* Group lenses sometimes have multiple\n background sources at different redshifts.\n- *\"Parametric or pixelised source?\"* Same trade-off as galaxy-scale.\n\n## Branch \u2014 small N: free per-companion mass profiles\n\n> TODO: recipe. Pattern: each companion gets its own `Galaxy` with light\n> + mass; centres are fixed from imaging measurements; mass-profile\n> normalisations are free. Bundle into a single `af.Collection`.\n\n## Branch \u2014 large N: scaling-relation companions\n\n> TODO: recipe. Pattern: a single set of shared scaling-relation\n> parameters (slope, normalisation, scatter) governs the mass of every\n> companion as a function of its measured luminosity. See\n> `PyAutoGalaxy:autogalaxy/galaxy/...` for the scaling-relation\n> machinery.\n\n## Branch \u2014 group with extra + scaling galaxies together\n\nSome companions are bright enough to deserve free mass; the rest follow\nthe scaling relation. Composed in one model.\n\n> TODO: recipe.\n\n## Combine\n\n- [`al_cluster_csv_api`](./al_cluster_csv_api.md) \u2014 for very large N\n (cluster-scale), spreadsheet-driven composition.\n- [`al_run_slam_pipeline`](./al_run_slam_pipeline.md) \u2014 group SLaM\n variant exists in the workspace.\n- [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md)\n \u2014 pixelised sources are common in group lenses.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 _ (no direct HowToLens chapter; group\n lensing is an advanced topic).\n- **General reference** \u2014 [RTD: overview_3_features](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n group lensing in the feature tour.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: group/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/group/start_here.py):\n the canonical group fit \u2014 extra galaxies, scaling relations, group\n SLaM.\n\nSee also [`wiki/core/concepts/group_and_cluster_lensing.md`](../wiki/core/concepts/group_and_cluster_lensing.md)\nfor the physics (group mass scale, cluster member kinematics, the\nextra-galaxy vs. scaling-relation choice).\n\n## Skill: al_build_imaging_model\n\n---\nname: al_build_imaging_model\ndescription: Compose a strong-lens model for imaging data \u2014 galaxies with light + mass profiles, prior customisation, and an `al.AnalysisImaging` ready to hand to a non-linear search. Writes a runnable Python script in scripts/. Pairs with `al_prepare_imaging_data` (which loads + masks the dataset) and `al_run_search` (which executes the fit). For visibility-plane data see `al_build_interferometer_model`.\n---\n\n# Composing an imaging lens model\n\nThe model is the PyAuto\\* representation of *what kind of lens you think this is* \u2014 how\nmany galaxies, at what redshifts, with what light and mass parameterisations, with\nwhich parameters free and which fixed. Building one is the step between \"I have a\nloaded `Imaging` dataset\" and \"I'm running a non-linear search\".\n\nThe canonical example is `autolens_workspace:scripts/imaging/modeling.py`. This skill\ngenerates the equivalent for the user's lens.\n\nThis skill assumes the imaging data is already preprocessing-ready. For real\nobservational data, confirm first that the user has **inspected `dataset.png`** and\nthought through mask extent, contaminating objects, and any regions to exclude \u2014 in\nparticular that any **extra galaxies** have been handled (noise-scaled via a\n`mask_extra_galaxies.fits`, or excluded by shrinking the circular mask). If not, route\nthem back to [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) before building the\nmodel \u2014 don't compose a model over data with an unaddressed contaminant.\n\n## Ask\n\n- *\"If this is real observational data, have you inspected `dataset.png`, decided the\n mask extent, and handled any extra galaxies (noise-scaled a `mask_extra_galaxies.fits`,\n or shrunk the mask to exclude them)?\"* \u2014 if not, stop and do that in\n [`al_prepare_imaging_data`](./al_prepare_imaging_data.md) first.\n- *\"How many galaxies in the model \u2014 single galaxy-scale, multi-galaxy (2+ co-dominant, no host halo), group (2\u201310, optional group halo), cluster?\"* \u2014\n this is the only structural choice. Skill below assumes galaxy-scale; bootstrap a\n variant for groups/clusters via `_bootstrap_skill` if needed.\n- *\"What's the lens light parameterisation \u2014 a single Sersic, MGE (multi-Gaussian\n expansion), bulge + disk, or no lens light at all (mass-only)?\"*\n- *\"What's the lens mass \u2014 Isothermal (SIE) + ExternalShear is the standard starting\n point; PowerLaw or NFW for total or dark-matter-only models.\"*\n- *\"What's the source \u2014 parametric Sersic, MGE, or pixelised inversion?\"* \u2014 pixelised\n needs a different `Analysis` wiring; see [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md).\n- *\"What are the lens and source redshifts?\"* \u2014 needed for distance ratios; even a\n ballpark value works for relative-comparison runs.\n\n## Branch \u2014 galaxy-scale, Sersic light + SIE mass + Sersic source\n\nThe minimum viable model. Save to `scripts/build_model.py`:\n\n```python\n# scripts/build_model.py\nfrom autonerves import jax_wrapper\nimport autofit as af\nimport autolens as al\n\n# Lens light \u2014 a Sersic for the bulge.\nlens_bulge = af.Model(al.lp.Sersic)\n\n# Lens mass \u2014 SIE plus a separate external field.\nlens_mass = af.Model(al.mp.Isothermal)\nlens_shear = af.Model(al.mp.ExternalShear)\n\nlens = af.Model(\n al.Galaxy,\n redshift=0.5,\n bulge=lens_bulge,\n mass=lens_mass,\n)\nfield = af.Model(al.MassField, redshift=0.5, shear=lens_shear)\n\n# Source light \u2014 a single Sersic.\nsource = af.Model(\n al.Galaxy,\n redshift=1.0,\n bulge=af.Model(al.lp.SersicCore),\n)\n\n# Compose into a Collection.\nmodel = af.Collection(galaxies=af.Collection(lens=lens, source=source), fields=field)\n\n# Optional: customise priors. E.g. tighten the lens centre.\nlens_mass.centre.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\nlens_mass.centre.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n\n# On real data, bound the Einstein radius from the ring you can see in the image\n# (the default prior is uniform over 0-8\"). A maximum-likelihood optimiser such as\n# MultiStartProdigy otherwise finds degenerate basins where theta_E exceeds the mask,\n# the \"source\" lands on a neighbouring galaxy and the ring is left in the residuals\n# (this is exactly what happened on the bundled COSMOS-Web Ring: theta_E 2.4\" vs 0.8\").\nlens_mass.einstein_radius = af.UniformPrior(lower_limit=0.3, upper_limit=1.5)\n\nprint(model.info)\n```\n\nSource citations:\n- `PyAutoGalaxy:autogalaxy/galaxy/galaxy.py` \u2014 `Galaxy`.\n- `PyAutoGalaxy:autogalaxy/galaxy/mass_field.py` \u2014 `MassField`.\n- `PyAutoGalaxy:autogalaxy/profiles/light/standard/sersic.py` \u2014 `Sersic`, `SersicCore`.\n- `PyAutoGalaxy:autogalaxy/profiles/mass/total/isothermal.py` \u2014 `Isothermal`.\n- `PyAutoFit:autofit/mapper/prior_model/prior_model.py` \u2014 `af.Model`.\n- `PyAutoFit:autofit/mapper/prior_model/collection.py` \u2014 `af.Collection`.\n\nWiki:\n- [`wiki/core/concepts/light_profiles.md`](../wiki/core/concepts/light_profiles.md) \u2014 what each\n light profile represents and when to pick which.\n- [`wiki/core/concepts/mass_profiles.md`](../wiki/core/concepts/mass_profiles.md) \u2014 same for mass.\n- [`wiki/core/concepts/galaxy_and_plane.md`](../wiki/core/concepts/galaxy_and_plane.md) \u2014 how\n galaxies, redshifts, and the `Tracer` fit together.\n\n## Branch \u2014 linear (MGE) lens light\n\nFor complex lens galaxy morphologies, replace the single Sersic bulge with a Multi-\nGaussian Expansion of *linear* light profiles. Linear profiles have their\n*intensities* solved analytically inside the fit, so the search only varies\nshape parameters \u2014 far fewer dimensions, much better convergence.\n\n```python\nn_gaussians = 30\ngaussian_per_basis = [\n af.Model(al.lp_linear.Gaussian) for _ in range(n_gaussians)\n]\n# Tie centres + ellipticities across the basis; let only sigma + intensity vary.\nfor g in gaussian_per_basis[1:]:\n g.centre = gaussian_per_basis[0].centre\n g.ell_comps = gaussian_per_basis[0].ell_comps\n\nlens_bulge = af.Model(al.lp_basis.Basis, profile_list=gaussian_per_basis)\n```\n\nSee `PyAutoGalaxy:autogalaxy/profiles/light/linear/` for the linear-profile classes.\n\n## Branch \u2014 pixelised source\n\nFor sources with complex morphology (lensed arcs, multiple components), reconstruct\nthe source on a pixel grid rather than as a parametric Sersic. The model wiring is\ndifferent: the source `Galaxy` carries a `Pixelization`, and the `Analysis` needs a\npositions likelihood penalty to keep the inversion well-posed.\n\nSee [`al_inspect_source_reconstruction`](./al_inspect_source_reconstruction.md) for\nthe full pattern.\n\n## Wrap with an analysis\n\nOnce the model is built, wrap your loaded `dataset` (from `al_prepare_imaging_data`)\nin an analysis object:\n\n```python\nanalysis = al.AnalysisImaging(dataset=dataset)\n```\n\nSource: `PyAutoLens:autolens/imaging/model/analysis.py`.\n\n`analysis` + `model` are the two inputs to the non-linear search. Pass them to\n[`al_run_search`](./al_run_search.md).\n\n## Combine\n\nNatural next steps:\n\n- [`al_configure_search`](./al_configure_search.md) \u2014 pick Nautilus (default), Dynesty,\n Emcee, or another search; tune live points / walkers.\n- [`al_run_search`](./al_run_search.md) \u2014 `search.fit(model=model, analysis=analysis)`.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 chain a fast Sersic source fit into\n a slower pixelised one, inheriting priors.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens: Non-linear searches and parameter\n inference](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_2_lens_modeling/tutorial_1_non_linear_search.ipynb):\n how non-linear searches find a best-fit model \u2014 parameter spaces, likelihoods,\n priors. The statistical foundation under model composition.\n- **General reference** \u2014 [RTD: Model cookbook](https://pyautolens.readthedocs.io/en/latest/general/model_cookbook.html):\n systematic reference for building lens models with `Model` and `Collection` \u2014\n two-component to multi-galaxy, prior customisation, parameter pairing, MGE.\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: imaging/modeling/start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling/start_here.py):\n the canonical imaging-modeling script \u2014 light-profile choice (Sersic vs. MGE),\n non-linear-search configuration, JAX/GPU fitting.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" @@ -776,4 +810,4 @@ }, "nbformat": 4, "nbformat_minor": 4 -} \ No newline at end of file +} diff --git a/notebooks/chapter_4_scaling_up_lensing/tutorial_2_multi_galaxy.ipynb b/notebooks/chapter_4_scaling_up_lensing/tutorial_2_multi_galaxy.ipynb index 09320f8..6f07497 100644 --- a/notebooks/chapter_4_scaling_up_lensing/tutorial_2_multi_galaxy.ipynb +++ b/notebooks/chapter_4_scaling_up_lensing/tutorial_2_multi_galaxy.ipynb @@ -7,31 +7,25 @@ "Tutorial 2: Multi-Galaxy Lenses\n", "===============================\n", "\n", - "In the previous tutorial, we learned how to deal with extra galaxies near a strong lens \u2014 nuisance objects whose\n", - "light contaminates the data but which play no meaningful role in the lensing itself. We removed their emission\n", - "from the analysis, or gave them a heavily restricted model, and the single dominant lens galaxy remained the\n", - "star of the show.\n", + "In the previous tutorial, we modeled a system with one dominant lens galaxy and a smaller nearby galaxy.\n", + "We saw that the extra galaxy's light and gravitational deflections required separate consideration.\n", "\n", - "In this tutorial, we meet systems where that picture breaks down entirely: **multi-galaxy lenses**, where two\n", - "(or more) galaxies of comparable mass both contribute significantly to the lensing of a single background source.\n", - "Neither galaxy is a minor perturber we can mask away or simplify \u2014 they are **co-dominant deflectors**, and every\n", - "one of them needs its own free light and mass model.\n", + "We now consider **multi-galaxy lenses**, where two or more galaxies contribute substantially to the lensing of a\n", + "background source. Each significant deflector needs to be represented in the mass model, although we can still\n", + "fix or link appropriate parameters.\n", "\n", - "How do such systems arise physically? There are two main channels:\n", + "Such configurations can arise when galaxies at similar redshifts lie close together in projection, including\n", + "interacting or merging systems. They can also arise through chance alignments of galaxies at different redshifts.\n", "\n", - "- **Merging galaxies**: two galaxies at the same redshift caught in the act of merging, or orbiting one another\n", - " in close proximity. Their projected separation is small compared to the Einstein radius of their combined mass,\n", - " so the source's light rays feel both galaxies' gravity at once. Because both deflectors are at one redshift,\n", - " ray tracing is single-plane: their deflection angles simply add.\n", + "When we approximate the deflectors as lying at the same redshift, their deflection angles add on a single lens\n", + "plane. Deflectors at different redshifts require multi-plane ray-tracing, which accounts for how earlier deflections\n", + "change a ray's position at subsequent planes.\n", "\n", - "- **Chance line-of-sight alignments**: two physically unrelated galaxies at *different* redshifts that happen to\n", - " lie along the same line of sight. Light from the source is deflected first by the more distant galaxy, and the\n", - " already-deflected rays are deflected again by the nearer one. This is compound, multi-plane ray tracing \u2014 the\n", - " `Tracer` handles it natively by simply assigning each galaxy its redshift, and we will defer its details to\n", - " later in this chapter, where multi-plane lensing becomes the default at cluster scale.\n", + "In this tutorial, both lens galaxies are at the same redshift. We therefore focus on two modeling challenges:\n", + "the growing number of parameters and the degeneracies between the galaxies' mass distributions.\n", "\n", - "In this tutorial, both lens galaxies are at the same redshift, so we stay in the simpler single-plane regime and\n", - "focus on the modeling challenge that defines multi-galaxy lensing: the growth of the model's parameter space.\n", + "We will also reuse the practical workflow introduced in Tutorial 1: measure galaxy light centres first, then\n", + "use those positions to constrain the model.\n", "\n", "__Contents__\n", "\n", @@ -109,13 +103,16 @@ "source": [ "__Initial Setup__\n", "\n", - "We begin with `Imaging` of a strong lens where **two** lens galaxies, separated by 2.0\", both deflect the light\n", - "of a single background source:\n", + "We begin with an `Imaging` dataset containing two lens galaxies, separated by 2.0\", which both deflect light from\n", + "a single background source.\n", "\n", - " - The two lens galaxies' light are `Sersic` profiles, centred at (0.0\", -1.0\") and (0.0\", 1.0\").\n", - " - The two lens galaxies' mass distributions are `Isothermal` profiles with comparable Einstein radii (1.0\" and\n", - " 0.8\") \u2014 this comparability is what makes them co-dominant.\n", - " - The source galaxy's light is an `ExponentialCoreSph`.\n", + "- Their light follows `Sersic` profiles centred at `(0.0, -1.0)` and `(0.0, 1.0)`, using our usual `(y, x)`\n", + " coordinates in arcseconds.\n", + "- Their mass follows `Isothermal` profiles with Einstein-radius parameters of 1.0\" and 0.8\".\n", + "- The source light follows an `ExponentialCoreSph` profile.\n", + "\n", + "Both galaxies contribute substantially to the deflection field. Their individual Einstein-radius parameters\n", + "describe the two mass profiles; neither alone describes the critical curves of the combined system.\n", "\n", "__Dataset Auto-Simulation__\n", "\n", @@ -153,9 +150,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "When we plot the data, the difference from every lens we have modeled so far is obvious: there are two bright\n", - "lens galaxies, and the lensed source's arcs wrap around the *pair as a whole* rather than around either galaxy\n", - "individually. The mass distribution the source's light responds to is the sum of both galaxies' mass." + "Plot the dataset and identify the two lens galaxies and the surrounding lensed source emission.\n", + "\n", + "The source is lensed by their combined deflection field, so we must interpret the image configuration using both\n", + "galaxies together. We cannot treat it as two independent single-galaxy lenses.\n", + "\n", + "Notice where the galaxies' light overlaps the source emission: our model will need to separate these contributions\n", + "while fitting the data." ] }, { @@ -173,16 +174,16 @@ "source": [ "__Mask__\n", "\n", - "We define a 3.0\" circular mask. For a multi-galaxy lens, sizing the mask needs more care than at galaxy scale:\n", - "the Einstein radius that matters is that of the *combined* mass distribution, not either galaxy's individually.\n", - "A mask sized by eye from one galaxy's light would clip the arcs, which extend beyond both galaxies' centres." + "We use a circular mask with radius 4.0\", centred between the two lens galaxies. Inspect the masked dataset to check\n", + "that it retains the lensed source emission, including its fainter outskirts. For multi-galaxy lenses, choose the\n", + "fitting region from the full image configuration rather than either galaxy's individual Einstein radius." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "mask_radius = 3.0\n", + "mask_radius = 4.0\n", "\n", "mask = al.Mask2D.circular(\n", " shape_native=dataset.shape_native,\n", @@ -201,14 +202,19 @@ "source": [ "__Over Sampling__\n", "\n", - "We use the adaptive over sampling scheme introduced in earlier chapters, which evaluates the steep central\n", - "regions of the lens galaxies' light at high resolution. The one multi-galaxy specific point is that the adaptive\n", - "grid is centred on **every** deflector, not just one \u2014 each galaxy has its own steep central light profile\n", - "needing accurate evaluation, and `centre_list` takes as many centres as we give it.\n", + "We use the adaptive over-sampling method introduced in earlier chapters to evaluate the galaxies' steep central\n", + "light profiles accurately.\n", + "\n", + "Here, we supply both galaxy centres through `centre_list`, so the higher-resolution sampling covers the central\n", + "region of each galaxy.\n", "\n", - "The two centres below are the observed centres of the two lens galaxies, which for this simulated dataset we\n", - "know exactly. For real data you would measure them from the image itself (the `autolens_workspace` provides a\n", - "GUI which writes them from mouse clicks)." + "This reuses the measured-position workflow from Tutorial 1. For real data, we can obtain the light centres using\n", + "a GUI, a source-detection tool or a preliminary light-profile fit. For this simulated dataset, we use the known\n", + "input positions.\n", + "\n", + "These positions currently determine where the grid receives finer sampling; supplying them to the over-sampling\n", + "function does **not** fix any model parameters. Later, we will explicitly fix the galaxies' mass centres to\n", + "these positions." ] }, { @@ -237,31 +243,38 @@ "source": [ "__Model__\n", "\n", - "We now compose the lens model, and here the multi-galaxy regime shows its teeth. Every co-dominant deflector\n", - "needs its own free light and mass model, so the model has one `Galaxy` entry per deflector.\n", + "We now build a model containing two lens galaxies and one background source.\n", + "\n", + "We loop over the measured lens-galaxy positions and create a separate `Galaxy` model for each deflector, named\n", + "`lens_0`, `lens_1`, and so on. This composition extends naturally to systems containing more galaxies.\n", + "\n", + "Each lens galaxy's light is represented by a Multi-Gaussian Expansion (MGE), using the\n", + "`al.model_util.mge_model_from` helper. This constructs the Gaussian basis using the approach introduced in chapter 2.\n", "\n", - "We build each lens galaxy in a loop over the observed centres and store them as `lens_0`, `lens_1`, etc. This\n", - "list-based composition scales to any number of deflectors, and it is the same API the `autolens_workspace`'s\n", - "`multi_galaxy` package (and the group-scale examples above it) use \u2014 so nothing needs re-learning later.\n", + "Each MGE contains 20 Gaussians with fixed widths, a shared centre and shared elliptical components. Their\n", + "intensities are solved by the linear inversion, leaving four non-linear light parameters per galaxy: two centre\n", + "coordinates and two elliptical components.\n", "\n", - "For each lens galaxy's light we use a Multi Gaussian Expansion (MGE) made of linear light profiles, built by the\n", - "utility function `al.model_util.mge_model_from` (this hides the longer `Basis` composition API we stepped through\n", - "in the linear profiles tutorial of chapter 2). For each lens galaxy's mass we use an `Isothermal` (SIE) profile,\n", - "initially with every parameter free. The source is also an MGE.\n", + "An MGE does not necessarily add any non-linear parameters. If its Gaussian widths are fixed, its centre is fixed\n", + "to the measured light position, and its Gaussians are spherical, only their intensities remain to be determined.\n", + "These are solved by the linear inversion, so the entire light model adds **zero non-linear parameters**,\n", + "regardless of how many Gaussians it contains.\n", "\n", - "The MGE choice matters more here than anywhere we have used it before. Each lens galaxy's 20 Gaussians add just\n", - "**4 non-linear parameters** (a shared centre and shared elliptical components \u2014 every `sigma` is fixed and every\n", - "`intensity` is solved for by the linear inversion). A single ordinary `Sersic` bulge would add 7 non-linear\n", - "parameters per galaxy, and would fit the blended, overlapping light of a close pair far less well. Because the\n", - "multi-galaxy regime multiplies whatever light model we choose by the number of deflectors, a light model that is\n", - "both cheap and flexible is close to essential \u2014 this is exactly where the MGE shines.\n", + "If we instead fit shared elliptical components while keeping the centre fixed, the MGE adds **two** non-linear\n", + "parameters. Freeing the shared centre as well increases this to **four**, as in the model used here.\n", "\n", - "Each Isothermal mass model adds 5 free parameters: its centre (2), elliptical components (2) and Einstein\n", - "radius (1).\n", + "An MGE offers flexibility when fitting overlapping galaxy light without sampling every Gaussian intensity.\n", + "Whether that flexibility is needed depends on the observed morphology; a simpler light profile can still be\n", + "appropriate.\n", "\n", - "An external shear would enter the model as a separate `MassField` through `fields=field`. It describes the tidal\n", - "field of structure *outside* the system, so it belongs to neither deflector. We omit it here to keep the parameter\n", - "accounting simple." + "Each galaxy's mass is represented by an `Isothermal` profile, initially with five free parameters: two centre\n", + "coordinates, two elliptical components and an Einstein radius. The source light is also represented by an MGE.\n", + "\n", + "The measured positions locate the priors on the lens light centres; those centres remain free in this model.\n", + "We will explicitly fix the mass centres in the next step.\n", + "\n", + "We omit external shear in this example. If included, it would enter through a separate `MassField`, representing\n", + "an additional tidal contribution to the combined deflection field." ] }, { @@ -307,8 +320,10 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The model's `info` shows `lens_0` and `lens_1` each carrying their own free mass model \u2014 the signature of the\n", - "multi-galaxy regime \u2014 and its `prior_count` gives the total number of free parameters." + "The model's `info` shows the light and mass components of `lens_0` and `lens_1`, together with the source model.\n", + "\n", + "Inspect which parameters are free, which are fixed and which are shared between Gaussian profiles. We will use\n", + "`model.prior_count` below to count the free non-linear parameters." ] }, { @@ -324,16 +339,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The same model can also be visualized as a figure, making its structure easier to understand at a glance.\n", + "The figure shows the structure of our initial model. Each lens galaxy has its own `Isothermal` mass profile,\n", + "with free centre coordinates, elliptical components and Einstein radius.\n", "\n", - "The figure shows how the model is organized: which parameters belong to each component, and whether they are free,\n", - "fixed, shared, linked by an expression, solved during the fit, or not configured. `model.info` provides the\n", - "corresponding numerical details, including the prior assigned to each free parameter and the value of each fixed\n", - "parameter.\n", + "This is an intermediate model used to illustrate the parameter count. Before fitting, we will fix each mass\n", + "centre to its measured light position.\n", "\n", - "Each deflector has its own `mass \u00b7 Isothermal` with a free `centre`, `ell_comps` and `einstein_radius`: two\n", - "independent, fully free mass models. That is the defining feature of this regime, and the thing every earlier\n", - "chapter lacked." + "Compare the light and mass components: sharing parameters within an MGE reduces its dimensionality, but the two\n", + "galaxies still have separate light and mass models." ] }, { @@ -351,31 +364,39 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The count is **22**: each deflector contributes 4 (MGE light) + 5 (SIE mass) = 9 free parameters, and the MGE\n", - "source contributes the final 4. Compare this to the equivalent single-galaxy model, which has just 13 \u2014 one\n", - "co-dominant deflector added 9 parameters, and every further deflector will add 9 more. Model complexity compounds\n", - "fast in this regime, and with plain Sersic light profiles instead of MGEs it would compound faster still (12 per\n", - "deflector rather than 9).\n", + "The initial model has **22 free non-linear parameters**:\n", + "\n", + "- Each lens galaxy contributes four light parameters and five mass parameters.\n", + "- The source contributes four light parameters.\n", + "\n", + "The equivalent single-lens model would have 13. Adding the second deflector therefore adds nine parameters before\n", + "we impose further restrictions.\n", "\n", "__Fixing the Mass Centres__\n", "\n", - "Before fitting, we make one change that is standard practice for multi-galaxy lenses: we **fix each galaxy's\n", - "mass centre to its observed light centre**, removing 2 free parameters per deflector.\n", + "We now fix each galaxy's mass centre to its measured light centre, removing two free parameters per deflector.\n", + "\n", + "This follows the common workflow introduced in Tutorial 1: measure galaxy positions from the image using a GUI,\n", + "a source-detection tool or a preliminary light-profile fit, then use those positions as fixed inputs to the lens\n", + "model.\n", + "\n", + "With multiple deflectors, the lensed images constrain their combined deflection field. Changes in one galaxy's\n", + "mass centre can sometimes be compensated by changes in another galaxy's position, ellipticity or mass\n", + "normalization. Fixing the centres reduces this freedom and can make the search more manageable.\n", "\n", - "Why? With a single lens galaxy, the data usually constrains the mass centre well: the arcs pin down where the\n", - "deflection field is centred, and there is only one plausible culprit. With multiple deflectors this breaks down.\n", - "The source's light responds to the *summed* deflection field, so a small shift of one galaxy's mass centre can be\n", - "compensated by shifts of the other's centre, ellipticity or Einstein radius \u2014 the free centres become extremely\n", - "degenerate with one another. The search wanders these degeneracies, converging slowly and often settling in\n", - "unphysical corners of parameter space where one galaxy's mass has drifted far from any light.\n", + "Here, we fix only the **mass centres**. The MGE light centres retain their existing priors and remain free,\n", + "allowing the light fit to refine their positions. The fixed mass positions are the supplied measurements;\n", + "they do not move with the fitted light centres.\n", "\n", - "Fixing each mass centre to the galaxy's light centre resolves this at minimal cost. Light traces stellar mass,\n", - "and the stellar body sits at the bottom of the galaxy's potential well, so the light centre is an excellent\n", - "estimate of the mass centre. (Measuring a genuine offset between mass and light \u2014 which interacting pairs can\n", - "show at the kiloparsec level \u2014 is real science, but it is a *follow-up* fit performed after a robust model with\n", - "fixed centres has been found.)\n", + "Fixing the mass centres alone does not reduce the MGE's parameter count: the current code still uses elliptical\n", + "MGEs with free light centres. A spherical MGE with fixed widths and a fixed light centre would instead add zero\n", + "non-linear light parameters, as described above.\n", "\n", - "Assigning a tuple to the mass model's `centre` fixes it, so it is no longer a free parameter with a prior." + "This assumes that each mass distribution is centred on its measured light position. It is a useful starting\n", + "point, but does not establish that light and mass must be perfectly aligned. Where positional uncertainty or\n", + "possible offsets matter, we can allow appropriate freedom and investigate its effect.\n", + "\n", + "Assigning a coordinate tuple to `mass.centre` fixes both coordinates rather than assigning them priors." ] }, { @@ -422,8 +443,12 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Printing the model's `info` again, each mass `centre` is now listed as a fixed value with no prior, and the\n", - "free parameter count has dropped from 22 to **18** \u2014 each SIE now contributes 3 free parameters instead of 5." + "Printing the updated model's `info` shows that both mass centres are now fixed.\n", + "\n", + "Each `Isothermal` profile therefore has three free parameters: two elliptical components and one Einstein radius.\n", + "The light models are unchanged.\n", + "\n", + "Fixing two coordinates for each of two galaxies removes four parameters, reducing the total from **22 to 18**." ] }, { @@ -439,10 +464,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The two `mass \u00b7 Isothermal` centres are now fixed to the measured light centres rather than sampled, and\n", - "nothing else about the model has changed: twenty-two free parameters down to eighteen.\n", + "The figure now shows each galaxy's mass centre fixed to its measured light position.\n", + "\n", + "Two fixed centres remove four non-linear parameters, reducing the model from 22 to 18. The MGE light centres and\n", + "elliptical components remain free, so each galaxy's light model still contributes four non-linear parameters.\n", "\n", - "Four centres fixed, four dimensions gone. That is the standard trick of the multi-galaxy regime." + "Recall that a spherical MGE with fixed widths and a fixed light centre would contribute zero non-linear\n", + "parameters. We retain the more flexible elliptical light models here." ] }, { @@ -462,10 +490,15 @@ "source": [ "__Model Fit__\n", "\n", - "We fit the model with the nested sampling algorithm `Nautilus`, as in previous chapters. Because this model has\n", - "more free parameters than the single-galaxy fits of chapter 2 (which used 100 live points), we raise `n_live`\n", - "to 200 \u2014 a multi-galaxy parameter space is more multi-modal, and too few live points risks converging on a local\n", - "maximum where the two galaxies' Einstein radii have been mis-apportioned." + "We fit the model using `Nautilus`, as in previous chapters.\n", + "\n", + "With two deflectors, the search must explore correlations between their mass profiles as well as the source\n", + "parameters. We use 200 live points here, compared with 100 in our earlier examples, to give the search more scope\n", + "to explore this parameter space.\n", + "\n", + "Increasing the number of live points does not guarantee a reliable result. Inspect the fitted images and\n", + "posterior distributions, and check the stability of important conclusions using repeated searches or more\n", + "demanding search settings where needed." ] }, { @@ -484,9 +517,9 @@ "analysis = al.AnalysisImaging(dataset=dataset)\n", "\n", "print(\n", - " \"The non-linear search has begun running - checkout the output/howtolens/chapter_4/tutorial_2_multi_galaxy\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell with progress once search has completed - this could take some time!\"\n", + " \"The non-linear search has begun. Check the output/howtolens/chapter_4/tutorial_2_multi_galaxy\"\n", + " \" folder for results and visualizations as the search progresses.\"\n", + " \" This cell will finish when the search completes.\"\n", ")\n", "\n", "result = search.fit(model=model, analysis=analysis)" @@ -500,8 +533,12 @@ "source": [ "__Result__\n", "\n", - "The result's `info` shows the inferred model, with each deflector's parameters listed under its own `lens_0` /\n", - "`lens_1` entry." + "The result's `info` summarizes the inferred parameters and their uncertainties. The two deflectors appear\n", + "separately under `lens_0` and `lens_1`.\n", + "\n", + "Compare their inferred Einstein radii and elliptical components, remembering that the parameters of one galaxy\n", + "may be correlated with those of the other. The fixed mass centres are assumptions supplied to the fit, rather\n", + "than positions measured independently by this search." ] }, { @@ -517,9 +554,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The tracer subplot is worth a close look for a multi-galaxy lens: the critical curve is that of the *combined*\n", - "mass distribution, so it wraps around the pair as a whole rather than encircling either galaxy individually \u2014\n", - "just as the arcs in the data do." + "Inspect the tracer subplot to see how the two galaxies combine to lens the source.\n", + "\n", + "The critical curves belong to the combined lens mapping. Depending on the galaxies' masses, shapes and separation,\n", + "they can form connected or separate structures; they are not obtained by simply drawing an Einstein ring around\n", + "each galaxy.\n", + "\n", + "Then inspect the fit subplot. Check whether the model reproduces both galaxies' light and the lensed source\n", + "emission, and look for coherent residuals around the arcs or where the light components overlap.\n", + "\n", + "A satisfactory image fit is an essential check, but it does not establish that each galaxy's mass is individually\n", + "well constrained. We investigate that next using the posterior." ] }, { @@ -539,9 +584,27 @@ "source": [ "__Mass Degeneracies__\n", "\n", - "The corner plot of the posterior is where the multi-galaxy regime reveals its most important lesson. Below we\n", - "plot the probability density function of every parameter; when you run this tutorial for real (rather than\n", - "skimming the generated output), focus on the panel showing `lens_0`'s Einstein radius against `lens_1`'s." + "Multiple significant deflectors introduce additional mass degeneracies beyond those encountered in single-galaxy\n", + "lenses. The lensed images constrain the galaxies' **combined deflection field**, so changes in one galaxy's mass\n", + "distribution can be compensated by changes in another's.\n", + "\n", + "Consequently, a model may reproduce the arcs accurately while leaving substantial uncertainty in how the mass is\n", + "divided between the galaxies. This is a major challenge of multi-galaxy modeling: a well-constrained combined lens\n", + "does not necessarily imply well-constrained individual galaxy masses.\n", + "\n", + "Single-galaxy lenses also have mass-source degeneracies, but multiple deflectors add freedom to redistribute mass\n", + "**between galaxies**. How severe this becomes depends on their separation and the positions and quality of the\n", + "lensed images.\n", + "\n", + "In the corner plot below, find the panel comparing the `einstein_radius` parameters of `lens_0` and `lens_1`.\n", + "Look for a correlation: can a larger mass normalization for one galaxy be compensated by a smaller normalization\n", + "for the other?\n", + "\n", + "Also inspect how these parameters correlate with the galaxies' elliptical components and the source parameters.\n", + "The degeneracy need not involve only the two Einstein radii.\n", + "\n", + "The shape and extent of these distributions tell us more about the uncertainty in the mass decomposition than a\n", + "single best-fit model can." ] }, { @@ -557,41 +620,54 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "You will see a strongly elongated, tilted degeneracy: the two Einstein radii are *anti-correlated*. When one\n", - "galaxy's Einstein radius goes up, the other's goes down, tracing out a narrow ridge in parameter space.\n", + "Look for an elongated distribution in the panel comparing the two Einstein-radius parameters. An anti-correlation\n", + "indicates that increasing one galaxy's mass normalization can be compensated by decreasing the other's.\n", + "\n", + "This illustrates the additional degeneracy introduced by multiple significant deflectors. The images respond to\n", + "the combined deflection field, so different allocations of mass between the galaxies can produce similar lensed\n", + "images.\n", "\n", - "The physical reason is the summed deflection field. The arcs constrain the **total** mass enclosed by the\n", - "combined Einstein ring extremely well \u2014 move along the ridge and the sum of the two galaxies' deflections barely\n", - "changes, so the fit to the data barely changes either. What the data constrains much more weakly is the **split**\n", - "of that mass between the two galaxies. The closer the pair (relative to the combined Einstein radius), the less\n", - "information the arcs carry about which galaxy the mass belongs to, and the longer the ridge grows.\n", + "The combined mass distribution can therefore be better constrained than its division between individual galaxies.\n", + "However, the strength and shape of this degeneracy depend on the configuration: arcs sampling different regions\n", + "around each galaxy can help distinguish their contributions.\n", "\n", - "This has a real scientific cost. For a single-galaxy lens, the Einstein mass is one of the cleanest measurements\n", - "in astrophysics. For a multi-galaxy lens, the total is still clean, but per-galaxy quantities \u2014 each galaxy's\n", - "mass, its mass-to-light ratio, its dark matter fraction \u2014 inherit the full width of the degeneracy, and their\n", - "error bars can be many times larger than the total's. Any interpretation built on the split (e.g. comparing the\n", - "two galaxies' dark matter content) must honestly propagate this, which is why we fit these systems with a\n", - "sampler that maps the full posterior rather than an optimizer that returns a single best-fit point: the best-fit\n", - "point sits somewhere on the ridge and tells you nothing about the ridge's length.\n", + "Single-galaxy lenses already have degeneracies involving the mass profile and source. Multi-galaxy lenses retain\n", + "these and introduce further freedom to redistribute mass between deflectors. Fixing their centres reduces that\n", + "freedom, but does not eliminate the degeneracy between their mass normalizations and shapes.\n", + "\n", + "This matters scientifically. Measurements of each galaxy's mass, mass-to-light ratio or dark matter fraction must\n", + "propagate the joint uncertainty, including correlations between galaxies. A single best-fit model cannot describe\n", + "the range of mass decompositions allowed by the data.\n", "\n", "__No Shared Halo__\n", "\n", - "It is worth being explicit about an assumption we did *not* make. We modeled two galaxies, each with its own\n", - "untruncated `Isothermal` mass profile, and simply added their deflections. We did not assume the pair inhabits a\n", - "single, large, shared dark matter halo \u2014 and because there is no host halo in the model, we also made no\n", - "assumptions about tidal stripping or the truncation of each galaxy's individual halo.\n", + "So far, we have represented the lens using separate galaxy-centred mass profiles, without adding a larger dark\n", + "matter halo shared by the galaxies.\n", + "\n", + "Such a model may describe an interacting or merging pair of field galaxies, where a separate group-scale halo is\n", + "not needed to explain the lensing. This is particularly relevant for smaller-separation lens systems, with\n", + "Einstein radii of roughly a few arcseconds or less -- around 3\" as an illustrative scale, rather than a strict\n", + "boundary.\n", "\n", - "At this scale, that is the right call: a pair (or triple) of comparable galaxies has no dominant halo for its\n", - "members to be stripped by, and the data cannot demand one. But climb the mass ladder and it changes. At the\n", - "group scale, a dominant group-sized halo enters the model as an explicit choice, and the member galaxies orbiting\n", - "within it are tidally truncated by its potential \u2014 assumptions that reshape the entire mass model, as we will\n", - "see later in this chapter.\n", + "Other systems are better described as members of a **galaxy group**, embedded in a common dark matter halo. The\n", + "Einstein radius alone does not establish which interpretation is appropriate; the galaxy environment and other\n", + "observations also matter.\n", + "\n", + "In the [group-scale tutorial](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_4_scaling_up_lensing/tutorial_4_group_scale.ipynb),\n", + "we extend the model by including a shared halo alongside the individual galaxies. We will explore how the lensing\n", + "signal is divided between these components and how to keep models containing many galaxies manageable.\n", + "\n", + "Omitting a shared halo here is therefore a modeling choice appropriate to our example, rather than a claim that\n", + "all galaxy pairs lack one.\n", "\n", "__Three Lens Galaxies__\n", "\n", - "What happens when a third co-dominant deflector joins the system? Let us load a triple-galaxy lens, simulated\n", - "with three `Isothermal` mass profiles of comparable Einstein radii (0.9\", 0.8\" and 0.7\") arranged in a triangle,\n", - "all lensing a single source." + "We now load a simulated system containing three lens galaxies, each contributing substantially to the lensing of\n", + "one background source.\n", + "\n", + "Their `Isothermal` profiles have Einstein-radius parameters of 0.9\", 0.8\" and 0.7\", with centres arranged in a\n", + "triangle. Plot the dataset and identify the three galaxies and the lensed source emission before composing the\n", + "model." ] }, { @@ -626,10 +702,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We compose the three-deflector model with exactly the same loop as before \u2014 this is the payoff of the list-based\n", - "API, which needs no changes as the deflector count grows. Each mass centre is again fixed to its galaxy's\n", - "observed light centre; with three deflectors the centre degeneracies are even more severe than for the pair, so\n", - "the standard trick matters even more." + "We build the three-deflector model using the same loop as before, now supplying three measured light positions.\n", + "\n", + "Each galaxy receives its own MGE light model and `Isothermal` mass profile. We again fix the mass centre to the\n", + "supplied light position while leaving the MGE light centre free within its priors.\n", + "\n", + "This illustrates why measuring positions before modeling is useful: adding another galaxy does not require the\n", + "search to discover where its mass profile belongs.\n", + "\n", + "The model still allows the galaxies' mass normalizations and shapes to compensate for one another. Fixing centres\n", + "makes the problem more manageable; it does not remove the mass-decomposition degeneracies." ] }, { @@ -646,6 +728,15 @@ "\n", "dataset = dataset.apply_mask(mask=mask)\n", "\n", + "over_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n", + " grid=dataset.grid,\n", + " sub_size_list=[4, 2, 2],\n", + " radial_list=[0.3, 0.6],\n", + " centre_list=lens_centres,\n", + ")\n", + "\n", + "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n", + "\n", "lens_dict = {}\n", "\n", "for i, centre in enumerate(lens_centres):\n", @@ -688,10 +779,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "A third deflector, `lens_2`, is an identical copy of the structure above, with its own fixed mass `centre`.\n", + "The figure now includes `lens_2`, with the same model structure as the other two deflectors but its own parameters\n", + "and fixed mass position.\n", + "\n", + "Each galaxy contributes four non-linear light parameters and three non-linear mass parameters. Adding the third\n", + "galaxy therefore adds seven parameters.\n", "\n", - "Nothing about the *shape* of the model changed when we added a galaxy, which is exactly the point the\n", - "list-based API is making. The model grows by one deflector, and the parameter count by seven." + "The code structure remains the same as the number of galaxies grows, but the inference problem becomes larger and\n", + "can develop stronger correlations between components." ] }, { @@ -709,52 +804,43 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The count is now **25**: even with fixed mass centres and cheap MGE light models, every deflector adds 7 free\n", - "parameters (4 light + 3 mass), and with free centres it would be 9. The trend is linear and unforgiving:\n", + "The three-galaxy model has **25 free non-linear parameters**: seven per lens galaxy and four for the source.\n", "\n", - " - 1 deflector: 13 free parameters.\n", - " - 2 deflectors: 18 (this tutorial's fit).\n", - " - 3 deflectors: 25.\n", - " - 10 deflectors: ~74. A group-scale lens can easily have this many members.\n", + "With the same model choices and fixed mass centres throughout:\n", "\n", - "And the parameter count is only half the problem. As the deflectors multiply, so do the degeneracies between\n", - "their masses \u2014 every pair of galaxies gets its own version of the Einstein radius ridge we saw above, and the\n", - "posterior becomes progressively harder for any sampler to map.\n", + "- One deflector: **11** parameters.\n", + "- Two deflectors: **18** parameters.\n", + "- Three deflectors: **25** parameters.\n", + "- Ten deflectors: **74** parameters.\n", "\n", - "You are welcome to fit this three-galaxy model yourself \u2014 the search above works unchanged, though expect it to\n", - "take noticeably longer than the pair. Clearly, freeing every galaxy's mass cannot scale to the tens or hundreds\n", - "of member galaxies in groups and clusters. Something has to give.\n", + "These counts depend on our light-model choices. Fixed-width, fixed-centre spherical MGEs would add zero non-linear\n", + "light parameters, reducing the totals substantially where that description is appropriate.\n", "\n", - "__Wrap Up__\n", + "Even then, independently fitting every galaxy's mass normalization and shape becomes demanding as the population\n", + "grows. The challenge is both the number of parameters and the degeneracies between their contributions to the\n", + "combined deflection field.\n", "\n", - "In this tutorial, we modeled strong lenses with multiple co-dominant deflectors. Let's summarise what we've\n", - "learnt:\n", + "You can explore fitting the three-galaxy model by creating an `AnalysisImaging` for this newly loaded dataset and\n", + "running a search with a distinct output name. Reusing the earlier analysis object would incorrectly fit the\n", + "two-galaxy dataset.\n", "\n", - "- **Co-dominant deflectors**: When two or more galaxies of comparable mass both contribute significantly to the\n", - " lensing, every one of them needs its own free light and mass model \u2014 unlike the nuisance neighbours of the\n", - " previous tutorial, none can be masked away or simplified.\n", - "\n", - "- **Physical origins**: Multi-galaxy lenses arise from merging galaxies at one redshift (single-plane, deflections\n", - " add) or chance line-of-sight alignments at different redshifts (multi-plane ray tracing, covered later in this\n", - " chapter).\n", - "\n", - "- **Parameter growth**: Each deflector added 9 free parameters (4 for its MGE light, 5 for its SIE mass) \u2014 and the\n", - " MGE is what kept it that cheap, since its Gaussian intensities are solved for by linear algebra rather than sampled.\n", - "\n", - "- **Fixed mass centres**: Fixing each galaxy's mass centre to its observed light centre (removing 2 parameters per\n", - " deflector) is the standard trick for taming the severe centre degeneracies of multi-deflector models.\n", - "\n", - "- **Mass degeneracies**: The data constrains the total mass well but its split between the galaxies poorly,\n", - " producing an anti-correlated ridge between the deflectors' Einstein radii \u2014 and inflating the uncertainties on\n", - " any per-galaxy science.\n", - "\n", - "- **No shared halo**: At this scale we do not assume the galaxies inhabit one large dark matter halo, so no tidal\n", - " truncation assumptions enter the model \u2014 that framing arrives at group scale.\n", + "__Wrap Up__\n", "\n", - "The three-galaxy model made the trajectory clear: freeing every deflector cannot scale. In the next tutorial, we\n", - "introduce the tool that stops this growth in its tracks \u2014 scaling relations, which tie the masses of many\n", - "galaxies to their observed luminosities so that an entire population of deflectors costs almost no extra free\n", - "parameters." + "In this tutorial, we learned:\n", + "\n", + "- Multiple significant deflectors require a model of their combined lensing effect.\n", + "- Measuring galaxy positions first and fixing mass centres can reduce the search dimensionality and restrict\n", + " unwanted solutions.\n", + "- MGE intensities are solved linearly. A spherical MGE with fixed widths and centre adds no non-linear parameters;\n", + " our more flexible light models retain four per galaxy.\n", + "- Multiple galaxies introduce additional mass degeneracies beyond those in single-galaxy lenses. A good image fit\n", + " can leave substantial uncertainty in the individual galaxy masses.\n", + "- A shared halo and tidal truncation are modeling choices to assess for the system, rather than properties\n", + " determined solely by how many galaxies are present.\n", + "\n", + "As the number of galaxies increases, giving every galaxy an independent mass model becomes increasingly demanding.\n", + "In the next tutorial, we introduce **scaling relations**, which link galaxy mass properties to observed\n", + "luminosities through shared parameters." ] } ], @@ -790,4 +876,4 @@ }, "nbformat": 4, "nbformat_minor": 4 -} \ No newline at end of file +} diff --git a/notebooks/chapter_4_scaling_up_lensing/tutorial_3_scaling_relation.ipynb b/notebooks/chapter_4_scaling_up_lensing/tutorial_3_scaling_relation.ipynb index e8dbca9..cb72ecd 100644 --- a/notebooks/chapter_4_scaling_up_lensing/tutorial_3_scaling_relation.ipynb +++ b/notebooks/chapter_4_scaling_up_lensing/tutorial_3_scaling_relation.ipynb @@ -7,40 +7,38 @@ "Tutorial 3: Scaling Relations\n", "=============================\n", "\n", - "The previous tutorial ended on a warning: every deflector we add to a lens model brings its own free parameters.\n", - "Two galaxies were manageable, but each one cost us a mass profile's worth of dimensions, and the arithmetic only\n", - "gets worse. A group-scale lens may have ten member galaxies, a cluster hundreds. If every member keeps its own\n", - "free mass, the parameter space explodes \u2014 a 100-galaxy cluster with 5 free mass parameters per galaxy is a\n", - "500-dimensional model, which no non-linear search can sample and no dataset can constrain anyway.\n", - "\n", - "This tutorial introduces the tool that stops the explosion: the **scaling relation**. Instead of giving every\n", - "galaxy its own mass freedom, we set each galaxy's mass from something we can *measure* \u2014 its luminosity \u2014 via a\n", - "relation shared by the whole population. The relation itself has only a few global parameters (in this tutorial,\n", - "zero new ones!), so the dimensionality of the model stops growing with the number of galaxies. Ten members or a\n", - "hundred, the parameter space stays the same size.\n", - "\n", - "This pairs beautifully with a tool we already have. In chapter 2, we saw that a Multi-Gaussian Expansion (MGE)\n", - "fits a galaxy's light using linear algebra, so its intensities add no non-linear parameters. Put the two\n", - "together and the recipe for a many-galaxy lens model emerges:\n", - "\n", - "- **Light:** MGE for every galaxy \u2014 flexible light models at (almost) no non-linear cost.\n", - "- **Mass:** a scaling relation tying every galaxy's mass to its measured luminosity \u2014 a whole population of\n", - " mass profiles at no non-linear cost.\n", - "\n", - "The entire many-galaxy system then costs barely more than a single-lens fit. This tutorial builds that model on\n", - "the two-lens dataset from the previous tutorial, verifies the parameter counting explicitly, and is honest about\n", - "what a scaling relation assumes and when it can bite you.\n", + "In the previous tutorial, we saw how adding significant deflectors increases both the number of parameters and\n", + "the degeneracies between galaxy masses. Independently fitting the mass of every member becomes increasingly\n", + "demanding for groups and clusters.\n", + "\n", + "A **scaling relation** reduces this freedom by linking galaxy mass properties to measured luminosities through\n", + "a relation shared by the population.\n", + "\n", + "Here, one galaxy anchors the relation: its Einstein radius remains free, while the other galaxies' Einstein\n", + "radii follow from their luminosity ratios. With fixed positions, spherical mass profiles and a fixed scaling\n", + "exponent, each additional tied galaxy adds **zero non-linear mass parameters**.\n", + "\n", + "The light-model choices still matter. As we discussed in Tutorial 2, a spherical MGE with fixed widths and centre\n", + "adds zero non-linear light parameters. An elliptical MGE with a fixed centre and free shared elliptical\n", + "components adds two, as in this tutorial.\n", + "\n", + "Scaling relations therefore control the growth of the mass model; they do not automatically make every part of\n", + "a many-galaxy model independent of galaxy count. More galaxies also increase the computational work required to\n", + "evaluate the model.\n", + "\n", + "We will introduce the method using the familiar two-galaxy dataset, compare parameter counts and examine the\n", + "assumptions we impose when tying galaxy masses together.\n", "\n", "__Overview__\n", "\n", "In this tutorial, we will:\n", "\n", - "- Explain the physics of why luminosity predicts lensing mass (mass-follows-light and the Faber-Jackson relation).\n", + "- Explain the assumptions linking luminosity to mass normalization through the Faber-Jackson relation.\n", "\n", "- Compose a lens model where one galaxy \"anchors\" the relation and the other galaxy's Einstein radius is tied to\n", " it via the ratio of their measured luminosities.\n", "\n", - "- Verify by explicit parameter counting that tied galaxies add zero free parameters, however many there are.\n", + "- Verify by explicit parameter counting that tied galaxies add zero additional non-linear mass parameters.\n", "\n", "- Fit the model and inspect how a tied parameter appears in the results.\n", "\n", @@ -68,41 +66,54 @@ "\n", "__Mass Follows Light__\n", "\n", - "Why should a galaxy's luminosity tell us anything about its lensing mass?\n", + "Galaxy luminosity provides useful information about mass, but it does not determine an individual galaxy's mass\n", + "exactly.\n", + "\n", + "For early-type galaxies, the empirical **Faber-Jackson relation** links luminosity to stellar velocity dispersion.\n", + "A commonly used approximate form is:\n", + "\n", + "$$\n", + "L \\propto \\sigma_\\star^4.\n", + "$$\n", + "\n", + "For a spherical isothermal lens, the Einstein radius is related to its mass-model velocity-dispersion parameter by:\n", "\n", - "The starting point is that light traces stars and stars trace mass. A more luminous elliptical galaxy contains\n", - "more stars, sits in a deeper potential well, and its stars therefore move faster. This is quantified by the\n", - "**Faber-Jackson relation**, an empirical scaling law for elliptical galaxies which states that luminosity grows\n", - "steeply with the velocity dispersion \\sigma of the stars:\n", + "$$\n", + "\\theta_{\\rm E}\n", + "=4\\pi\\left(\\frac{\\sigma_{\\rm SIS}}{c}\\right)^2\n", + "\\frac{D_{\\rm ls}}{D_{\\rm s}},\n", + "$$\n", "\n", - " L ~ \\sigma^4\n", + "where $D_{\\rm ls}$ and $D_{\\rm s}$ are angular-diameter distances from lens to source and observer to source.\n", "\n", - "Lensing connects \\sigma to the deflection of light. For the isothermal mass profiles we have used throughout\n", - "these tutorials, the Einstein radius is set directly by the velocity dispersion:\n", + "Assuming that the mass-model velocity dispersion scales with the measured stellar velocity dispersion, galaxies\n", + "at the same lens redshift lensing the same source approximately satisfy:\n", "\n", - " \\theta_E = 4 \\pi (\\sigma / c)^2 (D_ls / D_s)\n", + "$$\n", + "\\theta_{\\rm E}\\propto L^{1/2}.\n", + "$$\n", "\n", - "where the D's are distances between observer, lens and source. So \\theta_E ~ \\sigma^2, and combining the two\n", - "scalings gives us a relation between the two things we care about \u2014 the Einstein radius we want to know and the\n", - "luminosity we can measure:\n", + "We therefore adopt:\n", "\n", - " \\theta_E ~ \\sigma^2 ~ (L^{1/4})^2 = L^{1/2}\n", + "$$\n", + "\\theta_{{\\rm E},i}\n", + "=\\theta_{{\\rm E},{\\rm anchor}}\n", + "\\left(\\frac{L_i}{L_{\\rm anchor}}\\right)^{0.5}.\n", + "$$\n", "\n", - "If one galaxy in a lens system has a measured luminosity L_anchor and Einstein radius \\theta_E_anchor, every\n", - "other galaxy's Einstein radius follows from its own luminosity:\n", + "This is a population-level modeling assumption. The exponent need not be universal, individual galaxies scatter\n", + "around the relation, and stellar and mass-model velocity dispersions are not automatically identical.\n", "\n", - " \\theta_E_i = \\theta_E_anchor * (L_i / L_anchor)^{0.5}\n", + "The phrase \"mass follows light\" here refers to linking mass normalization to luminosity. We are not requiring\n", + "the spatial mass distribution to have the same shape as the observed light.\n", "\n", - "This is the scaling relation we will build into the model below. The exponent 0.5 is the Faber-Jackson value;\n", - "more sophisticated versions exist (the \"fundamental plane\" adds a dependence on galaxy size and surface\n", - "brightness, tightening the relation), but the Faber-Jackson form captures the essential physics and is the\n", - "standard workhorse for lens modeling. It is the same idea that cluster lensing studies have used for decades:\n", - "tie the hundreds of cluster member galaxies to their luminosities via a scaling relation, so the model stays\n", - "tractable.\n", + "Only luminosity ratios enter this expression, so a common multiplicative calibration cancels. However, the\n", + "measurements must use a consistent waveband and luminosity definition. Changing waveband can change the ratios\n", + "because galaxies have different stellar populations and colours.\n", "\n", - "The crucial property is that only *ratios* of luminosity enter the relation. The absolute calibration, the\n", - "units, even the waveband cancel out (so long as all galaxies are measured consistently) \u2014 which is what makes\n", - "the relation so easy to apply in practice." + "For galaxies at different redshifts, observed flux ratios are not directly luminosity ratios, and the\n", + "lensing-distance factors also differ. Our example avoids these complications by placing both deflectors at the\n", + "same redshift." ] }, { @@ -167,11 +178,17 @@ "source": [ "__Initial Setup__\n", "\n", - "We use the same two-lens-galaxy imaging dataset as the previous tutorial, where:\n", + "We use the same two-galaxy imaging dataset as in Tutorial 2:\n", "\n", - " - Both lens galaxies' light are `Sersic` profiles.\n", - " - Both lens galaxies' mass distributions are `Isothermal` profiles.\n", - " - The source galaxy's light is an `ExponentialCoreSph`." + "- Both lens galaxies have `Sersic` light profiles.\n", + "- Both have `Isothermal` mass profiles.\n", + "- The source light follows an `ExponentialCoreSph` profile.\n", + "\n", + "Reusing this dataset lets us compare independently fitted galaxy masses with masses linked through a scaling\n", + "relation.\n", + "\n", + "The simulated masses were specified independently, so we should check how closely they satisfy our adopted\n", + "relation rather than assume that they do." ] }, { @@ -225,15 +242,17 @@ "source": [ "__Mask__\n", "\n", - "We define a 3.0\" circular mask, which contains both lens galaxies (centred at (0.0\", -1.0\") and (0.0\", 1.0\"))\n", - "and the lensed source emission." + "We use the same 4.0\" circular mask as in Tutorial 2, centred between the two lens galaxies.\n", + "\n", + "Keeping the fitting region consistent helps us compare the effects of changing the model. Inspect the masked\n", + "subplot to check that the lensed emission we want to analyze is retained." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "mask_radius = 3.0\n", + "mask_radius = 4.0\n", "\n", "mask = al.Mask2D.circular(\n", " shape_native=dataset.shape_native,\n", @@ -254,19 +273,34 @@ "source": [ "__Measured Luminosities__\n", "\n", - "The scaling relation needs two inputs for every galaxy it touches: its centre and its luminosity. Neither is a\n", - "free parameter of the model \u2014 both are **measurements**, made from the imaging data before the mass model is\n", - "ever fitted.\n", + "Our relation uses a measured position and luminosity estimate for each galaxy. We treat these as fixed inputs\n", + "in this example.\n", + "\n", + "For real observations, positions and luminosities can come from a preliminary light-profile fit or a suitable\n", + "photometric catalogue. In blended systems, separating each galaxy's light from its neighbours and the lensed\n", + "source is an important part of this measurement.\n", + "\n", + "Magnitudes measured consistently in the same band can be converted to flux ratios using:\n", + "\n", + "$$\n", + "\\frac{F_i}{F_{\\rm anchor}}\n", + "=10^{0.4(m_{\\rm anchor}-m_i)}.\n", + "$$\n", + "\n", + "For galaxies at the same distance, with consistent photometric treatment, these provide the luminosity ratios\n", + "used here.\n", "\n", - "In a real analysis these come from a light-only fit performed first: for example, fitting an MGE to every\n", - "galaxy and integrating it to a total flux (the `autolens_workspace`'s scaling-relation SLaM pipeline does exactly\n", - "this). Because only luminosity *ratios* enter the relation, a magnitude catalogue from any survey works just as\n", - "well, converting via `L_i / L_anchor = 10 ** (0.4 * (m_anchor - m_i))`.\n", + "Because this dataset is simulated, we can load the true light profiles from `tracer.json`. We obtain each\n", + "galaxy's centre and integrate its profile within a circular aperture of radius `mask_radius`, centred on that\n", + "galaxy.\n", "\n", - "In this tutorial we take a shortcut available only with simulated data: the simulator saved the true galaxies to\n", - "a `tracer.json` file, so we load it and integrate each lens galaxy's true light profile directly. This keeps the\n", - "tutorial self-contained, but keep in mind that on real data this step is a fit to the data, with its own\n", - "(small) uncertainties." + "These are **aperture luminosities**, not integrals over the entire profile. Using the same aperture definition\n", + "makes the measurements consistent, but does not guarantee that the aperture contains the same fraction of every\n", + "galaxy's total light.\n", + "\n", + "This shortcut isolates the scaling-relation machinery. Real measurements have uncertainties from noise, blending\n", + "and light-model choices; treating their values as fixed does not propagate those uncertainties into the inferred\n", + "masses." ] }, { @@ -301,12 +335,19 @@ "source": [ "__The Anchor__\n", "\n", - "The relation needs an \"anchor\": one galaxy whose Einstein radius is a free parameter of the model, off which\n", - "every other galaxy's Einstein radius hangs. We use the brightest galaxy, identified by `argmax` over the\n", - "measured luminosities \u2014 a measurement, not an assumption about which galaxy happens to be listed first.\n", + "We choose one galaxy as the **anchor**: its Einstein radius is a free parameter, and the other galaxies' Einstein\n", + "radii are linked to it through their measured luminosity ratios.\n", + "\n", + "Here, we select the galaxy with the largest measured aperture luminosity using `argmax`. This provides a\n", + "convenient reference; it does not establish that the brightest galaxy has a precisely known mass or must follow\n", + "the relation perfectly.\n", "\n", - "Anchoring on a galaxy the model is already fitting is the key trick: the anchor's `einstein_radius` is not a new\n", - "parameter, so the relation itself will add **zero** free parameters to the model." + "The anchor's Einstein radius sets the normalization of the relation and is inferred from the lensing data.\n", + "Because it is already a parameter of the anchor's mass profile, tying additional galaxies to it introduces no\n", + "separate normalization parameter.\n", + "\n", + "We also fix the exponent to 0.5. Allowing the exponent or other properties of the relation to vary would add\n", + "shared parameters, rather than necessarily adding one parameter per galaxy." ] }, { @@ -331,8 +372,11 @@ "source": [ "__Over Sampling__\n", "\n", - "As in the previous tutorial, we apply adaptive over-sampling centred on both lens galaxies, so the steeply\n", - "varying central light of each is computed accurately." + "As in Tutorial 2, we apply adaptive over-sampling around both measured galaxy centres so that their steep central\n", + "light profiles are evaluated accurately.\n", + "\n", + "These positions determine where the light calculation receives finer sampling. Fixing a light or mass profile's\n", + "centre remains a separate model-composition step, which we perform below." ] }, { @@ -357,19 +401,22 @@ "source": [ "__Light Via MGE__\n", "\n", - "Every galaxy's light is modelled with a Multi-Gaussian Expansion, composed via the `al.model_util.mge_model_from`\n", - "convenience function (this wraps the `Basis` of linear `Gaussian` profiles we built by hand in chapter 2 into a\n", - "single call \u2014 the composition it returns is the same).\n", + "We represent each lens galaxy's light with an MGE, constructed using `al.model_util.mge_model_from`.\n", "\n", - "Because the galaxy centres were measured above, we fix each MGE's centre to them (passing the measured centre as\n", - "both the `centre` and `centre_fixed` inputs, which fixes it rather than giving it a prior). The Gaussian\n", - "`sigma` values are fixed by the basis and the intensities are solved for by linear algebra, so each galaxy's\n", - "light costs just **two** non-linear parameters: its elliptical components. This is the \"light adds (almost) no\n", - "parameters\" half of the recipe from the introduction.\n", + "We fix its centre to the measured light position. The Gaussian widths are also fixed, and their intensities are\n", + "solved by the linear inversion.\n", "\n", - "The anchor galaxy also gets its mass: a free `Isothermal` profile with its centre fixed at the measured light\n", - "centre. Its `einstein_radius` is an ordinary free parameter \u2014 but it is also what the scaling relation below\n", - "hangs off." + "If the Gaussians were spherical, this would leave **zero non-linear light parameters**, regardless of the number\n", + "of Gaussians.\n", + "\n", + "Here, we retain two free elliptical components shared by the Gaussians, allowing the light model to be flattened\n", + "and rotated. Each galaxy therefore contributes **two non-linear light parameters**.\n", + "\n", + "The anchor also receives an elliptical `Isothermal` mass profile with its centre fixed to the measured position.\n", + "Its two elliptical components and Einstein radius remain free.\n", + "\n", + "The anchor's Einstein radius serves two purposes: it determines the normalization of its own mass profile and\n", + "sets the normalization of the scaling relation for the other galaxies." ] }, { @@ -401,7 +448,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The source galaxy is also an MGE, with a free centre (we have no pre-measured position for the unlensed source)." + "The source is also represented by an MGE, but its centre remains free because its unlensed position is inferred\n", + "through the lens model.\n", + "\n", + "Its Gaussian widths are fixed and its intensities are solved linearly. The shared centre coordinates and\n", + "elliptical components contribute four non-linear source parameters." ] }, { @@ -426,22 +477,37 @@ "source": [ "__Scaling Relation__\n", "\n", - "Now the relation itself. The fainter galaxy's mass is a spherical isothermal profile whose `einstein_radius` is\n", - "not given a prior \u2014 instead, it is *assigned an expression*: the anchor's `einstein_radius` multiplied by the\n", - "luminosity ratio raised to the Faber-Jackson exponent of 0.5.\n", + "We now assign the other galaxy a spherical `IsothermalSph` mass profile and fix its centre to the measured\n", + "light position.\n", "\n", - "This single line is the whole trick. Because `mass_anchor.einstein_radius` is the model's own free parameter,\n", - "multiplying it by a fixed number produces a **derived quantity**, not a new parameter. Whenever the non-linear\n", - "search proposes an Einstein radius for the anchor, every tied galaxy's Einstein radius follows automatically.\n", + "Rather than assigning its `einstein_radius` an independent prior, we express it in terms of the anchor's:\n", "\n", - "The tied galaxy keeps its MGE bulge (its light is inside the mask and must be fitted), so it costs two light\n", - "parameters and **zero** mass parameters.\n", + "$$\n", + "\\theta_{{\\rm E},i}\n", + "=\\theta_{{\\rm E},{\\rm anchor}}\n", + "\\left(\\frac{L_i}{L_{\\rm anchor}}\\right)^{0.5}.\n", + "$$\n", "\n", - "An honest aside before we continue: this dataset's two galaxies are comparably bright, and for a genuine system\n", - "of two co-dominant deflectors the previous tutorial's model \u2014 full mass freedom for both \u2014 is the right choice.\n", - "A galaxy contributing half the lensing deserves its own parameters. We tie one here so you can learn the\n", - "machinery on a familiar dataset; the regime where the relation genuinely earns its keep is a *population* of\n", - "fainter members, which we build towards below and which dominates the next tutorial." + "Whenever the search proposes an Einstein radius for the anchor, the tied galaxy's Einstein radius follows\n", + "automatically. It is a **derived parameter**, with no independent sampling dimension.\n", + "\n", + "Three choices together give this galaxy zero non-linear mass parameters: its centre is fixed, its profile is\n", + "spherical, and its Einstein radius is tied to the anchor. The scaling relation itself removes only the independent\n", + "Einstein-radius parameter; fixing the centre and adopting a spherical profile provide the other reductions.\n", + "\n", + "Its elliptical MGE still contributes two non-linear light parameters. A spherical MGE with fixed widths and\n", + "centre would reduce that light contribution to zero as well.\n", + "\n", + "We use this familiar two-galaxy dataset to demonstrate the machinery. However, both galaxies contribute\n", + "substantially to the lensing, so tying their masses imposes a strong restriction on a quantity the previous\n", + "tutorial allowed the data to constrain.\n", + "\n", + "An independent mass model provides a useful comparison for such important deflectors. A scaling relation may be\n", + "appropriate when supported by the scientific assumptions, but its apparent precision must not be mistaken for\n", + "information supplied entirely by the lensing data.\n", + "\n", + "The simplification becomes especially useful for populations of less influential galaxies. We can tie that\n", + "population while retaining independent mass parameters for galaxies whose contributions need more flexibility." ] }, { @@ -483,14 +549,16 @@ "source": [ "__Model__\n", "\n", - "The model has two top-level collections: `galaxies` (the anchor and the source) and `scaling_galaxies` (the tied\n", - "population). This is not just presentational \u2014 `scaling_galaxies` is the collection name **PyAutoLens** expects a\n", - "scaling population in: the analysis appends it to the tracer's galaxy list when fitting, and results loaded back\n", - "via the aggregator restore it. It also keeps `model.info` readable, with the tied population visibly separate\n", - "from the freely modelled galaxies.\n", + "We assemble the model using two collections:\n", + "\n", + "- `galaxies` contains the anchor lens galaxy and the source.\n", + "- `scaling_galaxies` contains the galaxies whose mass normalizations follow the scaling relation.\n", + "\n", + "Both collections contribute to the lens model. Keeping the tied population separate makes its role easier to\n", + "inspect and follows the convention used in the workspace examples.\n", "\n", - "Inspecting `model.info` below, note that the tied galaxies have no `einstein_radius` prior of their own \u2014 it is\n", - "listed as a function of the anchor's." + "Inspect `model.info` below. The tied galaxy's `einstein_radius` is expressed in terms of the anchor's parameter\n", + "rather than assigned an independent prior." ] }, { @@ -511,15 +579,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The same model can also be visualized as a figure, making its structure easier to understand at a glance.\n", + "The figure shows how the tied galaxy's Einstein radius depends on the anchor's.\n", "\n", - "The figure shows how the model is organized: which parameters belong to each component, and whether they are free,\n", - "fixed, shared, linked by an expression, solved during the fit, or not configured. `model.info` provides the\n", - "corresponding numerical details, including the prior assigned to each free parameter and the value of each fixed\n", - "parameter.\n", + "It has no independent prior or sampling dimension, but it remains a parameter of the galaxy's mass profile. Its\n", + "value changes as the search varies the anchor's Einstein radius.\n", "\n", - "The tied galaxy's `einstein_radius` is not sampled at all. It is computed from the anchor lens galaxy's via the\n", - "scaling relation, so it has no prior, because it is not a parameter." + "With fixed luminosity ratios and a fixed exponent, uncertainty in the anchor propagates directly to the tied\n", + "Einstein radius. This does not include uncertainty in the luminosity measurements or intrinsic scatter around\n", + "the scaling relation." ] }, { @@ -537,9 +604,22 @@ "source": [ "__Parameter Counts__\n", "\n", - "Let's verify the claims above by counting, rather than believing. First we recompose the previous tutorial's\n", - "style of model on this dataset \u2014 every galaxy with its own free elliptical `Isothermal` mass (centres fixed at\n", - "the measured light centres, as above, so the comparison is like-for-like)." + "We now compare models with different amounts of mass freedom.\n", + "\n", + "First, we give each lens galaxy an independent elliptical `Isothermal` mass profile with a fixed centre. We\n", + "retain the same fixed-centre MGE light models and the same source model used above.\n", + "\n", + "Each lens galaxy then contributes two non-linear light parameters and three mass parameters. Including the\n", + "source's four parameters gives **14** in total.\n", + "\n", + "Our scaling-relation model has **11**: five for the anchor's light and mass, two for the tied galaxy's light,\n", + "and four for the source.\n", + "\n", + "The reduction from 14 to 11 combines two changes to the second galaxy: adopting a spherical mass profile removes\n", + "two elliptical components, and tying its Einstein radius removes one further parameter.\n", + "\n", + "This comparison differs from Tutorial 2's 18-parameter model because we have also fixed both lens galaxies'\n", + "light centres here." ] }, { @@ -569,7 +649,7 @@ ")\n", "\n", "print(\n", - " f\"Free parameters, per-galaxy model (previous tutorial): {model_per_galaxy.prior_count}\"\n", + " f\"Free parameters, independent elliptical masses: {model_per_galaxy.prior_count}\"\n", ")\n", "print(f\"Free parameters, scaling-relation model: {model.prior_count}\")" ], @@ -580,10 +660,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The scaling-relation model is smaller. To isolate exactly what the relation saves, we compose one more variant:\n", - "identical to the scaling-relation model in every way, except each tied galaxy's `einstein_radius` is freed with\n", - "a uniform prior instead of tied. The difference in parameter count must equal the number of tied galaxies \u2014\n", - "one saved `einstein_radius` each." + "To isolate the effect of the scaling relation itself, we build another model with exactly the same profiles,\n", + "fixed centres and light-model choices as the tied model.\n", + "\n", + "The only change is that the second galaxy's Einstein radius receives an independent uniform prior instead of\n", + "being linked to the anchor.\n", + "\n", + "This model has **12** free non-linear parameters, compared with **11** for the tied model. The scaling relation\n", + "therefore saves one parameter for this one tied galaxy.\n", + "\n", + "The assertion below checks that the difference equals the number of tied galaxies." ] }, { @@ -629,13 +715,29 @@ "source": [ "__Scaling To Many Galaxies__\n", "\n", - "Saving one parameter looks modest \u2014 the point is what happens as the population grows. Below we imagine this\n", - "lens had twelve additional member galaxies (we invent centres on a ring and plausible luminosities; this model\n", - "is composed for counting only, **not** fitted \u2014 our dataset contains no such galaxies!).\n", + "Saving one parameter becomes more consequential when we model a population of galaxies.\n", "\n", - "Each imagined member is mass-only (faint distant perturbers whose light is negligible or outside the mask need\n", - "no light model \u2014 the mass-only counterpart of the intermediate options tutorial 1 discussed), with its Einstein\n", - "radius tied to the anchor by the same relation. We count the parameters of this 14-galaxy lens model, and of its nightmare per-galaxy twin." + "Below, we add twelve hypothetical members with specified positions and luminosities. These galaxies are not\n", + "present in our simulated image: we construct these models only to compare parameter counts, and do not fit them\n", + "to the data.\n", + "\n", + "Each additional member receives a spherical mass profile with a fixed centre. In one model, its Einstein radius\n", + "follows the anchor through the scaling relation. In the comparison model, its Einstein radius has an independent\n", + "prior.\n", + "\n", + "We omit light profiles for these hypothetical members to isolate the mass-parameter count. In a real analysis,\n", + "their light would need to be assessed separately, as in Tutorial 1. Being a faint or secondary deflector does\n", + "not automatically make its light negligible.\n", + "\n", + "The original two-galaxy model is unchanged in both comparisons. In particular, its original tied galaxy remains\n", + "tied; only the twelve additional members differ.\n", + "\n", + "The tied model therefore remains at **11** non-linear parameters, while giving the twelve new members independent\n", + "Einstein radii increases the count to **23**.\n", + "\n", + "This demonstrates a constant mass-parameter count under our chosen restrictions. Evaluating the extra deflections\n", + "still adds computational work, and any additional light-model freedom or per-galaxy scatter parameters would\n", + "need to be counted separately." ] }, { @@ -688,7 +790,7 @@ " f\"Free parameters, 14-galaxy scaling model: {model_many_tied.prior_count}\"\n", ")\n", "print(\n", - " f\"Free parameters, 14-galaxy per-galaxy-mass model: {model_many_freed.prior_count}\"\n", + " f\"Free parameters, 12 additional members with free Einstein radii: {model_many_freed.prior_count}\"\n", ")\n", "\n", "assert model_many_tied.prior_count == model.prior_count" @@ -700,14 +802,22 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Twelve more galaxies, zero more parameters. The tied model's dimensionality is *independent of the number of\n", - "galaxies* \u2014 this is the property that makes group- and cluster-scale lens modeling possible at all, and it is\n", - "why the assertion above is worth having in the script rather than in prose.\n", + "Adding twelve mass-only galaxies through the fixed scaling relation leaves the non-linear parameter count\n", + "unchanged. Their positions are fixed, their profiles are spherical, and their Einstein radii all depend on the\n", + "existing anchor parameter.\n", + "\n", + "This does not mean the additional galaxies are computationally free: their deflections must still be evaluated.\n", + "It also does not include any extra freedom we might introduce for their light, positions or deviations from\n", + "the relation.\n", "\n", "__Model Fit__\n", "\n", - "We now fit the scaling-relation model to the data, using the familiar `Nautilus` search and `AnalysisImaging`\n", - "object. The parameter space is barely larger than a single-lens fit, which is the whole point." + "We now fit the original **two-galaxy scaling-relation model** to the data. The twelve hypothetical members were\n", + "used only for the parameter-counting exercise and are not included in this fit.\n", + "\n", + "We use the familiar `Nautilus` search and `AnalysisImaging` object. The model has 11 non-linear parameters, but its\n", + "smaller parameter space reflects stronger assumptions about the galaxies as well as fewer independent\n", + "quantities to infer." ] }, { @@ -726,14 +836,14 @@ "analysis = al.AnalysisImaging(dataset=dataset)\n", "\n", "print(\n", - " \"The non-linear search has begun running - checkout the output/howtolens/chapter_4/tutorial_3_scaling_relation\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell with progress once search has completed - this could take some time!\"\n", + " \"The non-linear search has begun. Check the output/howtolens/chapter_4/tutorial_3_scaling_relation\"\n", + " \" folder for results and visualizations as the search progresses.\"\n", + " \" This cell will finish when the search completes.\"\n", ")\n", "\n", "result = search.fit(model=model, analysis=analysis)\n", "\n", - "print(\"The search has finished run - you may now continue the notebook.\")" + "print(\"The search has finished \u2014 you may now continue the notebook.\")" ], "outputs": [], "execution_count": null @@ -744,9 +854,17 @@ "source": [ "__Results__\n", "\n", - "In `result.info`, the tied galaxy has no `einstein_radius` entry of its own \u2014 it is reported as a derived\n", - "function of the anchor's, which is what a tied parameter looks like in the output. Its posterior uncertainty\n", - "comes entirely from the anchor's." + "Inspect `result.info` and the maximum log likelihood fit below.\n", + "\n", + "The tied galaxy's Einstein radius is derived from the anchor's Einstein radius through the fixed luminosity\n", + "ratio and exponent. It has no independently sampled prior.\n", + "\n", + "Its inferred uncertainty therefore reflects uncertainty in the anchor within this model. It does not include\n", + "measurement uncertainty in the luminosity ratio, uncertainty in the exponent or intrinsic scatter around\n", + "the relation.\n", + "\n", + "Check the residuals around both galaxies and the lensed source. A compact model is useful only if its assumptions\n", + "provide an adequate description of the data." ] }, { @@ -764,11 +882,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The fit is good \u2014 but we should ask *why* it is good, because the answer is the honest heart of this tutorial.\n", + "Because this dataset is simulated, we can check how closely the input galaxy masses satisfy the relation we\n", + "imposed.\n", + "\n", + "Below, we use the anchor's true Einstein radius and the measured aperture-luminosity ratio to predict the other\n", + "galaxy's Einstein radius, then compare that prediction with its true value.\n", "\n", - "The tied model can only fit well if the true galaxies actually lie close to the relation we imposed. We can\n", - "check, because this is simulated data and we know the truth. Below we compare the fainter galaxy's true Einstein\n", - "radius against the value the relation predicts from the anchor's true Einstein radius and the luminosity ratio." + "This tests the mass-normalization relation. It does not test every assumption in the fitted model: for example,\n", + "the simulated second galaxy has an elliptical mass profile, while our tied model represents it as spherical.\n", + "\n", + "A visually satisfactory fit would not by itself demonstrate that either assumption is exact. Other parameters\n", + "may compensate for an imperfect scaling relation or profile choice." ] }, { @@ -796,75 +920,77 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The prediction lands within a few percent of the truth: this simulated pair happens to sit almost exactly on the\n", - "Faber-Jackson relation. That is why the tied fit succeeds. Real galaxies are not always so obliging.\n", + "Use the printed values to assess the agreement for this dataset and our chosen luminosity aperture. The\n", + "simulated masses were specified independently, so agreement with the scaling relation is something to check,\n", + "rather than a built-in guarantee.\n", "\n", "__Limitations__\n", "\n", - "A scaling relation is an assumption, and it is worth being clear-eyed about what we assumed:\n", - "\n", - "**Scatter.** Faber-Jackson is a statistical relation with real intrinsic scatter \u2014 at fixed luminosity,\n", - "galaxies show a spread in velocity dispersion, and therefore in Einstein radius. A tied model has no freedom to\n", - "absorb this scatter: it asserts every member sits exactly on the relation. For a population of faint members\n", - "whose individual lensing effects are small, the errors average down and this is fine. For any single galaxy\n", - "that matters a lot to the fit, it is a risk.\n", - "\n", - "**Deviant members.** Worse than scatter is a member that is systematically off the relation \u2014 a tidally\n", - "stripped satellite that has lost dark matter but kept its stars, a galaxy with an unusual mass-to-light ratio,\n", - "or a misclassified foreground/background interloper assigned a luminosity at the wrong distance. Because the\n", - "tied model *cannot* adjust that one galaxy, the non-linear search compensates the only way it can: by biasing\n", - "the parameters it does control \u2014 the anchor's mass, the source \u2014 dragging the whole lens model away from the\n", - "truth. One bad member can poison an otherwise excellent fit, and nothing in the residuals will neatly point at\n", - "the culprit.\n", - "\n", - "**The anchor itself.** Anchoring on the brightest galaxy assumes the anchor sits on the relation too. If it is\n", - "the anomalous one, every tied galaxy inherits its anomaly.\n", - "\n", - "The defence against all three is **selective freedom**. The tiers can be mixed within one model: keep the long\n", - "tail of faint members tied, but promote any galaxy that is bright, close to the lensed images, or visibly\n", - "suspicious to its own free mass profile \u2014 exactly as the extra galaxies were treated earlier in this chapter. A\n", - "middle option bounds a member's free Einstein radius using its luminosity (free, but only within a factor of the\n", - "relation's prediction). And the relation itself can be loosened: freeing `scaling_exponent` as a fit parameter\n", - "costs a single dimension *for the entire population* and is a useful systematics test. The `autolens_workspace`'s\n", - "`imaging/features/scaling_relation` example shows all of these tiers working together.\n", + "A scaling relation reduces parameter freedom by introducing assumptions about the galaxy population.\n", "\n", - "__Lens Environments__\n", + "**Intrinsic scatter.** Real galaxies do not lie exactly on a single luminosity-mass relation. Our deterministic\n", + "model allows no independent deviation for a tied member. Even when individual members have small effects, their\n", + "modeling errors do not necessarily cancel: the lensing impact depends on where those galaxies lie relative to\n", + "the images.\n", "\n", - "Everything above was framed around lenses with multiple deflectors, but the same machinery solves a problem we\n", - "met at the start of this chapter: the **environment** of an ordinary single-galaxy lens.\n", + "**Measurements and membership.** Luminosities and centres have measurement uncertainties, especially in blended\n", + "images. Incorrectly assigning a foreground or background galaxy to the lens population can also give it an\n", + "inappropriate luminosity and lensing geometry.\n", "\n", - "The first tutorial of this chapter modelled a nearby extra galaxy individually, which was fine for one.\n", - "But a deep image of a real lens can reveal dozens of galaxies near the line of sight, each contributing a small\n", - "perturbation to the deflection field. Modeling them individually is hopeless; ignoring them entirely can bias\n", - "precision measurements. With a scaling relation they cost nothing: measure each galaxy's centre and luminosity\n", - "from the image, tie the lot to the main lens galaxy (which is the natural anchor \u2014 it is usually the brightest\n", - "galaxy in the field), and the model gains dozens of physically motivated perturbers with zero added parameters.\n", + "**The adopted profiles.** We assume spherical mass profiles for tied members. Deviations in shape, radial\n", + "structure or tidal truncation can matter independently of whether the luminosity-normalization relation is\n", + "accurate.\n", "\n", - "__Wrap Up__\n", + "**The anchor.** The anchor's fitted Einstein radius normalizes the entire population. If the anchor is not\n", + "representative of that population, the imposed relation can give inappropriate masses to other members.\n", + "\n", + "These restrictions can lead to biased inferences or uncertainties that are too small. Residuals are useful\n", + "diagnostics, but a good image fit does not guarantee that the assumed mass decomposition is correct.\n", "\n", - "In this tutorial we learned:\n", + "A practical response is **selective freedom**: retain the scaling relation for a population of less influential\n", + "members while giving important galaxies independent mass parameters. Galaxies close to the lensed images may\n", + "warrant this even when they are faint.\n", "\n", - "1. Luminosity predicts lensing mass, via mass-follows-light arguments and the Faber-Jackson relation\n", - " (`L ~ \\sigma^4`, `\\theta_E ~ \\sigma^2`, hence `\\theta_E ~ L^{0.5}`).\n", + "Other approaches include fitting shared normalization or slope parameters, or explicitly modeling scatter.\n", + "Each changes the assumptions and parameter count, and should be assessed against the scientific goal and\n", + "available constraints.\n", "\n", - "2. A scaling relation replaces per-galaxy mass freedom with a shared relation anchored on a parameter the model\n", - " already fits, so tied galaxies add **zero** free parameters \u2014 verified by explicit parameter counting.\n", + "__Lens Environments__\n", + "\n", + "Scaling relations are also useful for the environment of a lens dominated by one galaxy. A population of nearby\n", + "galaxies can collectively perturb the lensing, even when no single member is a major deflector.\n", + "\n", + "For galaxies belonging to the same physical population at approximately the same redshift, measured positions\n", + "and consistent luminosities can support a shared relation. The main lens can serve as an anchor if that\n", + "assumption is appropriate; it need not always be the best reference.\n", + "\n", + "Galaxies projected nearby on the sky are not necessarily members of that population. Foreground and background\n", + "galaxies require appropriate redshifts, luminosity estimates and lensing-distance factors. We should not tie them\n", + "to the main lens using observed flux ratios alone.\n", + "\n", + "As throughout this chapter, their light and mass require separate consideration. A mass-only member adds no light\n", + "parameters, but its emission must still be negligible, excluded appropriately or modeled.\n", + "\n", + "__Wrap Up__\n", "\n", - "3. Combined with MGE light profiles, a many-galaxy lens model stays low-dimensional: dimensionality is\n", - " independent of the number of galaxies.\n", + "In this tutorial, we learned:\n", "\n", - "4. The relation is an assumption: scatter and deviant members can bias the whole model, and the remedy is\n", - " selective freedom \u2014 tie the faint majority, free the important few.\n", + "1. A luminosity-based scaling relation links galaxy mass normalizations through shared assumptions, rather than\n", + " measuring each mass independently.\n", + "2. With fixed centres, spherical mass profiles, a fixed exponent and an existing anchor parameter, additional\n", + " tied galaxies add zero non-linear mass parameters.\n", + "3. Light-model freedom must be counted separately. Fixed-centre elliptical MGEs add two parameters per galaxy;\n", + " fixed-centre spherical MGEs with fixed widths add none.\n", + "4. Reduced dimensionality does not remove computational cost or uncertainty associated with the relation's\n", + " assumptions.\n", + "5. Important galaxies can retain independent mass freedom while less influential members follow a shared relation.\n", "\n", - "5. The same machinery models the environments of single-lens systems, at no parameter cost.\n", + "In the next tutorial, we move to **group-scale lensing**, adding a shared dark matter halo alongside the\n", + "member galaxies.\n", "\n", - "So far, we tied galaxy to galaxy. But the biggest lenses in the Universe \u2014 galaxy groups and clusters \u2014 contain\n", - "something the galaxies themselves cannot account for: a massive dark matter halo enveloping the whole system,\n", - "holding most of its mass. In the next tutorial we step up to group-scale lenses, where the scaling relation\n", - "becomes essential (there are simply too many member galaxies to free) and a dark matter halo joins the model as\n", - "a new component. There, we will also meet a different way to normalise the relation \u2014 a shared free\n", - "normalization at a fixed reference luminosity, rather than an anchor galaxy \u2014 and truncated mass profiles, which\n", - "describe members whose outer dark matter has been tidally stripped by the very halo we are adding." + "We will also introduce a relation normalized at a fixed reference luminosity, rather than anchored to one galaxy,\n", + "and truncated mass profiles for describing member galaxies whose outer mass distributions may have been altered\n", + "by tidal stripping." ] } ], @@ -900,4 +1026,4 @@ }, "nbformat": 4, "nbformat_minor": 4 -} \ No newline at end of file +} diff --git a/notebooks/chapter_4_scaling_up_lensing/tutorial_4_group_scale.ipynb b/notebooks/chapter_4_scaling_up_lensing/tutorial_4_group_scale.ipynb index 3d463c4..7dae75c 100644 --- a/notebooks/chapter_4_scaling_up_lensing/tutorial_4_group_scale.ipynb +++ b/notebooks/chapter_4_scaling_up_lensing/tutorial_4_group_scale.ipynb @@ -7,52 +7,50 @@ "Tutorial 4: Group Scale\n", "=======================\n", "\n", - "In the previous tutorials we took our first steps beyond the single lens galaxy: we included extra galaxies near\n", - "the lens in the model, we modeled systems where two or more galaxies of comparable mass share the lensing, and we\n", - "introduced scaling relations, which tie the mass of a galaxy to its light so that adding more galaxies to a model\n", - "does not mean adding more free parameters.\n", - "\n", - "In this tutorial we put all of those tools together and take the first big step up the \"regime ladder\" of strong\n", - "lensing: the **group scale**.\n", - "\n", - "In the standard cosmological model (Lambda Cold Dark Matter, or LCDM), galaxies do not live in isolation. They\n", - "form and evolve inside \"dark matter halos\", and these halos are themselves nested: small halos hosting single\n", - "galaxies merge and fall into larger halos hosting many. A **galaxy group** is the next rung above a single\n", - "galaxy in this hierarchy: a dark matter halo of roughly 10^13 to 10^14 solar masses hosting anywhere from a\n", - "handful to a few dozen galaxies. (Our own Milky Way lives in such a structure, the Local Group.) Above groups\n", - "sit **galaxy clusters**, halos of 10^14 solar masses and beyond hosting hundreds or thousands of galaxies, which\n", - "are the subject of the next tutorial.\n", - "\n", - "When a group acts as a strong lens, several of its galaxies contribute significantly to the deflection of the\n", - "source's light. The brightest galaxy of the group -- called the brightest group galaxy (BGG), or the brightest\n", - "cluster galaxy (BCG) at cluster scale -- typically sits near the centre of the group's dark matter halo and\n", - "dominates the lensing. The other group members perturb the lensed image around it. The group's shared dark\n", - "matter halo may also enter the mass model as its own component, often centred on the BGG where one exists --\n", - "though as we will see, whether it is needed is an explicit modelling choice, not an automatic ingredient.\n", + "The previous tutorials introduced nearby galaxies, multiple significant deflectors and scaling relations. We now\n", + "combine these ideas to model a **group-scale lens**.\n", + "\n", + "A galaxy group contains galaxies associated with a larger gravitationally bound structure. Its lensing signal\n", + "can include contributions from a shared dark matter halo, a central galaxy and other member galaxies.\n", + "\n", + "The brightest group galaxy is often called the **BGG**. In some groups it lies near the centre of the shared halo\n", + "and contributes strongly to the lensing. Other groups have several prominent galaxies or a less clearly defined\n", + "centre.\n", + "\n", + "Our example contains one dominant central component, two member galaxies and one background source. We will\n", + "introduce truncated member-galaxy mass profiles, compare independent member masses with a scaling relation, and\n", + "use Bayesian evidence to compare models with and without an explicit NFW dark matter halo.\n", "\n", "__Groups vs Multi-Galaxy Lenses__\n", "\n", - "You may now be wondering how a \"group-scale lens\" differs from the multi-galaxy lenses of the previous tutorials,\n", - "and the honest answer is that the line between them is **blurry**. Every group is a multi-galaxy lens: it has\n", - "multiple galaxies whose mass matters for the lensing. But not every multi-galaxy lens is a group: two galaxies of\n", - "comparable mass that happen to sit close on the sky (or are mid-merger) share the lensing without being embedded\n", - "in a massive shared halo with a member population.\n", + "The distinction between group-scale and multi-galaxy lensing is not a strict boundary in galaxy count or Einstein\n", + "radius.\n", + "\n", + "As discussed in Tutorial 2, an interacting or merging pair of field galaxies may be modeled without a separate\n", + "group-scale halo. Other systems inhabit a shared halo whose contribution matters for interpreting the lensing.\n", + "\n", + "The important questions are which mass components contribute to the observed images and whether the data can\n", + "distinguish them. A mass profile centred on the BGG can describe the combined central mass without separately\n", + "identifying the contributions of the galaxy and the group halo.\n", "\n", - "The physically meaningful distinction is the **environment**: a group has a shared dark matter halo, a dominant\n", - "central galaxy, and members orbiting inside the host's potential. That environment leaves signatures in the mass\n", - "model, and the most important one is **tidal truncation**, which we introduce below.\n", + "We therefore distinguish **including the group's gravitational effect** from **representing its halo as a\n", + "separate model component**. Our initial model uses a central total-mass profile; later, we examine an additional\n", + "halo component.\n", "\n", "__Tidal Truncation and the dPIE Profile__\n", "\n", - "A galaxy orbiting inside a group does not keep its full dark matter halo. The tidal field of the host group\n", - "strips the outer, loosely bound parts of the member's halo, so the member's mass distribution is cut off -- or\n", - "\"truncated\" -- at a finite radius. The isothermal profiles we have used so far are a poor description of this:\n", - "their density falls as 1/r^2 forever, so their total mass diverges with radius.\n", + "Galaxies orbiting within a group can lose material from their outer dark matter halos through tidal stripping.\n", + "The extent of this stripping depends on their orbits, internal structure and interaction history.\n", "\n", - "The standard truncated profile of group- and cluster-scale lensing is the **dPIE** (dual Pseudo-Isothermal\n", - "Elliptical) profile, available in **PyAutoLens** as `al.mp.dPIEMassSph`. It behaves isothermally at intermediate\n", - "radii but its density falls off much more steeply beyond a truncation radius, giving it a finite total mass --\n", - "exactly the behaviour we expect for a tidally stripped group member.\n", + "The isothermal profiles used so far extend indefinitely and have divergent total mass. They can describe lensing\n", + "over a limited radial range, but do not represent a finite outer halo.\n", + "\n", + "The **dPIE** profile provides a useful alternative. It has an approximately isothermal region and steepens smoothly\n", + "beyond a characteristic truncation scale, giving it finite total mass.\n", + "\n", + "We use its spherical implementation, `al.mp.dPIEMassSph`, for the member galaxies. Its truncation scale lets us\n", + "represent a reduced outer mass distribution, although adopting this profile does not by itself measure a\n", + "galaxy's stripping history.\n", "\n", "__Contents__\n", "\n", @@ -61,8 +59,10 @@ "- **Galaxy Centres:** Load the centres of the BGG and member galaxies from .json files.\n", "- **The dPIE Profile:** Introduce the truncated dPIE mass profile and its parameters.\n", "- **Fitting a Group:** Fit the data with a tracer containing the BGG, members and source.\n", - "- **A Group Halo?:** Add a group-scale dark matter halo to the tracer and see how it changes the fit.\n", - "- **Model Fit:** Compose and fit a group-scale lens model with individually modeled members.\n", + "- **A Group Halo?:** Motivate a shared NFW dark matter halo and define two models to compare.\n", + "- **Model Fit:** Compose and fit the galaxy-only model with individually modeled members.\n", + "- **Fit With a Shared NFW Dark Matter Halo:** Refit with an additional NFW halo and unchanged galaxy priors.\n", + "- **Bayesian Model Comparison:** Compare the evidences of the galaxy-only and galaxy-plus-halo models.\n", "- **Scaling Relation Members:** Tie the members' masses to their light so they cost almost no parameters.\n", "- **The Group Scale Sweet Spot:** Why groups are the sweet spot of the familiar lens modeling toolkit.\n", "- **Wrap Up:** Summary of the script and next steps." @@ -115,6 +115,7 @@ "\n", "from autolens import setup_notebook; setup_notebook()\n", "\n", + "import copy\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "from pathlib import Path\n", @@ -132,13 +133,18 @@ "source": [ "__Initial Setup__\n", "\n", - "We begin by loading the group-scale strong lens dataset `simple`, which was simulated with:\n", + "We load the simulated group-scale dataset `simple`, containing:\n", + "\n", + "- A central galaxy at `(0.0, 0.0)`, represented by `SersicSph` light and an `IsothermalSph` total-mass profile\n", + " with Einstein-radius parameter 4.0\".\n", + "- Two member galaxies at `(3.5, 2.5)` and `(-4.4, -5.0)`, with `SersicSph` light and truncated `dPIEMassSph`\n", + " mass profiles.\n", + "- One background source with a `SersicCore` light profile.\n", "\n", - " - A main lens galaxy (the BGG) at (0.0\", 0.0\"), with a `SersicSph` light profile and an `IsothermalSph` mass\n", - " profile with a 4.0\" Einstein radius.\n", - " - Two member galaxies at (3.5\", 2.5\") and (-4.4\", -5.0\"), with `SersicSph` light profiles and tidally\n", - " truncated `dPIEMassSph` mass profiles.\n", - " - A single source galaxy with a `SersicCore` light profile." + "Coordinates use the usual `(y, x)` convention in arcseconds.\n", + "\n", + "The simulation contains no separate group-halo profile. Its central mass component provides a simple description\n", + "of the dominant deflection field, without decomposing that mass into the BGG and a shared halo." ] }, { @@ -188,10 +194,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "When we plot the dataset, the difference from a galaxy-scale lens is immediately clear: the lensed arcs form a\n", - "much larger ring (the BGG's Einstein radius is 4.0\", compared to the ~1.0\" typical of a single galaxy), and two\n", - "smaller galaxies are visible away from the centre. Their light -- and, more importantly for the lensing, their\n", - "mass -- must be included in our analysis." + "Plot the dataset and identify the central galaxy, the extended lensed arcs and the two member galaxies.\n", + "\n", + "The central mass profile has an Einstein-radius parameter of 4.0\", so this example's lensed emission spans a larger\n", + "angular region than the earlier examples. The members modify the combined deflection field.\n", + "\n", + "As in Tutorial 1, consider their light and mass separately. We will explicitly model both here, but a galaxy's\n", + "mass can affect the arcs even when its light lies outside the fitting region." ] }, { @@ -209,9 +218,18 @@ "source": [ "__Mask__\n", "\n", - "We define a 7.5\" circular mask, much larger than the 2.5\"-3.0\" masks of previous chapters. It must enclose the\n", - "full lensed arc system and the member galaxies, because all of them contribute light and mass to the region we\n", - "fit." + "We use a circular mask with radius 7.5\", centred on the central galaxy. This includes the lensed arcs and both\n", + "member-galaxy centres.\n", + "\n", + "Inspect the masked subplot to assess the retained source emission and member light. The outer member lies\n", + "approximately 6.7\" from the origin, so its centre is inside the mask but some of its extended light lies outside it.\n", + "\n", + "The mask selects the image pixels used in the fit; it does not set a boundary on which galaxies can contribute\n", + "gravitational deflections. A member outside the mask can still be included in the mass model if its lensing\n", + "effect matters.\n", + "\n", + "Here, we retain a broad fitting region so that we can model the central galaxy, member light and lensed source\n", + "together." ] }, { @@ -239,17 +257,20 @@ "source": [ "__Galaxy Centres__\n", "\n", - "Following the convention of the previous tutorials, the centres of the galaxies are loaded from .json files in\n", - "the dataset folder. For a group we distinguish two categories:\n", + "We load the measured galaxy positions from JSON files, separating them into:\n", + "\n", + "- `main_lens_centres`: positions of the main deflectors, here the central galaxy.\n", + "- `member_centres`: positions of the additional group members.\n", "\n", - " - `main_lens_centres`: the main lens galaxies -- here just the BGG at (0.0\", 0.0\") -- which are modeled with\n", - " full freedom.\n", + "This separation helps organize the model; it does not itself fix parameters or determine how much freedom each\n", + "galaxy receives.\n", "\n", - " - `member_centres`: the group members, which are modeled with restrictive assumptions (fixed centres, and\n", - " later a scaling relation) to keep the model dimensionality low.\n", + "As in the previous tutorials, measuring light centres before constructing the mass model is a common practical\n", + "workflow. For real observations, these positions can come from a GUI, a source-detection catalogue or a\n", + "preliminary light-profile fit. Here, the simulator supplies them.\n", "\n", - "For real data these centres come from the observed light of each galaxy (e.g. via a click-based GUI or a\n", - "photometry catalogue), exactly as for the extra galaxies of the earlier tutorials." + "We will fix the member profiles to these positions and use the combined list of galaxy centres when setting up\n", + "adaptive over-sampling." ] }, { @@ -261,7 +282,16 @@ "member_centres = al.from_json(file_path=dataset_path / \"extra_galaxies_centres.json\")\n", "\n", "print(f\"Main lens centres: {main_lens_centres}\")\n", - "print(f\"Member centres: {member_centres}\")" + "print(f\"Member centres: {member_centres}\")\n", + "\n", + "over_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n", + " grid=dataset.grid,\n", + " sub_size_list=[4, 2, 2],\n", + " radial_list=[0.3, 0.6],\n", + " centre_list=list(main_lens_centres) + list(member_centres),\n", + ")\n", + "\n", + "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)" ], "outputs": [], "execution_count": null @@ -272,30 +302,23 @@ "source": [ "__The dPIE Profile__\n", "\n", - "Before fitting anything, lets get to know the dPIE profile, since it is the workhorse mass profile of the group\n", - "and cluster regimes.\n", - "\n", - "The `dPIEMassSph` profile is parameterized in the convention of Lenstool (a long-established cluster lensing\n", - "code), which differs from the profiles we have met so far:\n", + "The spherical `dPIEMassSph` profile uses the parameter convention of the lens-modeling software Lenstool:\n", "\n", - " - `sigma`: the fiducial velocity dispersion of the galaxy in km/s. This sets the overall lensing strength,\n", - " playing the role the `einstein_radius` played for the isothermal profile (for an isothermal sphere the two\n", - " are directly related: a bigger velocity dispersion means a bigger Einstein radius).\n", + "- `sigma`: a fiducial velocity-dispersion parameter in km/s that sets the mass normalization. It is not\n", + " automatically equal to an observed stellar velocity dispersion; comparisons require attention to the profile\n", + " convention and how the observation was measured.\n", + "- `r_core`: the core scale in arcseconds. A nonzero value flattens the central density. We set it to zero here,\n", + " giving a singular central profile.\n", + "- `r_cut`: the truncation scale in arcseconds. The density steepens smoothly around this scale, giving a finite\n", + " total mass. It is not a sharp boundary beyond which the mass vanishes.\n", + "- `redshift_object`, `redshift_source`, `H0` and `Om0`: the redshifts and cosmological parameters used to\n", + " convert the physical normalization into lensing quantities. We hold them fixed in this tutorial.\n", "\n", - " - `r_core`: the core radius in arcseconds, within which the density profile flattens. It is common to fix\n", - " `r_core = 0.0` (a \"vanishing core\", where the profile has an exact analytic form), which we do throughout\n", - " this tutorial.\n", + "We create two profiles with the same `sigma` and zero core radius, but different truncation scales: 8.0\" and\n", + "1000.0\".\n", "\n", - " - `r_cut`: the truncation radius in arcseconds -- the key new parameter. Outside `r_cut` the density falls off\n", - " steeply (as 1/r^4 rather than the isothermal 1/r^2), encoding the tidal stripping of the member's outer dark\n", - " matter halo and giving the profile a finite total mass.\n", - "\n", - " - `redshift_object`, `redshift_source`, `H0`, `Om0`: because `sigma` is a physical velocity, converting it to\n", - " deflection angles requires the lensing geometry and a cosmology. These are fixed inputs describing the lens\n", - " system, not parameters we fit.\n", - "\n", - "Lets make two dPIE profiles with identical `sigma` but different truncation radii -- one truncated at 8.0\" and\n", - "one truncated so far out (1000.0\") that it is effectively untruncated -- and compare their convergence profiles." + "The second profile is effectively untruncated over the radial range we plot, although it still has a finite\n", + "truncation scale." ] }, { @@ -327,8 +350,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We evaluate the convergence of both profiles on a 1D line of radial coordinates, using a `Grid2DIrregular` so we\n", - "can choose the radii ourselves." + "We evaluate both profiles along a radial line using `Grid2DIrregular`.\n", + "\n", + "The plotted quantity is **convergence**: projected surface mass density divided by the critical surface density\n", + "for lensing. It is not the three-dimensional density.\n", + "\n", + "The logarithmic vertical axis helps us compare the profiles over a wide range of convergence. The dashed line\n", + "marks the 8.0\" truncation scale of the more strongly truncated profile." ] }, { @@ -343,7 +371,7 @@ "convergence_untruncated = dpie_untruncated.convergence_2d_from(grid=radial_grid)\n", "\n", "plt.semilogy(radii, np.asarray(convergence_truncated), label=\"dPIE (r_cut = 8.0)\")\n", - "plt.semilogy(radii, np.asarray(convergence_untruncated), label=\"dPIE (untruncated)\")\n", + "plt.semilogy(radii, np.asarray(convergence_untruncated), label=\"dPIE (r_cut = 1000.0)\")\n", "plt.axvline(x=8.0, color=\"k\", linestyle=\"--\", label=\"r_cut\")\n", "plt.xlabel(\"Radius (arcseconds)\")\n", "plt.ylabel(\"Convergence\")\n", @@ -358,26 +386,25 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Inside `r_cut` the two profiles are nearly identical -- both behave isothermally. Beyond `r_cut`, the truncated\n", - "profile's convergence plummets while the untruncated one keeps its shallow isothermal decline. The truncated\n", - "member therefore contributes far less mass at large radii, which is exactly what tidal stripping does.\n", + "At radii much smaller than 8.0\", the profiles approach similar isothermal behaviour. As we move towards and\n", + "beyond the smaller truncation scale, that profile's convergence falls more steeply.\n", "\n", - "This is why the dPIE, and not the isothermal profile, is the standard choice for group and cluster members: the\n", - "extra galaxies of a galaxy-scale lens have no host environment stripping them, so untruncated isothermal\n", - "profiles are fine there, but a member orbiting inside a shared group halo is physically truncated whether or\n", - "not the model includes that halo as an explicit component.\n", + "The transition is gradual: `r_cut` does not mark an abrupt edge, and the profiles can differ before reaching it.\n", + "The truncated profile also continues to contribute mass and deflections beyond that radius.\n", "\n", - "For scale: a member with `sigma = 200.0` km/s at these redshifts has an Einstein radius of ~0.7\", roughly a\n", - "fifth of the BGG's -- a perturber, not a co-dominant lens.\n", + "This flexibility makes the dPIE useful for representing member galaxies with reduced outer halos. However,\n", + "neither group membership nor proximity to another galaxy uniquely determines a truncation radius. Its value\n", + "remains a modeling choice or an inferred parameter, depending on the available constraints.\n", "\n", "__Fitting a Group__\n", "\n", - "Now lets fit the data. Following the fitting tutorials of earlier chapters, we first build a tracer from\n", - "galaxies whose light and mass profiles match the true values used to simulate the data, and fit it with the\n", - "`FitImaging` object.\n", + "We first evaluate a model using the parameter values supplied to the simulator. This is a direct fit evaluation,\n", + "rather than a search for the best-fitting parameters.\n", + "\n", + "The tracer contains the central galaxy, two members and the source. Because the deflectors share a redshift,\n", + "their deflections combine on one lens plane before mapping the source light into the image.\n", "\n", - "The tracer contains four galaxies: the BGG, the two members and the source. The fit handles all of them\n", - "simultaneously, summing the deflection field of every mass profile to ray-trace the source's light." + "The familiar `FitImaging` object compares this predicted image with the data, including the PSF and noise map." ] }, { @@ -446,9 +473,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Because this is the true model, the residuals are consistent with noise and the log likelihood is as high as it\n", - "can be for this dataset. Note that nothing about the `FitImaging` object changed: the same fitting machinery we\n", - "learnt at galaxy scale simply receives a tracer with more galaxies in it." + "Inspect the residuals of the fit evaluated at the simulation's input parameters.\n", + "\n", + "With consistent simulation and fitting calculations, we expect residuals compatible with the added noise.\n", + "Coherent structure could instead indicate a mismatch in the profiles, PSF, numerical sampling or other assumptions.\n", + "\n", + "The fitting machinery is unchanged from earlier chapters. We have supplied a tracer containing more galaxies and\n", + "a different member-mass profile." ] }, { @@ -466,83 +497,58 @@ "source": [ "__A Group Halo?__\n", "\n", - "You may have noticed that the model above contains no group-scale dark matter halo, despite this tutorial\n", - "opening with the statement that a group is defined by one. Two things are going on here.\n", + "In the standard cosmological model, **Lambda Cold Dark Matter (LCDM)**, galaxies form within dark matter halos.\n", + "Galaxy groups are expected to occupy larger **host dark matter halos**, within which member galaxies orbit,\n", + "often retaining their own smaller halos.\n", "\n", - "First, the BGG's `IsothermalSph` has a 4.0\" Einstein radius -- far larger than the ~1.0\" of an isolated galaxy\n", - "of its luminosity. A mass profile centred on the BGG cannot tell \"stars and dark matter belonging to the BGG\"\n", - "apart from \"group dark matter centred on the BGG\": a single isothermal profile at the group centre soaks up\n", - "both. So the group's halo is partly hidden inside the BGG's mass profile already.\n", + "This gives us a physical reason to include an extended, shared dark matter component when modeling a group-scale\n", + "lens.\n", "\n", - "Second, whether to add a *separate* halo component to the model is an **explicit modelling choice**, and this\n", - "dataset was deliberately simulated without one. Lets see what happens if we add one anyway. We add a fifth\n", - "galaxy carrying only mass -- an `IsothermalSph` centred on the BGG, the conventional choice for a group halo\n", - "where a BGG exists -- and refit." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "group_halo = al.Galaxy(\n", - " redshift=0.5,\n", - " mass=al.mp.IsothermalSph(centre=(0.0, 0.0), einstein_radius=1.5),\n", - ")\n", + "However, seeing several galaxies close together on the sky does not automatically establish that they inhabit\n", + "a group-scale halo. They could be projected neighbours or an interacting pair of field galaxies, for which\n", + "separate galaxy-centred mass profiles provide an adequate description. Those galaxies still contain dark matter;\n", + "what may be unnecessary is an **additional shared group-scale component**.\n", "\n", - "tracer_with_halo = al.Tracer(galaxies=[bgg, group_halo, member_0, member_1, source])\n", + "The astronomical question is therefore whether the system's environment and lensing signal support a shared\n", + "host halo, and whether the data can distinguish its contribution from the masses associated with individual\n", + "galaxies.\n", "\n", - "fit_with_halo = al.FitImaging(dataset=dataset, tracer=tracer_with_halo)\n", + "We investigate this by fitting two models:\n", "\n", - "aplt.subplot_fit_imaging(fit=fit_with_halo)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The fit is now visibly worse -- the extra 1.5\" Einstein radius of mass at the centre over-deflects the source's\n", - "light, displacing the model arcs from the observed ones -- and the log likelihood drops accordingly." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(f\"Log likelihood with a group halo added: {fit_with_halo.log_likelihood}\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "On real data the same experiment runs in reverse: fit the group with and without an explicit halo component and\n", - "let the data decide (via the residuals and the Bayesian evidence introduced in earlier chapters). Some groups\n", - "are well described by their galaxies alone, with the central galaxy's profile absorbing the halo; others --\n", - "typically those with the largest Einstein radii or image configurations no galaxy-mass model can reproduce --\n", - "require a dominant halo component, often centred on the BGG.\n", + "- **Galaxy mass profiles only:** a central galaxy and member galaxies, without a separate host halo.\n", + "- **Galaxy mass profiles plus a shared dark matter halo:** the same components, with an additional NFW halo\n", + " at the group redshift.\n", + "\n", + "The Navarro-Frenk-White (NFW) profile is a commonly used description of dark matter halos in LCDM. We allow the\n", + "galaxy parameters to adjust in both fits and compare the Bayesian evidences. This tests whether the data support\n", + "the additional NFW component, given our profile choices and priors.\n", + "\n", + "If the simpler model is sufficient, it does not overturn the LCDM expectation: the shared halo's contribution\n", + "may be absorbed by the galaxy-centred profiles, or the available images may not distinguish it separately.\n", + "\n", + "Our simulated dataset contains no separate NFW halo, so it provides a useful starting point for this comparison.\n", "\n", "__Model Fit__\n", "\n", - "We now perform a proper model-fit with a non-linear search, as a scientist would for a group whose true\n", - "parameters are unknown. We compose the model as follows:\n", + "We first fit the galaxy-only model:\n", "\n", - " - The BGG's light is a linear `SersicSph` (its centre free) and its mass an `IsothermalSph` [7 parameters].\n", + "- The BGG has a linear `SersicSph` light profile and an `IsothermalSph` mass profile, with free centres:\n", + " seven non-linear parameters.\n", + "- Each member has a linear `SersicSph` light profile and a `dPIEMassSph` mass profile. Both centres are fixed\n", + " to the measured position. The light's effective radius and Sersic index, together with the mass normalization\n", + " `sigma`, give three parameters per member.\n", + "- The source has a linear `SersicCore` light profile: six non-linear parameters.\n", "\n", - " - Each member's light is a linear `SersicSph` with its centre fixed to the observed centre, and its mass a\n", - " `dPIEMassSph` with a free `sigma`, its centre fixed, `r_core = 0.0` and `r_cut` fixed to a fiducial 10.0\"\n", - " [3 parameters per member, 6 total].\n", + "For each member, we fix `r_core = 0.0` and adopt `r_cut = 10.0\"`. We also fix the redshifts and cosmological\n", + "parameters.\n", "\n", - " - The source's light is a linear `SersicCore` [6 parameters].\n", + "Fixing the member centres follows the measured-position workflow used throughout this chapter. Fixing their\n", + "truncation scales is a further assumption: the arcs may constrain a member's lensing strength more readily\n", + "than its outer mass distribution.\n", "\n", - "Fixing the member centres to their observed light and fixing `r_cut` follows the reasoning of the extra\n", - "galaxies tutorial: the data rarely constrains a perturber's truncation radius, so we spend our parameter budget\n", - "on the quantity that matters most -- each member's overall mass, via `sigma`. The redshifts and cosmology of\n", - "the dPIE are pinned to their known values, since they are properties of the lens system, not parameters to\n", - "sample." + "The chosen 10.0\" truncation scale differs from the simulation's member values of 8.0\" and 13.3\". This fit therefore\n", + "tests a simplified model rather than reproducing every simulation assumption exactly. We use the same member\n", + "treatment in both halo-comparison models." ] }, { @@ -598,11 +604,15 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Printing the model's `info` confirms its composition: the BGG and source under `galaxies`, and the two members\n", - "under `extra_galaxies` with only their `sigma`, `effective_radius` and `sersic_index` free.\n", + "Inspect `model.info` to check the galaxy-only model's components and priors.\n", + "\n", + "The BGG and source appear under `galaxies`, while the two members appear under `extra_galaxies`. Each member has\n", + "three free non-linear parameters: `sigma`, `effective_radius` and `sersic_index`.\n", + "\n", + "The total is **19 non-linear parameters**: seven for the BGG, six across the two members and six for the source.\n", "\n", - "The total number of free parameters is N=19 -- take note of this number, as it is central to the discussion at\n", - "the end of this tutorial." + "Light-profile intensities are solved by the linear inversion during each likelihood evaluation, so they do not\n", + "add sampling dimensions. This is Model 1 of our dark matter halo comparison." ] }, { @@ -618,12 +628,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The same model can also be visualized as a figure, making its structure easier to understand at a glance.\n", + "The model figure shows how these components are organized.\n", "\n", - "The figure shows how the model is organized: which parameters belong to each component, and whether they are free,\n", - "fixed, shared, linked by an expression, solved during the fit, or not configured. `model.info` provides the\n", - "corresponding numerical details, including the prior assigned to each free parameter and the value of each fixed\n", - "parameter." + "Notice that the central galaxy's light and mass centres remain free, whereas the member centres are fixed to\n", + "their measured positions. Each member's mass profile has only `sigma` free; its core and truncation scales\n", + "are fixed.\n", + "\n", + "Compare the figure with `model.info` and check the printed parameter count. These choices keep the model\n", + "compact while retaining independent mass normalizations for the members." ] }, { @@ -641,33 +653,22 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Before fitting, we set up the adaptive over-sampling scheme at the centre of every galaxy in the group (not\n", - "just the BGG), following the standard workspace approach. As in previous tutorials, the details are not\n", - "important yet -- just note that at group scale every galaxy centre needs it." + "Adaptive over-sampling was configured around every galaxy centre before the initial fit evaluations. The same\n", + "configuration is retained for the non-linear search." ] }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "over_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from(\n", - " grid=dataset.grid,\n", - " sub_size_list=[4, 2, 2],\n", - " radial_list=[0.3, 0.6],\n", - " centre_list=list(main_lens_centres) + list(member_centres),\n", - ")\n", - "\n", - "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)" - ], - "outputs": [], - "execution_count": null - }, { "cell_type": "markdown", "metadata": {}, "source": [ - "We fit the model with the `Nautilus` non-linear search, using the same `AnalysisImaging` object as every\n", - "imaging fit so far -- another sign that the group scale does not require new machinery." + "We first fit the galaxy-only model using `Nautilus` and the familiar `AnalysisImaging` object.\n", + "\n", + "The likelihood calculation uses the same imaging framework as in earlier chapters, now with the central galaxy\n", + "and two members contributing to the predicted image.\n", + "\n", + "This search provides the first fit and Bayesian evidence for our comparison. We will then fit the model\n", + "containing an additional NFW dark matter halo using the same dataset and unchanged priors for the\n", + "galaxy components." ] }, { @@ -686,14 +687,14 @@ "analysis = al.AnalysisImaging(dataset=dataset)\n", "\n", "print(\n", - " \"The non-linear search has begun running - checkout the output/howtolens/chapter_4/tutorial_4_group_scale\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell with progress once search has completed - this could take some time!\"\n", + " \"The non-linear search has begun. Check the output/howtolens/chapter_4/tutorial_4_group_scale\"\n", + " \" folder for results and visualizations as the search progresses.\"\n", + " \" This cell will finish when the search completes.\"\n", ")\n", "\n", "result = search.fit(model=model, analysis=analysis)\n", "\n", - "print(\"The search has finished run - you may now continue the notebook.\")" + "print(\"The search has finished \u2014 you may now continue the notebook.\")" ], "outputs": [], "execution_count": null @@ -702,8 +703,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The result's `info` and maximum likelihood fit show the model recovers the group: the BGG's Einstein radius,\n", - "the members' velocity dispersions and the source's properties are all inferred from the data." + "Inspect the inferred parameters in `result.info` and the fit subplot below.\n", + "\n", + "Check how well the model reproduces the central galaxy, member light and lensed arcs. Look for coherent\n", + "residuals, particularly near the member galaxies and the source emission they perturb.\n", + "\n", + "The inferred member `sigma` values describe their dPIE mass normalizations under our adopted profile\n", + "assumptions. Remember that we fixed both truncation scales to 10.0\", whereas the simulation used 8.0\" and 13.3\".\n", + "\n", + "We next add the shared NFW dark matter halo and refit, allowing the galaxy parameters to adjust alongside the\n", + "halo parameters." ] }, { @@ -712,7 +721,112 @@ "source": [ "print(result.info)\n", "\n", - "aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit)" + "aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit)\n" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Fit With a Shared NFW Dark Matter Halo__\n", + "\n", + "We now construct Model 2 by copying the galaxy-only model and adding a spherical NFW dark matter halo at the\n", + "group redshift. Copying the original model preserves the galaxy priors: we do not replace them with posterior\n", + "constraints from the first fit.\n", + "\n", + "For this illustrative comparison, we fix the halo centre to the measured central-galaxy position and fit two\n", + "parameters:\n", + "\n", + "- `kappa_s`: the dimensionless NFW density normalization, with a uniform prior from 0.0 to 0.5.\n", + "- `scale_radius`: the NFW scale radius in arcseconds, with a uniform prior from 5.0\" to 50.0\".\n", + "\n", + "These are explicit example priors, not universal choices for galaxy groups. The halo's shape and position are\n", + "also assumptions here. For a scientific analysis, choose priors appropriate to the system and assess how they\n", + "affect the evidence and inferred mass decomposition.\n", + "\n", + "Both models fit the same dataset, mask, noise map and source description. All galaxy parameters that were free\n", + "in Model 1 remain free in Model 2, allowing mass to be redistributed between the central galaxy and host halo." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model_galaxies_only = model\n", + "model_with_halo = copy.deepcopy(model_galaxies_only)\n", + "\n", + "halo_mass = af.Model(al.mp.NFWSph)\n", + "halo_mass.centre = tuple(main_lens_centres[0])\n", + "halo_mass.kappa_s = af.UniformPrior(lower_limit=0.0, upper_limit=0.5)\n", + "halo_mass.scale_radius = af.UniformPrior(lower_limit=5.0, upper_limit=50.0)\n", + "\n", + "model_with_halo.galaxies.group_halo = af.Model(\n", + " al.Galaxy, redshift=0.5, mass=halo_mass\n", + ")\n", + "\n", + "print(model_with_halo.info)\n", + "\n", + "search_with_halo = af.Nautilus(\n", + " path_prefix=Path(\"howtolens\") / \"chapter_4\",\n", + " name=\"tutorial_4_group_scale_with_nfw_halo\",\n", + " unique_tag=dataset_name,\n", + " n_live=100,\n", + " n_batch=50,\n", + " iterations_per_quick_update=2500,\n", + ")\n", + "\n", + "result_with_halo = search_with_halo.fit(model=model_with_halo, analysis=analysis)\n", + "\n", + "print(result_with_halo.info)\n", + "aplt.subplot_fit_imaging(fit=result_with_halo.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Bayesian Model Comparison__\n", + "\n", + "Compare the log evidences from the two fitted models. We report the difference as the NFW-halo model minus\n", + "the galaxy-only model: a positive difference favours including the NFW halo, while a negative difference favours\n", + "the galaxy-only description, under the adopted priors.\n", + "\n", + "Interpret this alongside fit diagnostics and the numerical reliability of the searches. The evidence comparison\n", + "accounts for the additional parameter space; it is not simply a comparison of the best-fitting images.\n", + "For equal prior model probabilities, the difference in log evidences is the log posterior odds between the models.\n", + "\n", + "A preference for the NFW model supports that explicit component within these model choices. A preference for the\n", + "simpler model does not demonstrate the absence of a physical dark matter halo.\n", + "\n", + "The next scaling-relation exercise returns to the galaxy-only setup, keeping the halo comparison separate from\n", + "the change in member-mass treatment." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "log_evidence_galaxies_only = result.samples_summary.log_evidence\n", + "log_evidence_with_halo = result_with_halo.samples_summary.log_evidence\n", + "\n", + "if (\n", + " log_evidence_galaxies_only is not None\n", + " and log_evidence_with_halo is not None\n", + " and np.isfinite(log_evidence_galaxies_only)\n", + " and np.isfinite(log_evidence_with_halo)\n", + "):\n", + " print(f\"Log evidence, galaxy-only model: {log_evidence_galaxies_only:.3f}\")\n", + " print(f\"Log evidence, galaxy + NFW model: {log_evidence_with_halo:.3f}\")\n", + " print(\n", + " \"Delta log evidence (NFW minus galaxy-only): \"\n", + " f\"{log_evidence_with_halo - log_evidence_galaxies_only:.3f}\"\n", + " )\n", + "else:\n", + " print(\"Finite evidences are unavailable; complete both nested-sampling fits before comparing the models.\")" ], "outputs": [], "execution_count": null @@ -723,29 +837,37 @@ "source": [ "__Scaling Relation Members__\n", "\n", - "The model above gave every member its own free `sigma`. With two members that costs two parameters -- harmless.\n", - "But groups can host dozens of members, and one free mass parameter per member quickly bloats the model, slows\n", - "the search, and asks the data to constrain masses it barely feels individually.\n", - "\n", - "The previous tutorial's solution applies directly here: tie the members' masses to their light through a\n", - "scaling relation. More luminous galaxies are more massive, so we write each member's `sigma` and `r_cut` as\n", - "power laws of its luminosity, normalized by a single shared free parameter:\n", - "\n", - " - `sigma = sigma_ref * (L / L_ref) ** 0.25`\n", - " - `r_cut = r_cut_ref * (L / L_ref) ** 0.7`\n", - "\n", - "These exponents follow the convention of modern cluster lensing analyses, and `L_ref` is a fixed reference\n", - "luminosity. The 0.25 is the previous tutorial's Faber-Jackson relation recast for velocity dispersion:\n", - "`L ~ sigma^4` inverts to `sigma ~ L^0.25`, and since `theta_E ~ sigma^2` this reproduces the `theta_E ~ L^0.5`\n", - "scaling we anchored there. Note also the change of normalization: rather than hanging the relation off an\n", - "anchor galaxy the model already fits, we normalise it with a shared free parameter at a fixed reference\n", - "luminosity. Now the *entire member population's mass* costs one free parameter (`sigma_ref`), no matter how\n", - "many members the group has, and each member's observed luminosity acts as a physically motivated prior on its\n", - "mass.\n", - "\n", - "For real data the luminosities come from your photometry catalogue (only luminosity ratios enter the model, so\n", - "any consistent units work). Here we compute them from the true member light profiles, using an aperture\n", - "luminosity within 3.0\"." + "We now return to the galaxy-only model and change how its member galaxies are described. This keeps the\n", + "scaling-relation exercise separate from the NFW halo comparison.\n", + "\n", + "Previously, each member had an independent mass normalization, `sigma`. We now link the members through\n", + "their luminosities:\n", + "\n", + "$$\n", + "\\sigma_i=\\sigma_{\\rm ref}\n", + "\\left(\\frac{L_i}{L_{\\rm ref}}\\right)^{0.25},\n", + "\\qquad\n", + "r_{{\\rm cut},i}=r_{{\\rm cut},{\\rm ref}}\n", + "\\left(\\frac{L_i}{L_{\\rm ref}}\\right)^{0.7}.\n", + "$$\n", + "\n", + "The exponent 0.25 follows the approximate Faber-Jackson scaling introduced in Tutorial 3. The truncation exponent\n", + "0.7 is an adopted prescription for this example, rather than a universal property of group members.\n", + "\n", + "Unlike the previous tutorial's anchor-galaxy approach, we introduce a shared free normalization, `sigma_ref`,\n", + "at a fixed reference luminosity. We hold both exponents and `r_cut_ref` fixed.\n", + "\n", + "With member centres fixed and spherical mass profiles, the entire member **mass population** therefore has one\n", + "non-linear parameter, regardless of how many members we include.\n", + "\n", + "Their light parameters remain separate. Here, each member's fixed-centre linear `SersicSph` contributes two\n", + "non-linear parameters: effective radius and Sersic index. Its intensity is solved linearly.\n", + "\n", + "For this simulated example, we obtain luminosities from the known member light profiles within a 3.0\" aperture\n", + "centred on each galaxy. This photometric aperture is separate from the 7.5\" fitting mask.\n", + "\n", + "For real observations, use consistently measured luminosities and account for the measurement and population\n", + "assumptions discussed in Tutorial 3." ] }, { @@ -797,22 +919,22 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Note that the tied members now live in the `scaling_galaxies` collection \u2014 the home the previous tutorial\n", - "introduced for a scaling-relation population \u2014 whereas the individually-modelled members above sat in\n", - "`extra_galaxies`, like tutorial 1's interlopers. Both collections are included in the ray-tracing; the split\n", - "keeps `model.info` readable and tells the results machinery which galaxies are a tied population.\n", + "The tied members now appear under `scaling_galaxies`, while the individually modeled members previously appeared\n", + "under `extra_galaxies`. Both contribute to the ray-tracing.\n", + "\n", + "Inspect `model.info`: both member `sigma` expressions depend on the same `sigma_ref` prior.\n", + "\n", + "The model has **18 non-linear parameters**: seven for the BGG, six for the source, four for the member light\n", + "profiles and one shared member-mass normalization.\n", "\n", - "The model's `info` shows that both members' `sigma` values now trace back to the single shared `sigma_ref`\n", - "prior, and the parameter count has dropped to N=18.\n", + "With N members, the corresponding count is 14 + 2N, because their light models still contribute two parameters\n", + "each. Only the member mass-parameter count remains constant.\n", "\n", - "A drop of one parameter looks unremarkable -- until you scale it up. A group with 20 members modeled\n", - "individually would need 20 free mass parameters; with the scaling relation it still needs exactly one. (In\n", - "practice the members' light is handled the same way, using the Multi Gaussian Expansion from earlier in the\n", - "lectures, whose fixed-centre members add almost no free parameters either -- so entire member populations can\n", - "be added to a group model almost for free.)\n", + "Fixed-width, fixed-centre spherical MGEs could remove those non-linear member-light parameters where that light\n", + "description is appropriate. Elliptical MGEs with fixed centres would retain two per member.\n", "\n", - "This dataset was in fact simulated with members that obey this exact scaling relation, so the model remains the\n", - "true model." + "The truncation radii also change: instead of fixing both to 10.0\", we now assign luminosity-dependent values.\n", + "The comparison therefore changes both the mass-normalization freedom and the truncation prescription." ] }, { @@ -828,17 +950,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The tied members have moved out of `extra_galaxies` into `scaling_galaxies`, and they no longer share one\n", - "description: each member's `sigma` is no longer an independent prior but an expression,\n", - "`sigma = scaling_galaxies.1.mass.sigma.sigma_ref * `, with a different ratio for each. One\n", - "free prior, two galaxies \u2014 the scaling relation.\n", + "The figure shows the two member `sigma` values linked to one shared prior. Each is computed from `sigma_ref`\n", + "and its fixed luminosity ratio.\n", "\n", - "`r_cut` stays fixed, as it was before. `r_cut_ref * luminosity_ratio ** 0.7` is arithmetic on plain numbers\n", - "rather than on a prior, so it yields a fixed value rather than a relation.\n", + "Their truncation radii are also calculated from luminosity, but every input to that calculation is fixed.\n", + "Each member therefore receives a fixed `r_cut` value, which can differ between members.\n", "\n", - "Nineteen free parameters fall to eighteen. One parameter is an unremarkable saving for two members, but the\n", - "saving keeps growing: however many members you add to `scaling_galaxies`, every one of their `sigma` values\n", - "points back at that single `sigma_ref`." + "Replacing two independent `sigma` parameters with one shared normalization reduces the count from 19 to 18.\n", + "\n", + "For a larger population, the saving grows: replacing N independent member normalizations with one shared\n", + "parameter removes N - 1 sampling dimensions, provided the other model choices remain unchanged." ] }, { @@ -856,7 +977,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We fit this model with an identical search set up." + "We fit the scaling-relation model using the same dataset, analysis object and search settings as the galaxy-only\n", + "fit with independently modeled members.\n", + "\n", + "Inspect the resulting parameters and residuals to assess whether the restricted member model describes the data\n", + "adequately.\n", + "\n", + "Remember that this comparison changes the truncation prescription as well as tying the mass normalizations.\n", + "Any difference in the fit cannot be attributed solely to the reduction of one parameter." ] }, { @@ -873,14 +1001,14 @@ ")\n", "\n", "print(\n", - " \"The non-linear search has begun running - checkout the output/howtolens/chapter_4/\"\n", - " \"tutorial_4_group_scale_scaling_relation folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell with progress once search has completed - this could take some time!\"\n", + " \"The non-linear search has begun. Check the output/howtolens/chapter_4/\"\n", + " \"tutorial_4_group_scale_scaling_relation folder for results and visualizations as the search progresses.\"\n", + " \" This cell will finish when the search completes.\"\n", ")\n", "\n", "result_scaling = search.fit(model=model, analysis=analysis)\n", "\n", - "print(\"The search has finished run - you may now continue the notebook.\")\n", + "print(\"The search has finished \u2014 you may now continue the notebook.\")\n", "\n", "print(result_scaling.info)\n", "\n", @@ -895,55 +1023,47 @@ "source": [ "__The Group Scale Sweet Spot__\n", "\n", - "Step back and consider what this tutorial did *not* require: no new fitting machinery, no new analysis object,\n", - "no new data format. The `FitImaging`, `AnalysisImaging`, linear light profiles and `Nautilus` search of the\n", - "galaxy-scale chapters handled the group unchanged -- we just put more galaxies in the tracer, reached for the\n", - "truncated dPIE profile, and used scaling relations to keep the member population cheap. Even the pixelized\n", - "source reconstructions of the previous chapter work at group scale exactly as they do at galaxy scale, and for\n", - "real groups with complex arcs they are the recommended source model.\n", - "\n", - "This is why the group scale is the **sweet spot** of strong lens modeling. The full toolkit of galaxy-scale\n", - "modeling still applies, and the model dimensionality stays low: our individually-modeled-member fit had N=19\n", - "free parameters and the scaling-relation fit N=18. Real group models are of this order -- a few tens of free\n", - "parameters at most (N < 30 or so) -- comfortably within reach of the non-linear searches we already know, with\n", - "run times of minutes to hours.\n", - "\n", - "Push the system any richer, however, and this toolkit breaks down. A cluster hosts hundreds of members and\n", - "lenses many sources at once; its image is too large and complex to fit pixel-by-pixel with a tracer's light\n", - "model, and its model would need hundreds of parameters. Cluster-scale modeling therefore switches to a\n", - "different tool set -- fitting the *positions* of the multiple images of many point-like sources, with member\n", - "catalogues driving the mass model -- which is the subject of the next tutorial.\n", - "\n", - "__Wrap Up__\n", + "Group-scale lenses let us apply much of the toolkit developed for individual galaxies to a richer mass\n", + "distribution.\n", "\n", - "In this tutorial, we took the tools of the previous tutorials to the group scale. Lets recap what we learnt:\n", + "We still use `FitImaging`, `AnalysisImaging`, linear light profiles and a non-linear search. Pixelized source\n", + "reconstructions can also be used when the lensed source has structure that a simple parametric profile does\n", + "not capture.\n", "\n", - "- **Groups in LCDM**: A galaxy group is a dark matter halo of roughly 10^13 to 10^14 solar masses hosting a\n", - " handful to a few dozen galaxies, with the brightest group galaxy (BGG) typically near its centre. The group's\n", - " halo may enter the mass model as its own component, often centred on the BGG -- but whether it is needed is\n", - " an explicit modelling choice, tested by fitting with and without it.\n", + "Our examples remain compact: 19 non-linear parameters for independently normalized members, 21 after adding the\n", + "illustrative NFW halo, and 18 for the galaxy-only scaling-relation model.\n", "\n", - "- **Groups vs multi-galaxy lenses**: The line is blurry. All groups are multi-galaxy lenses, but not all\n", - " multi-galaxy lenses are groups -- the group's defining feature is the shared halo environment its members\n", - " orbit within.\n", + "These counts describe our chosen examples, rather than an upper limit for group modeling. Real systems may\n", + "require more galaxies, additional sources, more flexible mass profiles or further freedom in the scaling relation.\n", "\n", - "- **Tidal truncation and the dPIE**: Members orbiting in the group's potential have their outer dark matter\n", - " tidally stripped, so their profiles are truncated. The `dPIEMassSph` profile encodes this via its `r_cut`\n", - " truncation radius, with `sigma` setting the lensing strength and `r_core` the (usually vanishing) core.\n", + "Groups are particularly useful for studying how mass is divided between a central galaxy, satellite galaxies\n", + "and a larger dark matter halo. As throughout this chapter, that decomposition can remain uncertain even when\n", + "the lensed images are fitted well.\n", "\n", - "- **Fitting and modeling groups**: The galaxy-scale machinery works unchanged -- a tracer with more galaxies,\n", - " members with fixed centres and free `sigma`, and a `Nautilus` search over N=19 parameters.\n", + "At cluster scale, many multiply imaged sources can provide constraints across a much larger region. A common\n", + "approach is to fit their image positions, using a catalogue to describe the member population.\n", "\n", - "- **Scaling relations**: Tying member `sigma` and `r_cut` to luminosity via power laws with one shared free\n", - " normalization means the whole member population costs a single parameter, however many members there are.\n", + "This is the approach introduced in the next tutorial. It complements surface-brightness modeling rather than\n", + "marking a fundamental scale beyond which pixel-based fitting is impossible.\n", "\n", - "- **The sweet spot**: Groups are the largest systems the familiar toolkit -- including pixelized source\n", - " reconstruction -- still handles, with model dimensionality staying below a few tens of parameters.\n", + "__Wrap Up__\n", "\n", - "In the next tutorial we climb the final rung of the ladder to galaxy clusters, where tens to hundreds of member\n", - "galaxies lens many sources simultaneously. There the toolkit changes: we will model the positions of multiply\n", - "imaged point sources rather than every pixel of the data, and drive the mass model from member catalogues via\n", - "a csv interface built on the same scaling relations we used here." + "In this tutorial, we learned:\n", + "\n", + "- Group lenses combine contributions from central galaxies, members and potentially an explicitly modeled shared\n", + " dark matter halo.\n", + "- The dPIE profile provides a finite-mass description of members, with a smooth truncation scale whose\n", + " interpretation depends on the adopted model.\n", + "- Measuring member positions first and fixing centres helps keep the inference manageable.\n", + "- Comparing fitted galaxy-only and galaxy-plus-NFW models tests whether the data support a separate halo\n", + " component under the chosen priors.\n", + "- Luminosity-based scaling relations can replace independent member mass normalizations with shared parameters,\n", + " while member-light freedom must still be counted separately.\n", + "- The familiar imaging toolkit extends naturally to groups, but reliable mass decomposition requires attention\n", + " to degeneracies and modeling assumptions.\n", + "\n", + "In the next tutorial, we move to **galaxy clusters**, fitting the positions of multiple images from background\n", + "sources and building member-galaxy models from a CSV catalogue." ] } ], @@ -979,4 +1099,4 @@ }, "nbformat": 4, "nbformat_minor": 4 -} \ No newline at end of file +} diff --git a/notebooks/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.ipynb b/notebooks/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.ipynb index 3403eae..38f48e3 100644 --- a/notebooks/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.ipynb +++ b/notebooks/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.ipynb @@ -7,43 +7,35 @@ "Tutorial 5: Cluster Scale\n", "=========================\n", "\n", - "Throughout this chapter we have been climbing a ladder of scale: from a single lens galaxy with an extra\n", - "galaxy nearby, to multi-galaxy lenses, to galaxy groups whose members share a common dark matter halo.\n", + "We now extend the tools developed for galaxies and groups to **galaxy clusters**.\n", "\n", - "This tutorial climbs the final rung: **galaxy clusters**, the most massive gravitationally-bound structures in\n", - "the Universe. A cluster-scale strong lens contains:\n", + "Galaxy clusters typically inhabit dark matter halos with masses of roughly $10^{14}$-$10^{15}$ solar masses,\n", + "with the most massive systems exceeding $10^{15}$ solar masses. Within this shared halo, a cluster can contain\n", + "**hundreds of individual lens galaxies**, including a brightest cluster galaxy, other prominent galaxies and a\n", + "large population of lower-mass members.\n", "\n", - "- **30+ to hundreds of lens galaxies**: a brightest cluster galaxy (BCG) and bright satellites, plus a large\n", - " population of lower-mass member galaxies, all embedded in...\n", + "Their combined mass can produce multiple images of many background sources at different redshifts.\n", "\n", - "- **A cluster-scale dark matter halo of more than 10^14 solar masses** (the most massive exceed 10^15 solar\n", - " masses) \u2014 hundreds of times more massive than the halo of a single lens galaxy.\n", + "These systems offer two important scientific opportunities:\n", "\n", - "- **Many multiply-imaged background sources** \u2014 often tens of them \u2014 and, crucially, these sources typically\n", - " all sit at **different redshifts**. Light from each source therefore traverses a different path through the\n", - " Universe, and modeling them together requires **multi-plane ray tracing**, which we explain below.\n", + "- **Studying magnified background galaxies:** lensing can make faint sources brighter and stretch their images,\n", + " revealing details that would otherwise be difficult to observe.\n", + "- **Mapping the cluster's mass distribution:** multiple-image systems at different positions and redshifts\n", + " constrain the combined contributions of the cluster halo and its galaxies.\n", "\n", - "The science a cluster lens delivers is different from the galaxy-scale lensing of earlier chapters:\n", + "High magnification occurs near critical curves in both galaxy- and cluster-scale lenses. Clusters provide\n", + "extended regions in which many background sources can be lensed, but the magnification of an individual source\n", + "depends on its position, size and the lens model.\n", "\n", - "- **Extreme magnification**: near a cluster's critical curves, magnifications of tens to hundreds are common\n", - " (compared to the factors of a few of galaxy-scale lensing). Clusters act as natural telescopes, letting us\n", - " study intrinsically faint galaxies in the early Universe that would otherwise be invisible \u2014 many of the\n", - " most distant galaxies known were discovered behind lensing clusters.\n", + "In this tutorial, we fit **multiple-image positions** rather than the full surface-brightness distribution of\n", + "every arc. This provides a compact set of constraints for exploring the cluster mass model.\n", "\n", - "- **Mapping the cluster's mass**: every multiply-imaged source constrains the cluster's total mass\n", - " distribution along a different line of sight. With many sources, the mass model pins down the shape of the\n", - " cluster's dark matter halo and the substructure within it \u2014 the granularity of dark matter on sub-cluster\n", - " scales \u2014 providing some of the sharpest tests of the cold dark matter model.\n", - "\n", - "The modeling toolkit also changes at this scale. Fitting the extended arcs of every source, with a light\n", - "profile or pixelization each, is computationally prohibitive when there are tens of sources and hundreds of\n", - "member galaxies. The standard approach instead fits only the **positions** of each source's multiple images \u2014\n", - "point-source modeling \u2014 and drives the mass model from spreadsheet-editable **CSV catalogues**, because\n", - "writing Python model code for hundreds of galaxies by hand is not sensible either.\n", + "We also introduce CSV catalogues for the image positions, individually modeled components and member population.\n", + "These make larger systems easier to organize while retaining the model-composition tools used earlier.\n", "\n", "__Contents__\n", "\n", - "- **Multi-Plane Ray Tracing:** What it means for sources at different redshifts to be lensed together.\n", + "- **Multi-Plane Ray Tracing:** Distinguish multiple source planes from multiple deflecting planes.\n", "- **Dataset:** Load the simulated cluster's CCD imaging and inspect the true multi-plane tracer.\n", "- **Point Source Modeling:** Why cluster modeling fits multiple-image positions rather than extended arcs.\n", "- **Point Datasets:** The per-source multiple-image positions, loaded from a single hand-editable CSV.\n", @@ -60,34 +52,26 @@ "\n", "__Multi-Plane Ray Tracing__\n", "\n", - "Every lens system in the tutorials so far had two planes: an image plane (the lens galaxies, all at one\n", - "redshift) and a source plane (the lensed galaxy). The lens equation was applied once, mapping image-plane\n", - "coordinates to source-plane coordinates via the deflection angles:\n", + "Our simulated cluster places all deflecting mass at redshift $z=0.5$, with background sources at $z=1.0$ and\n", + "$z=2.0$.\n", "\n", - "$\\beta = \\theta - \\alpha(\\theta)$\n", + "This gives us **one deflecting plane and two source planes**. Each source is mapped through the same cluster\n", + "mass distribution, but with the lensing-distance factors appropriate to its redshift.\n", "\n", - "A cluster breaks this picture, because its sources sit at different redshifts. Consider our simulated cluster,\n", - "which has lens galaxies at $z = 0.5$ and two sources, at $z = 1.0$ and $z = 2.0$:\n", + "Different source redshifts therefore require different geometric scaling; they do not automatically imply that\n", + "light is deflected by mass on several planes.\n", "\n", - "- Light from the $z = 1.0$ source is deflected by the $z = 0.5$ cluster and travels to us: the familiar\n", - " two-plane system.\n", + "Genuine multi-plane deflection arises when significant mass occupies more than one redshift plane. For example,\n", + "a galaxy at $z=1.0$ could both be lensed by the cluster and deflect light from a more distant source at $z=2.0$.\n", "\n", - "- Light from the $z = 2.0$ source first passes the $z = 1.0$ plane, then the $z = 0.5$ cluster plane. If any\n", - " galaxy at $z = 1.0$ had mass, it would deflect this light too \u2014 the deflections of successive planes\n", - " accumulate, each applied at the position the ray has reached by that plane.\n", + "In that case, the ray's position at a later plane depends on the deflections accumulated at earlier planes.\n", + "The multi-plane lens equation accounts for this sequentially.\n", "\n", - "This is **multi-plane ray tracing**: the lens equation is applied recursively, plane by plane in redshift\n", - "order. There is a second, subtler effect: the strength of a deflection depends on the distances between the\n", - "observer, the deflector and the source. The same cluster bends light from a $z = 2.0$ source through a larger\n", - "effective angle than light from a $z = 1.0$ source, because the geometry of the light paths differs. The\n", - "recursive lens equation accounts for this by scaling each plane's deflections by ratios of cosmological\n", - "(angular diameter) distances.\n", + "The `Tracer` supports both situations. It organizes galaxies by redshift and computes the appropriate mappings\n", + "to each source plane. Our example uses that machinery with mass on the cluster plane only.\n", "\n", - "The maths is more bookkeeping than new physics, and the good news is that the `Tracer` handles all of it\n", - "automatically: give it galaxies at three or more redshifts and it groups them into planes, orders them, scales\n", - "their deflections and applies the recursion. Every source's redshift must simply be *correct* \u2014 hardcoding the\n", - "wrong redshift silently produces the wrong multi-plane geometry, which is why the dataset CSVs below carry a\n", - "redshift for every source." + "Source redshifts are therefore essential inputs. Here they are known from the simulation; observational\n", + "redshift uncertainties must be considered when interpreting a real cluster model." ] }, { @@ -164,11 +148,21 @@ "source": [ "__Dataset__\n", "\n", - "We use a simulated cluster whose scale is kept deliberately small so it runs quickly, but which contains every\n", - "ingredient of the cluster regime: 2 main lens galaxies (a BCG and a satellite), 10 lower-mass member galaxies\n", - "on a luminosity-mass scaling relation, a 10^15.3 solar-mass dark matter halo, and 2 multiply-imaged sources at\n", - "different redshifts (z = 1.0 and z = 2.0). A real cluster simply has more of everything \u2014 and we will see that\n", - "scaling this model up to hundreds of members does not add a single free parameter." + "We use a simplified simulated cluster containing:\n", + "\n", + "- Two individually modeled lens galaxies: a brightest cluster galaxy, or BCG, and a satellite.\n", + "- Ten additional member galaxies whose masses follow a luminosity-based scaling relation.\n", + "- A shared dark matter halo with input `mass_at_200` of $10^{15.3}$ solar masses.\n", + "- Two multiply imaged sources at redshifts 1.0 and 2.0.\n", + "\n", + "The cluster's deflecting components are all at redshift 0.5.\n", + "\n", + "This example demonstrates the catalogue and fitting workflow with a small member population. Adding more members\n", + "need not add non-linear mass parameters when their positions and profile properties are fixed or tied through\n", + "the same relation, although evaluating their deflections still adds computational work.\n", + "\n", + "Real clusters can require additional halos, more flexible galaxy models and further treatment of redshift or\n", + "membership uncertainties." ] }, { @@ -211,12 +205,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We first load and plot the cluster's CCD imaging. Note the pixel scale of 0.2\" and the sheer size of the\n", - "field: 100\" x 100\", compared to the ~6\" fields of the galaxy-scale tutorials. The Einstein radius of a\n", - "10^15 solar-mass cluster is ~20-30\", so its multiple images and arcs are spread across a region hundreds of\n", - "times larger in area than a galaxy-scale lens.\n", + "We first load and plot the simulated cluster image. Its pixel scale is 0.2\" and its field spans 100\" x 100\",\n", + "allowing us to see the cluster galaxies and widely separated lensed images.\n", + "\n", + "Inspect where the multiple images lie relative to the central galaxies and member population.\n", "\n", - "The imaging is loaded for visualization only \u2014 as we discuss next, the model is not fitted to these pixels." + "The angular extent of strong lensing depends on the mass distribution and source redshift, not simply the\n", + "cluster's total halo mass.\n", + "\n", + "We use this image for visualization. The fit below uses measured multiple-image positions rather than these\n", + "image pixels." ] }, { @@ -234,9 +232,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The simulator saved the true `Tracer` used to make this dataset, which we can load to inspect the multi-plane\n", - "structure described above. The tracer has three planes: the lens plane at z = 0.5 (holding all 13 lens-plane\n", - "galaxies \u2014 2 main galaxies, 10 scaling members and the dark matter halo) and one source plane per source." + "We load the `Tracer` saved by the simulator to inspect its redshift structure.\n", + "\n", + "It contains three planes: the cluster plane at $z=0.5$, followed by source planes at $z=1.0$ and $z=2.0$.\n", + "\n", + "The cluster plane contains 13 `Galaxy` objects: two main galaxies, ten scaling-relation members and one mass-only\n", + "object carrying the shared dark matter halo. The halo's use of a `Galaxy` container is an API convention; it does\n", + "not represent an additional luminous galaxy.\n", + "\n", + "All deflecting mass in this example lies on the cluster plane. The two source planes specify where we evaluate\n", + "the mappings for their respective background sources." ] }, { @@ -258,45 +263,39 @@ "source": [ "__Point Source Modeling__\n", "\n", - "In every previous tutorial we fitted the data pixel-by-pixel: a model image of the lens and source light was\n", - "computed, convolved with the PSF and compared to every image pixel. For a cluster this becomes computationally\n", - "prohibitive:\n", + "We now describe each multiply imaged source using a set of image positions rather than fitting its full\n", + "surface-brightness distribution.\n", "\n", - "- Every one of the tens of sources needs its own light model (or pixelization), each adding parameters (or an\n", - " expensive linear inversion) to the fit.\n", + "For extended galaxies, these positions should identify **corresponding features** in the different images -- for\n", + "example, recognizable knots that represent the same source structure. Selecting each image's brightest pixel\n", + "independently does not necessarily identify matching features.\n", "\n", - "- The image is enormous \u2014 our modest simulated cluster already spans 500 x 500 pixels \u2014 and the deflection\n", - " angles of hundreds of member galaxies would need evaluating at every one of them, for every likelihood\n", - " evaluation.\n", + "This reduces the amount of data evaluated during the fit and avoids constructing a light-profile or pixelized\n", + "reconstruction for every source. It is a widely used approach for building cluster mass models.\n", "\n", - "The standard approach in cluster lensing therefore simplifies the data dramatically: each multiply-imaged\n", - "source is reduced to the **positions of its multiple images** \u2014 the (y,x) coordinates of the brightest pixel\n", - "of each image, measured from the imaging. The model then only has to answer a much cheaper question: does this\n", - "mass model ray-trace all of a source's observed image positions back to the same source-plane location?\n", + "The trade-off is that position fitting does not use the full information in the extended arcs. Surface-brightness\n", + "modeling can provide complementary constraints and remains possible for selected systems or more detailed analyses.\n", "\n", - "This is **point-source modeling**. We are deliberately discarding the information in the arcs' extended light\n", - "in exchange for a likelihood that is fast enough to evaluate with hundreds of galaxies and tens of sources.\n", - "(For lensed quasars and supernovae \u2014 genuine point sources \u2014 nothing is even discarded.) Extended-source\n", - "cluster modeling, where individual arcs are fitted at pixel level with the pixelizations of the previous\n", - "chapter, does exist in **PyAutoLens** as a specialised follow-up analysis \u2014 see the `autolens_workspace`\n", - "cluster examples \u2014 but position fitting is the workhorse that published cluster mass models are built on.\n", + "For genuine point sources such as quasars or supernovae, image positions are natural measurements, although\n", + "fluxes, time delays and other observables can provide additional information.\n", "\n", "__Point Datasets__\n", "\n", - "The positions of each source's multiple images are stored in a single CSV file, `point_datasets.csv`, with\n", - "one row per observed multiple image:\n", + "We load the multiple-image measurements from `point_datasets.csv`, with one row per observed image:\n", + "\n", + "- `name`: identifies the source or matched source feature. Rows sharing a name form one multiple-image system.\n", + "- `y`, `x`: its observed image-plane coordinates in arcseconds.\n", + "- `positions_noise`: the positional uncertainty adopted by the likelihood, in arcseconds.\n", + "- `redshift`: the source redshift, shared by the rows belonging to that system.\n", "\n", - " - `name`: the source identifier (e.g. `point_0`). All rows sharing a `name` belong to the same source.\n", - " - `y`, `x`: the image-plane position of the multiple image, in arc-seconds.\n", - " - `positions_noise`: the positional uncertainty in arc-seconds \u2014 how precisely the image's centroid is\n", - " measured (for space-telescope imaging ~0.005\", set by PSF-fitting precision, not the pixel scale).\n", - " - `redshift`: the source redshift, which every row of a group must share. This column is what makes the\n", - " multi-plane geometry reproducible from the file alone.\n", + "The positional uncertainty should reflect the measurement and modeling assumptions. Precise centroid measurements\n", + "do not imply that a simplified cluster mass model predicts positions to the same precision; unresolved structure\n", + "and other modeling limitations can also matter.\n", "\n", - "This CSV is the recommended input format for cluster datasets because it is hand-editable: measuring your own\n", - "cluster's multiple images means filling in a spreadsheet, not writing Python.\n", + "For this simulation, we use the supplied uncertainties. For real observations, choose and justify them rather\n", + "than adopting a universal value from the pixel scale or telescope resolution.\n", "\n", - "`al.list_from_csv` loads the file into a list of `PointDataset` objects, one per source." + "`al.list_from_csv` loads the file into a list of `PointDataset` objects, one per named system." ] }, { @@ -317,10 +316,15 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Plotting each dataset shows just how sparse point-source data is: a handful of (y,x) coordinates per source.\n", - "That a full cluster mass model can be constrained by so few numbers is because each coordinate is measured to\n", - "milli-arcsecond precision, and because every source at its own redshift probes the mass distribution\n", - "differently." + "Plot each dataset to inspect its multiple-image positions.\n", + "\n", + "Each system supplies a small set of coordinates that must be consistent with a common source position under the\n", + "lens model. Systems distributed across the cluster probe different parts of its deflection field, while their\n", + "redshifts determine the appropriate lensing geometry.\n", + "\n", + "The information available depends on the number and configuration of images, their uncertainties and the model's\n", + "flexibility. A small number of precise positions does not automatically determine a unique cluster mass\n", + "distribution." ] }, { @@ -342,36 +346,29 @@ "source": [ "__The CSV Interface__\n", "\n", - "With hundreds of member galaxies, composing the lens model in Python \u2014 one `af.Model(al.Galaxy)` per galaxy,\n", - "as in every previous tutorial \u2014 stops being sensible. The cluster workflow therefore defines the model in CSV\n", - "files as well, which the simulator wrote alongside the data:\n", + "CSV files provide a convenient way to organize a model containing many components. They separate the measured\n", + "catalogue and profile choices from the Python code that assembles the model.\n", + "\n", + "The simulator supplies:\n", "\n", - " - `mass.csv`: every individually-modelled mass profile \u2014 the two main lens galaxies' `dPIEMassSph` profiles\n", - " and the host halo's `NFWMCRLudlowSph`.\n", - " - `light.csv`: the light profiles (not used in point-source modeling, since light does not lens).\n", - " - `point.csv`: the source galaxies' `Point` components.\n", + "- `mass.csv`: the individually described mass profiles, including the main galaxies and shared dark matter halo.\n", + "- `light.csv`: light-profile descriptions, which are not needed for this positions-only likelihood.\n", + "- `point.csv`: the source point components.\n", "\n", - "Each row of these CSVs carries:\n", + "Each profile row specifies a galaxy name, attribute name, profile class, redshift and relevant profile parameters.\n", + "Rows with the same galaxy name are assembled into one `Galaxy`.\n", "\n", - " - `galaxy`: a galaxy name (e.g. `lens_0`, `host_halo`, `source_0`). Rows sharing a name compose into one\n", - " galaxy.\n", - " - `attr_name`: the attribute the profile is bound to on the galaxy (e.g. `mass`, `dark`, `point_0`).\n", - " - `profile_class`: the profile class name (e.g. `dPIEMassSph`), looked up in `al.mp` / `al.lp` / `al.ps`.\n", - " - The profile's constructor parameters as columns (tuples like `centre` split into `y` / `x`); parameters a\n", - " row's class does not use are left blank.\n", - " - `redshift`: the galaxy's redshift.\n", + "The lower-mass member population is listed separately in `scaling_galaxies.csv`, with measured positions and\n", + "luminosities. We assign its mass profiles and shared scaling relation in Python.\n", "\n", - "The lower-mass member population lives in a fourth, simpler catalogue, `scaling_galaxies.csv`, with one row\n", - "per member and columns `y, x, luminosity`. No profile class, no mass parameters \u2014 because, as the previous\n", - "tutorial showed, the members' masses are not free parameters but derive from their luminosities via a scaling\n", - "relation. The catalogue is exactly what an observer measures: where each member is and how bright it is.\n", + "Adding members to this catalogue does not add independent mass parameters **under our fixed-centre,\n", + "spherical-profile and shared-relation assumptions**. Adding an individually modeled galaxy or halo can add\n", + "parameters, depending on which quantities we allow to vary.\n", "\n", - "This is the key scaling property of the CSV interface: modeling a richer cluster means appending rows to\n", - "`scaling_galaxies.csv` (and, for another individually-modelled galaxy or halo, to `mass.csv`) \u2014 the Python\n", - "below does not change, and the number of free parameters does not grow with the member count.\n", + "The catalogue format makes a larger model easier to assemble; the modeling assumptions determine its\n", + "dimensionality.\n", "\n", - "We load the mass and point families (`al.galaxy_models_from_csv`) and the member catalogue\n", - "(`al.galaxy_table_from_csv`):" + "We now load the mass and point-profile tables, followed by the member catalogue." ] }, { @@ -400,24 +397,37 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "In a real analysis the member centres and luminosities come from light fits to the imaging data (or an\n", - "external photometric catalogue), and the main-galaxy centres in `mass.csv` are pinned to the observed light\n", - "centres. Fixing the centres to observed values is essential at cluster scale: a handful of multiple-image\n", - "positions cannot constrain hundreds of free centre coordinates, but the imaging measures them for free.\n", + "In real observations, member positions and luminosities can come from preliminary light fits or a suitable\n", + "catalogue. As in earlier tutorials, fixing member mass centres to measured light positions is a useful way to\n", + "limit the model's freedom.\n", + "\n", + "These measurements are not exact, and selected galaxies can be given positional freedom where the data and\n", + "scientific question justify it.\n", "\n", "__Point Solver__\n", "\n", - "Point-source modeling needs one new piece of machinery: given a mass model and a source-plane (y,x)\n", - "coordinate, where in the image plane do its multiple images appear? Answering this means solving the lens\n", - "equation *backwards*, which has no analytic solution.\n", + "We met the `PointSolver` earlier when finding the multiple images of a point source, such as a lensed quasar,\n", + "behind a single lens galaxy.\n", + "\n", + "We use exactly the same tool here. Given a mass model and a source position, it solves the lens equation\n", + "numerically to locate the multiple images. The difference is that our mass model now contains a cluster halo\n", + "and many galaxies, and we repeat the calculation for sources at their respective redshifts.\n", + "\n", + "Recall that the solver divides the image plane into triangles, maps them to the source plane and refines\n", + "candidate regions until the requested positional resolution is reached.\n", "\n", - "The `PointSolver` solves it numerically: it tiles the image plane with triangles, ray-traces each triangle's\n", - "corners to the source plane, keeps the triangles that land on the source-plane coordinate, and subdivides\n", - "them repeatedly until the image positions are located to a precision of `pixel_scale_precision`.\n", + "The grid should cover the region in which we want to search for images. Here, it spans the same approximate 100\"\n", + "field as the simulated imaging. Images outside that search region will not be found.\n", "\n", - "The solver's grid must span the full 100\" cluster field \u2014 the multiple images sit tens of arc-seconds from\n", - "the cluster centre. The `magnification_threshold` discards heavily demagnified images (e.g. the faint central\n", - "image of a typical lens configuration, which real observations do not detect)." + "`pixel_scale_precision` sets the solver's numerical resolution in arcseconds; it is separate from the\n", + "observational uncertainties in `positions_noise`.\n", + "\n", + "`magnification_threshold` filters out predicted images with low absolute magnification. This is a numerical\n", + "selection rule, not a complete model of detectability, which also depends on source brightness, noise and blending.\n", + "\n", + "Unlike an image-plane position likelihood that uses the solver during fitting, our chosen cluster likelihood\n", + "back-traces the observed positions without solving for predicted images at every evaluation. We will use the\n", + "familiar `PointSolver` after fitting to check the predicted image configuration for each source." ] }, { @@ -442,38 +452,30 @@ "source": [ "__Model__\n", "\n", - "We now compose the cluster model, which has four tiers of component \u2014 the same four tiers every published\n", - "cluster mass model is built from:\n", - "\n", - " - **Main lens galaxies (2)**: the BCG and satellite, modelled individually with `dPIEMassSph` profiles. As\n", - " the previous tutorial on group-scale lenses discussed, the dPIE is the standard truncated profile of this\n", - " regime: members orbiting in the cluster's shared potential have their outer dark matter tidally stripped,\n", - " so their mass genuinely ends at a finite truncation radius `r_cut`. Each main galaxy has free `sigma` (its\n", - " fiducial velocity dispersion, setting the lens strength) and free `r_cut`, with its centre fixed to the\n", - " observed light centre [4 free parameters].\n", - "\n", - " - **Scaling-tier members (10)**: `dPIEMassSph` profiles with centres fixed from the catalogue and `sigma` /\n", - " `r_cut` derived from each member's luminosity via the scaling relation introduced earlier in this chapter:\n", - " sigma = sigma_ref * (L / L_ref)^0.25 and r_cut = r_cut_ref * (L / L_ref)^0.7. Only the normalization\n", - " `sigma_ref` \u2014 the velocity dispersion of a member at the reference luminosity \u2014 is free. Whether the\n", - " catalogue holds 10 members or 300, the tier costs [1 free parameter].\n", - "\n", - " - **Host dark matter halo (1)**: a standalone galaxy carrying the cluster's `NFWMCRLudlowSph` halo, centred\n", - " on the BCG, with a free total mass `mass_at_200` [1 free parameter].\n", - "\n", - " - **Source galaxies (2)**: parameter-free `PointSolved` components. Rather than sampling each source's\n", - " (y,x) source-plane centre as free parameters, the fit solves for the centre analytically \u2014 the\n", - " precision-weighted mean of the back-traced image positions. With tens of sources this matters: it removes\n", - " two parameters per source from the search [0 free parameters].\n", - "\n", - "**Total: N = 6 free parameters** \u2014 for a model containing 13 galaxies and 2 sources. This is the punchline of\n", - "the cluster workflow: catalogues and scaling relations decouple the model's physical richness from the\n", - "dimensionality of the non-linear search.\n", - "\n", - "`al.galaxy_af_models_from_csv_tables` converts the CSV tables into a dictionary of `af.Model(Galaxy)` objects\n", - "keyed by galaxy name, with every CSV value fixed as a default. We then selectively promote parameters to free\n", - "priors \u2014 exactly the `af.Model` customization API used throughout the earlier chapters, just applied to\n", - "models built from files instead of Python." + "Our example combines four types of component:\n", + "\n", + "- **Two main lens galaxies:** each has a spherical dPIE mass profile with fixed centre and core radius, but free\n", + " `sigma` and `r_cut`. Together they contribute **four parameters**.\n", + "- **Ten scaling-relation members:** their positions and core radii are fixed. Their velocity-dispersion\n", + " normalizations depend on one shared `sigma_ref`; their truncation radii follow a fixed luminosity prescription.\n", + " This population contributes **one parameter**.\n", + "- **One shared dark matter halo:** an `NFWMCRLudlowSph` profile with fixed centre and free `mass_at_200`.\n", + " Its mass-concentration prescription supplies additional structure without an independent concentration\n", + " parameter. It contributes **one parameter**.\n", + "- **Two background sources:** `PointSolved` components whose source positions are solved within the selected\n", + " likelihood rather than sampled independently. They contribute **zero non-linear sampling parameters**.\n", + "\n", + "The total is therefore **six free non-linear parameters**.\n", + "\n", + "This small count reflects strong restrictions on the model: spherical profiles, fixed positions and redshifts,\n", + "a prescribed halo mass-concentration relation, and a deterministic member scaling relation. It is not a claim\n", + "that real cluster mass distributions generally require only six parameters.\n", + "\n", + "The model contains twelve lens galaxies, one mass-only halo component and two source objects. Adding more tied\n", + "members preserves the parameter count only while those restrictions remain in place.\n", + "\n", + "`al.galaxy_af_models_from_csv_tables` builds the named galaxy models from the CSV tables, initially fixing their\n", + "supplied values. We then assign priors to the particular parameters we want the search to vary." ] }, { @@ -492,10 +494,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The main lens galaxies get free dPIE `sigma` / `r_cut`; their centres and redshifts stay fixed at the CSV\n", - "values, and `r_core` stays fixed at the CSV's 0.0 (the vanishing-core convention discussed in the previous\n", - "tutorial). The cosmology constants `H0` / `Om0` are pinned explicitly: they are model *constants*, not\n", - "parameters to sample \u2014 left unset they would inherit priors from the configuration files and float." + "We give each main lens galaxy two free dPIE parameters: `sigma`, which controls its mass normalization, and\n", + "`r_cut`, which controls its outer truncation scale.\n", + "\n", + "Their centres, redshifts and zero core radii retain the values supplied by the catalogue. As in the group\n", + "tutorial, `sigma` uses the Lenstool profile convention and is not automatically identical to a measured stellar\n", + "velocity dispersion.\n", + "\n", + "We explicitly fix `H0` and `Om0`, because this example assumes a cosmology rather than attempting to infer it.\n", + "\n", + "The prior ranges below are choices for this simulated example. For real data, they should reflect the system\n", + "being studied, and results near their boundaries warrant further inspection." ] }, { @@ -517,9 +526,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The host halo gets a free `mass_at_200`, spanning the full range of cluster masses with a log-uniform prior\n", - "(mass scales spanning orders of magnitude are sampled in log space, as we saw for intensities in earlier\n", - "chapters)." + "The shared dark matter halo receives a free `mass_at_200` parameter, expressed in solar masses.\n", + "\n", + "This is the mass parameter of the NFW host component, not the sum of every mass component in our cluster model.\n", + "The main galaxies and scaling-relation members contribute additional mass.\n", + "\n", + "The `NFWMCRLudlowSph` profile uses a prescribed mass-concentration relation, so changing the halo mass also changes\n", + "its associated profile structure. We do not fit concentration independently here.\n", + "\n", + "We use a log-uniform prior from $10^{14.5}$ to $10^{16}$ solar masses, assigning equal prior weight to equal\n", + "logarithmic intervals. This is a broad example range, rather than a universal prior for cluster lenses." ] }, { @@ -537,10 +553,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Each source's `point_i` component is swapped for the parameter-free `al.ps.PointSolved`. The name pairing\n", - "(`point_0`, `point_1`) is what links each model component to the `PointDataset` with the same name \u2014 in a\n", - "multi-source cluster this pairing is what guarantees every source's positions are fitted by the correct\n", - "component." + "We replace each source's point component with `PointSolved`.\n", + "\n", + "With the source-plane likelihood used below, the source position is solved from the back-traced image positions\n", + "for each proposed mass model, rather than sampled as two independent coordinates.\n", + "\n", + "This does not mean the source position is known exactly or remains fixed. It changes as the mass model changes,\n", + "and its interpretation depends on the positional uncertainties and likelihood assumptions.\n", + "\n", + "Each component name, such as `point_0`, must match the name of its `PointDataset`. We also retain the source\n", + "redshift associated with that dataset so that its images are traced to the correct plane." ] }, { @@ -557,9 +579,24 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The scaling tier is composed in a loop over the catalogue, exactly as in the previous tutorial: the single\n", - "shared prior `scaling_sigma_ref` is defined once outside the loop, and each member's `sigma` / `r_cut` derive\n", - "from it via that member's luminosity ratio. The truth value used by the simulator is sigma_ref = 85 km/s." + "We build the member population by looping over its measured positions and luminosities, using the same approach\n", + "as in the previous tutorials.\n", + "\n", + "The shared `scaling_sigma_ref` prior is defined once, outside the loop. Each member's `sigma` is an expression\n", + "involving that prior and its fixed luminosity ratio.\n", + "\n", + "Each `r_cut`, however, is calculated entirely from fixed quantities: the reference truncation scale, luminosity\n", + "ratio and exponent. It therefore receives a fixed value, rather than depending on `scaling_sigma_ref`.\n", + "\n", + "We adopt $\\sigma\\propto L^{0.25}$ and $r_{\\rm cut}\\propto L^{0.7}$, with fixed centres and zero core radii.\n", + "These assumptions leave one free mass parameter for the entire member population.\n", + "\n", + "The simulator used `sigma_ref = 85 km/s`. We will later inspect whether the fit constrains this normalization.\n", + "\n", + "The dPIE `redshift_source` input specifies the reference source redshift used to normalize the profile's lensing\n", + "quantities. Here, we use the highest source redshift consistently for the scaling members. The tracer then\n", + "evaluates the lens mapping to each source's own plane; this does not place every source at that reference\n", + "redshift." ] }, { @@ -602,8 +639,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The named galaxies and the scaling tier combine into the overall model. Printing `model.info` confirms the\n", - "parameter count: for all its 15 galaxies, the search explores just 6 dimensions." + "We combine the individually named components and scaling-relation members into the overall model.\n", + "\n", + "The `galaxies` collection contains the two main lens galaxies, the mass-only host-halo component and the two\n", + "sources. The `scaling_galaxies` collection contains the ten additional members.\n", + "\n", + "This gives **15 `Galaxy` objects**, representing twelve lens galaxies, one shared dark matter halo and two\n", + "background sources.\n", + "\n", + "Inspect `model.info` to check the fixed values, independent priors and linked expressions. Under the assumptions\n", + "above, the model has **six free non-linear parameters**: four for the main galaxies, one for the host halo and\n", + "one shared by the scaling members." ] }, { @@ -624,16 +670,15 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The same model can also be visualized as a figure, making its structure easier to understand at a glance.\n", + "The figure shows the model's independent priors, fixed values and linked expressions.\n", "\n", - "The figure shows how the model is organized: which parameters belong to each component, and whether they are free,\n", - "fixed, shared, linked by an expression, solved during the fit, or not configured. `model.info` provides the\n", - "corresponding numerical details, including the prior assigned to each free parameter and the value of each fixed\n", - "parameter.\n", + "Each main galaxy has its own free `sigma` and `r_cut`. The host halo has one free mass parameter, and the ten\n", + "scaling members share one `scaling_sigma_ref` prior.\n", "\n", - "Thirteen galaxies and two sources are modelled with six free parameters. That compression \u2014 main galaxies and\n", - "sources sharing priors, one halo, and a scaling relation tying ten members to a single free prior \u2014 is what makes\n", - "a cluster-scale model tractable at all." + "The source positions are solved within the selected likelihood rather than sampled independently.\n", + "\n", + "These choices give six non-linear parameters across fifteen `Galaxy` objects. The small parameter count comes\n", + "from the restrictions and shared relations we imposed, rather than from the catalogue format itself." ] }, { @@ -651,20 +696,29 @@ "source": [ "__Analysis + Factor Graph__\n", "\n", - "Each source's dataset gets its own `AnalysisPoint`, which defines the log likelihood for that source: how\n", - "well do the model's predictions match this source's observed image positions?\n", + "We create one `AnalysisPoint` for each source's dataset. Each analysis evaluates how well the same cluster mass\n", + "model explains that source's observed multiple-image positions.\n", + "\n", + "We select `FitPositionsSourceSolved`, which:\n", "\n", - "`fit_positions_cls=al.FitPositionsSourceSolved` selects the **solved source-plane** likelihood \u2014 the default\n", - "cluster configuration. Rather than forward-solving the lens equation for the model's image positions on every\n", - "likelihood evaluation (accurate but expensive), it ray-traces the *observed* positions back to the source\n", - "plane and measures how tightly they converge around the analytically-solved source centre, with a weighting\n", - "that maps source-plane scatter back to image-plane precision. No lens-equation solve per evaluation makes\n", - "cluster-scale inference fast; the `PointSolver` is reserved for validating the final model below.\n", + "1. Traces the observed image positions back to the source's redshift plane.\n", + "2. Solves for a common source position under the adopted weighting.\n", + "3. Evaluates the scatter around that position using the positional uncertainties and the likelihood's\n", + " source-plane weighting.\n", "\n", - "The analyses are then combined through a **factor graph**, the same multi-dataset machinery used for\n", - "multi-wavelength imaging: each analysis becomes a factor sharing the one global model, and the total log\n", - "likelihood is the sum over the per-source likelihoods. This is what lets every source \u2014 each at its own\n", - "redshift, each with its own multi-plane geometry \u2014 constrain the same cluster mass model simultaneously." + "This avoids solving for predicted image positions at every likelihood evaluation. It is a source-plane fitting\n", + "approach, rather than a direct comparison between observed and forward-solved image positions.\n", + "\n", + "We will use the `PointSolver` afterwards to inspect the predicted images. That check is important because a\n", + "compact set of back-traced positions does not by itself establish that the model predicts the observed image\n", + "configuration.\n", + "\n", + "We combine the analyses using a **factor graph**. Each source contributes a likelihood factor, and all factors\n", + "share the same global mass model.\n", + "\n", + "Assuming the datasets are conditionally independent given that model, the total log likelihood is the sum of\n", + "their individual log likelihoods. The shared parameters are sampled once, with every source contributing\n", + "constraints through its own positions and redshift." ] }, { @@ -697,8 +751,13 @@ "source": [ "__Search__\n", "\n", - "We fit the model with Nautilus. The parameter space is only 6-dimensional, so a modest number of live points\n", - "suffices; a richer cluster with several individually-modelled galaxies would warrant more." + "We use `Nautilus` with 100 live points as the starting configuration for this six-parameter example.\n", + "\n", + "A low parameter count helps, but does not guarantee a simple posterior. Correlations between the halo, main\n", + "galaxies and member normalization can still make inference challenging.\n", + "\n", + "Inspect the resulting fits and posterior distributions, and assess whether important conclusions remain stable\n", + "under repeated runs or more demanding search settings." ] }, { @@ -723,9 +782,15 @@ "source": [ "__Model Fit__\n", "\n", - "We pass the factor graph's global model and the factor graph itself (as the analysis) to the search. Because\n", - "the likelihood involves no pixel-level computation, a full cluster point-source fit takes minutes \u2014 this is\n", - "the payoff of point-source modeling, given that a pixel-level fit of the same system would take days." + "We pass the factor graph's global model and combined analysis to the search.\n", + "\n", + "Each proposed parameter set defines one cluster mass model, which is evaluated against both source datasets.\n", + "Their log likelihoods combine to guide the search.\n", + "\n", + "The position-based likelihood avoids constructing a full model image at each evaluation. Runtime nevertheless\n", + "depends on the model, number of images and members, hardware and search settings.\n", + "\n", + "When the search finishes, we will inspect both the global mass parameters and the fit to each source." ] }, { @@ -733,18 +798,14 @@ "metadata": {}, "source": [ "print(\n", - " \"\"\"\n", - " The non-linear search has begun running.\n", - "\n", - " This Jupyter notebook cell will progress once the search has completed - this could take a few minutes!\n", - "\n", - " On-the-fly updates every iterations_per_quick_update are printed to the notebook.\n", - " \"\"\"\n", + " \"The non-linear search has begun. \"\n", + " \"Progress updates are printed during the search. \"\n", + " \"This cell will finish when the search completes.\"\n", ")\n", "\n", "result_list = search.fit(model=factor_graph.global_prior_model, analysis=factor_graph)\n", "\n", - "print(\"The search has finished run - you may now continue the notebook.\")" + "print(\"The search has finished \u2014 you may now continue the notebook.\")" ], "outputs": [], "execution_count": null @@ -755,14 +816,16 @@ "source": [ "__Results__\n", "\n", - "A cluster fit produces the most complex results object we have met: many galaxies across multiple planes,\n", - "tiers whose parameters are derived rather than sampled, and one result per source dataset. This section tours\n", - "how to pull out each quantity you will actually need \u2014 it is worth working through slowly, because navigating\n", - "results is half the practical skill of cluster modeling.\n", + "The factor-graph fit returns one result per source dataset, in the same order as `dataset_list`.\n", + "\n", + "These results come from **one joint inference**, not separate searches. They share the global mass model and\n", + "posterior, while each provides access to its own dataset and corresponding `FitPointDataset`.\n", "\n", - "A factor-graph fit returns one `Result` per dataset (in the same order as `dataset_list`). All results share\n", - "the same global model \u2014 and therefore the same samples and maximum likelihood model \u2014 but each carries its own\n", - "dataset and its own maximum likelihood `FitPointDataset`." + "We first use one result to inspect the shared model parameters and tracer. We then loop over the results to\n", + "examine each source's inferred position and fit diagnostics.\n", + "\n", + "This separates two useful questions: what mass distribution describes the cluster, and how well does that\n", + "distribution explain each observed multiple-image system?" ] }, { @@ -782,9 +845,14 @@ "source": [ "__Results: The Maximum Likelihood Instance__\n", "\n", - "The `max_log_likelihood_instance` is the model instance with the highest likelihood found. Its structure\n", - "mirrors the model composition above: named galaxies under `.galaxies`, the scaling tier under\n", - "`.scaling_galaxies`. We can read off the best-fit parameters of every tier." + "The `max_log_likelihood_instance` contains the parameter values of the highest-likelihood sample found by\n", + "the search.\n", + "\n", + "Its structure follows the model we constructed: named components appear under `.galaxies`, while the tied\n", + "members appear under `.scaling_galaxies`.\n", + "\n", + "We can inspect the main galaxies' dPIE parameters and the host halo's `mass_at_200` directly. These describe one\n", + "fitted realization; later, we use the posterior samples to examine their uncertainties and correlations." ] }, { @@ -810,10 +878,18 @@ "source": [ "__Results: Per-Member Profiles__\n", "\n", - "The scaling tier's single free parameter was `sigma_ref`, but the instance contains the fully-realised\n", - "`dPIEMassSph` of every member \u2014 the scaling relation has been applied, so each member carries the `sigma` and\n", - "`r_cut` its luminosity implies. This is how you would tabulate the inferred mass of every member galaxy in a\n", - "real cluster analysis." + "Although the member population shares one free normalization, the fitted instance contains a complete\n", + "`dPIEMassSph` profile for every member.\n", + "\n", + "Each member's `sigma` has been calculated from the fitted shared normalization and its luminosity ratio.\n", + "Its centre, core radius and luminosity-derived truncation radius retain their fixed values.\n", + "\n", + "The loop below lists these realized profile parameters. They are not independent measurements of every member's\n", + "mass: they inherit the scaling relation and its assumptions.\n", + "\n", + "To quantify their uncertainties, evaluate the derived quantities across posterior samples. With fixed\n", + "luminosities and exponent, the members' `sigma` values vary together through their shared normalization.\n", + "Intrinsic scatter and photometric uncertainty are not included unless explicitly modeled." ] }, { @@ -835,10 +911,19 @@ "source": [ "__Results: The Tracer__\n", "\n", - "`max_log_likelihood_tracer` assembles every galaxy of the instance \u2014 named tiers and scaling members alike \u2014\n", - "into the best-fit multi-plane `Tracer`. This is the object to use for any lensing calculation with the\n", - "best-fit mass model: convergence maps, deflection fields, critical curves and caustics, all computed exactly\n", - "as in the earlier chapters, but now for the full cluster." + "`max_log_likelihood_tracer` assembles the named components and scaling members into a tracer for the fitted model.\n", + "\n", + "It provides the same lensing calculations used in earlier chapters, now with the full cluster mass distribution\n", + "and both source redshifts.\n", + "\n", + "Inspect the plane redshifts and number of objects in the lens plane. Remember that the host halo occupies a\n", + "mass-only `Galaxy` object alongside the twelve lens galaxies.\n", + "\n", + "When calculating quantities such as critical curves or magnifications, specify the relevant source plane:\n", + "the same cluster produces different lens mappings for sources at different redshifts.\n", + "\n", + "This tracer represents one fitted realization. Uncertainty in derived lensing quantities requires repeating\n", + "the calculation over appropriate posterior samples." ] }, { @@ -861,11 +946,17 @@ "source": [ "__Results: Solved Source-Plane Positions__\n", "\n", - "Each result's `max_log_likelihood_fit` is the `FitPointDataset` of that source. Because we fitted with the\n", - "solved source-plane likelihood, the fit's `positions` object carries the analytically-solved source-plane\n", - "centre \u2014 the model's inferred true position of the source, before lensing. Its `residual_map` lists how far\n", - "each back-traced image lands from that centre (in the source plane): for a good model these residuals are\n", - "tiny, since all images of a source originate from the same point." + "Each result's `max_log_likelihood_fit` describes the fit to its own source dataset.\n", + "\n", + "With our selected likelihood, `fit.positions.source_plane_coordinate` gives the source position solved from\n", + "that system's back-traced image positions under the fitted mass model.\n", + "\n", + "The `residual_map` records their offsets from this common position in the source plane. Inspect these together\n", + "with the positional uncertainties and likelihood weighting, rather than judging the fit solely by whether\n", + "the raw offsets look small.\n", + "\n", + "The printed log likelihood is the position-likelihood contribution for that source. The joint inference combines\n", + "the contributions from all source datasets." ] }, { @@ -889,11 +980,18 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can perform the same back-tracing manually with the tracer, which makes explicit what the fit just did:\n", - "ray-trace each source's observed image positions through the multi-plane lens equation to that source's own\n", - "plane. `plane_index_via_redshift_from` maps a source redshift to its plane, and `traced_grid_2d_list_from`\n", - "returns the positions traced to every plane \u2014 the multi-plane generalisation of the two-plane ray tracing of\n", - "chapter 1." + "We can inspect the same mapping directly using the tracer, following the ray-tracing approach introduced in\n", + "Chapter 1.\n", + "\n", + "For each dataset, we identify its source plane from its redshift and trace the observed image positions through\n", + "the model. We then select the coordinates at that source plane.\n", + "\n", + "Images identified as the same source feature should map to a common location within the accuracy allowed by the\n", + "data and model. Differences between their back-traced positions reveal where the proposed mass distribution\n", + "does not bring them into agreement.\n", + "\n", + "This calculation displays the traced coordinates. It does not reproduce the full likelihood weighting or\n", + "independently calculate the solved source position." ] }, { @@ -916,14 +1014,15 @@ "source": [ "__Results: Magnifications__\n", "\n", - "The magnification of each multiple image tells us how much the cluster brightens the source at that position \u2014\n", - "the \"natural telescope\" number. It is computed from the local distortion of the multi-plane deflection field\n", - "(its Hessian) at each observed position, via the `LensCalc` object. `plane_j` selects the source's plane, so\n", - "each source's magnifications are evaluated through its own multi-plane chain.\n", + "We calculate the magnification at each observed image position using the fitted tracer.\n", "\n", - "At cluster scale, images near the critical curves can reach magnifications of tens to hundreds \u2014 this is\n", - "precisely the quantity you would quote when using the cluster to study an intrinsically faint background\n", - "galaxy, since the source's true luminosity is the observed luminosity divided by the magnification." + "`plane_j` selects the relevant source plane, ensuring that each calculation uses the geometry appropriate to that source\u2019s redshift.\n", + "\n", + "Magnification describes the local change in image area and, because lensing preserves surface brightness, the corresponding amplification of a sufficiently small source element. The code prints its absolute value; the sign also carries information about image parity.\n", + "\n", + "For an extended arc, the magnification can vary substantially across the image. The value at one position is therefore not necessarily the appropriate correction for the arc\u2019s total flux.\n", + "\n", + "Near critical curves, magnifications can be large and sensitive to the mass model and source position. To infer an intrinsic luminosity, use a magnification appropriate to the measured emission and propagate the lens-model uncertainty." ] }, { @@ -951,11 +1050,17 @@ "source": [ "__Results: Image-Plane Validation__\n", "\n", - "The solved source-plane likelihood never solves the lens equation forwards, so it cannot tell us whether the\n", - "best-fit model predicts the *right number* of multiple images \u2014 a model that would produce an extra image, or\n", - "lose an observed one, looks the same to it. The standard final check is therefore to forward-solve the\n", - "best-fit model with the `PointSolver` and compare the predicted image positions to the observed ones,\n", - "per source." + "Our source-plane likelihood compares the back-traced positions of the observed images. It does not explicitly search for every image predicted by the model.\n", + "\n", + "We therefore return to the familiar `PointSolver`. For each source, we use its solved source position and redshift to predict the image-plane positions, then compare them with the observations.\n", + "\n", + "Inspect both their positions and their number. Significant mismatches can reveal limitations that were not apparent from the source-plane residuals alone.\n", + "\n", + "The comparison also depends on the solver\u2019s search region, numerical resolution and magnification threshold. An apparently missing predicted image may lie outside the searched region or have been filtered out.\n", + "\n", + "Conversely, an additional predicted image is not automatically ruled out by its absence from the catalogue: it may be too faint, blended with a galaxy or outside the observations. Assess its expected detectability before interpreting it as a failure of the mass model.\n", + "\n", + "This is a diagnostic of the fitted realization. Important conclusions should also be checked across the posterior and, where appropriate, with an image-plane likelihood." ] }, { @@ -993,10 +1098,17 @@ "source": [ "__Results: Samples and Errors__\n", "\n", - "Everything above used the maximum likelihood model, but the `Samples` object gives the full posterior \u2014 the\n", - "same API as chapter 2, unchanged by the cluster's complexity. Of particular scientific interest here are the\n", - "inferred halo mass and the scaling-relation normalization `sigma_ref` (whose truth value in the simulator was\n", - "85 km/s): the marginalised errors on these are what a cluster paper reports." + "The calculations above used one fitted realization. The posterior samples describe the range of model parameters supported by the data under our chosen priors and assumptions.\n", + "\n", + "We use the same `Samples` interface introduced in Chapter 2 to inspect marginal medians, credible intervals and correlations.\n", + "\n", + "Of particular interest are the host halo mass, the main galaxies\u2019 mass-profile parameters and the shared member normalization. Examine their joint distributions: a narrow interval for one parameter does not describe all freedom in the cluster\u2019s mass decomposition.\n", + "\n", + "The model returned by `median_pdf()` contains the marginal median of each parameter. It is a useful summary, but need not be a single sampled realization or the best-fitting combination.\n", + "\n", + "The intervals below describe posterior uncertainty within this model. They do not automatically include uncertainties associated with fixed redshifts, member luminosities, the mass\u2013concentration relation or omitted mass structure.\n", + "\n", + "The corner plot helps reveal these parameter correlations and whether the sampled distributions approach their prior boundaries." ] }, { @@ -1031,55 +1143,33 @@ "source": [ "__Customization__\n", "\n", - "This tutorial used the default point-source setup throughout: `Point` / `PointSolved` source components, the\n", - "solved source-plane likelihood, and default `PointSolver` settings. Point-source modeling has a rich set of\n", - "options beyond these \u2014 image-plane likelihoods and their pairing schemes, free source centres, fitting the\n", - "fluxes of the multiple images, fitting time delays (the observable behind lensed-quasar cosmology) \u2014 and a\n", - "dedicated workspace guide covers them extensively:\n", - "\n", - " - `autolens_workspace/scripts/point_source`: the galaxy-scale point-source examples (lensed quasars and\n", - " supernovae), including the `fit.py` guide to every fit variant and the `features` folder (fluxes, time\n", - " delays, multiple sources).\n", - " - `autolens_workspace/scripts/guides/point_solver/pairing.py`: the full matrix of position-fitting schemes\n", - " and when to use each.\n", - " - `autolens_workspace/scripts/cluster`: the cluster-scale workflow this tutorial is built on, including a\n", - " fit to real Hubble Space Telescope data of the cluster Abell 2744 with 188 catalogue members and 7\n", - " sources, the CSV-schema guide (`csv_api.py`) and a step-by-step walkthrough of the point-source\n", - " likelihood (`likelihood_function.py`).\n", + "This tutorial used solved source positions and a source-plane position likelihood. Other analyses may require image-plane likelihoods, independently sampled source positions, flux measurements or time delays.\n", "\n", - "__Wrap Up__\n", + "The workspace provides examples and step-by-step guides:\n", "\n", - "This tutorial reached the top of the strong-lensing mass ladder. Lets recap what we learnt:\n", + "- `autolens_workspace/scripts/point_source`: point-source modeling, including the familiar quasar examples and additional observables.\n", + "- `autolens_workspace/scripts/guides/point_solver/pairing.py`: image-position pairing schemes and their use.\n", + "- `autolens_workspace/scripts/cluster`: cluster workflows, CSV inputs and a walkthrough of the cluster point-source likelihood.\n", "\n", - "- **Clusters**: 30+ to hundreds of lens galaxies inside a dark matter halo of more than 10^14 solar masses,\n", - " lensing many background sources at once. Their science is extreme magnification \u2014 using the cluster as a\n", - " natural telescope onto the faint early Universe \u2014 and mapping the cluster's dark matter distribution.\n", + "Use these guides when adapting the tutorial to a different dataset or likelihood.\n", "\n", - "- **Multi-plane ray tracing**: cluster sources sit at different redshifts, so the lens equation is applied\n", - " recursively through the planes, with each plane's deflections scaled by cosmological distance ratios. The\n", - " `Tracer` handles this automatically, provided every source's redshift is set correctly.\n", + "__Wrap Up__\n", "\n", - "- **Point-source modeling**: fitting the extended light of every source is computationally prohibitive at\n", - " this scale, so the standard workflow fits the positions of each source's multiple images, reducing the\n", - " likelihood to source-plane geometry that evaluates in milliseconds.\n", + "In this tutorial, we learned:\n", "\n", - "- **The CSV interface**: the data (`point_datasets.csv`), the individually-modelled galaxies (`mass.csv` /\n", - " `point.csv`) and the member catalogue (`scaling_galaxies.csv`) are all spreadsheet-editable files. Scaling\n", - " the model to a richer cluster is a row-append, not a code change.\n", + "- Cluster lenses combine a shared dark matter halo with many individual galaxies and can multiply image sources at several redshifts.\n", + "- Multiple source planes require the appropriate redshift-dependent geometry. Multiple **deflecting** planes arise when significant mass lies at different redshifts.\n", + "- Position fitting uses matched image features to constrain the mass model without reconstructing every arc\u2019s full surface brightness.\n", + "- CSV catalogues organize the data and model components; fixed quantities and shared relations determine how many parameters remain free.\n", + "- Our restricted example has six non-linear parameters. That compactness comes from its assumptions, rather than implying that cluster mass distributions are intrinsically simple.\n", + "- A joint fit combines the source datasets while allowing us to inspect each system\u2019s contribution separately.\n", + "- Interpreting the result requires both posterior uncertainties and checks of the predicted image configuration. Derived member masses and magnifications inherit the model\u2019s assumptions.\n", "\n", - "- **Six parameters, fifteen galaxies**: fixed observed centres, a scaling relation for the member population\n", - " and solved source centres decouple the model's physical richness from the dimensionality of the search.\n", + "Strong lensing has now taken us from individual galaxies to groups and clusters.\n", "\n", - "- **Results access**: per-member realised profiles, the multi-plane tracer, solved source-plane centres,\n", - " per-image magnifications and forward-solved image positions \u2014 the complete toolkit for interpreting a\n", - " cluster fit.\n", + "Beyond the central region producing multiple images, the same mass distribution continues to distort background galaxies. Those distortions are often too small to identify reliably in an individual galaxy because its unlensed shape is unknown.\n", "\n", - "Strong lensing \u2014 multiple images, arcs, Einstein rings \u2014 has carried us from single galaxies to the most\n", - "massive structures in the Universe. But a cluster's gravity does not stop deflecting light at the radius\n", - "where multiple images form. Far beyond it, every background galaxy is still subtly sheared \u2014 distorted by a\n", - "percent or less \u2014 and by measuring those distortions statistically across thousands of galaxies, the\n", - "cluster's mass can be mapped out to its edges. That is **weak lensing**, a different regime with different\n", - "data and different statistics, and it is where the next tutorial takes us." + "By measuring the coherent distortions across a population of background galaxies, we can constrain mass over a much wider region. This is **weak lensing**, the subject of the final tutorial in this chapter." ] } ], @@ -1115,4 +1205,4 @@ }, "nbformat": 4, "nbformat_minor": 4 -} \ No newline at end of file +} diff --git a/notebooks/chapter_4_scaling_up_lensing/tutorial_6_weak_lensing.ipynb b/notebooks/chapter_4_scaling_up_lensing/tutorial_6_weak_lensing.ipynb index ceafb7e..62e4a83 100644 --- a/notebooks/chapter_4_scaling_up_lensing/tutorial_6_weak_lensing.ipynb +++ b/notebooks/chapter_4_scaling_up_lensing/tutorial_6_weak_lensing.ipynb @@ -7,58 +7,36 @@ "Tutorial 6: Weak Lensing\n", "========================\n", "\n", - "Every tutorial in this series so far \u2014 indeed, every fit performed in all four chapters of **HowToLens** \u2014 has been\n", - "a *strong* lensing analysis. Strong lensing occurs when a background galaxy lies so close (in projection) to a\n", - "foreground mass that its light is bent into multiple images, arcs or a complete Einstein ring. These dramatic\n", - "features are what we simulated, fitted and modeled, from the single galaxy-scale lenses of chapters 1 and 2 up to\n", - "the group-scale and cluster-scale systems earlier in this chapter.\n", - "\n", - "Strong lensing is spectacular, but it is also rare and spatially confined. Multiple images only form inside (or very\n", - "near) the Einstein radius, so a strong-lensing analysis constrains the mass distribution only within that region \u2014\n", - "a few arc-seconds for a galaxy, tens of arc-seconds for a cluster core. Outside it, the arcs and multiple images\n", - "simply do not exist, and everything we have built so far has nothing to fit.\n", - "\n", - "Yet the gravity of the foreground mass does not stop at the Einstein radius. *Every* background galaxy, however far\n", - "from the lens centre, has its shape slightly distorted \u2014 sheared \u2014 by the foreground mass it sits behind. This is\n", - "**weak lensing**: a percent-level stretching of each background galaxy's observed ellipticity, tangentially aligned\n", - "around the foreground mass.\n", - "\n", - "The catch is that we cannot see this distortion in any single galaxy. Galaxies are not intrinsically round: a\n", - "typical galaxy has a random unlensed ellipticity of ~0.25 per component, whereas the weak-lensing shear it receives\n", - "is ~0.01-0.1. The signal is buried an order of magnitude below the intrinsic \"shape noise\" of any one object.\n", - "\n", - "The solution is statistical. The intrinsic ellipticities of different galaxies are randomly oriented and average to\n", - "zero, whereas the lensing shear is coherent \u2014 every galaxy near a given point on the sky is sheared the same way.\n", - "Average the measured shapes of many background galaxies and the random part cancels while the lensing part remains.\n", - "This is the fundamental contrast with everything the series has done so far: strong lensing extracts an exquisite\n", - "signal from a single special system, weak lensing extracts a faint signal from the ensemble of many ordinary ones.\n", - "\n", - "This changes what the data even *is*. There is no image to fit, no PSF to convolve, no mask, no pixelized source\n", - "reconstruction. A weak-lensing dataset is a **shear catalogue**: a table of background-galaxy sky positions, each\n", - "with a measured shear estimate (two ellipticity components) and a per-galaxy uncertainty. Fitting one means\n", - "comparing a mass model's predicted shear field, evaluated at those positions, against the measured values.\n", - "\n", - "In this tutorial we simulate a weak-lensing shear catalogue around a cluster-scale lens (entirely in memory \u2014 no\n", - "files are written), visualize its shear field, fit it with a mass model whose parameters we know, and then infer\n", - "those parameters with a non-linear search. You will recognise every step: the `Tracer`, `Fit`, `Analysis` and\n", - "search workflow of the whole series, applied to a completely different kind of data.\n", + "Our modeling tutorials have concentrated on **strong lensing**: the multiple images, arcs and Einstein rings produced by galaxy, group and cluster lenses.\n", + "\n", + "In the previous tutorial, we used the positions of multiply imaged sources to constrain a cluster\u2019s mass distribution. Those images provide particularly valuable information in the central region where they form. To measure the mass distribution over a much wider region, we can also use **weak lensing**.\n", + "\n", + "The same gravitational field distorts the shapes of background galaxies beyond the region containing prominent arcs. These distortions are usually difficult to distinguish from a galaxy\u2019s unknown intrinsic shape: an elongated galaxy might have been elongated even without lensing.\n", + "\n", + "The signal becomes measurable statistically. Nearby background galaxies experience a coherent lensing distortion, while their intrinsic orientations contribute scatter. Measuring many galaxies allows us to estimate that coherent signal.\n", + "\n", + "This scatter is called **shape noise**. Increasing the number of usable background galaxies reduces its contribution to the uncertainty, although observational biases and correlations between intrinsic galaxy shapes also require attention in real analyses.\n", + "\n", + "You first encountered a weak-lensing dataset in Chapter 1. Here we return to its **shear catalogue**: background-galaxy positions, two components describing the estimated distortion, and their uncertainties.\n", + "\n", + "We simulate a catalogue around a cluster-scale lens, visualize it, inspect a fit using the input mass model, and then infer the model parameters with a non-linear search. The familiar `Tracer`, `Fit`, `Analysis` and search workflow remains central.\n", "\n", "This tutorial closes both this chapter and the four core chapters of **HowToLens**.\n", "\n", "__Contents__\n", "\n", - "- **Shear Catalogues:** What a weak-lensing dataset is and where the catalogue comes from in a real analysis.\n", - "- **Mass Scales:** Why weak lensing is a cluster-scale tool, tying to the mass scales of the previous tutorials.\n", - "- **Ray Tracing:** Build a `Tracer` for a cluster-scale lens, the mass whose shear field we will measure.\n", - "- **Source Galaxy Positions:** Draw background galaxies in an annulus outside the strong-lensing core.\n", - "- **Simulate:** Create a `WeakDataset` in memory with `SimulatorShearYX`, adding realistic shape noise.\n", - "- **Visualize:** Plot the shear field as a whisker map and the dataset's 2x2 summary mosaic.\n", - "- **Mass Map:** Invert the shear catalogue into a model-independent convergence map (Kaiser-Squires).\n", - "- **Fitting:** Fit the catalogue with the true mass model via `FitWeak` and inspect its goodness-of-fit.\n", - "- **Model Fit:** Infer the mass model from the shear catalogue alone with `AnalysisWeak` and a non-linear search.\n", - "- **Result:** The inferred model, the fit mosaic and the tangential shear profile.\n", - "- **Joint Strong and Weak Lensing:** How PyAutoLens expects weak lensing to be used \u2014 combined with strong lensing.\n", - "- **Wrap Up:** The end of the chapter, and of the core HowToLens lectures." + "- **Shear Catalogues:** The measurements used in a weak-lensing analysis.\n", + "- **Mass Scales:** Weak lensing around galaxies, groups and clusters.\n", + "- **Ray Tracing:** Build a simple cluster-scale mass model.\n", + "- **Source Galaxy Positions:** Sample background galaxies across the observed field.\n", + "- **Simulate:** Generate a shear catalogue with shape noise.\n", + "- **Visualize:** Inspect the shear field and dataset summary.\n", + "- **Mass Map:** Reconstruct a convergence map from the catalogue.\n", + "- **Fitting:** Inspect the likelihood and residuals for a specified mass model.\n", + "- **Model Fit:** Infer mass-model parameters with a non-linear search.\n", + "- **Result:** Inspect the inferred model and tangential shear profile.\n", + "- **Joint Strong and Weak Lensing:** Combine constraints across different radii.\n", + "- **Wrap Up:** Complete the core HowToLens lectures." ] }, { @@ -124,61 +102,51 @@ "source": [ "__Shear Catalogues__\n", "\n", - "Before we simulate anything, lets be clear about what a real weak-lensing dataset looks like, because it is unlike\n", - "any data this series has fitted before.\n", + "A shear catalogue contains one row per background galaxy, including:\n", + "\n", + "- Its observed sky position, expressed here as `(y, x)` offsets in arc-seconds.\n", + "- Two components describing its estimated lensing distortion.\n", + "- An uncertainty that accounts for intrinsic shape dispersion and measurement noise.\n", + "\n", + "Real catalogues also require information about source redshifts, selection and calibration. The lensing signal depends on the geometry between the observer, lens and source, just as it did for the multiple source redshifts in the cluster tutorial.\n", + "\n", + "Producing these measurements begins with telescope images. Galaxies must be detected and selected, and their shapes measured while accounting for the PSF, noise and instrumental effects. The PSF can both blur galaxy shapes and introduce coherent distortions that could be mistaken for lensing.\n", "\n", - "A **shear catalogue** is a table with one row per background galaxy, containing:\n", + "We start after this shape-measurement stage. The dataset supplied to this tutorial contains catalogue measurements rather than image pixels, so our likelihood does not convolve a model image with a PSF. This does not make observational systematics disappear: their calibration and uncertainty remain part of a real weak-lensing analysis.\n", "\n", - " - The galaxy's sky position (for us, (y, x) arc-second offsets from a chosen centre).\n", - " - A measured shear estimate (gamma_1, gamma_2) \u2014 in practice the galaxy's measured ellipticity components, which\n", - " estimate the lensing shear because the intrinsic shape averages to zero over many galaxies.\n", - " - A per-galaxy uncertainty, combining the intrinsic shape dispersion (~0.25 per component) with the measurement\n", - " error, added in quadrature.\n", + "There is also an important distinction between **shear** and **reduced shear**. Galaxy-shape measurements generally estimate the reduced shear:\n", "\n", - "Producing this catalogue from raw telescope images is a substantial data-reduction task in its own right: galaxies\n", - "must be detected, stars separated from galaxies, the PSF measured and its blurring of galaxy shapes corrected\n", - "(the PSF makes every galaxy look rounder, diluting the shear signal), and calibration biases characterised.\n", - "Dedicated shape-measurement pipelines exist for exactly this job, and entire survey collaborations are built\n", - "around getting it right.\n", + "\\[\n", + "g = \\frac{\\gamma}{1-\\kappa}.\n", + "\\]\n", "\n", - "**All of that is outside PyAutoLens's scope.** PyAutoLens assumes the shear catalogue has already been produced\n", - "upstream by such a pipeline, and starts where the catalogue ends: fitting mass models to the measured shears. This\n", - "division of labour is why the weak-lensing API is so lean \u2014 no PSF, no mask, no image \u2014 the hard observational\n", - "systematics were dealt with before the data reached us.\n", + "When the convergence is sufficiently small, reduced shear is approximately equal to shear. This tutorial uses an idealized catalogue of shear measurements generated directly from the model. When working with observed catalogues, check which quantity the measurements estimate and ensure that the model predicts the same quantity.\n", "\n", "__Mass Scales__\n", "\n", - "This chapter has climbed a ladder of mass scales, and weak lensing is its top rung. The strength of the statistical\n", - "shear signal around a lens scales with its mass, so whether weak lensing is even measurable depends on where on the\n", - "ladder we stand:\n", + "Weak lensing is useful across the mass scales explored in this chapter.\n", "\n", - " - **A single galaxy** (Einstein radius ~1-2\", the lenses of chapters 1-3): the shear imprinted on background\n", - " galaxies beyond the Einstein radius is far too weak to detect around any one system \u2014 there are too few\n", - " background galaxies carrying too little shear. (Surveys recover it only by *stacking* thousands of lens\n", - " galaxies, a technique called galaxy-galaxy lensing that averages over the lens population.)\n", + "For individual galaxy lenses, the available background galaxies usually provide too little information for a precise halo measurement. **Galaxy\u2013galaxy lensing** therefore commonly combines measurements around many foreground galaxies to constrain the average mass distribution of a population.\n", "\n", - " - **A group** (Einstein radius ~4-10\", the scale of the group tutorial earlier in this chapter): the signal is\n", - " marginal \u2014 detectable for well-observed individual groups, but noisy.\n", + "Groups produce larger signals, but the precision obtainable for an individual system depends on its mass, redshift and the depth and quality of the observations. Combining groups can also improve the measurement.\n", "\n", - " - **A cluster** (Einstein radius ~10-30\"+, the previous tutorial's scale): the signal is strong enough to measure\n", - " around a *single* system. Hundreds to thousands of background galaxies within a few arc-minutes each carry a\n", - " |gamma| ~ 0.01-0.2 shear, and their average traces the cluster's mass out to radii of arc-minutes \u2014 ten or more\n", - " times further out than the strong-lensing core.\n", + "Massive clusters can produce measurable coherent distortions across hundreds or thousands of background galaxies. These measurements extend well beyond the central arcs and help constrain the cluster\u2019s extended dark matter halo.\n", "\n", - "This reach is the scientific point. The dark matter halo of a cluster extends to Mpc scales, far beyond where arcs\n", - "form. Weak lensing is the only lensing probe of that outer halo, which is why it is the tool of choice for cluster\n", - "mass measurements, and it is why this tutorial simulates a cluster-scale lens.\n", + "There is no sharp Einstein-radius boundary separating these applications. Detectability depends on the lensing geometry, the radii sampled, the number of usable sources and their shape uncertainties.\n", + "\n", + "We use a cluster-scale lens here because it provides a useful demonstration of an individual-system weak-lensing analysis.\n", "\n", "__Ray Tracing__\n", "\n", - "We begin exactly as the series always has: with a `Tracer`. The lens is a cluster-scale `Isothermal` mass profile\n", - "with an Einstein radius of 25.0\" \u2014 the same order as the previous tutorial's cluster, and a mass for which the\n", - "weak shear signal is genuinely measurable. The source galaxy carries no light profile: weak lensing measures the\n", - "lens's shear field at the background galaxies' positions, so their appearance is irrelevant \u2014 they are pure probes,\n", - "included only to give the `Tracer` its source-plane redshift.\n", + "We begin with a `Tracer`, using an elliptical `Isothermal` mass profile with an Einstein radius of 25.0 arc-seconds.\n", + "\n", + "This is a deliberately simple cluster-scale mass distribution. Real cluster analyses often use NFW dark matter halos and additional mass components, as discussed in the previous tutorial.\n", + "\n", + "The lens has no light profile because this fit uses catalogue measurements rather than an image of the lens.\n", "\n", - "Note also what the lens galaxy lacks: no light profile. A shear catalogue contains no image of the lens, so there\n", - "is no lens light to model \u2014 another simplification compared to every imaging fit in this series." + "The source galaxy also has no light profile. It supplies the source-plane redshift needed to calculate the lensing geometry; it does not represent the detailed appearance of an individual background galaxy.\n", + "\n", + "For simplicity, all background galaxies in this simulation lie at redshift 1.0, behind a lens at redshift 0.5." ] }, { @@ -207,18 +175,17 @@ "source": [ "__Source Galaxy Positions__\n", "\n", - "Real weak-lensing measurements avoid the strong-lensing core: inside it the shear is no longer weak (the linear\n", - "shear approximation breaks down), and cluster-member galaxies contaminate the background sample. We therefore draw\n", - "our background galaxies in an **annulus**, from an inner radius of 50\" (twice the Einstein radius, safely into the\n", - "weak regime) to an outer radius of 200\" (over 3 arc-minutes), distributed uniformly in area.\n", + "We draw 1500 observed background-galaxy positions in an annulus extending from 50 to 200 arc-seconds from the lens centre, distributed uniformly in area.\n", + "\n", + "This excludes the central region containing the strongest lensing features. In real observations, the usable region also depends on blending, cluster-member contamination and the reliability of the shape measurements.\n", "\n", - "At 50\" from this lens the shear is |gamma| ~ 0.25, and by 200\" it has fallen to |gamma| ~ 0.06 \u2014 every galaxy is a\n", - "weak probe whose individual distortion is at or below the shape noise. With 1500 galaxies (a deep-survey source\n", - "density of ~45 per square arc-minute) the *ensemble* nonetheless carries a decisive signal, exactly as in a real\n", - "cluster analysis.\n", + "The annulus covers approximately 33 square arc-minutes, giving a source density of about 46 galaxies per square arc-minute. This represents a deep illustrative catalogue; the usable density in an observation depends on its depth, resolution and selection criteria.\n", "\n", - "The positions are stored as an `al.Grid2DIrregular` of (y, x) coordinates \u2014 the same irregular-grid structure the\n", - "point-source tutorials used, because a catalogue of sky positions is not a uniform pixel grid." + "For comparison, a spherical isothermal lens with an Einstein radius of 25 arc-seconds has shear and convergence of 0.25 at 50 arc-seconds, falling to about 0.06 at 200 arc-seconds. Our elliptical model varies with position angle as well.\n", + "\n", + "The inner boundary is therefore outside the Einstein radius, but it does not guarantee that reduced shear is approximately equal to shear. For the spherical example, the reduced shear at 50 arc-seconds is about 0.33. Remember that our simulation generates shear directly rather than simulating observed galaxy ellipticities.\n", + "\n", + "The positions are stored in an `al.Grid2DIrregular`, using the same `(y, x)` coordinate convention as the point-source tutorials. These are observed image-plane positions at which we evaluate the lensing field, not reconstructed source-plane coordinates." ] }, { @@ -228,7 +195,7 @@ "rng = np.random.default_rng(1)\n", "\n", "n_galaxies = 1500\n", - "radius_inner = 50.0 # arc-seconds \u2014 inside this we are in the strong-lensing core.\n", + "radius_inner = 50.0 # arc-seconds \u2014 excludes the central region of the simulated lens.\n", "radius_outer = 200.0 # arc-seconds \u2014 the edge of our simulated weak-lensing field.\n", "\n", "radii = np.sqrt(rng.uniform(radius_inner**2.0, radius_outer**2.0, n_galaxies))\n", @@ -247,19 +214,15 @@ "source": [ "__Simulate__\n", "\n", - "The `SimulatorShearYX` object simulates a weak-lensing shear catalogue from a tracer: its `via_tracer_from` method\n", - "evaluates the tracer's shear field at every galaxy position (by differentiating the deflection-angle field) and\n", - "adds Gaussian shape noise to each measurement.\n", + "`SimulatorShearYX` evaluates the tracer\u2019s shear field at each catalogue position and adds independent Gaussian noise to its two components.\n", + "\n", + "We use `noise_sigma=0.25` per component as an illustrative shape-noise dispersion. The intrinsic shapes of real galaxies produce substantial scatter, and measurement errors add further uncertainty.\n", + "\n", + "This is a simplified statistical simulation. We do not generate images of individual background galaxies or run a shape-measurement pipeline. Instead, we directly generate noisy estimates of the shear field that our likelihood will fit.\n", "\n", - "A `noise_sigma` of 0.25 per shear component is the standard intrinsic shape dispersion of real galaxies \u2014 this is\n", - "the dominant noise source in weak lensing, and it is what makes the per-galaxy signal invisible: the noise on each\n", - "measurement is several times larger than the shear it contains.\n", + "The simulator\u2019s default configuration generates shear rather than reduced shear, matching the idealization described above.\n", "\n", - "Unlike every previous tutorial, we do not write this dataset to disk and reload it. The whole catalogue is a few\n", - "thousand numbers, so we keep it in memory and use it directly \u2014 which also mirrors how you might resimulate\n", - "catalogues on the fly when testing survey sensitivities. (This repo's `scripts/simulator/weak_lensing.py` \u2014 the\n", - "script chapter 1's data tutorial auto-ran to give you your first glimpse of a shear catalogue \u2014 shows the\n", - "disk-based version, with the same JSON output pattern as the imaging simulators.)" + "We keep the catalogue in memory and pass it directly to the fitting tools. The script `scripts/simulator/weak_lensing.py`, used for the weak-lensing example in Chapter 1, demonstrates saving a catalogue to disk." ] }, { @@ -287,16 +250,15 @@ "source": [ "__Visualize__\n", "\n", - "Weak-lensing data has its own visual language. The shear field is drawn as a **whisker map**: at each galaxy\n", - "position, a line segment whose length is the shear magnitude |gamma| and whose orientation is the shear's position\n", - "angle. The segments are deliberately *headless* (no arrowheads), because shear is a spin-2 quantity \u2014 rotating a\n", - "shear by 180 degrees maps it back onto itself, so a whisker has an orientation but no direction, and an arrowhead\n", - "would suggest information the data does not contain.\n", + "We display the catalogue as a **whisker map**. Each galaxy position has a line segment whose length represents the magnitude of its measured shear estimate and whose orientation represents the corresponding position angle.\n", "\n", - "Around a massive lens, the whiskers align *tangentially* \u2014 each traces a small piece of a circle around the lens\n", - "centre, the statistical echo of the rings and arcs of strong lensing. Squint at the plot below and you can see it,\n", - "though the shape noise makes it far from obvious galaxy-by-galaxy: this is what a signal an order of magnitude\n", - "below the per-object noise looks like." + "The segments have no arrowheads. A shear orientation is unchanged by a rotation of 180 degrees, so a line represents it more appropriately than a directed arrow.\n", + "\n", + "Around a centrally concentrated lens, the coherent pattern is predominantly tangential: the whiskers tend to follow circles around the lens centre. Ellipticity and additional mass structure can modify that pattern.\n", + "\n", + "Shape noise introduces substantial scatter in both the lengths and orientations of the plotted whiskers. Individual measurements need not align with the underlying field, even when the ensemble constrains it well.\n", + "\n", + "The plot provides an initial view of the measurements. Later, we will compare them with a model and summarize their tangential component in radial bins." ] }, { @@ -312,8 +274,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "`aplt.subplot_weak_dataset` summarises the full dataset as a 2x2 mosaic: the whisker map, the per-galaxy noise-map,\n", - "the shear magnitude |gamma| and the position angle phi at every galaxy." + "`aplt.subplot_weak_dataset` summarizes the catalogue in four panels: the shear whiskers, the per-galaxy uncertainties, the measured shear magnitudes and their position angles.\n", + "\n", + "Our simulation assigns the same uncertainty to every galaxy. Real catalogues generally have varying uncertainties because galaxies differ in brightness, size and the quality of their shape measurements.\n", + "\n", + "The magnitude and position-angle panels describe the noisy measurements. They should not be interpreted as direct maps of the underlying lensing field." ] }, { @@ -331,18 +296,19 @@ "source": [ "__Mass Map__\n", "\n", - "A remarkable property of weak lensing is that the shear catalogue can be inverted directly into a map of the\n", - "convergence `kappa` \u2014 the dimensionless projected mass density we have used throughout the series \u2014 *without\n", - "assuming any mass model at all*. In Fourier space, shear and convergence are related algebraically, so two FFTs\n", - "turn the catalogue into a \"dark matter map\". This is the Kaiser-Squires technique, and it produced some of the most\n", - "famous images in cosmology, such as the mass map of the Bullet Cluster showing dark matter offset from the\n", - "colliding gas.\n", - "\n", - "`aplt.plot_convergence_map` bins the catalogue onto a regular grid, applies a small Gaussian smoothing (per-cell\n", - "shears are shape-noise dominated) and plots the reconstruction. For our simulated cluster it peaks at the lens\n", - "centre at (0.0\", 0.0\"). Two caveats: the map's mean is unconstrained (the mass-sheet degeneracy, which chapter 3\n", - "met in its strong-lensing form) and FFT periodicity produces edge artefacts \u2014 for quantitative masses we fit a\n", - "mass model, which is what the rest of this tutorial does." + "The shear field contains information about the convergence `kappa`, the dimensionless projected mass density introduced earlier in the series.\n", + "\n", + "The **Kaiser\u2013Squires** method uses the relationship between shear and convergence in Fourier space to reconstruct a convergence map without choosing a parametric mass profile such as an Isothermal or NFW.\n", + "\n", + "`aplt.plot_convergence_map` bins the catalogue onto a regular grid, smooths the binned shear field and performs this reconstruction.\n", + "\n", + "The resulting map provides a useful view of the projected mass structure. It traces the total lensing mass, including both dark matter and baryons; identifying a feature specifically with dark matter requires additional information.\n", + "\n", + "Avoid interpreting every peak as a real mass concentration. Shape noise, smoothing, the finite field and gaps in the catalogue all affect the reconstruction. Our catalogue has no measurements inside its central hole, so the displayed map there is not a direct local measurement.\n", + "\n", + "Shear also leaves an additive constant in the reconstructed convergence unconstrained. This is related to the mass-sheet degeneracy discussed in Chapter 3.\n", + "\n", + "Use this map as an exploratory diagnostic. Quantitative measurements require uncertainty estimates and careful treatment of the survey geometry. Here, we proceed by fitting a parametric mass model directly to the catalogue." ] }, { @@ -364,21 +330,21 @@ "source": [ "__Fitting__\n", "\n", - "We now fit the catalogue, following the same pattern as every fit in this series: build a model `Tracer`, pass it\n", - "with the dataset to a `Fit` object, and inspect residuals and the log likelihood. For weak lensing the fit object\n", - "is `FitWeak`, and because we simulated the data ourselves we can hand it the *true* tracer and see what a perfect\n", - "model looks like.\n", - "\n", - "`FitWeak` evaluates the model tracer's shear field at the dataset's galaxy positions and compares it with the\n", - "measured shears, assuming each component is independently Gaussian-distributed around the model with the\n", - "per-galaxy noise. Each galaxy contributes **two** independent data points (gamma_1 and gamma_2), so the number of\n", - "degrees of freedom is 2 * n_galaxies, and for a good fit whose residuals are pure shape noise the chi-squared\n", - "should be close to that number.\n", - "\n", - "Compare this to the imaging fits of chapter 1: there, the fit convolved a model image with the PSF and compared\n", - "tens of thousands of pixels; here there is no convolution, no mask and only a few thousand numbers. A weak-lensing\n", - "likelihood is orders of magnitude cheaper \u2014 which is precisely why it is so inexpensive to add to a strong-lensing\n", - "analysis, as discussed at the end of this tutorial." + "We now follow the fitting workflow introduced in Chapter 1: specify a model `Tracer`, combine it with the dataset in a fit object, and inspect the residuals and log likelihood.\n", + "\n", + "For this dataset, the fit object is `FitWeak`. It evaluates the predicted shear at each observed galaxy position and compares its two components with the catalogue measurements.\n", + "\n", + "Our likelihood assumes independent Gaussian errors for the two components, using the supplied uncertainties. This matches the way we generated this simulated catalogue.\n", + "\n", + "We first supply the input tracer used by the simulator. Its predictions describe the underlying shear field, while the residuals contain the Gaussian noise added during simulation.\n", + "\n", + "There are two measured components per galaxy, giving 3000 scalar measurements. At this fixed input model, the expected chi-squared is therefore 3000, with statistical fluctuations between noise realizations.\n", + "\n", + "This count should not be confused with the residual degrees of freedom after estimating parameters from the same data. We will shortly allow the mass parameters to vary in a non-linear search.\n", + "\n", + "Unlike an imaging likelihood, this calculation does not generate and convolve a model image or reconstruct source surface brightness. Its main task is evaluating the lensing field at the catalogue positions and calculating the likelihood.\n", + "\n", + "The computational cost depends on the catalogue size, mass model and implementation, but this makes catalogue fitting a useful complement to the imaging and point-source analyses explored earlier." ] }, { @@ -391,7 +357,7 @@ "print(\"Fit Summary (true model)\")\n", "print(\"------------------------\")\n", "print(f\"n_galaxies : {dataset.n_galaxies}\")\n", - "print(f\"degrees_of_freedom: {2 * dataset.n_galaxies}\")\n", + "print(f\"n_data_components: {2 * dataset.n_galaxies}\")\n", "print(f\"chi_squared : {fit.chi_squared:.3f}\")\n", "print(f\"log_likelihood : {fit.log_likelihood:.3f}\")" ], @@ -402,8 +368,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "As always, an incorrect mass model produces a worse fit. Halving the Einstein radius halves the predicted shear\n", - "everywhere, leaving coherent tangential residuals across the field, and the log likelihood drops accordingly." + "We next halve the model\u2019s Einstein radius while keeping its centre and ellipticity fixed.\n", + "\n", + "For this Isothermal profile, that change halves the predicted shear at every catalogue position. The model therefore underpredicts the coherent signal present in the simulated data.\n", + "\n", + "Compare the two printed log likelihoods. This deliberately large change illustrates how the catalogue distinguishes different mass normalizations, even though individual galaxy measurements are noisy.\n", + "\n", + "The likelihood combines information from the whole catalogue: the preference does not require every individual measurement to lie closer to the input model." ] }, { @@ -437,10 +408,15 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "`aplt.subplot_fit_weak` visualises a weak-lensing fit as a 2x2 mosaic: the observed shear field, the model shear\n", - "field, the two overlaid on one axes (data in black, model in red), and the per-galaxy chi-squared map. For the true\n", - "model the overlay's residuals are short and randomly oriented \u2014 the shape-noise floor \u2014 and the chi-squared map is\n", - "spatially uniform." + "`aplt.subplot_fit_weak` displays the observed shear field, the model field, an overlay of the two and the per-galaxy chi-squared contributions.\n", + "\n", + "The input model produces a smooth, coherent pattern. The observed whiskers scatter around that pattern because of shape noise, so a good fit does not require close agreement for every galaxy.\n", + "\n", + "Likewise, the chi-squared map need not look uniform. Individual galaxies can have large contributions simply because their noise realizations are large.\n", + "\n", + "Look for coherent discrepancies across the field, alongside the overall likelihood and residual statistics. Such patterns can indicate missing mass structure, an inadequate model or problems with the measurements.\n", + "\n", + "For this simulation, the input model and noise assumptions match the data-generation process, providing a reference for interpreting these diagnostics." ] }, { @@ -458,20 +434,23 @@ "source": [ "__Model Fit__\n", "\n", - "In a real analysis we do not know the mass model \u2014 we infer it. The workflow is the one you have used since\n", - "chapter 2: compose a model with `af.Model` and `af.Collection`, choose a non-linear search, create an `Analysis`\n", - "object and fit. For weak lensing the analysis object is `AnalysisWeak`, whose `log_likelihood_function` builds a\n", - "`Tracer` from each sampled parameter set, evaluates its shear field at the catalogue positions and returns the\n", - "Gaussian log likelihood \u2014 the same `FitWeak` machinery we just used by hand.\n", + "We now infer the mass-model parameters using the workflow introduced in Chapter 2: compose a model with `af.Model` and `af.Collection`, choose a non-linear search, create an analysis object and fit.\n", + "\n", + "`AnalysisWeak` builds a `Tracer` from each sampled parameter set and evaluates the catalogue likelihood using the same `FitWeak` calculation we inspected above.\n", + "\n", + "Our Isothermal model has five non-linear parameters:\n", "\n", - "The model is the lens's `Isothermal` mass [5 parameters]; the source galaxy again carries no components. Note the\n", - "tiny parameter space \u2014 no lens light, no source light, no shear-as-nuisance-parameter (the shear field *is* the\n", - "data here) \u2014 compared to the N=20+ models of the imaging tutorials.\n", + "- Two centre coordinates.\n", + "- Two ellipticity components.\n", + "- The Einstein radius.\n", "\n", - "One adjustment is needed, familiar from the group and cluster tutorials: the default priors are tuned for\n", - "galaxy-scale lenses (Einstein radii of 0\"-8\", centres within a fraction of an arc-second). Our cluster's 25\"\n", - "Einstein radius lies entirely outside that prior, so we widen the priors to cluster scales \u2014 always match your\n", - "priors to the mass scale of the system you are fitting." + "The lens and source redshifts remain fixed. Neither galaxy has a light profile, so there are no light-profile parameters or source reconstructions to fit.\n", + "\n", + "Earlier in this chapter, we often fixed individual galaxy centres to their measured centres of light. Here, the mass profile represents the cluster as a whole, and we allow its centre to vary. A cluster\u2019s overall mass centre need not coincide exactly with the light centre of its brightest galaxy.\n", + "\n", + "We assign an Einstein-radius prior spanning 0\u201360 arc-seconds and Gaussian centre priors with a width of 20 arc-seconds around the origin. These are illustrative choices suited to this simulated system.\n", + "\n", + "As in the group and cluster tutorials, check that the priors describe the scale and plausible configurations of the system being analyzed. Inspect the resulting posterior to determine whether the data constrain these parameters within their allowed ranges." ] }, { @@ -498,15 +477,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The same model can also be visualized as a figure, making its structure easier to understand at a glance.\n", + "The model figure summarizes this structure: one lens mass profile with five free parameters and a source galaxy supplying a fixed redshift.\n", "\n", - "The figure shows how the model is organized: which parameters belong to each component, and whether they are free,\n", - "fixed, shared, linked by an expression, solved during the fit, or not configured. `model.info` provides the\n", - "corresponding numerical details, including the prior assigned to each free parameter and the value of each fixed\n", - "parameter.\n", + "Use it alongside `model.info`, which lists the priors and fixed values.\n", "\n", - "In weak lensing the source galaxies are the *data*, a catalogue of measured shapes, so there is no source light\n", - "to fit and the source galaxy in this model carries no light profile at all." + "The single source galaxy in this model does not mean that the catalogue contains only one background galaxy. It supplies the common source-plane redshift assumed for all 1500 catalogue entries.\n", + "\n", + "Their individual observed positions and shear estimates belong to the dataset; we do not introduce a separate light profile or free source position for each entry." ] }, { @@ -522,10 +499,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We fit the model with the nested sampling algorithm Nautilus, as throughout the series. A weak-lensing likelihood\n", - "evaluation takes milliseconds (one shear-field evaluation at 1500 positions plus a chi-squared sum), so this\n", - "5-parameter fit completes in minutes on an ordinary CPU \u2014 a refreshing contrast to the imaging fits of the earlier\n", - "chapters." + "We use Nautilus to sample the posterior, as in the earlier tutorials, and pass the catalogue to `AnalysisWeak`.\n", + "\n", + "Each likelihood evaluation predicts the shear field at the 1500 galaxy positions and compares it with the measurements. There is no image convolution or source reconstruction in this calculation.\n", + "\n", + "This is a compact five-parameter example, but its runtime still depends on the implementation, hardware and number of likelihood evaluations required by the search.\n", + "\n", + "Use the search outputs to monitor progress and assess convergence before interpreting the inferred parameters. The familiar output directory contains the model information, samples and fit diagnostics." ] }, { @@ -543,14 +523,15 @@ "analysis = al.AnalysisWeak(dataset=dataset)\n", "\n", "print(\n", - " \"The non-linear search has begun running - checkout the output/howtolens/chapter_4/tutorial_6_weak_lensing\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell with progress once search has completed - this could take some time!\"\n", + " \"The non-linear search has begun. Check \"\n", + " \"output/howtolens/chapter_4/tutorial_6_weak_lensing \"\n", + " \"for live results, images and model information. \"\n", + " \"Continue once the search has completed.\"\n", ")\n", "\n", "result = search.fit(model=model, analysis=analysis)\n", "\n", - "print(\"The search has finished run - you may now continue the notebook.\")" + "print(\"The search has finished. You may now continue the notebook.\")" ], "outputs": [], "execution_count": null @@ -561,9 +542,17 @@ "source": [ "__Result__\n", "\n", - "The result's `info` attribute confirms the search recovers the input mass model \u2014 Einstein radius, ellipticity and\n", - "centre \u2014 from nothing but the statistically-averaged shapes of background galaxies. No arc, no ring, no multiple\n", - "images: the ensemble alone constrains the cluster's mass." + "Inspect `result.info` to see the inferred parameters and their uncertainties.\n", + "\n", + "Because we simulated this catalogue, we can compare them with the input Einstein radius of 25 arc-seconds, axis ratio of 0.8, position angle of 45 degrees and centre at the origin.\n", + "\n", + "The code parameterizes ellipticity using two components, so convert between those components and axis ratio and position angle when making that comparison.\n", + "\n", + "Noise means that the inferred values need not equal the inputs exactly. Consider the posterior intervals and parameter correlations, rather than judging recovery from a single fitted realization.\n", + "\n", + "The fit subplot below displays the maximum-likelihood realization found by the search. Compare its coherent shear pattern with the noisy measurements, using the diagnostics discussed above.\n", + "\n", + "These constraints are conditional on our chosen mass profile, fixed redshifts and noise assumptions. A real cluster may require a more flexible mass distribution and additional treatment of observational uncertainties." ] }, { @@ -581,14 +570,21 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Cluster weak-lensing measurements are conventionally presented as the **tangential shear profile**: the mean\n", - "tangential shear gamma_t of background galaxies in radial bins about the lens centre, which traces the projected\n", - "mass profile. `aplt.plot_shear_profile` bins our catalogue and, given the fit, overlays the model's profile as a\n", - "line.\n", + "Weak-lensing measurements around clusters are often summarized using a **tangential shear profile**.\n", + "\n", + "For each background galaxy, we resolve its shear into components defined relative to a chosen centre. The tangential component describes the tendency for images to stretch around that centre.\n", + "\n", + "`aplt.plot_shear_profile` groups the catalogue into radial bins and plots the mean tangential component with uncertainties. Passing a fit also overlays the model\u2019s binned tangential profile.\n", + "\n", + "Here we use eight bins around the simulation\u2019s input centre, `(0.0, 0.0)`. This plotting choice does not fix the mass centre in the fit: the model still has two free centre coordinates.\n", + "\n", + "The plot is a summary of the fitted catalogue. Our likelihood used both shear components at every galaxy position, retaining angular information that radial averaging can hide.\n", + "\n", + "The second set of points shows the **cross component**, defined at 45 degrees to the tangential component. Its azimuthal average is expected to be consistent with zero for the ideal lensing signal and suitable angular sampling.\n", + "\n", + "A significant cross signal therefore motivates checks of the measurements, angular coverage and model geometry. However, a cross profile consistent with zero does not establish that all systematic errors are absent; some biases can change the tangential signal without producing a cross signal.\n", "\n", - "The plot also shows the *cross* component gamma_x \u2014 the shear rotated by 45 degrees. Gravitational lensing produces\n", - "no cross component at leading order, so cross points scattering around zero is the standard \"B-mode\" null test of a\n", - "weak-lensing measurement: a systematic contaminating the shapes would show up there." + "Use the radial profiles together with the two-dimensional fit diagnostics and posterior uncertainties." ] }, { @@ -610,71 +606,62 @@ "source": [ "__Joint Strong and Weak Lensing__\n", "\n", - "We fitted this catalogue on its own, and weak-lensing-only fits of real catalogues are a fully supported PyAutoLens\n", - "workflow. But the way PyAutoLens really expects weak lensing to be used is **jointly with strong lensing**, because\n", - "the two probes are perfectly complementary:\n", + "We fitted the weak-lensing catalogue on its own. When a system also has strong-lensing observations, combining the two can constrain its mass distribution across a wider range of radii.\n", "\n", - " - **Strong lensing** (everything before this tutorial) pins the mass in the inner region with exquisite precision \u2014\n", - " the positions of multiple images and arcs nail the Einstein mass and the inner density profile \u2014 but says\n", - " nothing beyond the Einstein radius.\n", + "**Strong lensing** provides detailed information where multiple images and arcs form. It often tightly constrains the enclosed projected mass near the Einstein radius, while the inferred density profile and division between mass components remain subject to degeneracies.\n", "\n", - " - **Weak lensing** (this tutorial) constrains the mass profile out to arc-minute radii \u2014 the outskirts of the dark\n", - " matter halo \u2014 but its centre and inner profile are only weakly pinned by the field's geometry.\n", + "**Weak lensing** adds measurements over a larger field, extending our sensitivity to the outer dark matter halo. Its constraining power depends on the background-source density, redshifts, shape uncertainties and area observed.\n", "\n", - "Fit both datasets simultaneously with a single mass model \u2014 one analysis for the imaging or point-source data, one\n", - "`AnalysisWeak` for the shear catalogue, combined exactly as the multi-dataset fits earlier in this chapter combined\n", - "their analyses \u2014 and the model is anchored at the centre by strong lensing while its outer profile is measured by\n", - "weak lensing. This hybrid is the state of the art for cluster mass measurements, used across systems like the\n", - "Frontier Fields clusters, and PyAutoLens's shared `Tracer` infrastructure makes it natural: the same mass profiles\n", - "that ray-traced arcs in the previous tutorial produce the shear field fitted here.\n", + "These are complementary measurements of the same gravitational field. Strong lensing does not become insensitive to all mass outside the Einstein radius, and weak lensing does not independently determine every feature of the outer halo.\n", "\n", - "The workspace's `autolens_workspace/*/weak` package has the complete treatment:\n", + "A joint analysis uses shared mass-model parameters to predict both datasets. We combine an imaging or point-source analysis with `AnalysisWeak`, following the multi-dataset approach used earlier in this chapter.\n", "\n", - " - `weak/start_here.py`: fits a real shear catalogue of the merging cluster Abell 2744 (\"Pandora's Cluster\") \u2014\n", - " download, quality cuts, mass map, NFW halo fit.\n", - " - `weak/simulator.py`, `weak/fit.py`, `weak/modeling.py`: the disk-based versions of this tutorial's workflow.\n", - " - `weak/likelihood_function.py`: a step-by-step walkthrough of the weak-lensing likelihood.\n", - " - `weak/features/strong_lensing`: the joint strong-plus-weak fits described above.\n", + "For datasets whose measurement errors can be treated as independent, their log likelihoods add. Each analysis retains its own data model and uncertainties, while the shared mass parameters must explain both sets of observations.\n", + "\n", + "The source populations need not have the same redshift. Each prediction must use the geometry appropriate to its sources, just as in the previous cluster tutorial.\n", + "\n", + "For example, strong-lensing images can constrain the central mass distribution while a weak-lensing catalogue helps constrain the mass and concentration of an extended NFW halo. Combining them can reduce degeneracies, although the result still depends on the chosen mass components and observational assumptions.\n", + "\n", + "Inspect the contributions from both datasets separately. A satisfactory joint fit should describe both, and a disagreement can reveal missing mass structure, calibration problems or overly restrictive assumptions.\n", + "\n", + "The `autolens_workspace/scripts/weak` directory provides examples for continuing this work:\n", + "\n", + "- [start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/start_here.py): an introduction using a real galaxy-shape catalogue for Abell 2744.\n", + "- [simulator.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/simulator.py), [fit.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/fit.py) and [modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/modeling.py): simulation, fitting and inference examples.\n", + "- [likelihood_function.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/likelihood_function.py): a step-by-step explanation of the weak-lensing likelihood.\n", + "- [features/strong_lensing](https://github.com/PyAutoLabs/autolens_workspace/tree/main/scripts/weak/features/strong_lensing): examples combining strong- and weak-lensing measurements.\n", "\n", "__Wrap Up__\n", "\n", - "This tutorial completed the chapter's journey up the mass ladder, and with it the four core chapters of\n", - "**HowToLens**. Lets take stock of how far we have come.\n", + "This tutorial completes Chapter 4 and the four core chapters of **HowToLens**.\n", + "\n", + "We have learned how to:\n", + "\n", + "- Represent weak-lensing measurements as a catalogue of positions, shear estimates and uncertainties.\n", + "- Simulate an idealized catalogue and understand how shape noise affects its measurements.\n", + "- Visualize the shear field and construct an exploratory convergence map.\n", + "- Evaluate a catalogue likelihood and infer mass-model parameters using the familiar search workflow.\n", + "- Interpret fit diagnostics and posterior uncertainties, and understand the motivation for joint strong- and weak-lensing analyses.\n", + "\n", + "The distinction between shear and reduced shear matters when moving from this idealized simulation to observed galaxy shapes. So do source redshifts, calibration, selection and the flexibility of the mass model.\n", "\n", - "Chapter 1 built lensing from first principles: grids, light and mass profiles, ray tracing, the lens equation, and\n", - "fitting imaging data with a `Tracer`. Chapter 2 turned fitting into inference \u2014 non-linear searches, priors,\n", - "Bayesian model comparison \u2014 so we could *infer* lens models rather than guess them. Chapter 3 replaced analytic\n", - "sources with pixelized reconstructions, letting the data itself reveal the source's morphology.\n", + "Across the series, the same ideas have supported increasingly complex analyses.\n", "\n", - "This chapter then scaled those tools up through every regime nature offers, and in this tutorial:\n", + "**Chapter 1** introduced grids, light and mass profiles, ray tracing and fitting data. These calculations came together as a likelihood function.\n", "\n", - "- **Weak Lensing:** Outside the strong-lensing region every background galaxy is still weakly sheared; the signal\n", - " is invisible per galaxy beneath intrinsic shape noise but emerges statistically over an ensemble.\n", + "**Chapter 2** used that likelihood for inference: defining priors, running non-linear searches, examining posterior uncertainties and comparing models.\n", "\n", - "- **Shear Catalogues:** The weak-lensing dataset is a catalogue of galaxy positions, measured shear estimates and\n", - " uncertainties, produced upstream by a dedicated shape-measurement pipeline \u2014 PyAutoLens fits mass models to it\n", - " and leaves the shape measurement to those pipelines.\n", + "**Chapter 3** introduced pixelized source reconstructions, allowing more flexible descriptions of source morphology while controlling that flexibility through regularization.\n", "\n", - "- **Mass Scales:** The statistical signal is hopeless around a single galaxy, marginal around a group and\n", - " measurable around a cluster \u2014 and it probes the dark matter halo to radii far beyond the reach of arcs.\n", + "**Chapter 4** extended the modeling to additional galaxies, shared scaling relations, groups, clusters and weak lensing. We saw how fixed measurements and shared relations can make large models tractable, while also shaping the conclusions we can draw from them.\n", "\n", - "- **The Same Workflow:** `SimulatorShearYX`, `FitWeak` and `AnalysisWeak` slot into the identical\n", - " simulate-fit-model pattern the series has used since chapter 1, and a non-linear search recovered the cluster's\n", - " mass from galaxy shapes alone.\n", + "You now have a foundation for building lens models, understanding their likelihoods and assessing their results. Applying those tools to a scientific question means choosing an appropriate model, checking the data and testing which conclusions remain robust when assumptions change.\n", "\n", - "- **Joint Fits:** Strong lensing pins the inner mass, weak lensing measures the outskirts; fitting both with one\n", - " model is the expected PyAutoLens workflow for cluster and group science.\n", + "The next step is the [autolens_workspace](https://github.com/PyAutoLabs/autolens_workspace). Start with the example closest to your dataset, then use its feature examples and likelihood guides to build up the analysis you need.\n", "\n", - "And that is the series: from a single lens galaxy, to lenses with extra galaxies, to multi-galaxy lenses, to\n", - "scaling relations that keep many-galaxy models tractable, to group-scale and cluster-scale systems, and finally\n", - "beyond the Einstein radius altogether into the weak-lensing regime. You have every conceptual tool the modern\n", - "lensing literature uses, and you have used each one on data.\n", + "The workspace covers imaging, interferometry, point sources, groups, clusters and weak lensing, alongside tools such as the automated SLaM pipelines.\n", "\n", - "Where next? The `autolens_workspace` is the destination for real science. Its `imaging`, `point_source`, `group`,\n", - "`cluster` and `weak` packages hold the production-ready versions of everything taught here \u2014 including the\n", - "`start_here.py` scripts that are each topic's canonical, always-current reference \u2014 plus the features this series\n", - "could only gesture at: multi-wavelength fits, interferometry, automated SLaM pipelines and more. Take your own\n", - "data there, and good luck with your science!" + "Bring your own data, keep inspecting what the model is doing, and enjoy exploring the Universe through gravitational lensing!" ] } ], @@ -710,4 +697,4 @@ }, "nbformat": 4, "nbformat_minor": 4 -} \ No newline at end of file +} diff --git a/scripts/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.py b/scripts/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.py index 976f04e..b3953c8 100644 --- a/scripts/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.py +++ b/scripts/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.py @@ -2,41 +2,30 @@ Tutorial 1: Extra Galaxies ========================== -Welcome to chapter 4 of **HowToLens**, where we scale up lens modeling beyond a single lens galaxy. +Welcome to chapter 4 of **HowToLens**, where we scale up lens modeling beyond a single dominant lens galaxy. -In chapters 1 to 3, every strong lens we studied had the same simple anatomy: one lens galaxy, whose light and mass -we modeled, and one background source galaxy, whose lensed emission we fitted. This is the cleanest possible lensing -configuration, and it was the right place to learn the fundamentals of ray-tracing, non-linear searches and -pixelized source reconstructions. +In chapters 2 and 3, we focused on modeling systems with one main lens galaxy and one background source galaxy. +These examples introduced non-linear searches, lens modeling and pixelized source reconstructions. -Real strong lenses are rarely this tidy. Galaxies live in crowded fields: a lens galaxy may have a faint companion a -few arc-seconds away, sit in a small group of comparably massive galaxies, or be embedded in a cluster containing -hundreds of members and a vast dark matter halo. The science of strong lensing scales up through this hierarchy, and -so must our modeling: +In chapter 1, we also saw that lensing occurs in more complex systems, including groups and clusters of galaxies. +We now explore how to build and fit models of these systems, starting with a nearby galaxy that complicates an +otherwise familiar galaxy-scale lens. -- **Extra galaxies (this tutorial)**: a single dominant lens galaxy, with one or more nearby interloper galaxies - whose light and mass may contaminate the analysis. +This chapter introduces: -- **Multi-galaxy lenses (next tutorial)**: systems where two or more galaxies are co-equal lenses, and no single - galaxy can be called "the" lens. +- **Extra galaxies:** nearby galaxies whose light or mass may affect our analysis. +- **Multi-galaxy lenses:** systems where two or more galaxies contribute substantially to the lensing. +- **Scaling relations:** linking the mass properties of many galaxies to their luminosities, reducing the number + of free parameters. +- **Group and cluster scales:** modeling member galaxies together with a shared dark matter halo. +- **Weak lensing:** using the small distortions of background galaxies to constrain foreground mass beyond the + strongly lensed region. -- **Scaling relations**: modeling many galaxies at once by tying their properties to their luminosity, so that - adding galaxies does not add free parameters. +Many of these modeling techniques also apply to studies of galaxy morphology without lensing. **PyAutoGalaxy** +provides the same tools for fitting galaxy light and composing models of multiple galaxies, without ray-tracing. -- **Group and cluster scales**: lenses whose deflectors are entire groups or clusters of galaxies, including a - shared dark matter halo. - -- **Weak lensing**: the statistical distortion of many background galaxies by foreground mass, extending lensing - beyond the strong regime entirely. - -Much of the methodology in this chapter is not specific to lensing. Fitting the light of extra galaxies, modeling -blended multi-galaxy fields and composing models via scaling relations are equally important for non-lensing galaxy -studies, and **PyAutoGalaxy** provides the same API for these tasks applied to galaxy morphology (without the -ray-tracing). - -In this first tutorial, we take the first step up in scale: a galaxy-scale lens with one extra galaxy nearby. We -will learn how to decide whether the extra galaxy matters, and the two approaches to dealing with it when it does: -removing its light from the data, or including it in the lens model. +In this tutorial, we consider one extra galaxy near a dominant lens galaxy. We will distinguish the effects of its +light and mass, then compare excluding its light from the fit with explicitly including the galaxy in our model. __Contents__ @@ -64,15 +53,17 @@ """ __Initial Setup__ -Lets load the `Imaging` dataset we'll fit in this tutorial. It is similar to the `lens_sersic` dataset used -throughout chapter 2, where: +Let's load the `Imaging` dataset we will fit in this tutorial. It is similar to the `lens_sersic` dataset used in +chapter 2: + +- The lens galaxy's light follows a `Sersic` profile. +- Its mass follows an `Isothermal` profile, with a separate `ExternalShear` field. +- The source galaxy's light follows a `SersicCore` profile. - - The lens galaxy's light is an `Sersic`. - - The lens system uses an `Isothermal` galaxy mass profile and a separate `ExternalShear` field. - - The source galaxy's light is an `SersicCore`. +This dataset also contains an extra galaxy a few arcseconds from the main lens. Its light follows an +`ExponentialSph` profile and its mass follows an `IsothermalSph` profile. -However, there is one addition: an extra galaxy, with its own light (an `ExponentialSph`) and its own -mass (an `IsothermalSph`), located a few arc-seconds from the lens galaxy. +Both its emission and its gravitational deflections are therefore present in the simulated data. """ dataset_name = "lens_extra_galaxy" dataset_path = Path("dataset") / "imaging" / dataset_name @@ -100,48 +91,54 @@ ) """ -When we plot the dataset, the familiar sight of a lens galaxy surrounded by a lensed source's ring of emission is -joined by a blob of light in the upper-right of the image. +Plotting the dataset shows the familiar lens galaxy and lensed source emission, together with an extra galaxy +nearby. -This is the extra galaxy. It is not part of the strong lens system we are studying: it is an interloper, a galaxy -that happens to lie close to the lens on the sky. Interlopers like this are extremely common in real imaging of -strong lenses, and every lens modeler has to decide what to do about them. +We call this an **extra galaxy** because the main lens remains the dominant deflector. This does not mean the extra +galaxy has no lensing effect: its mass also deflects the source's light. + +Nearby galaxies are common in observations of strong lenses. Before fitting the data, we must decide whether their +light, their mass, or both need to be accounted for. """ aplt.subplot_imaging_dataset(dataset=dataset) """ __Light Versus Mass__ -The decision of what to do about an extra galaxy hinges on one question, asked twice: +An extra galaxy raises two separate questions. -**Does its light affect the analysis?** The extra galaxy's emission may extend into the region of the image we fit. -If it does, and we fit a model containing only the lens and source, the model has no component that can produce -this emission. The fit will respond by distorting the lens light, source light or mass model to soak it up, -biasing every parameter we infer. +**Does its light affect the analysis?** If its emission falls within the region we fit, a model containing only the +main lens and source may try to reproduce that light using the wrong components. This can distort the inferred +lens light, source reconstruction or mass model. -**Does its mass affect the analysis?** The extra galaxy's mass deflects light rays, just like the lens galaxy's -mass does. If the galaxy is close (in projection) to the lensed source's light, its deflections measurably perturb -the ray-tracing. A model without this mass will compensate by biasing the main lens galaxy's mass parameters, for -example its `einstein_radius` or `ell_comps`. +**Does its mass affect the analysis?** The extra galaxy also deflects the source's light. Whether we need to model +these deflections depends on its mass, position and redshift, together with the precision of the data and the +measurements we want to make. -These two effects are dealt with separately, which gives us two approaches: +Removing the extra galaxy's light from the fit does not remove its gravitational effect. Likewise, including its +mass does not account for its emission. -- **Approach 1 (remove its light)**: If only the light matters, we can remove the extra galaxy's emission from the - fit entirely, without adding anything to the model. The mass is ignored. +We will compare two approaches: -- **Approach 2 (model it explicitly)**: If the mass matters (or the light blends too closely with the lensed source - to cleanly remove), we include the extra galaxy in the lens model, with its own light and / or mass profiles. +- **Noise scaling:** use the method introduced in chapter 2 to prevent the extra galaxy's light from meaningfully + constraining the fit. In this first example, we also omit its mass, allowing us to explore the limitation of + that choice. +- **Explicit modeling:** include the extra galaxy's light and mass profiles, fitting its emission and accounting + for its deflections. -We will now perform both, and at the end of the tutorial discuss when each is appropriate. +These are not the only combinations. We can also noise-scale the light while retaining a mass profile, or model +the light while omitting the mass when its lensing effect is negligible. __Mask__ -We first define the circular mask used to fit the data. In chapter 2 we typically used a 2.6" - 3.0" mask, which -tightly contained the lens and lensed source. +We use a circular mask with a radius of 4.0", which includes the main lens, the lensed source emission and the +extra galaxy. + +Keeping the extra galaxy inside the mask lets us compare noise scaling and explicit modeling using the same +overall fitting region. -Here, we use a larger 4.0" mask, so that the region containing the extra galaxy is included in the fit. If we -simply shrank the mask to exclude the extra galaxy, we would also throw away pixels containing lensed source -emission, and the mask's hard edge could still cut through the extra galaxy's light. +For other datasets, a smaller mask may exclude an unwanted galaxy. This is appropriate only if it retains the +lensed emission we want to analyze and avoids significant contamination from the extra galaxy's light. """ mask = al.Mask2D.circular( shape_native=dataset.shape_native, @@ -152,31 +149,26 @@ dataset = dataset.apply_mask(mask=mask) """ -Plotting the masked dataset confirms the extra galaxy's emission is inside the mask, and will therefore impact the -model-fit unless we do something about it. +Plotting the masked dataset confirms that the extra galaxy's emission lies within the fitting region. We must +therefore account for its light, either by noise scaling the affected pixels or by modeling the emission explicitly. """ aplt.subplot_imaging_dataset(dataset=dataset) """ __Approach 1 Noise Scaling__ -Our first approach removes the extra galaxy's light from the fit. - -The most obvious way to do this would be to mask the extra galaxy's pixels, removing them from the fit entirely. -However, removing pixels changes the fit in subtle ways: their coordinates are no longer used in the ray-tracing, -and for certain models (e.g. the pixelized source reconstructions of chapter 3) removing interior pixels creates -discontinuities in the pixelization that introduce unexpected systematics. +We first use the noise-scaling method introduced in chapter 2. Recall that this sets selected data values to zero +and increases their noise values, giving those pixels negligible weight when constraining the model while +retaining them in the dataset's geometry. -Instead, we use **noise scaling**: the pixels stay in the fit, but their data values are set to zero and their -noise-map values are increased to very large values. A pixel with enormous noise contributes negligibly to the -likelihood, so the extra galaxy's light cannot influence the model, while the pixels themselves remain part of the -fit's geometry. +Here, we apply it to the region containing the extra galaxy's light. Any lensed source emission within that region +will also lose its constraining power, so we should avoid this approach where the extra galaxy and source are +strongly blended. -To do this we need a mask of the extra galaxy's region. For real data, you would create this yourself by -inspecting the image (the workspace's `data_preparation` package includes a GUI for drawing it); for this simulated -dataset the simulator script has already output a `mask_extra_galaxies.fits` circle covering the extra galaxy. +For this simulated dataset, the simulator provides a `mask_extra_galaxies.fits` file identifying the extra galaxy's +region. For real observations, we would define this region by inspecting the image. -We reload the dataset first, because noise scaling must be applied before the circular mask. +We reload the original dataset, apply noise scaling, and then apply the same 4.0" circular mask. """ dataset = al.Imaging.from_fits( data_path=dataset_path / "data.fits", @@ -202,17 +194,25 @@ dataset = dataset.apply_mask(mask=mask) """ -Plotting the dataset shows the extra galaxy's emission has vanished: its data values are zero and the -signal-to-noise of its pixels is effectively zero, so the fit will simply ignore that region of the image. +The subplot shows that the selected region now has zero data values and effectively zero signal-to-noise. Its +pixels therefore contribute negligibly to constraining the fit. + +This excludes the extra galaxy's light from the analysis, but its mass has still deflected the source light +recorded elsewhere in the image. Noise scaling does not undo those deflections. """ aplt.subplot_imaging_dataset(dataset=dataset) """ __Noise Scaling Fit__ -We now fit this noise-scaled dataset with a lens model that does **not** include the extra galaxy. The model is the -same one we used in chapter 2's linear profiles tutorial: a linear `Sersic` lens bulge, an `Isothermal` plus -`ExternalShear` mass model and a linear `SersicCore` source. +We now fit the noise-scaled dataset using the familiar model from chapter 2: a linear `Sersic` lens light profile, +an `Isothermal` lens mass profile, a separate `ExternalShear` field and a linear `SersicCore` source light profile. + +This model contains no extra galaxy. Its light has been handled by noise scaling, but its mass is deliberately +omitted. + +The fit therefore illustrates an important distinction: excluding contaminating light does not necessarily make a +single-galaxy mass model adequate. """ # Lens: @@ -242,34 +242,40 @@ analysis = al.AnalysisImaging(dataset=dataset) print( - "The non-linear search has begun running - checkout the output/howtolens/chapter_4/tutorial_1_extra_galaxies_noise_scaling" - " folder for live output of the results, images and model." - " This Jupyter notebook cell with progress once search has completed - this could take some time!" + "The non-linear search has begun. Check the " + "output/howtolens/chapter_4/tutorial_1_extra_galaxies_noise_scaling " + "folder for results and visualizations as the search progresses. " + "This cell will finish when the search completes." ) result_noise_scaling = search.fit(model=model, analysis=analysis) -print("The search has finished run - you may now continue the notebook.") +print("The search has finished — you may now continue the notebook.") """ -Plotting the maximum log likelihood fit shows the lens and source are fitted well, with the noise-scaled region -contributing nothing to the residuals. +Inspect the maximum log likelihood fit below, paying particular attention to the residuals and normalized +residuals around the lensed source. + +The noise-scaled pixels have negligible weight in the fit. Their raw residuals need not be zero, because the model +can still predict emission there. -The extra galaxy's light has been dealt with. However, note what this approach did **not** do: the extra galaxy's -mass is completely absent from the model. Its deflection of the source's light rays is unaccounted for, and the -inferred lens mass model will have absorbed that perturbation as best it can. For an extra galaxy that is small -and / or far from the lensed emission this bias is negligible; for one that is massive and close, it is not. +Elsewhere, the model must reproduce source emission that was lensed by both the main lens and the extra galaxy, +even though it includes only the main lens mass and external shear. These components may absorb some of the +missing perturbation, potentially shifting the inferred parameters. + +A visually satisfactory fit therefore does not establish that the extra galaxy's mass can safely be ignored. +Next, we include it explicitly so that we can compare the results. """ aplt.subplot_fit_imaging(fit=result_noise_scaling.max_log_likelihood_fit) """ __Approach 2 Extra Galaxies Model__ -Our second approach includes the extra galaxy in the lens model, fitting its light (so we no longer need to remove -it from the data) and its mass (so its deflections are included in the ray-tracing). +We now include the extra galaxy's light and mass in the model. Its light profile accounts for its emission, while +its mass profile contributes to the deflections of the background source. -We reload the dataset and apply the 4.0" circular mask, but this time we do **not** apply noise scaling, because -the extra galaxy's emission is now something the model itself will fit. +We reload the original dataset and apply the same 4.0" circular mask. This time, we do not apply noise scaling, +because we want to fit the extra galaxy's light. """ dataset = al.Imaging.from_fits( data_path=dataset_path / "data.fits", @@ -289,21 +295,30 @@ """ __Extra Galaxy Centres__ -To include the extra galaxy in the model, we input the centre of its light, as observed in the image. +We first load the extra galaxy's observed light centre. + +Allowing its light and mass centres to vary freely would introduce additional parameters and give the search more +opportunities to find unwanted solutions. For example, its light profile might fit part of a lensed arc, or its +mass profile might move towards the main lens and contribute to that galaxy's mass distribution. + +Measuring galaxy light centres first and then fixing them in the model is a common workflow throughout +extra-galaxy modeling. It becomes especially useful for the more complex multi-galaxy, group and cluster systems +we encounter later in this chapter, where allowing every centre to vary would introduce many additional parameters. -In principle, we could add the extra galaxy to the model with a completely free centre, and let the non-linear -search figure out where it is. In practice this is a bad idea: the extra parameters make parameter space more -complex, and fits commonly go wrong in characteristic ways. For example, the extra galaxy's light profile may -wander off and fit one of the lensed source's multiple images instead of the interloper, or its mass profile may -recentre itself onto the main lens galaxy and act as part of its mass distribution. +Typically, we inspect the image and record each galaxy's light centre using a GUI, a source-detection tool or a +preliminary light-profile fit. We then use these measured positions as fixed centres for its light and mass +profiles in the lens model. The workspace's data-preparation tools support this workflow; here, we load the +positions supplied by the simulator. -Fixing each extra galaxy's light and mass centres to its observed light centre removes these failure modes and -keeps the model as simple as possible. The observed centre is an excellent estimate of the true centre, because -(unlike the lensed source) the extra galaxy's light is not distorted by lensing. +Fixing centres is therefore a practical modeling choice used in many analyses, rather than just a simplification +for this tutorial. It keeps galaxies anchored to their observed positions and reduces the freedom for their +profiles to fit unrelated emission or move towards the main lens. -For real data you would measure these centres from the image (the workspace's `data_preparation` package shows -how, including a GUI for marking them); for this simulated dataset the simulator has output them to a .json file, -which we load below. +This still assumes that each mass profile is centred on the observed light. Where positional uncertainties or +possible light-mass offsets matter scientifically, we can relax that assumption using informative priors. + +In this example, the extra galaxy is at the main lens's redshift, so its light is not lensed by the main lens. +This need not be true of every galaxy projected nearby on the sky. """ extra_galaxies_centres = al.Grid2DIrregular( al.from_json(file_path=dataset_path / "extra_galaxies_centres.json") @@ -314,7 +329,8 @@ """ __Extra Galaxies Model Composition__ -We compose the main lens and source model exactly as before. +We compose the main lens and source model exactly as before. Keeping these components unchanged makes it easier +to assess the effect of adding the extra galaxy. """ # Lens: @@ -329,25 +345,27 @@ source = af.Model(al.Galaxy, redshift=1.0, bulge=al.lp_linear.SersicCore) """ -We now compose the model of the extra galaxy, using the dedicated `extra_galaxies` modeling API. +We now build the extra galaxy using the `extra_galaxies` modeling API. + +For each observed centre, we create a galaxy containing: -For each extra galaxy centre (there is only one here, but the loop below scales to any number) we create a `Galaxy` -model with: +- A linear `ExponentialSph` light profile. Its centre is fixed, leaving `effective_radius` as one free non-linear + parameter. Its intensity is solved for during the linear inversion. +- An `IsothermalSph` mass profile. Its centre is also fixed, leaving `einstein_radius` as one free non-linear + parameter. - - A linear `ExponentialSph` light profile, with its `centre` fixed to the observed centre [1 free - parameter: `effective_radius`, as the `intensity` is solved for by the linear inversion]. +The spherical profiles and fixed centres keep this model compact: the extra galaxy adds just two non-linear +parameters. - - An `IsothermalSph` mass profile, with its `centre` fixed to the observed centre [1 free - parameter: `einstein_radius`]. +We assign its Einstein radius a uniform prior between 0.0" and 0.5", appropriate for the small companion in this +simulated example. For real data, this range should reflect what we know about the galaxy, and we should check +whether the inferred value approaches either prior boundary. -Extra galaxy mass profiles can wander to unphysically high `einstein_radius` values, degrading the fit, so we set -a `UniformPrior` with an upper limit of 0.5" to prevent this. The extra galaxy is much less massive than the main -lens (whose `einstein_radius` is around 1.6"), so this prior comfortably contains all plausible solutions. +We place the extra galaxies in an `af.Collection` and pass it through the overall model's `extra_galaxies` input, +alongside the main lens and source. -The extra galaxies are grouped into their own `af.Collection`, which is passed to the overall model via its -`extra_galaxies` input, alongside the `galaxies` collection containing the lens and source. This is the same -API used throughout the `autolens_workspace` for extra galaxies, and it is how **PyAutoLens** knows to include -these galaxies in the ray-tracing without treating them as the main lens or source. +Here, the extra galaxy has redshift 0.5, matching the main lens. A galaxy at a different redshift would require +its appropriate redshift in the model. """ # Extra Galaxies: @@ -383,30 +401,37 @@ ) """ -The `info` attribute confirms the model includes the extra galaxy, with its fixed centres and its -free `effective_radius` and `einstein_radius` parameters. +The `info` attribute shows the extra galaxy's fixed centres and the priors on its two free non-linear parameters: +`effective_radius` and `einstein_radius`. + +Its light-profile intensity is determined by the linear inversion during each likelihood evaluation, rather than +sampled by the non-linear search. """ print(model.info) """ -The same model can also be visualized as a figure, making its structure easier to understand at a glance. +The model can also be visualized as a figure, showing how its components and parameters are organized. -The figure shows how the model is organized: which parameters belong to each component, and whether they are free, -fixed, shared, linked by an expression, solved during the fit, or not configured. `model.info` provides the -corresponding numerical details, including the prior assigned to each free parameter and the value of each fixed -parameter. +Notice that the extra galaxy's light and mass centres are fixed to its measured position. This is the workflow +we will reuse as we introduce larger populations of galaxies: measure their positions first, then keep those +positions fixed while fitting their other properties. -The extra galaxy is part of the model and part of the ray-tracing, but it is neither the lens nor the source. -Its centres are fixed to the values we measured from the data and its light is linear, so an entire extra galaxy -costs just two more free parameters than the same lens-and-source model without it. +Here, spherical profiles and a linearly solved light intensity mean the extra galaxy adds only two non-linear +parameters. The figure shows this structure, while `model.info` gives the numerical values and priors. """ af.ModelPlotter(model).figure() """ __Extra Galaxies Fit__ -We fit this model with the same search set up as before. The model has only two more free parameters than the -noise-scaling fit, thanks to the fixed centres and linear light profile, so the fit remains fast. +We fit the model using the same search settings as before. + +The extra galaxy adds only two non-linear parameters, keeping the increase in search dimensionality small. +Nevertheless, fitting time also depends on degeneracies between components and the cost of each likelihood +evaluation. + +This fit uses the original, unscaled data, so the extra galaxy's light now contributes to constraining the model +alongside the main lens and source. """ search = af.Nautilus( path_prefix=Path("howtolens", "chapter_4"), @@ -420,73 +445,82 @@ analysis = al.AnalysisImaging(dataset=dataset) print( - "The non-linear search has begun running - checkout the output/howtolens/chapter_4/tutorial_1_extra_galaxies_model" - " folder for live output of the results, images and model." - " This Jupyter notebook cell with progress once search has completed - this could take some time!" + "The non-linear search has begun. Check the output/howtolens/chapter_4/tutorial_1_extra_galaxies_model" + " folder for results and visualizations as the search progresses." + " This cell will finish when the search completes." ) result_extra_galaxies = search.fit(model=model, analysis=analysis) -print("The search has finished run - you may now continue the notebook.") +print("The search has finished — you may now continue the notebook.") """ -Plotting the maximum log likelihood fit shows the extra galaxy's emission is now fitted by its own light profile, -and its mass has contributed deflections to the ray-tracing of the source. +Inspect the maximum log likelihood fit below. The extra galaxy's emission is now represented by its own light +profile, and its mass contributes to the ray-tracing of the background source. + +Compare the residuals around the extra galaxy and the lensed arcs with the earlier fit. Also compare the inferred +main-lens parameters: accounting for the extra galaxy's mass may change them even if both fits appear visually +satisfactory. + +The two fits use different noise maps and different sets of informative pixels. Their raw likelihood or Bayesian +evidence values should therefore not be interpreted as a straightforward model comparison. """ aplt.subplot_fit_imaging(fit=result_extra_galaxies.max_log_likelihood_fit) """ -The result's `info` shows the inferred `einstein_radius` of the extra galaxy, quantifying how much lensing power -the interloper contributes to the system. +The result's `info` summarizes the inferred parameters and their uncertainties, including the extra galaxy's +`einstein_radius`. + +Inspect its uncertainty and whether it lies close to a prior boundary. Including a mass profile does not +guarantee that the data tightly constrain its normalization. + +The inferred Einstein radius describes the lensing strength of the adopted `IsothermalSph` profile; it is not a +direct measurement of the galaxy's total mass. """ print(result_extra_galaxies.info) """ __Which Approach When__ -We have seen the two extremes of dealing with an extra galaxy. Choosing between them comes back to the -light-versus-mass question at the start of this tutorial, which in practice is settled by three properties of the -interloper: - -- **Distance from the lensed emission**: An extra galaxy whose light is well separated from the lensed source (as - in this tutorial) can be cleanly noise-scaled away. If its light blends into the source's arcs, noise scaling - would also delete source emission we need, and the light must be modeled instead. +Choosing how to handle an extra galaxy returns us to two separate questions: does its light affect the fit, +and do its gravitational deflections matter for the measurements we want to make? -- **Brightness**: A faint interloper whose emission barely rises above the noise can often be ignored entirely, or - noise-scaled with no consequence. A bright one must be removed or modeled, or it will bias the fit. +**Consider the light first.** If its emission is outside the fitting region or negligible compared with the noise, +we may not need a light profile. If it contaminates pixels we would otherwise fit, we can noise-scale those pixels +or model the emission explicitly. -- **Mass and proximity to the lens**: The mass matters when the extra galaxy is massive enough, and close enough - (in projection) to the lensed source's light, for its deflections to measurably perturb the ray-tracing. A rough - rule of thumb is to compare its expected Einstein radius to the astrometric precision of the data: a small galaxy - several arc-seconds from the arcs can have its mass safely ignored, whereas one abutting the Einstein ring - cannot. When in doubt, fit both approaches and compare the inferred lens models: if the main lens's mass - parameters shift appreciably, the extra galaxy's mass matters. +Noise scaling is useful when we can exclude the contaminated region without losing important source information. +If the extra galaxy overlaps the lensed arcs, explicitly modeling its light lets us retain those pixels, although +the accuracy of its light profile then matters. -Intermediate options also exist and are fully supported by the API: you can noise-scale the light but still include -the mass profile in the model, or model the light but omit the mass. The `extra_galaxies` collection simply -contains whatever profiles you give it. +**Consider the mass separately.** Its importance depends on its mass, redshift and position relative to the lensed +images, as well as the precision of the data and the scientific question. Neither faintness nor separation alone +guarantees that its deflections are negligible. -__Wrap Up__ - -In this tutorial, we took the first step up in scale from the single lens galaxy of chapters 1 to 3, and learnt: +To investigate its effect, compare models with and without the extra mass profile while keeping the data +treatment and other modeling choices consistent. Inspect changes in the residuals and inferred parameters +relative to their uncertainties. A small change is useful evidence of robustness within the models tested, +rather than proof that every possible perturbation is negligible. -1. Real lenses live in crowded fields, and interloping extra galaxies are the first complication real data throws - at us. +The API supports each combination: model both light and mass, model only the light, or noise-scale the light while +retaining a mass profile. -2. Whether an extra galaxy matters hinges on two separate questions: does its **light** contaminate the region of - the image we fit, and does its **mass** perturb the ray-tracing of the source? +__Wrap Up__ -3. Noise scaling removes an extra galaxy's light from the fit without adding model complexity, by zeroing its data - and inflating its noise, but leaves its mass unaccounted for. +In this tutorial, we learned: -4. The `extra_galaxies` modeling API includes extra galaxies in the model with their own light and mass profiles, - with their centres fixed to the observed light centres to keep parameter space simple and well behaved. +1. An extra galaxy's light and mass affect the analysis in different ways and should be considered separately. +2. Noise scaling, introduced in chapter 2, can exclude contaminating light from constraining the fit, but does not + remove the galaxy's gravitational effect. +3. The `extra_galaxies` collection lets us include the light and mass profiles needed for each galaxy. +4. Measuring light centres first and fixing them in the model is a common practical workflow. It becomes + increasingly useful as the number of galaxies grows. +5. The appropriate treatment depends on the data and scientific goal, and should be checked through fit + diagnostics and comparisons between consistent modeling choices. -5. Which approach is appropriate depends on the interloper's distance from the lensed emission, its brightness, - and its mass's proximity to the lens. +Here, one galaxy remained the dominant lens, with a smaller nearby galaxy adding a complication. -Throughout, the extra galaxy was a nuisance: something to remove or account for, so that our analysis of the -main lens remained accurate. In the next tutorial we meet systems where that framing breaks down entirely, because -a second galaxy is not a nuisance but a co-equal lens, with light and mass comparable to the first. There, no -single galaxy is "the" lens, and the model must treat them all on an equal footing. +In the next tutorial, we consider systems where two or more galaxies contribute substantially to the lensing. +We will build models containing multiple main deflectors and explore the degeneracies between their mass +distributions. """ diff --git a/scripts/chapter_4_scaling_up_lensing/tutorial_2_multi_galaxy.py b/scripts/chapter_4_scaling_up_lensing/tutorial_2_multi_galaxy.py index b8e3380..2992b62 100644 --- a/scripts/chapter_4_scaling_up_lensing/tutorial_2_multi_galaxy.py +++ b/scripts/chapter_4_scaling_up_lensing/tutorial_2_multi_galaxy.py @@ -2,31 +2,25 @@ Tutorial 2: Multi-Galaxy Lenses =============================== -In the previous tutorial, we learned how to deal with extra galaxies near a strong lens — nuisance objects whose -light contaminates the data but which play no meaningful role in the lensing itself. We removed their emission -from the analysis, or gave them a heavily restricted model, and the single dominant lens galaxy remained the -star of the show. +In the previous tutorial, we modeled a system with one dominant lens galaxy and a smaller nearby galaxy. +We saw that the extra galaxy's light and gravitational deflections required separate consideration. -In this tutorial, we meet systems where that picture breaks down entirely: **multi-galaxy lenses**, where two -(or more) galaxies of comparable mass both contribute significantly to the lensing of a single background source. -Neither galaxy is a minor perturber we can mask away or simplify — they are **co-dominant deflectors**, and every -one of them needs its own free light and mass model. +We now consider **multi-galaxy lenses**, where two or more galaxies contribute substantially to the lensing of a +background source. Each significant deflector needs to be represented in the mass model, although we can still +fix or link appropriate parameters. -How do such systems arise physically? There are two main channels: +Such configurations can arise when galaxies at similar redshifts lie close together in projection, including +interacting or merging systems. They can also arise through chance alignments of galaxies at different redshifts. -- **Merging galaxies**: two galaxies at the same redshift caught in the act of merging, or orbiting one another - in close proximity. Their projected separation is small compared to the Einstein radius of their combined mass, - so the source's light rays feel both galaxies' gravity at once. Because both deflectors are at one redshift, - ray tracing is single-plane: their deflection angles simply add. +When we approximate the deflectors as lying at the same redshift, their deflection angles add on a single lens +plane. Deflectors at different redshifts require multi-plane ray-tracing, which accounts for how earlier deflections +change a ray's position at subsequent planes. -- **Chance line-of-sight alignments**: two physically unrelated galaxies at *different* redshifts that happen to - lie along the same line of sight. Light from the source is deflected first by the more distant galaxy, and the - already-deflected rays are deflected again by the nearer one. This is compound, multi-plane ray tracing — the - `Tracer` handles it natively by simply assigning each galaxy its redshift, and we will defer its details to - later in this chapter, where multi-plane lensing becomes the default at cluster scale. +In this tutorial, both lens galaxies are at the same redshift. We therefore focus on two modeling challenges: +the growing number of parameters and the degeneracies between the galaxies' mass distributions. -In this tutorial, both lens galaxies are at the same redshift, so we stay in the simpler single-plane regime and -focus on the modeling challenge that defines multi-galaxy lensing: the growth of the model's parameter space. +We will also reuse the practical workflow introduced in Tutorial 1: measure galaxy light centres first, then +use those positions to constrain the model. __Contents__ @@ -55,13 +49,16 @@ """ __Initial Setup__ -We begin with `Imaging` of a strong lens where **two** lens galaxies, separated by 2.0", both deflect the light -of a single background source: +We begin with an `Imaging` dataset containing two lens galaxies, separated by 2.0", which both deflect light from +a single background source. - - The two lens galaxies' light are `Sersic` profiles, centred at (0.0", -1.0") and (0.0", 1.0"). - - The two lens galaxies' mass distributions are `Isothermal` profiles with comparable Einstein radii (1.0" and - 0.8") — this comparability is what makes them co-dominant. - - The source galaxy's light is an `ExponentialCoreSph`. +- Their light follows `Sersic` profiles centred at `(0.0, -1.0)` and `(0.0, 1.0)`, using our usual `(y, x)` + coordinates in arcseconds. +- Their mass follows `Isothermal` profiles with Einstein-radius parameters of 1.0" and 0.8". +- The source light follows an `ExponentialCoreSph` profile. + +Both galaxies contribute substantially to the deflection field. Their individual Einstein-radius parameters +describe the two mass profiles; neither alone describes the critical curves of the combined system. __Dataset Auto-Simulation__ @@ -88,20 +85,24 @@ ) """ -When we plot the data, the difference from every lens we have modeled so far is obvious: there are two bright -lens galaxies, and the lensed source's arcs wrap around the *pair as a whole* rather than around either galaxy -individually. The mass distribution the source's light responds to is the sum of both galaxies' mass. +Plot the dataset and identify the two lens galaxies and the surrounding lensed source emission. + +The source is lensed by their combined deflection field, so we must interpret the image configuration using both +galaxies together. We cannot treat it as two independent single-galaxy lenses. + +Notice where the galaxies' light overlaps the source emission: our model will need to separate these contributions +while fitting the data. """ aplt.subplot_imaging_dataset(dataset=dataset) """ __Mask__ -We define a 3.0" circular mask. For a multi-galaxy lens, sizing the mask needs more care than at galaxy scale: -the Einstein radius that matters is that of the *combined* mass distribution, not either galaxy's individually. -A mask sized by eye from one galaxy's light would clip the arcs, which extend beyond both galaxies' centres. +We use a circular mask with radius 4.0", centred between the two lens galaxies. Inspect the masked dataset to check +that it retains the lensed source emission, including its fainter outskirts. For multi-galaxy lenses, choose the +fitting region from the full image configuration rather than either galaxy's individual Einstein radius. """ -mask_radius = 3.0 +mask_radius = 4.0 mask = al.Mask2D.circular( shape_native=dataset.shape_native, @@ -114,14 +115,19 @@ """ __Over Sampling__ -We use the adaptive over sampling scheme introduced in earlier chapters, which evaluates the steep central -regions of the lens galaxies' light at high resolution. The one multi-galaxy specific point is that the adaptive -grid is centred on **every** deflector, not just one — each galaxy has its own steep central light profile -needing accurate evaluation, and `centre_list` takes as many centres as we give it. +We use the adaptive over-sampling method introduced in earlier chapters to evaluate the galaxies' steep central +light profiles accurately. + +Here, we supply both galaxy centres through `centre_list`, so the higher-resolution sampling covers the central +region of each galaxy. -The two centres below are the observed centres of the two lens galaxies, which for this simulated dataset we -know exactly. For real data you would measure them from the image itself (the `autolens_workspace` provides a -GUI which writes them from mouse clicks). +This reuses the measured-position workflow from Tutorial 1. For real data, we can obtain the light centres using +a GUI, a source-detection tool or a preliminary light-profile fit. For this simulated dataset, we use the known +input positions. + +These positions currently determine where the grid receives finer sampling; supplying them to the over-sampling +function does **not** fix any model parameters. Later, we will explicitly fix the galaxies' mass centres to +these positions. """ lens_centres = [(0.0, -1.0), (0.0, 1.0)] @@ -139,31 +145,38 @@ """ __Model__ -We now compose the lens model, and here the multi-galaxy regime shows its teeth. Every co-dominant deflector -needs its own free light and mass model, so the model has one `Galaxy` entry per deflector. +We now build a model containing two lens galaxies and one background source. + +We loop over the measured lens-galaxy positions and create a separate `Galaxy` model for each deflector, named +`lens_0`, `lens_1`, and so on. This composition extends naturally to systems containing more galaxies. + +Each lens galaxy's light is represented by a Multi-Gaussian Expansion (MGE), using the +`al.model_util.mge_model_from` helper. This constructs the Gaussian basis using the approach introduced in chapter 2. -We build each lens galaxy in a loop over the observed centres and store them as `lens_0`, `lens_1`, etc. This -list-based composition scales to any number of deflectors, and it is the same API the `autolens_workspace`'s -`multi_galaxy` package (and the group-scale examples above it) use — so nothing needs re-learning later. +Each MGE contains 20 Gaussians with fixed widths, a shared centre and shared elliptical components. Their +intensities are solved by the linear inversion, leaving four non-linear light parameters per galaxy: two centre +coordinates and two elliptical components. -For each lens galaxy's light we use a Multi Gaussian Expansion (MGE) made of linear light profiles, built by the -utility function `al.model_util.mge_model_from` (this hides the longer `Basis` composition API we stepped through -in the linear profiles tutorial of chapter 2). For each lens galaxy's mass we use an `Isothermal` (SIE) profile, -initially with every parameter free. The source is also an MGE. +An MGE does not necessarily add any non-linear parameters. If its Gaussian widths are fixed, its centre is fixed +to the measured light position, and its Gaussians are spherical, only their intensities remain to be determined. +These are solved by the linear inversion, so the entire light model adds **zero non-linear parameters**, +regardless of how many Gaussians it contains. -The MGE choice matters more here than anywhere we have used it before. Each lens galaxy's 20 Gaussians add just -**4 non-linear parameters** (a shared centre and shared elliptical components — every `sigma` is fixed and every -`intensity` is solved for by the linear inversion). A single ordinary `Sersic` bulge would add 7 non-linear -parameters per galaxy, and would fit the blended, overlapping light of a close pair far less well. Because the -multi-galaxy regime multiplies whatever light model we choose by the number of deflectors, a light model that is -both cheap and flexible is close to essential — this is exactly where the MGE shines. +If we instead fit shared elliptical components while keeping the centre fixed, the MGE adds **two** non-linear +parameters. Freeing the shared centre as well increases this to **four**, as in the model used here. -Each Isothermal mass model adds 5 free parameters: its centre (2), elliptical components (2) and Einstein -radius (1). +An MGE offers flexibility when fitting overlapping galaxy light without sampling every Gaussian intensity. +Whether that flexibility is needed depends on the observed morphology; a simpler light profile can still be +appropriate. -An external shear would enter the model as a separate `MassField` through `fields=field`. It describes the tidal -field of structure *outside* the system, so it belongs to neither deflector. We omit it here to keep the parameter -accounting simple. +Each galaxy's mass is represented by an `Isothermal` profile, initially with five free parameters: two centre +coordinates, two elliptical components and an Einstein radius. The source light is also represented by an MGE. + +The measured positions locate the priors on the lens light centres; those centres remain free in this model. +We will explicitly fix the mass centres in the next step. + +We omit external shear in this example. If included, it would enter through a separate `MassField`, representing +an additional tidal contribution to the combined deflection field. """ lens_dict = {} @@ -198,53 +211,61 @@ model = af.Collection(galaxies=af.Collection(**lens_dict, source=source)) """ -The model's `info` shows `lens_0` and `lens_1` each carrying their own free mass model — the signature of the -multi-galaxy regime — and its `prior_count` gives the total number of free parameters. +The model's `info` shows the light and mass components of `lens_0` and `lens_1`, together with the source model. + +Inspect which parameters are free, which are fixed and which are shared between Gaussian profiles. We will use +`model.prior_count` below to count the free non-linear parameters. """ print(model.info) """ -The same model can also be visualized as a figure, making its structure easier to understand at a glance. +The figure shows the structure of our initial model. Each lens galaxy has its own `Isothermal` mass profile, +with free centre coordinates, elliptical components and Einstein radius. -The figure shows how the model is organized: which parameters belong to each component, and whether they are free, -fixed, shared, linked by an expression, solved during the fit, or not configured. `model.info` provides the -corresponding numerical details, including the prior assigned to each free parameter and the value of each fixed -parameter. +This is an intermediate model used to illustrate the parameter count. Before fitting, we will fix each mass +centre to its measured light position. -Each deflector has its own `mass · Isothermal` with a free `centre`, `ell_comps` and `einstein_radius`: two -independent, fully free mass models. That is the defining feature of this regime, and the thing every earlier -chapter lacked. +Compare the light and mass components: sharing parameters within an MGE reduces its dimensionality, but the two +galaxies still have separate light and mass models. """ af.ModelPlotter(model).figure() print(f"Free parameters (free mass centres): {model.prior_count}") """ -The count is **22**: each deflector contributes 4 (MGE light) + 5 (SIE mass) = 9 free parameters, and the MGE -source contributes the final 4. Compare this to the equivalent single-galaxy model, which has just 13 — one -co-dominant deflector added 9 parameters, and every further deflector will add 9 more. Model complexity compounds -fast in this regime, and with plain Sersic light profiles instead of MGEs it would compound faster still (12 per -deflector rather than 9). +The initial model has **22 free non-linear parameters**: + +- Each lens galaxy contributes four light parameters and five mass parameters. +- The source contributes four light parameters. + +The equivalent single-lens model would have 13. Adding the second deflector therefore adds nine parameters before +we impose further restrictions. __Fixing the Mass Centres__ -Before fitting, we make one change that is standard practice for multi-galaxy lenses: we **fix each galaxy's -mass centre to its observed light centre**, removing 2 free parameters per deflector. +We now fix each galaxy's mass centre to its measured light centre, removing two free parameters per deflector. + +This follows the common workflow introduced in Tutorial 1: measure galaxy positions from the image using a GUI, +a source-detection tool or a preliminary light-profile fit, then use those positions as fixed inputs to the lens +model. + +With multiple deflectors, the lensed images constrain their combined deflection field. Changes in one galaxy's +mass centre can sometimes be compensated by changes in another galaxy's position, ellipticity or mass +normalization. Fixing the centres reduces this freedom and can make the search more manageable. -Why? With a single lens galaxy, the data usually constrains the mass centre well: the arcs pin down where the -deflection field is centred, and there is only one plausible culprit. With multiple deflectors this breaks down. -The source's light responds to the *summed* deflection field, so a small shift of one galaxy's mass centre can be -compensated by shifts of the other's centre, ellipticity or Einstein radius — the free centres become extremely -degenerate with one another. The search wanders these degeneracies, converging slowly and often settling in -unphysical corners of parameter space where one galaxy's mass has drifted far from any light. +Here, we fix only the **mass centres**. The MGE light centres retain their existing priors and remain free, +allowing the light fit to refine their positions. The fixed mass positions are the supplied measurements; +they do not move with the fitted light centres. -Fixing each mass centre to the galaxy's light centre resolves this at minimal cost. Light traces stellar mass, -and the stellar body sits at the bottom of the galaxy's potential well, so the light centre is an excellent -estimate of the mass centre. (Measuring a genuine offset between mass and light — which interacting pairs can -show at the kiloparsec level — is real science, but it is a *follow-up* fit performed after a robust model with -fixed centres has been found.) +Fixing the mass centres alone does not reduce the MGE's parameter count: the current code still uses elliptical +MGEs with free light centres. A spherical MGE with fixed widths and a fixed light centre would instead add zero +non-linear light parameters, as described above. -Assigning a tuple to the mass model's `centre` fixes it, so it is no longer a free parameter with a prior. +This assumes that each mass distribution is centred on its measured light position. It is a useful starting +point, but does not establish that light and mass must be perfectly aligned. Where positional uncertainty or +possible offsets matter, we can allow appropriate freedom and investigate its effect. + +Assigning a coordinate tuple to `mass.centre` fixes both coordinates rather than assigning them priors. """ lens_dict = {} @@ -280,16 +301,23 @@ model = af.Collection(galaxies=af.Collection(**lens_dict, source=source)) """ -Printing the model's `info` again, each mass `centre` is now listed as a fixed value with no prior, and the -free parameter count has dropped from 22 to **18** — each SIE now contributes 3 free parameters instead of 5. +Printing the updated model's `info` shows that both mass centres are now fixed. + +Each `Isothermal` profile therefore has three free parameters: two elliptical components and one Einstein radius. +The light models are unchanged. + +Fixing two coordinates for each of two galaxies removes four parameters, reducing the total from **22 to 18**. """ print(model.info) """ -The two `mass · Isothermal` centres are now fixed to the measured light centres rather than sampled, and -nothing else about the model has changed: twenty-two free parameters down to eighteen. +The figure now shows each galaxy's mass centre fixed to its measured light position. + +Two fixed centres remove four non-linear parameters, reducing the model from 22 to 18. The MGE light centres and +elliptical components remain free, so each galaxy's light model still contributes four non-linear parameters. -Four centres fixed, four dimensions gone. That is the standard trick of the multi-galaxy regime. +Recall that a spherical MGE with fixed widths and a fixed light centre would contribute zero non-linear +parameters. We retain the more flexible elliptical light models here. """ af.ModelPlotter(model).figure() @@ -298,10 +326,15 @@ """ __Model Fit__ -We fit the model with the nested sampling algorithm `Nautilus`, as in previous chapters. Because this model has -more free parameters than the single-galaxy fits of chapter 2 (which used 100 live points), we raise `n_live` -to 200 — a multi-galaxy parameter space is more multi-modal, and too few live points risks converging on a local -maximum where the two galaxies' Einstein radii have been mis-apportioned. +We fit the model using `Nautilus`, as in previous chapters. + +With two deflectors, the search must explore correlations between their mass profiles as well as the source +parameters. We use 200 live points here, compared with 100 in our earlier examples, to give the search more scope +to explore this parameter space. + +Increasing the number of live points does not guarantee a reliable result. Inspect the fitted images and +posterior distributions, and check the stability of important conclusions using repeated searches or more +demanding search settings where needed. """ search = af.Nautilus( path_prefix=Path("howtolens", "chapter_4"), @@ -315,9 +348,9 @@ analysis = al.AnalysisImaging(dataset=dataset) print( - "The non-linear search has begun running - checkout the output/howtolens/chapter_4/tutorial_2_multi_galaxy" - " folder for live output of the results, images and model." - " This Jupyter notebook cell with progress once search has completed - this could take some time!" + "The non-linear search has begun. Check the output/howtolens/chapter_4/tutorial_2_multi_galaxy" + " folder for results and visualizations as the search progresses." + " This cell will finish when the search completes." ) result = search.fit(model=model, analysis=analysis) @@ -325,15 +358,27 @@ """ __Result__ -The result's `info` shows the inferred model, with each deflector's parameters listed under its own `lens_0` / -`lens_1` entry. +The result's `info` summarizes the inferred parameters and their uncertainties. The two deflectors appear +separately under `lens_0` and `lens_1`. + +Compare their inferred Einstein radii and elliptical components, remembering that the parameters of one galaxy +may be correlated with those of the other. The fixed mass centres are assumptions supplied to the fit, rather +than positions measured independently by this search. """ print(result.info) """ -The tracer subplot is worth a close look for a multi-galaxy lens: the critical curve is that of the *combined* -mass distribution, so it wraps around the pair as a whole rather than encircling either galaxy individually — -just as the arcs in the data do. +Inspect the tracer subplot to see how the two galaxies combine to lens the source. + +The critical curves belong to the combined lens mapping. Depending on the galaxies' masses, shapes and separation, +they can form connected or separate structures; they are not obtained by simply drawing an Einstein ring around +each galaxy. + +Then inspect the fit subplot. Check whether the model reproduces both galaxies' light and the lensed source +emission, and look for coherent residuals around the arcs or where the light components overlap. + +A satisfactory image fit is an essential check, but it does not establish that each galaxy's mass is individually +well constrained. We investigate that next using the posterior. """ aplt.subplot_tracer(tracer=result.max_log_likelihood_tracer, grid=result.grids.lp) @@ -342,48 +387,79 @@ """ __Mass Degeneracies__ -The corner plot of the posterior is where the multi-galaxy regime reveals its most important lesson. Below we -plot the probability density function of every parameter; when you run this tutorial for real (rather than -skimming the generated output), focus on the panel showing `lens_0`'s Einstein radius against `lens_1`'s. +Multiple significant deflectors introduce additional mass degeneracies beyond those encountered in single-galaxy +lenses. The lensed images constrain the galaxies' **combined deflection field**, so changes in one galaxy's mass +distribution can be compensated by changes in another's. + +Consequently, a model may reproduce the arcs accurately while leaving substantial uncertainty in how the mass is +divided between the galaxies. This is a major challenge of multi-galaxy modeling: a well-constrained combined lens +does not necessarily imply well-constrained individual galaxy masses. + +Single-galaxy lenses also have mass-source degeneracies, but multiple deflectors add freedom to redistribute mass +**between galaxies**. How severe this becomes depends on their separation and the positions and quality of the +lensed images. + +In the corner plot below, find the panel comparing the `einstein_radius` parameters of `lens_0` and `lens_1`. +Look for a correlation: can a larger mass normalization for one galaxy be compensated by a smaller normalization +for the other? + +Also inspect how these parameters correlate with the galaxies' elliptical components and the source parameters. +The degeneracy need not involve only the two Einstein radii. + +The shape and extent of these distributions tell us more about the uncertainty in the mass decomposition than a +single best-fit model can. """ aplt.corner_anesthetic(samples=result.samples) """ -You will see a strongly elongated, tilted degeneracy: the two Einstein radii are *anti-correlated*. When one -galaxy's Einstein radius goes up, the other's goes down, tracing out a narrow ridge in parameter space. +Look for an elongated distribution in the panel comparing the two Einstein-radius parameters. An anti-correlation +indicates that increasing one galaxy's mass normalization can be compensated by decreasing the other's. + +This illustrates the additional degeneracy introduced by multiple significant deflectors. The images respond to +the combined deflection field, so different allocations of mass between the galaxies can produce similar lensed +images. -The physical reason is the summed deflection field. The arcs constrain the **total** mass enclosed by the -combined Einstein ring extremely well — move along the ridge and the sum of the two galaxies' deflections barely -changes, so the fit to the data barely changes either. What the data constrains much more weakly is the **split** -of that mass between the two galaxies. The closer the pair (relative to the combined Einstein radius), the less -information the arcs carry about which galaxy the mass belongs to, and the longer the ridge grows. +The combined mass distribution can therefore be better constrained than its division between individual galaxies. +However, the strength and shape of this degeneracy depend on the configuration: arcs sampling different regions +around each galaxy can help distinguish their contributions. -This has a real scientific cost. For a single-galaxy lens, the Einstein mass is one of the cleanest measurements -in astrophysics. For a multi-galaxy lens, the total is still clean, but per-galaxy quantities — each galaxy's -mass, its mass-to-light ratio, its dark matter fraction — inherit the full width of the degeneracy, and their -error bars can be many times larger than the total's. Any interpretation built on the split (e.g. comparing the -two galaxies' dark matter content) must honestly propagate this, which is why we fit these systems with a -sampler that maps the full posterior rather than an optimizer that returns a single best-fit point: the best-fit -point sits somewhere on the ridge and tells you nothing about the ridge's length. +Single-galaxy lenses already have degeneracies involving the mass profile and source. Multi-galaxy lenses retain +these and introduce further freedom to redistribute mass between deflectors. Fixing their centres reduces that +freedom, but does not eliminate the degeneracy between their mass normalizations and shapes. + +This matters scientifically. Measurements of each galaxy's mass, mass-to-light ratio or dark matter fraction must +propagate the joint uncertainty, including correlations between galaxies. A single best-fit model cannot describe +the range of mass decompositions allowed by the data. __No Shared Halo__ -It is worth being explicit about an assumption we did *not* make. We modeled two galaxies, each with its own -untruncated `Isothermal` mass profile, and simply added their deflections. We did not assume the pair inhabits a -single, large, shared dark matter halo — and because there is no host halo in the model, we also made no -assumptions about tidal stripping or the truncation of each galaxy's individual halo. +So far, we have represented the lens using separate galaxy-centred mass profiles, without adding a larger dark +matter halo shared by the galaxies. + +Such a model may describe an interacting or merging pair of field galaxies, where a separate group-scale halo is +not needed to explain the lensing. This is particularly relevant for smaller-separation lens systems, with +Einstein radii of roughly a few arcseconds or less -- around 3" as an illustrative scale, rather than a strict +boundary. -At this scale, that is the right call: a pair (or triple) of comparable galaxies has no dominant halo for its -members to be stripped by, and the data cannot demand one. But climb the mass ladder and it changes. At the -group scale, a dominant group-sized halo enters the model as an explicit choice, and the member galaxies orbiting -within it are tidally truncated by its potential — assumptions that reshape the entire mass model, as we will -see later in this chapter. +Other systems are better described as members of a **galaxy group**, embedded in a common dark matter halo. The +Einstein radius alone does not establish which interpretation is appropriate; the galaxy environment and other +observations also matter. + +In the [group-scale tutorial](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_4_scaling_up_lensing/tutorial_4_group_scale.ipynb), +we extend the model by including a shared halo alongside the individual galaxies. We will explore how the lensing +signal is divided between these components and how to keep models containing many galaxies manageable. + +Omitting a shared halo here is therefore a modeling choice appropriate to our example, rather than a claim that +all galaxy pairs lack one. __Three Lens Galaxies__ -What happens when a third co-dominant deflector joins the system? Let us load a triple-galaxy lens, simulated -with three `Isothermal` mass profiles of comparable Einstein radii (0.9", 0.8" and 0.7") arranged in a triangle, -all lensing a single source. +We now load a simulated system containing three lens galaxies, each contributing substantially to the lensing of +one background source. + +Their `Isothermal` profiles have Einstein-radius parameters of 0.9", 0.8" and 0.7", with centres arranged in a +triangle. Plot the dataset and identify the three galaxies and the lensed source emission before composing the +model. """ dataset_name = "x3_lens_galaxies" dataset_path = Path("dataset") / "imaging" / dataset_name @@ -407,10 +483,16 @@ aplt.subplot_imaging_dataset(dataset=dataset) """ -We compose the three-deflector model with exactly the same loop as before — this is the payoff of the list-based -API, which needs no changes as the deflector count grows. Each mass centre is again fixed to its galaxy's -observed light centre; with three deflectors the centre degeneracies are even more severe than for the pair, so -the standard trick matters even more. +We build the three-deflector model using the same loop as before, now supplying three measured light positions. + +Each galaxy receives its own MGE light model and `Isothermal` mass profile. We again fix the mass centre to the +supplied light position while leaving the MGE light centre free within its priors. + +This illustrates why measuring positions before modeling is useful: adding another galaxy does not require the +search to discover where its mass profile belongs. + +The model still allows the galaxies' mass normalizations and shapes to compensate for one another. Fixing centres +makes the problem more manageable; it does not remove the mass-decomposition degeneracies. """ lens_centres = [(0.9, 0.0), (-0.6, -0.9), (-0.6, 0.9)] @@ -422,6 +504,15 @@ dataset = dataset.apply_mask(mask=mask) +over_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from( + grid=dataset.grid, + sub_size_list=[4, 2, 2], + radial_list=[0.3, 0.6], + centre_list=lens_centres, +) + +dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) + lens_dict = {} for i, centre in enumerate(lens_centres): @@ -458,60 +549,55 @@ print(model.info) """ -A third deflector, `lens_2`, is an identical copy of the structure above, with its own fixed mass `centre`. +The figure now includes `lens_2`, with the same model structure as the other two deflectors but its own parameters +and fixed mass position. + +Each galaxy contributes four non-linear light parameters and three non-linear mass parameters. Adding the third +galaxy therefore adds seven parameters. -Nothing about the *shape* of the model changed when we added a galaxy, which is exactly the point the -list-based API is making. The model grows by one deflector, and the parameter count by seven. +The code structure remains the same as the number of galaxies grows, but the inference problem becomes larger and +can develop stronger correlations between components. """ af.ModelPlotter(model).figure() print(f"Free parameters (three deflectors, fixed mass centres): {model.prior_count}") """ -The count is now **25**: even with fixed mass centres and cheap MGE light models, every deflector adds 7 free -parameters (4 light + 3 mass), and with free centres it would be 9. The trend is linear and unforgiving: +The three-galaxy model has **25 free non-linear parameters**: seven per lens galaxy and four for the source. - - 1 deflector: 13 free parameters. - - 2 deflectors: 18 (this tutorial's fit). - - 3 deflectors: 25. - - 10 deflectors: ~74. A group-scale lens can easily have this many members. +With the same model choices and fixed mass centres throughout: -And the parameter count is only half the problem. As the deflectors multiply, so do the degeneracies between -their masses — every pair of galaxies gets its own version of the Einstein radius ridge we saw above, and the -posterior becomes progressively harder for any sampler to map. +- One deflector: **11** parameters. +- Two deflectors: **18** parameters. +- Three deflectors: **25** parameters. +- Ten deflectors: **74** parameters. -You are welcome to fit this three-galaxy model yourself — the search above works unchanged, though expect it to -take noticeably longer than the pair. Clearly, freeing every galaxy's mass cannot scale to the tens or hundreds -of member galaxies in groups and clusters. Something has to give. +These counts depend on our light-model choices. Fixed-width, fixed-centre spherical MGEs would add zero non-linear +light parameters, reducing the totals substantially where that description is appropriate. -__Wrap Up__ +Even then, independently fitting every galaxy's mass normalization and shape becomes demanding as the population +grows. The challenge is both the number of parameters and the degeneracies between their contributions to the +combined deflection field. -In this tutorial, we modeled strong lenses with multiple co-dominant deflectors. Let's summarise what we've -learnt: +You can explore fitting the three-galaxy model by creating an `AnalysisImaging` for this newly loaded dataset and +running a search with a distinct output name. Reusing the earlier analysis object would incorrectly fit the +two-galaxy dataset. -- **Co-dominant deflectors**: When two or more galaxies of comparable mass both contribute significantly to the - lensing, every one of them needs its own free light and mass model — unlike the nuisance neighbours of the - previous tutorial, none can be masked away or simplified. - -- **Physical origins**: Multi-galaxy lenses arise from merging galaxies at one redshift (single-plane, deflections - add) or chance line-of-sight alignments at different redshifts (multi-plane ray tracing, covered later in this - chapter). - -- **Parameter growth**: Each deflector added 9 free parameters (4 for its MGE light, 5 for its SIE mass) — and the - MGE is what kept it that cheap, since its Gaussian intensities are solved for by linear algebra rather than sampled. - -- **Fixed mass centres**: Fixing each galaxy's mass centre to its observed light centre (removing 2 parameters per - deflector) is the standard trick for taming the severe centre degeneracies of multi-deflector models. - -- **Mass degeneracies**: The data constrains the total mass well but its split between the galaxies poorly, - producing an anti-correlated ridge between the deflectors' Einstein radii — and inflating the uncertainties on - any per-galaxy science. - -- **No shared halo**: At this scale we do not assume the galaxies inhabit one large dark matter halo, so no tidal - truncation assumptions enter the model — that framing arrives at group scale. +__Wrap Up__ -The three-galaxy model made the trajectory clear: freeing every deflector cannot scale. In the next tutorial, we -introduce the tool that stops this growth in its tracks — scaling relations, which tie the masses of many -galaxies to their observed luminosities so that an entire population of deflectors costs almost no extra free -parameters. +In this tutorial, we learned: + +- Multiple significant deflectors require a model of their combined lensing effect. +- Measuring galaxy positions first and fixing mass centres can reduce the search dimensionality and restrict + unwanted solutions. +- MGE intensities are solved linearly. A spherical MGE with fixed widths and centre adds no non-linear parameters; + our more flexible light models retain four per galaxy. +- Multiple galaxies introduce additional mass degeneracies beyond those in single-galaxy lenses. A good image fit + can leave substantial uncertainty in the individual galaxy masses. +- A shared halo and tidal truncation are modeling choices to assess for the system, rather than properties + determined solely by how many galaxies are present. + +As the number of galaxies increases, giving every galaxy an independent mass model becomes increasingly demanding. +In the next tutorial, we introduce **scaling relations**, which link galaxy mass properties to observed +luminosities through shared parameters. """ diff --git a/scripts/chapter_4_scaling_up_lensing/tutorial_3_scaling_relation.py b/scripts/chapter_4_scaling_up_lensing/tutorial_3_scaling_relation.py index 981468e..d494627 100644 --- a/scripts/chapter_4_scaling_up_lensing/tutorial_3_scaling_relation.py +++ b/scripts/chapter_4_scaling_up_lensing/tutorial_3_scaling_relation.py @@ -2,40 +2,38 @@ Tutorial 3: Scaling Relations ============================= -The previous tutorial ended on a warning: every deflector we add to a lens model brings its own free parameters. -Two galaxies were manageable, but each one cost us a mass profile's worth of dimensions, and the arithmetic only -gets worse. A group-scale lens may have ten member galaxies, a cluster hundreds. If every member keeps its own -free mass, the parameter space explodes — a 100-galaxy cluster with 5 free mass parameters per galaxy is a -500-dimensional model, which no non-linear search can sample and no dataset can constrain anyway. - -This tutorial introduces the tool that stops the explosion: the **scaling relation**. Instead of giving every -galaxy its own mass freedom, we set each galaxy's mass from something we can *measure* — its luminosity — via a -relation shared by the whole population. The relation itself has only a few global parameters (in this tutorial, -zero new ones!), so the dimensionality of the model stops growing with the number of galaxies. Ten members or a -hundred, the parameter space stays the same size. - -This pairs beautifully with a tool we already have. In chapter 2, we saw that a Multi-Gaussian Expansion (MGE) -fits a galaxy's light using linear algebra, so its intensities add no non-linear parameters. Put the two -together and the recipe for a many-galaxy lens model emerges: - -- **Light:** MGE for every galaxy — flexible light models at (almost) no non-linear cost. -- **Mass:** a scaling relation tying every galaxy's mass to its measured luminosity — a whole population of - mass profiles at no non-linear cost. - -The entire many-galaxy system then costs barely more than a single-lens fit. This tutorial builds that model on -the two-lens dataset from the previous tutorial, verifies the parameter counting explicitly, and is honest about -what a scaling relation assumes and when it can bite you. +In the previous tutorial, we saw how adding significant deflectors increases both the number of parameters and +the degeneracies between galaxy masses. Independently fitting the mass of every member becomes increasingly +demanding for groups and clusters. + +A **scaling relation** reduces this freedom by linking galaxy mass properties to measured luminosities through +a relation shared by the population. + +Here, one galaxy anchors the relation: its Einstein radius remains free, while the other galaxies' Einstein +radii follow from their luminosity ratios. With fixed positions, spherical mass profiles and a fixed scaling +exponent, each additional tied galaxy adds **zero non-linear mass parameters**. + +The light-model choices still matter. As we discussed in Tutorial 2, a spherical MGE with fixed widths and centre +adds zero non-linear light parameters. An elliptical MGE with a fixed centre and free shared elliptical +components adds two, as in this tutorial. + +Scaling relations therefore control the growth of the mass model; they do not automatically make every part of +a many-galaxy model independent of galaxy count. More galaxies also increase the computational work required to +evaluate the model. + +We will introduce the method using the familiar two-galaxy dataset, compare parameter counts and examine the +assumptions we impose when tying galaxy masses together. __Overview__ In this tutorial, we will: -- Explain the physics of why luminosity predicts lensing mass (mass-follows-light and the Faber-Jackson relation). +- Explain the assumptions linking luminosity to mass normalization through the Faber-Jackson relation. - Compose a lens model where one galaxy "anchors" the relation and the other galaxy's Einstein radius is tied to it via the ratio of their measured luminosities. -- Verify by explicit parameter counting that tied galaxies add zero free parameters, however many there are. +- Verify by explicit parameter counting that tied galaxies add zero additional non-linear mass parameters. - Fit the model and inspect how a tied parameter appears in the results. @@ -63,41 +61,54 @@ __Mass Follows Light__ -Why should a galaxy's luminosity tell us anything about its lensing mass? +Galaxy luminosity provides useful information about mass, but it does not determine an individual galaxy's mass +exactly. + +For early-type galaxies, the empirical **Faber-Jackson relation** links luminosity to stellar velocity dispersion. +A commonly used approximate form is: + +$$ +L \propto \sigma_\star^4. +$$ + +For a spherical isothermal lens, the Einstein radius is related to its mass-model velocity-dispersion parameter by: -The starting point is that light traces stars and stars trace mass. A more luminous elliptical galaxy contains -more stars, sits in a deeper potential well, and its stars therefore move faster. This is quantified by the -**Faber-Jackson relation**, an empirical scaling law for elliptical galaxies which states that luminosity grows -steeply with the velocity dispersion \sigma of the stars: +$$ +\theta_{\rm E} +=4\pi\left(\frac{\sigma_{\rm SIS}}{c}\right)^2 +\frac{D_{\rm ls}}{D_{\rm s}}, +$$ - L ~ \sigma^4 +where $D_{\rm ls}$ and $D_{\rm s}$ are angular-diameter distances from lens to source and observer to source. -Lensing connects \sigma to the deflection of light. For the isothermal mass profiles we have used throughout -these tutorials, the Einstein radius is set directly by the velocity dispersion: +Assuming that the mass-model velocity dispersion scales with the measured stellar velocity dispersion, galaxies +at the same lens redshift lensing the same source approximately satisfy: - \theta_E = 4 \pi (\sigma / c)^2 (D_ls / D_s) +$$ +\theta_{\rm E}\propto L^{1/2}. +$$ -where the D's are distances between observer, lens and source. So \theta_E ~ \sigma^2, and combining the two -scalings gives us a relation between the two things we care about — the Einstein radius we want to know and the -luminosity we can measure: +We therefore adopt: - \theta_E ~ \sigma^2 ~ (L^{1/4})^2 = L^{1/2} +$$ +\theta_{{\rm E},i} +=\theta_{{\rm E},{\rm anchor}} +\left(\frac{L_i}{L_{\rm anchor}}\right)^{0.5}. +$$ -If one galaxy in a lens system has a measured luminosity L_anchor and Einstein radius \theta_E_anchor, every -other galaxy's Einstein radius follows from its own luminosity: +This is a population-level modeling assumption. The exponent need not be universal, individual galaxies scatter +around the relation, and stellar and mass-model velocity dispersions are not automatically identical. - \theta_E_i = \theta_E_anchor * (L_i / L_anchor)^{0.5} +The phrase "mass follows light" here refers to linking mass normalization to luminosity. We are not requiring +the spatial mass distribution to have the same shape as the observed light. -This is the scaling relation we will build into the model below. The exponent 0.5 is the Faber-Jackson value; -more sophisticated versions exist (the "fundamental plane" adds a dependence on galaxy size and surface -brightness, tightening the relation), but the Faber-Jackson form captures the essential physics and is the -standard workhorse for lens modeling. It is the same idea that cluster lensing studies have used for decades: -tie the hundreds of cluster member galaxies to their luminosities via a scaling relation, so the model stays -tractable. +Only luminosity ratios enter this expression, so a common multiplicative calibration cancels. However, the +measurements must use a consistent waveband and luminosity definition. Changing waveband can change the ratios +because galaxies have different stellar populations and colours. -The crucial property is that only *ratios* of luminosity enter the relation. The absolute calibration, the -units, even the waveband cancel out (so long as all galaxies are measured consistently) — which is what makes -the relation so easy to apply in practice. +For galaxies at different redshifts, observed flux ratios are not directly luminosity ratios, and the +lensing-distance factors also differ. Our example avoids these complications by placing both deflectors at the +same redshift. """ from autolens import jax_wrapper # Sets JAX environment before other imports @@ -113,11 +124,17 @@ """ __Initial Setup__ -We use the same two-lens-galaxy imaging dataset as the previous tutorial, where: +We use the same two-galaxy imaging dataset as in Tutorial 2: - - Both lens galaxies' light are `Sersic` profiles. - - Both lens galaxies' mass distributions are `Isothermal` profiles. - - The source galaxy's light is an `ExponentialCoreSph`. +- Both lens galaxies have `Sersic` light profiles. +- Both have `Isothermal` mass profiles. +- The source light follows an `ExponentialCoreSph` profile. + +Reusing this dataset lets us compare independently fitted galaxy masses with masses linked through a scaling +relation. + +The simulated masses were specified independently, so we should check how closely they satisfy our adopted +relation rather than assume that they do. """ dataset_name = "x2_lens_galaxies" dataset_path = Path("dataset") / "imaging" / dataset_name @@ -149,10 +166,12 @@ """ __Mask__ -We define a 3.0" circular mask, which contains both lens galaxies (centred at (0.0", -1.0") and (0.0", 1.0")) -and the lensed source emission. +We use the same 4.0" circular mask as in Tutorial 2, centred between the two lens galaxies. + +Keeping the fitting region consistent helps us compare the effects of changing the model. Inspect the masked +subplot to check that the lensed emission we want to analyze is retained. """ -mask_radius = 3.0 +mask_radius = 4.0 mask = al.Mask2D.circular( shape_native=dataset.shape_native, @@ -164,22 +183,37 @@ aplt.subplot_imaging_dataset(dataset=dataset) -""" +r""" __Measured Luminosities__ -The scaling relation needs two inputs for every galaxy it touches: its centre and its luminosity. Neither is a -free parameter of the model — both are **measurements**, made from the imaging data before the mass model is -ever fitted. +Our relation uses a measured position and luminosity estimate for each galaxy. We treat these as fixed inputs +in this example. + +For real observations, positions and luminosities can come from a preliminary light-profile fit or a suitable +photometric catalogue. In blended systems, separating each galaxy's light from its neighbours and the lensed +source is an important part of this measurement. + +Magnitudes measured consistently in the same band can be converted to flux ratios using: + +$$ +\frac{F_i}{F_{\rm anchor}} +=10^{0.4(m_{\rm anchor}-m_i)}. +$$ -In a real analysis these come from a light-only fit performed first: for example, fitting an MGE to every -galaxy and integrating it to a total flux (the `autolens_workspace`'s scaling-relation SLaM pipeline does exactly -this). Because only luminosity *ratios* enter the relation, a magnitude catalogue from any survey works just as -well, converting via `L_i / L_anchor = 10 ** (0.4 * (m_anchor - m_i))`. +For galaxies at the same distance, with consistent photometric treatment, these provide the luminosity ratios +used here. -In this tutorial we take a shortcut available only with simulated data: the simulator saved the true galaxies to -a `tracer.json` file, so we load it and integrate each lens galaxy's true light profile directly. This keeps the -tutorial self-contained, but keep in mind that on real data this step is a fit to the data, with its own -(small) uncertainties. +Because this dataset is simulated, we can load the true light profiles from `tracer.json`. We obtain each +galaxy's centre and integrate its profile within a circular aperture of radius `mask_radius`, centred on that +galaxy. + +These are **aperture luminosities**, not integrals over the entire profile. Using the same aperture definition +makes the measurements consistent, but does not guarantee that the aperture contains the same fraction of every +galaxy's total light. + +This shortcut isolates the scaling-relation machinery. Real measurements have uncertainties from noise, blending +and light-model choices; treating their values as fixed does not propagate those uncertainties into the inferred +masses. """ tracer_true = al.from_json(file_path=dataset_path / "tracer.json") @@ -203,12 +237,19 @@ """ __The Anchor__ -The relation needs an "anchor": one galaxy whose Einstein radius is a free parameter of the model, off which -every other galaxy's Einstein radius hangs. We use the brightest galaxy, identified by `argmax` over the -measured luminosities — a measurement, not an assumption about which galaxy happens to be listed first. +We choose one galaxy as the **anchor**: its Einstein radius is a free parameter, and the other galaxies' Einstein +radii are linked to it through their measured luminosity ratios. + +Here, we select the galaxy with the largest measured aperture luminosity using `argmax`. This provides a +convenient reference; it does not establish that the brightest galaxy has a precisely known mass or must follow +the relation perfectly. + +The anchor's Einstein radius sets the normalization of the relation and is inferred from the lensing data. +Because it is already a parameter of the anchor's mass profile, tying additional galaxies to it introduces no +separate normalization parameter. -Anchoring on a galaxy the model is already fitting is the key trick: the anchor's `einstein_radius` is not a new -parameter, so the relation itself will add **zero** free parameters to the model. +We also fix the exponent to 0.5. Allowing the exponent or other properties of the relation to vary would add +shared parameters, rather than necessarily adding one parameter per galaxy. """ anchor_index = int(np.argmax(luminosities)) @@ -222,8 +263,11 @@ """ __Over Sampling__ -As in the previous tutorial, we apply adaptive over-sampling centred on both lens galaxies, so the steeply -varying central light of each is computed accurately. +As in Tutorial 2, we apply adaptive over-sampling around both measured galaxy centres so that their steep central +light profiles are evaluated accurately. + +These positions determine where the light calculation receives finer sampling. Fixing a light or mass profile's +centre remains a separate model-composition step, which we perform below. """ over_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from( grid=dataset.grid, @@ -237,19 +281,22 @@ """ __Light Via MGE__ -Every galaxy's light is modelled with a Multi-Gaussian Expansion, composed via the `al.model_util.mge_model_from` -convenience function (this wraps the `Basis` of linear `Gaussian` profiles we built by hand in chapter 2 into a -single call — the composition it returns is the same). +We represent each lens galaxy's light with an MGE, constructed using `al.model_util.mge_model_from`. + +We fix its centre to the measured light position. The Gaussian widths are also fixed, and their intensities are +solved by the linear inversion. + +If the Gaussians were spherical, this would leave **zero non-linear light parameters**, regardless of the number +of Gaussians. + +Here, we retain two free elliptical components shared by the Gaussians, allowing the light model to be flattened +and rotated. Each galaxy therefore contributes **two non-linear light parameters**. -Because the galaxy centres were measured above, we fix each MGE's centre to them (passing the measured centre as -both the `centre` and `centre_fixed` inputs, which fixes it rather than giving it a prior). The Gaussian -`sigma` values are fixed by the basis and the intensities are solved for by linear algebra, so each galaxy's -light costs just **two** non-linear parameters: its elliptical components. This is the "light adds (almost) no -parameters" half of the recipe from the introduction. +The anchor also receives an elliptical `Isothermal` mass profile with its centre fixed to the measured position. +Its two elliptical components and Einstein radius remain free. -The anchor galaxy also gets its mass: a free `Isothermal` profile with its centre fixed at the measured light -centre. Its `einstein_radius` is an ordinary free parameter — but it is also what the scaling relation below -hangs off. +The anchor's Einstein radius serves two purposes: it determines the normalization of its own mass profile and +sets the normalization of the scaling relation for the other galaxies. """ bulge_anchor = al.model_util.mge_model_from( mask_radius=mask_radius, @@ -270,7 +317,11 @@ ) """ -The source galaxy is also an MGE, with a free centre (we have no pre-measured position for the unlensed source). +The source is also represented by an MGE, but its centre remains free because its unlensed position is inferred +through the lens model. + +Its Gaussian widths are fixed and its intensities are solved linearly. The shared centre coordinates and +elliptical components contribute four non-linear source parameters. """ source_bulge = al.model_util.mge_model_from( mask_radius=mask_radius, @@ -281,25 +332,40 @@ source = af.Model(al.Galaxy, redshift=1.0, bulge=source_bulge) -""" +r""" __Scaling Relation__ -Now the relation itself. The fainter galaxy's mass is a spherical isothermal profile whose `einstein_radius` is -not given a prior — instead, it is *assigned an expression*: the anchor's `einstein_radius` multiplied by the -luminosity ratio raised to the Faber-Jackson exponent of 0.5. +We now assign the other galaxy a spherical `IsothermalSph` mass profile and fix its centre to the measured +light position. + +Rather than assigning its `einstein_radius` an independent prior, we express it in terms of the anchor's: + +$$ +\theta_{{\rm E},i} +=\theta_{{\rm E},{\rm anchor}} +\left(\frac{L_i}{L_{\rm anchor}}\right)^{0.5}. +$$ + +Whenever the search proposes an Einstein radius for the anchor, the tied galaxy's Einstein radius follows +automatically. It is a **derived parameter**, with no independent sampling dimension. + +Three choices together give this galaxy zero non-linear mass parameters: its centre is fixed, its profile is +spherical, and its Einstein radius is tied to the anchor. The scaling relation itself removes only the independent +Einstein-radius parameter; fixing the centre and adopting a spherical profile provide the other reductions. + +Its elliptical MGE still contributes two non-linear light parameters. A spherical MGE with fixed widths and +centre would reduce that light contribution to zero as well. -This single line is the whole trick. Because `mass_anchor.einstein_radius` is the model's own free parameter, -multiplying it by a fixed number produces a **derived quantity**, not a new parameter. Whenever the non-linear -search proposes an Einstein radius for the anchor, every tied galaxy's Einstein radius follows automatically. +We use this familiar two-galaxy dataset to demonstrate the machinery. However, both galaxies contribute +substantially to the lensing, so tying their masses imposes a strong restriction on a quantity the previous +tutorial allowed the data to constrain. -The tied galaxy keeps its MGE bulge (its light is inside the mask and must be fitted), so it costs two light -parameters and **zero** mass parameters. +An independent mass model provides a useful comparison for such important deflectors. A scaling relation may be +appropriate when supported by the scientific assumptions, but its apparent precision must not be mistaken for +information supplied entirely by the lensing data. -An honest aside before we continue: this dataset's two galaxies are comparably bright, and for a genuine system -of two co-dominant deflectors the previous tutorial's model — full mass freedom for both — is the right choice. -A galaxy contributing half the lensing deserves its own parameters. We tie one here so you can learn the -machinery on a familiar dataset; the regime where the relation genuinely earns its keep is a *population* of -fainter members, which we build towards below and which dominates the next tutorial. +The simplification becomes especially useful for populations of less influential galaxies. We can tie that +population while retaining independent mass parameters for galaxies whose contributions need more flexibility. """ scaling_exponent = 0.5 @@ -330,14 +396,16 @@ """ __Model__ -The model has two top-level collections: `galaxies` (the anchor and the source) and `scaling_galaxies` (the tied -population). This is not just presentational — `scaling_galaxies` is the collection name **PyAutoLens** expects a -scaling population in: the analysis appends it to the tracer's galaxy list when fitting, and results loaded back -via the aggregator restore it. It also keeps `model.info` readable, with the tied population visibly separate -from the freely modelled galaxies. +We assemble the model using two collections: -Inspecting `model.info` below, note that the tied galaxies have no `einstein_radius` prior of their own — it is -listed as a function of the anchor's. +- `galaxies` contains the anchor lens galaxy and the source. +- `scaling_galaxies` contains the galaxies whose mass normalizations follow the scaling relation. + +Both collections contribute to the lens model. Keeping the tied population separate makes its role easier to +inspect and follows the convention used in the workspace examples. + +Inspect `model.info` below. The tied galaxy's `einstein_radius` is expressed in terms of the anchor's parameter +rather than assigned an independent prior. """ model = af.Collection( galaxies=af.Collection(lens=lens_anchor, source=source), @@ -347,24 +415,36 @@ print(model.info) """ -The same model can also be visualized as a figure, making its structure easier to understand at a glance. +The figure shows how the tied galaxy's Einstein radius depends on the anchor's. -The figure shows how the model is organized: which parameters belong to each component, and whether they are free, -fixed, shared, linked by an expression, solved during the fit, or not configured. `model.info` provides the -corresponding numerical details, including the prior assigned to each free parameter and the value of each fixed -parameter. +It has no independent prior or sampling dimension, but it remains a parameter of the galaxy's mass profile. Its +value changes as the search varies the anchor's Einstein radius. -The tied galaxy's `einstein_radius` is not sampled at all. It is computed from the anchor lens galaxy's via the -scaling relation, so it has no prior, because it is not a parameter. +With fixed luminosity ratios and a fixed exponent, uncertainty in the anchor propagates directly to the tied +Einstein radius. This does not include uncertainty in the luminosity measurements or intrinsic scatter around +the scaling relation. """ af.ModelPlotter(model).figure() """ __Parameter Counts__ -Let's verify the claims above by counting, rather than believing. First we recompose the previous tutorial's -style of model on this dataset — every galaxy with its own free elliptical `Isothermal` mass (centres fixed at -the measured light centres, as above, so the comparison is like-for-like). +We now compare models with different amounts of mass freedom. + +First, we give each lens galaxy an independent elliptical `Isothermal` mass profile with a fixed centre. We +retain the same fixed-centre MGE light models and the same source model used above. + +Each lens galaxy then contributes two non-linear light parameters and three mass parameters. Including the +source's four parameters gives **14** in total. + +Our scaling-relation model has **11**: five for the anchor's light and mass, two for the tied galaxy's light, +and four for the source. + +The reduction from 14 to 11 combines two changes to the second galaxy: adopting a spherical mass profile removes +two elliptical components, and tying its Einstein radius removes one further parameter. + +This comparison differs from Tutorial 2's 18-parameter model because we have also fixed both lens galaxies' +light centres here. """ per_galaxy_lens_dict = {} @@ -389,15 +469,21 @@ ) print( - f"Free parameters, per-galaxy model (previous tutorial): {model_per_galaxy.prior_count}" + f"Free parameters, independent elliptical masses: {model_per_galaxy.prior_count}" ) print(f"Free parameters, scaling-relation model: {model.prior_count}") """ -The scaling-relation model is smaller. To isolate exactly what the relation saves, we compose one more variant: -identical to the scaling-relation model in every way, except each tied galaxy's `einstein_radius` is freed with -a uniform prior instead of tied. The difference in parameter count must equal the number of tied galaxies — -one saved `einstein_radius` each. +To isolate the effect of the scaling relation itself, we build another model with exactly the same profiles, +fixed centres and light-model choices as the tied model. + +The only change is that the second galaxy's Einstein radius receives an independent uniform prior instead of +being linked to the anchor. + +This model has **12** free non-linear parameters, compared with **11** for the tied model. The scaling relation +therefore saves one parameter for this one tied galaxy. + +The assertion below checks that the difference equals the number of tied galaxies. """ freed_galaxies_list = [] @@ -432,13 +518,29 @@ """ __Scaling To Many Galaxies__ -Saving one parameter looks modest — the point is what happens as the population grows. Below we imagine this -lens had twelve additional member galaxies (we invent centres on a ring and plausible luminosities; this model -is composed for counting only, **not** fitted — our dataset contains no such galaxies!). +Saving one parameter becomes more consequential when we model a population of galaxies. + +Below, we add twelve hypothetical members with specified positions and luminosities. These galaxies are not +present in our simulated image: we construct these models only to compare parameter counts, and do not fit them +to the data. + +Each additional member receives a spherical mass profile with a fixed centre. In one model, its Einstein radius +follows the anchor through the scaling relation. In the comparison model, its Einstein radius has an independent +prior. -Each imagined member is mass-only (faint distant perturbers whose light is negligible or outside the mask need -no light model — the mass-only counterpart of the intermediate options tutorial 1 discussed), with its Einstein -radius tied to the anchor by the same relation. We count the parameters of this 14-galaxy lens model, and of its nightmare per-galaxy twin. +We omit light profiles for these hypothetical members to isolate the mass-parameter count. In a real analysis, +their light would need to be assessed separately, as in Tutorial 1. Being a faint or secondary deflector does +not automatically make its light negligible. + +The original two-galaxy model is unchanged in both comparisons. In particular, its original tied galaxy remains +tied; only the twelve additional members differ. + +The tied model therefore remains at **11** non-linear parameters, while giving the twelve new members independent +Einstein radii increases the count to **23**. + +This demonstrates a constant mass-parameter count under our chosen restrictions. Evaluating the extra deflections +still adds computational work, and any additional light-model freedom or per-galaxy scatter parameters would +need to be counted separately. """ total_members = 12 @@ -486,20 +588,28 @@ f"Free parameters, 14-galaxy scaling model: {model_many_tied.prior_count}" ) print( - f"Free parameters, 14-galaxy per-galaxy-mass model: {model_many_freed.prior_count}" + f"Free parameters, 12 additional members with free Einstein radii: {model_many_freed.prior_count}" ) assert model_many_tied.prior_count == model.prior_count """ -Twelve more galaxies, zero more parameters. The tied model's dimensionality is *independent of the number of -galaxies* — this is the property that makes group- and cluster-scale lens modeling possible at all, and it is -why the assertion above is worth having in the script rather than in prose. +Adding twelve mass-only galaxies through the fixed scaling relation leaves the non-linear parameter count +unchanged. Their positions are fixed, their profiles are spherical, and their Einstein radii all depend on the +existing anchor parameter. + +This does not mean the additional galaxies are computationally free: their deflections must still be evaluated. +It also does not include any extra freedom we might introduce for their light, positions or deviations from +the relation. __Model Fit__ -We now fit the scaling-relation model to the data, using the familiar `Nautilus` search and `AnalysisImaging` -object. The parameter space is barely larger than a single-lens fit, which is the whole point. +We now fit the original **two-galaxy scaling-relation model** to the data. The twelve hypothetical members were +used only for the parameter-counting exercise and are not included in this fit. + +We use the familiar `Nautilus` search and `AnalysisImaging` object. The model has 11 non-linear parameters, but its +smaller parameter space reflects stronger assumptions about the galaxies as well as fewer independent +quantities to infer. """ search = af.Nautilus( path_prefix=Path("howtolens") / "chapter_4", @@ -513,32 +623,46 @@ analysis = al.AnalysisImaging(dataset=dataset) print( - "The non-linear search has begun running - checkout the output/howtolens/chapter_4/tutorial_3_scaling_relation" - " folder for live output of the results, images and model." - " This Jupyter notebook cell with progress once search has completed - this could take some time!" + "The non-linear search has begun. Check the output/howtolens/chapter_4/tutorial_3_scaling_relation" + " folder for results and visualizations as the search progresses." + " This cell will finish when the search completes." ) result = search.fit(model=model, analysis=analysis) -print("The search has finished run - you may now continue the notebook.") +print("The search has finished — you may now continue the notebook.") """ __Results__ -In `result.info`, the tied galaxy has no `einstein_radius` entry of its own — it is reported as a derived -function of the anchor's, which is what a tied parameter looks like in the output. Its posterior uncertainty -comes entirely from the anchor's. +Inspect `result.info` and the maximum log likelihood fit below. + +The tied galaxy's Einstein radius is derived from the anchor's Einstein radius through the fixed luminosity +ratio and exponent. It has no independently sampled prior. + +Its inferred uncertainty therefore reflects uncertainty in the anchor within this model. It does not include +measurement uncertainty in the luminosity ratio, uncertainty in the exponent or intrinsic scatter around +the relation. + +Check the residuals around both galaxies and the lensed source. A compact model is useful only if its assumptions +provide an adequate description of the data. """ print(result.info) aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) """ -The fit is good — but we should ask *why* it is good, because the answer is the honest heart of this tutorial. +Because this dataset is simulated, we can check how closely the input galaxy masses satisfy the relation we +imposed. -The tied model can only fit well if the true galaxies actually lie close to the relation we imposed. We can -check, because this is simulated data and we know the truth. Below we compare the fainter galaxy's true Einstein -radius against the value the relation predicts from the anchor's true Einstein radius and the luminosity ratio. +Below, we use the anchor's true Einstein radius and the measured aperture-luminosity ratio to predict the other +galaxy's Einstein radius, then compare that prediction with its true value. + +This tests the mass-normalization relation. It does not test every assumption in the fitted model: for example, +the simulated second galaxy has an elliptical mass profile, while our tied model represents it as spherical. + +A visually satisfactory fit would not by itself demonstrate that either assumption is exact. Other parameters +may compensate for an imperfect scaling relation or profile choice. """ einstein_radii_true = [ float(galaxy.mass.einstein_radius) for galaxy in lens_galaxies_true @@ -555,73 +679,75 @@ ) r""" -The prediction lands within a few percent of the truth: this simulated pair happens to sit almost exactly on the -Faber-Jackson relation. That is why the tied fit succeeds. Real galaxies are not always so obliging. +Use the printed values to assess the agreement for this dataset and our chosen luminosity aperture. The +simulated masses were specified independently, so agreement with the scaling relation is something to check, +rather than a built-in guarantee. __Limitations__ -A scaling relation is an assumption, and it is worth being clear-eyed about what we assumed: - -**Scatter.** Faber-Jackson is a statistical relation with real intrinsic scatter — at fixed luminosity, -galaxies show a spread in velocity dispersion, and therefore in Einstein radius. A tied model has no freedom to -absorb this scatter: it asserts every member sits exactly on the relation. For a population of faint members -whose individual lensing effects are small, the errors average down and this is fine. For any single galaxy -that matters a lot to the fit, it is a risk. - -**Deviant members.** Worse than scatter is a member that is systematically off the relation — a tidally -stripped satellite that has lost dark matter but kept its stars, a galaxy with an unusual mass-to-light ratio, -or a misclassified foreground/background interloper assigned a luminosity at the wrong distance. Because the -tied model *cannot* adjust that one galaxy, the non-linear search compensates the only way it can: by biasing -the parameters it does control — the anchor's mass, the source — dragging the whole lens model away from the -truth. One bad member can poison an otherwise excellent fit, and nothing in the residuals will neatly point at -the culprit. - -**The anchor itself.** Anchoring on the brightest galaxy assumes the anchor sits on the relation too. If it is -the anomalous one, every tied galaxy inherits its anomaly. - -The defence against all three is **selective freedom**. The tiers can be mixed within one model: keep the long -tail of faint members tied, but promote any galaxy that is bright, close to the lensed images, or visibly -suspicious to its own free mass profile — exactly as the extra galaxies were treated earlier in this chapter. A -middle option bounds a member's free Einstein radius using its luminosity (free, but only within a factor of the -relation's prediction). And the relation itself can be loosened: freeing `scaling_exponent` as a fit parameter -costs a single dimension *for the entire population* and is a useful systematics test. The `autolens_workspace`'s -`imaging/features/scaling_relation` example shows all of these tiers working together. +A scaling relation reduces parameter freedom by introducing assumptions about the galaxy population. -__Lens Environments__ +**Intrinsic scatter.** Real galaxies do not lie exactly on a single luminosity-mass relation. Our deterministic +model allows no independent deviation for a tied member. Even when individual members have small effects, their +modeling errors do not necessarily cancel: the lensing impact depends on where those galaxies lie relative to +the images. -Everything above was framed around lenses with multiple deflectors, but the same machinery solves a problem we -met at the start of this chapter: the **environment** of an ordinary single-galaxy lens. +**Measurements and membership.** Luminosities and centres have measurement uncertainties, especially in blended +images. Incorrectly assigning a foreground or background galaxy to the lens population can also give it an +inappropriate luminosity and lensing geometry. -The first tutorial of this chapter modelled a nearby extra galaxy individually, which was fine for one. -But a deep image of a real lens can reveal dozens of galaxies near the line of sight, each contributing a small -perturbation to the deflection field. Modeling them individually is hopeless; ignoring them entirely can bias -precision measurements. With a scaling relation they cost nothing: measure each galaxy's centre and luminosity -from the image, tie the lot to the main lens galaxy (which is the natural anchor — it is usually the brightest -galaxy in the field), and the model gains dozens of physically motivated perturbers with zero added parameters. +**The adopted profiles.** We assume spherical mass profiles for tied members. Deviations in shape, radial +structure or tidal truncation can matter independently of whether the luminosity-normalization relation is +accurate. -__Wrap Up__ +**The anchor.** The anchor's fitted Einstein radius normalizes the entire population. If the anchor is not +representative of that population, the imposed relation can give inappropriate masses to other members. -In this tutorial we learned: +These restrictions can lead to biased inferences or uncertainties that are too small. Residuals are useful +diagnostics, but a good image fit does not guarantee that the assumed mass decomposition is correct. -1. Luminosity predicts lensing mass, via mass-follows-light arguments and the Faber-Jackson relation - (`L ~ \sigma^4`, `\theta_E ~ \sigma^2`, hence `\theta_E ~ L^{0.5}`). +A practical response is **selective freedom**: retain the scaling relation for a population of less influential +members while giving important galaxies independent mass parameters. Galaxies close to the lensed images may +warrant this even when they are faint. -2. A scaling relation replaces per-galaxy mass freedom with a shared relation anchored on a parameter the model - already fits, so tied galaxies add **zero** free parameters — verified by explicit parameter counting. +Other approaches include fitting shared normalization or slope parameters, or explicitly modeling scatter. +Each changes the assumptions and parameter count, and should be assessed against the scientific goal and +available constraints. + +__Lens Environments__ + +Scaling relations are also useful for the environment of a lens dominated by one galaxy. A population of nearby +galaxies can collectively perturb the lensing, even when no single member is a major deflector. + +For galaxies belonging to the same physical population at approximately the same redshift, measured positions +and consistent luminosities can support a shared relation. The main lens can serve as an anchor if that +assumption is appropriate; it need not always be the best reference. + +Galaxies projected nearby on the sky are not necessarily members of that population. Foreground and background +galaxies require appropriate redshifts, luminosity estimates and lensing-distance factors. We should not tie them +to the main lens using observed flux ratios alone. + +As throughout this chapter, their light and mass require separate consideration. A mass-only member adds no light +parameters, but its emission must still be negligible, excluded appropriately or modeled. + +__Wrap Up__ -3. Combined with MGE light profiles, a many-galaxy lens model stays low-dimensional: dimensionality is - independent of the number of galaxies. +In this tutorial, we learned: -4. The relation is an assumption: scatter and deviant members can bias the whole model, and the remedy is - selective freedom — tie the faint majority, free the important few. +1. A luminosity-based scaling relation links galaxy mass normalizations through shared assumptions, rather than + measuring each mass independently. +2. With fixed centres, spherical mass profiles, a fixed exponent and an existing anchor parameter, additional + tied galaxies add zero non-linear mass parameters. +3. Light-model freedom must be counted separately. Fixed-centre elliptical MGEs add two parameters per galaxy; + fixed-centre spherical MGEs with fixed widths add none. +4. Reduced dimensionality does not remove computational cost or uncertainty associated with the relation's + assumptions. +5. Important galaxies can retain independent mass freedom while less influential members follow a shared relation. -5. The same machinery models the environments of single-lens systems, at no parameter cost. +In the next tutorial, we move to **group-scale lensing**, adding a shared dark matter halo alongside the +member galaxies. -So far, we tied galaxy to galaxy. But the biggest lenses in the Universe — galaxy groups and clusters — contain -something the galaxies themselves cannot account for: a massive dark matter halo enveloping the whole system, -holding most of its mass. In the next tutorial we step up to group-scale lenses, where the scaling relation -becomes essential (there are simply too many member galaxies to free) and a dark matter halo joins the model as -a new component. There, we will also meet a different way to normalise the relation — a shared free -normalization at a fixed reference luminosity, rather than an anchor galaxy — and truncated mass profiles, which -describe members whose outer dark matter has been tidally stripped by the very halo we are adding. +We will also introduce a relation normalized at a fixed reference luminosity, rather than anchored to one galaxy, +and truncated mass profiles for describing member galaxies whose outer mass distributions may have been altered +by tidal stripping. """ diff --git a/scripts/chapter_4_scaling_up_lensing/tutorial_4_group_scale.py b/scripts/chapter_4_scaling_up_lensing/tutorial_4_group_scale.py index fb998b8..cbf94a4 100644 --- a/scripts/chapter_4_scaling_up_lensing/tutorial_4_group_scale.py +++ b/scripts/chapter_4_scaling_up_lensing/tutorial_4_group_scale.py @@ -2,52 +2,50 @@ Tutorial 4: Group Scale ======================= -In the previous tutorials we took our first steps beyond the single lens galaxy: we included extra galaxies near -the lens in the model, we modeled systems where two or more galaxies of comparable mass share the lensing, and we -introduced scaling relations, which tie the mass of a galaxy to its light so that adding more galaxies to a model -does not mean adding more free parameters. - -In this tutorial we put all of those tools together and take the first big step up the "regime ladder" of strong -lensing: the **group scale**. - -In the standard cosmological model (Lambda Cold Dark Matter, or LCDM), galaxies do not live in isolation. They -form and evolve inside "dark matter halos", and these halos are themselves nested: small halos hosting single -galaxies merge and fall into larger halos hosting many. A **galaxy group** is the next rung above a single -galaxy in this hierarchy: a dark matter halo of roughly 10^13 to 10^14 solar masses hosting anywhere from a -handful to a few dozen galaxies. (Our own Milky Way lives in such a structure, the Local Group.) Above groups -sit **galaxy clusters**, halos of 10^14 solar masses and beyond hosting hundreds or thousands of galaxies, which -are the subject of the next tutorial. - -When a group acts as a strong lens, several of its galaxies contribute significantly to the deflection of the -source's light. The brightest galaxy of the group -- called the brightest group galaxy (BGG), or the brightest -cluster galaxy (BCG) at cluster scale -- typically sits near the centre of the group's dark matter halo and -dominates the lensing. The other group members perturb the lensed image around it. The group's shared dark -matter halo may also enter the mass model as its own component, often centred on the BGG where one exists -- -though as we will see, whether it is needed is an explicit modelling choice, not an automatic ingredient. +The previous tutorials introduced nearby galaxies, multiple significant deflectors and scaling relations. We now +combine these ideas to model a **group-scale lens**. + +A galaxy group contains galaxies associated with a larger gravitationally bound structure. Its lensing signal +can include contributions from a shared dark matter halo, a central galaxy and other member galaxies. + +The brightest group galaxy is often called the **BGG**. In some groups it lies near the centre of the shared halo +and contributes strongly to the lensing. Other groups have several prominent galaxies or a less clearly defined +centre. + +Our example contains one dominant central component, two member galaxies and one background source. We will +introduce truncated member-galaxy mass profiles, compare independent member masses with a scaling relation, and +use Bayesian evidence to compare models with and without an explicit NFW dark matter halo. __Groups vs Multi-Galaxy Lenses__ -You may now be wondering how a "group-scale lens" differs from the multi-galaxy lenses of the previous tutorials, -and the honest answer is that the line between them is **blurry**. Every group is a multi-galaxy lens: it has -multiple galaxies whose mass matters for the lensing. But not every multi-galaxy lens is a group: two galaxies of -comparable mass that happen to sit close on the sky (or are mid-merger) share the lensing without being embedded -in a massive shared halo with a member population. +The distinction between group-scale and multi-galaxy lensing is not a strict boundary in galaxy count or Einstein +radius. -The physically meaningful distinction is the **environment**: a group has a shared dark matter halo, a dominant -central galaxy, and members orbiting inside the host's potential. That environment leaves signatures in the mass -model, and the most important one is **tidal truncation**, which we introduce below. +As discussed in Tutorial 2, an interacting or merging pair of field galaxies may be modeled without a separate +group-scale halo. Other systems inhabit a shared halo whose contribution matters for interpreting the lensing. + +The important questions are which mass components contribute to the observed images and whether the data can +distinguish them. A mass profile centred on the BGG can describe the combined central mass without separately +identifying the contributions of the galaxy and the group halo. + +We therefore distinguish **including the group's gravitational effect** from **representing its halo as a +separate model component**. Our initial model uses a central total-mass profile; later, we examine an additional +halo component. __Tidal Truncation and the dPIE Profile__ -A galaxy orbiting inside a group does not keep its full dark matter halo. The tidal field of the host group -strips the outer, loosely bound parts of the member's halo, so the member's mass distribution is cut off -- or -"truncated" -- at a finite radius. The isothermal profiles we have used so far are a poor description of this: -their density falls as 1/r^2 forever, so their total mass diverges with radius. +Galaxies orbiting within a group can lose material from their outer dark matter halos through tidal stripping. +The extent of this stripping depends on their orbits, internal structure and interaction history. + +The isothermal profiles used so far extend indefinitely and have divergent total mass. They can describe lensing +over a limited radial range, but do not represent a finite outer halo. -The standard truncated profile of group- and cluster-scale lensing is the **dPIE** (dual Pseudo-Isothermal -Elliptical) profile, available in **PyAutoLens** as `al.mp.dPIEMassSph`. It behaves isothermally at intermediate -radii but its density falls off much more steeply beyond a truncation radius, giving it a finite total mass -- -exactly the behaviour we expect for a tidally stripped group member. +The **dPIE** profile provides a useful alternative. It has an approximately isothermal region and steepens smoothly +beyond a characteristic truncation scale, giving it finite total mass. + +We use its spherical implementation, `al.mp.dPIEMassSph`, for the member galaxies. Its truncation scale lets us +represent a reduced outer mass distribution, although adopting this profile does not by itself measure a +galaxy's stripping history. __Contents__ @@ -56,8 +54,10 @@ - **Galaxy Centres:** Load the centres of the BGG and member galaxies from .json files. - **The dPIE Profile:** Introduce the truncated dPIE mass profile and its parameters. - **Fitting a Group:** Fit the data with a tracer containing the BGG, members and source. -- **A Group Halo?:** Add a group-scale dark matter halo to the tracer and see how it changes the fit. -- **Model Fit:** Compose and fit a group-scale lens model with individually modeled members. +- **A Group Halo?:** Motivate a shared NFW dark matter halo and define two models to compare. +- **Model Fit:** Compose and fit the galaxy-only model with individually modeled members. +- **Fit With a Shared NFW Dark Matter Halo:** Refit with an additional NFW halo and unchanged galaxy priors. +- **Bayesian Model Comparison:** Compare the evidences of the galaxy-only and galaxy-plus-halo models. - **Scaling Relation Members:** Tie the members' masses to their light so they cost almost no parameters. - **The Group Scale Sweet Spot:** Why groups are the sweet spot of the familiar lens modeling toolkit. - **Wrap Up:** Summary of the script and next steps. @@ -67,6 +67,7 @@ # from autolens import setup_notebook; setup_notebook() +import copy import matplotlib.pyplot as plt import numpy as np from pathlib import Path @@ -78,13 +79,18 @@ """ __Initial Setup__ -We begin by loading the group-scale strong lens dataset `simple`, which was simulated with: +We load the simulated group-scale dataset `simple`, containing: + +- A central galaxy at `(0.0, 0.0)`, represented by `SersicSph` light and an `IsothermalSph` total-mass profile + with Einstein-radius parameter 4.0". +- Two member galaxies at `(3.5, 2.5)` and `(-4.4, -5.0)`, with `SersicSph` light and truncated `dPIEMassSph` + mass profiles. +- One background source with a `SersicCore` light profile. + +Coordinates use the usual `(y, x)` convention in arcseconds. - - A main lens galaxy (the BGG) at (0.0", 0.0"), with a `SersicSph` light profile and an `IsothermalSph` mass - profile with a 4.0" Einstein radius. - - Two member galaxies at (3.5", 2.5") and (-4.4", -5.0"), with `SersicSph` light profiles and tidally - truncated `dPIEMassSph` mass profiles. - - A single source galaxy with a `SersicCore` light profile. +The simulation contains no separate group-halo profile. Its central mass component provides a simple description +of the dominant deflection field, without decomposing that mass into the BGG and a shared halo. """ dataset_name = "simple" dataset_path = Path("dataset") / "group" / dataset_name @@ -112,19 +118,31 @@ ) """ -When we plot the dataset, the difference from a galaxy-scale lens is immediately clear: the lensed arcs form a -much larger ring (the BGG's Einstein radius is 4.0", compared to the ~1.0" typical of a single galaxy), and two -smaller galaxies are visible away from the centre. Their light -- and, more importantly for the lensing, their -mass -- must be included in our analysis. +Plot the dataset and identify the central galaxy, the extended lensed arcs and the two member galaxies. + +The central mass profile has an Einstein-radius parameter of 4.0", so this example's lensed emission spans a larger +angular region than the earlier examples. The members modify the combined deflection field. + +As in Tutorial 1, consider their light and mass separately. We will explicitly model both here, but a galaxy's +mass can affect the arcs even when its light lies outside the fitting region. """ aplt.subplot_imaging_dataset(dataset=dataset) """ __Mask__ -We define a 7.5" circular mask, much larger than the 2.5"-3.0" masks of previous chapters. It must enclose the -full lensed arc system and the member galaxies, because all of them contribute light and mass to the region we -fit. +We use a circular mask with radius 7.5", centred on the central galaxy. This includes the lensed arcs and both +member-galaxy centres. + +Inspect the masked subplot to assess the retained source emission and member light. The outer member lies +approximately 6.7" from the origin, so its centre is inside the mask but some of its extended light lies outside it. + +The mask selects the image pixels used in the fit; it does not set a boundary on which galaxies can contribute +gravitational deflections. A member outside the mask can still be included in the mass model if its lensing +effect matters. + +Here, we retain a broad fitting region so that we can model the central galaxy, member light and lensed source +together. """ mask_radius = 7.5 @@ -141,17 +159,20 @@ """ __Galaxy Centres__ -Following the convention of the previous tutorials, the centres of the galaxies are loaded from .json files in -the dataset folder. For a group we distinguish two categories: +We load the measured galaxy positions from JSON files, separating them into: + +- `main_lens_centres`: positions of the main deflectors, here the central galaxy. +- `member_centres`: positions of the additional group members. - - `main_lens_centres`: the main lens galaxies -- here just the BGG at (0.0", 0.0") -- which are modeled with - full freedom. +This separation helps organize the model; it does not itself fix parameters or determine how much freedom each +galaxy receives. - - `member_centres`: the group members, which are modeled with restrictive assumptions (fixed centres, and - later a scaling relation) to keep the model dimensionality low. +As in the previous tutorials, measuring light centres before constructing the mass model is a common practical +workflow. For real observations, these positions can come from a GUI, a source-detection catalogue or a +preliminary light-profile fit. Here, the simulator supplies them. -For real data these centres come from the observed light of each galaxy (e.g. via a click-based GUI or a -photometry catalogue), exactly as for the extra galaxies of the earlier tutorials. +We will fix the member profiles to these positions and use the combined list of galaxy centres when setting up +adaptive over-sampling. """ main_lens_centres = al.from_json(file_path=dataset_path / "main_lens_centres.json") @@ -160,33 +181,35 @@ print(f"Main lens centres: {main_lens_centres}") print(f"Member centres: {member_centres}") -""" -__The dPIE Profile__ - -Before fitting anything, lets get to know the dPIE profile, since it is the workhorse mass profile of the group -and cluster regimes. +over_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from( + grid=dataset.grid, + sub_size_list=[4, 2, 2], + radial_list=[0.3, 0.6], + centre_list=list(main_lens_centres) + list(member_centres), +) -The `dPIEMassSph` profile is parameterized in the convention of Lenstool (a long-established cluster lensing -code), which differs from the profiles we have met so far: +dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) - - `sigma`: the fiducial velocity dispersion of the galaxy in km/s. This sets the overall lensing strength, - playing the role the `einstein_radius` played for the isothermal profile (for an isothermal sphere the two - are directly related: a bigger velocity dispersion means a bigger Einstein radius). +""" +__The dPIE Profile__ - - `r_core`: the core radius in arcseconds, within which the density profile flattens. It is common to fix - `r_core = 0.0` (a "vanishing core", where the profile has an exact analytic form), which we do throughout - this tutorial. +The spherical `dPIEMassSph` profile uses the parameter convention of the lens-modeling software Lenstool: - - `r_cut`: the truncation radius in arcseconds -- the key new parameter. Outside `r_cut` the density falls off - steeply (as 1/r^4 rather than the isothermal 1/r^2), encoding the tidal stripping of the member's outer dark - matter halo and giving the profile a finite total mass. +- `sigma`: a fiducial velocity-dispersion parameter in km/s that sets the mass normalization. It is not + automatically equal to an observed stellar velocity dispersion; comparisons require attention to the profile + convention and how the observation was measured. +- `r_core`: the core scale in arcseconds. A nonzero value flattens the central density. We set it to zero here, + giving a singular central profile. +- `r_cut`: the truncation scale in arcseconds. The density steepens smoothly around this scale, giving a finite + total mass. It is not a sharp boundary beyond which the mass vanishes. +- `redshift_object`, `redshift_source`, `H0` and `Om0`: the redshifts and cosmological parameters used to + convert the physical normalization into lensing quantities. We hold them fixed in this tutorial. - - `redshift_object`, `redshift_source`, `H0`, `Om0`: because `sigma` is a physical velocity, converting it to - deflection angles requires the lensing geometry and a cosmology. These are fixed inputs describing the lens - system, not parameters we fit. +We create two profiles with the same `sigma` and zero core radius, but different truncation scales: 8.0" and +1000.0". -Lets make two dPIE profiles with identical `sigma` but different truncation radii -- one truncated at 8.0" and -one truncated so far out (1000.0") that it is effectively untruncated -- and compare their convergence profiles. +The second profile is effectively untruncated over the radial range we plot, although it still has a finite +truncation scale. """ dpie_truncated = al.mp.dPIEMassSph( centre=(0.0, 0.0), @@ -207,8 +230,13 @@ ) """ -We evaluate the convergence of both profiles on a 1D line of radial coordinates, using a `Grid2DIrregular` so we -can choose the radii ourselves. +We evaluate both profiles along a radial line using `Grid2DIrregular`. + +The plotted quantity is **convergence**: projected surface mass density divided by the critical surface density +for lensing. It is not the three-dimensional density. + +The logarithmic vertical axis helps us compare the profiles over a wide range of convergence. The dashed line +marks the 8.0" truncation scale of the more strongly truncated profile. """ radii = np.linspace(0.01, 20.0, 200) @@ -218,7 +246,7 @@ convergence_untruncated = dpie_untruncated.convergence_2d_from(grid=radial_grid) plt.semilogy(radii, np.asarray(convergence_truncated), label="dPIE (r_cut = 8.0)") -plt.semilogy(radii, np.asarray(convergence_untruncated), label="dPIE (untruncated)") +plt.semilogy(radii, np.asarray(convergence_untruncated), label="dPIE (r_cut = 1000.0)") plt.axvline(x=8.0, color="k", linestyle="--", label="r_cut") plt.xlabel("Radius (arcseconds)") plt.ylabel("Convergence") @@ -227,26 +255,25 @@ plt.close() """ -Inside `r_cut` the two profiles are nearly identical -- both behave isothermally. Beyond `r_cut`, the truncated -profile's convergence plummets while the untruncated one keeps its shallow isothermal decline. The truncated -member therefore contributes far less mass at large radii, which is exactly what tidal stripping does. +At radii much smaller than 8.0", the profiles approach similar isothermal behaviour. As we move towards and +beyond the smaller truncation scale, that profile's convergence falls more steeply. -This is why the dPIE, and not the isothermal profile, is the standard choice for group and cluster members: the -extra galaxies of a galaxy-scale lens have no host environment stripping them, so untruncated isothermal -profiles are fine there, but a member orbiting inside a shared group halo is physically truncated whether or -not the model includes that halo as an explicit component. +The transition is gradual: `r_cut` does not mark an abrupt edge, and the profiles can differ before reaching it. +The truncated profile also continues to contribute mass and deflections beyond that radius. -For scale: a member with `sigma = 200.0` km/s at these redshifts has an Einstein radius of ~0.7", roughly a -fifth of the BGG's -- a perturber, not a co-dominant lens. +This flexibility makes the dPIE useful for representing member galaxies with reduced outer halos. However, +neither group membership nor proximity to another galaxy uniquely determines a truncation radius. Its value +remains a modeling choice or an inferred parameter, depending on the available constraints. __Fitting a Group__ -Now lets fit the data. Following the fitting tutorials of earlier chapters, we first build a tracer from -galaxies whose light and mass profiles match the true values used to simulate the data, and fit it with the -`FitImaging` object. +We first evaluate a model using the parameter values supplied to the simulator. This is a direct fit evaluation, +rather than a search for the best-fitting parameters. + +The tracer contains the central galaxy, two members and the source. Because the deflectors share a redshift, +their deflections combine on one lens plane before mapping the source light into the image. -The tracer contains four galaxies: the BGG, the two members and the source. The fit handles all of them -simultaneously, summing the deflection field of every mass profile to ray-trace the source's light. +The familiar `FitImaging` object compares this predicted image with the data, including the PSF and noise map. """ bgg = al.Galaxy( redshift=0.5, @@ -304,70 +331,71 @@ aplt.subplot_fit_imaging(fit=fit) """ -Because this is the true model, the residuals are consistent with noise and the log likelihood is as high as it -can be for this dataset. Note that nothing about the `FitImaging` object changed: the same fitting machinery we -learnt at galaxy scale simply receives a tracer with more galaxies in it. +Inspect the residuals of the fit evaluated at the simulation's input parameters. + +With consistent simulation and fitting calculations, we expect residuals compatible with the added noise. +Coherent structure could instead indicate a mismatch in the profiles, PSF, numerical sampling or other assumptions. + +The fitting machinery is unchanged from earlier chapters. We have supplied a tracer containing more galaxies and +a different member-mass profile. """ print(f"Log likelihood of the true model: {fit.log_likelihood}") """ __A Group Halo?__ -You may have noticed that the model above contains no group-scale dark matter halo, despite this tutorial -opening with the statement that a group is defined by one. Two things are going on here. +In the standard cosmological model, **Lambda Cold Dark Matter (LCDM)**, galaxies form within dark matter halos. +Galaxy groups are expected to occupy larger **host dark matter halos**, within which member galaxies orbit, +often retaining their own smaller halos. -First, the BGG's `IsothermalSph` has a 4.0" Einstein radius -- far larger than the ~1.0" of an isolated galaxy -of its luminosity. A mass profile centred on the BGG cannot tell "stars and dark matter belonging to the BGG" -apart from "group dark matter centred on the BGG": a single isothermal profile at the group centre soaks up -both. So the group's halo is partly hidden inside the BGG's mass profile already. +This gives us a physical reason to include an extended, shared dark matter component when modeling a group-scale +lens. -Second, whether to add a *separate* halo component to the model is an **explicit modelling choice**, and this -dataset was deliberately simulated without one. Lets see what happens if we add one anyway. We add a fifth -galaxy carrying only mass -- an `IsothermalSph` centred on the BGG, the conventional choice for a group halo -where a BGG exists -- and refit. -""" -group_halo = al.Galaxy( - redshift=0.5, - mass=al.mp.IsothermalSph(centre=(0.0, 0.0), einstein_radius=1.5), -) +However, seeing several galaxies close together on the sky does not automatically establish that they inhabit +a group-scale halo. They could be projected neighbours or an interacting pair of field galaxies, for which +separate galaxy-centred mass profiles provide an adequate description. Those galaxies still contain dark matter; +what may be unnecessary is an **additional shared group-scale component**. -tracer_with_halo = al.Tracer(galaxies=[bgg, group_halo, member_0, member_1, source]) +The astronomical question is therefore whether the system's environment and lensing signal support a shared +host halo, and whether the data can distinguish its contribution from the masses associated with individual +galaxies. -fit_with_halo = al.FitImaging(dataset=dataset, tracer=tracer_with_halo) +We investigate this by fitting two models: -aplt.subplot_fit_imaging(fit=fit_with_halo) +- **Galaxy mass profiles only:** a central galaxy and member galaxies, without a separate host halo. +- **Galaxy mass profiles plus a shared dark matter halo:** the same components, with an additional NFW halo + at the group redshift. -""" -The fit is now visibly worse -- the extra 1.5" Einstein radius of mass at the centre over-deflects the source's -light, displacing the model arcs from the observed ones -- and the log likelihood drops accordingly. -""" -print(f"Log likelihood with a group halo added: {fit_with_halo.log_likelihood}") +The Navarro-Frenk-White (NFW) profile is a commonly used description of dark matter halos in LCDM. We allow the +galaxy parameters to adjust in both fits and compare the Bayesian evidences. This tests whether the data support +the additional NFW component, given our profile choices and priors. -""" -On real data the same experiment runs in reverse: fit the group with and without an explicit halo component and -let the data decide (via the residuals and the Bayesian evidence introduced in earlier chapters). Some groups -are well described by their galaxies alone, with the central galaxy's profile absorbing the halo; others -- -typically those with the largest Einstein radii or image configurations no galaxy-mass model can reproduce -- -require a dominant halo component, often centred on the BGG. +If the simpler model is sufficient, it does not overturn the LCDM expectation: the shared halo's contribution +may be absorbed by the galaxy-centred profiles, or the available images may not distinguish it separately. + +Our simulated dataset contains no separate NFW halo, so it provides a useful starting point for this comparison. __Model Fit__ -We now perform a proper model-fit with a non-linear search, as a scientist would for a group whose true -parameters are unknown. We compose the model as follows: +We first fit the galaxy-only model: - - The BGG's light is a linear `SersicSph` (its centre free) and its mass an `IsothermalSph` [7 parameters]. +- The BGG has a linear `SersicSph` light profile and an `IsothermalSph` mass profile, with free centres: + seven non-linear parameters. +- Each member has a linear `SersicSph` light profile and a `dPIEMassSph` mass profile. Both centres are fixed + to the measured position. The light's effective radius and Sersic index, together with the mass normalization + `sigma`, give three parameters per member. +- The source has a linear `SersicCore` light profile: six non-linear parameters. - - Each member's light is a linear `SersicSph` with its centre fixed to the observed centre, and its mass a - `dPIEMassSph` with a free `sigma`, its centre fixed, `r_core = 0.0` and `r_cut` fixed to a fiducial 10.0" - [3 parameters per member, 6 total]. +For each member, we fix `r_core = 0.0` and adopt `r_cut = 10.0"`. We also fix the redshifts and cosmological +parameters. - - The source's light is a linear `SersicCore` [6 parameters]. +Fixing the member centres follows the measured-position workflow used throughout this chapter. Fixing their +truncation scales is a further assumption: the arcs may constrain a member's lensing strength more readily +than its outer mass distribution. -Fixing the member centres to their observed light and fixing `r_cut` follows the reasoning of the extra -galaxies tutorial: the data rarely constrains a perturber's truncation radius, so we spend our parameter budget -on the quantity that matters most -- each member's overall mass, via `sigma`. The redshifts and cosmology of -the dPIE are pinned to their known values, since they are properties of the lens system, not parameters to -sample. +The chosen 10.0" truncation scale differs from the simulation's member values of 8.0" and 13.3". This fit therefore +tests a simplified model rather than reproducing every simulation assumption exactly. We use the same member +treatment in both halo-comparison models. """ # BGG: @@ -412,43 +440,47 @@ ) """ -Printing the model's `info` confirms its composition: the BGG and source under `galaxies`, and the two members -under `extra_galaxies` with only their `sigma`, `effective_radius` and `sersic_index` free. +Inspect `model.info` to check the galaxy-only model's components and priors. -The total number of free parameters is N=19 -- take note of this number, as it is central to the discussion at -the end of this tutorial. +The BGG and source appear under `galaxies`, while the two members appear under `extra_galaxies`. Each member has +three free non-linear parameters: `sigma`, `effective_radius` and `sersic_index`. + +The total is **19 non-linear parameters**: seven for the BGG, six across the two members and six for the source. + +Light-profile intensities are solved by the linear inversion during each likelihood evaluation, so they do not +add sampling dimensions. This is Model 1 of our dark matter halo comparison. """ print(model.info) """ -The same model can also be visualized as a figure, making its structure easier to understand at a glance. +The model figure shows how these components are organized. + +Notice that the central galaxy's light and mass centres remain free, whereas the member centres are fixed to +their measured positions. Each member's mass profile has only `sigma` free; its core and truncation scales +are fixed. -The figure shows how the model is organized: which parameters belong to each component, and whether they are free, -fixed, shared, linked by an expression, solved during the fit, or not configured. `model.info` provides the -corresponding numerical details, including the prior assigned to each free parameter and the value of each fixed -parameter. +Compare the figure with `model.info` and check the printed parameter count. These choices keep the model +compact while retaining independent mass normalizations for the members. """ af.ModelPlotter(model).figure() print(f"Total free parameters: {model.prior_count}") """ -Before fitting, we set up the adaptive over-sampling scheme at the centre of every galaxy in the group (not -just the BGG), following the standard workspace approach. As in previous tutorials, the details are not -important yet -- just note that at group scale every galaxy centre needs it. +Adaptive over-sampling was configured around every galaxy centre before the initial fit evaluations. The same +configuration is retained for the non-linear search. """ -over_sample_size = al.util.over_sample.over_sample_size_via_radial_bins_from( - grid=dataset.grid, - sub_size_list=[4, 2, 2], - radial_list=[0.3, 0.6], - centre_list=list(main_lens_centres) + list(member_centres), -) -dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) """ -We fit the model with the `Nautilus` non-linear search, using the same `AnalysisImaging` object as every -imaging fit so far -- another sign that the group scale does not require new machinery. +We first fit the galaxy-only model using `Nautilus` and the familiar `AnalysisImaging` object. + +The likelihood calculation uses the same imaging framework as in earlier chapters, now with the central galaxy +and two members contributing to the predicted image. + +This search provides the first fit and Bayesian evidence for our comparison. We will then fit the model +containing an additional NFW dark matter halo using the same dataset and unchanged priors for the +galaxy components. """ search = af.Nautilus( path_prefix=Path("howtolens") / "chapter_4", @@ -462,49 +494,149 @@ analysis = al.AnalysisImaging(dataset=dataset) print( - "The non-linear search has begun running - checkout the output/howtolens/chapter_4/tutorial_4_group_scale" - " folder for live output of the results, images and model." - " This Jupyter notebook cell with progress once search has completed - this could take some time!" + "The non-linear search has begun. Check the output/howtolens/chapter_4/tutorial_4_group_scale" + " folder for results and visualizations as the search progresses." + " This cell will finish when the search completes." ) result = search.fit(model=model, analysis=analysis) -print("The search has finished run - you may now continue the notebook.") +print("The search has finished — you may now continue the notebook.") """ -The result's `info` and maximum likelihood fit show the model recovers the group: the BGG's Einstein radius, -the members' velocity dispersions and the source's properties are all inferred from the data. +Inspect the inferred parameters in `result.info` and the fit subplot below. + +Check how well the model reproduces the central galaxy, member light and lensed arcs. Look for coherent +residuals, particularly near the member galaxies and the source emission they perturb. + +The inferred member `sigma` values describe their dPIE mass normalizations under our adopted profile +assumptions. Remember that we fixed both truncation scales to 10.0", whereas the simulation used 8.0" and 13.3". + +We next add the shared NFW dark matter halo and refit, allowing the galaxy parameters to adjust alongside the +halo parameters. """ print(result.info) aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) + +""" +__Fit With a Shared NFW Dark Matter Halo__ + +We now construct Model 2 by copying the galaxy-only model and adding a spherical NFW dark matter halo at the +group redshift. Copying the original model preserves the galaxy priors: we do not replace them with posterior +constraints from the first fit. + +For this illustrative comparison, we fix the halo centre to the measured central-galaxy position and fit two +parameters: + +- `kappa_s`: the dimensionless NFW density normalization, with a uniform prior from 0.0 to 0.5. +- `scale_radius`: the NFW scale radius in arcseconds, with a uniform prior from 5.0" to 50.0". + +These are explicit example priors, not universal choices for galaxy groups. The halo's shape and position are +also assumptions here. For a scientific analysis, choose priors appropriate to the system and assess how they +affect the evidence and inferred mass decomposition. + +Both models fit the same dataset, mask, noise map and source description. All galaxy parameters that were free +in Model 1 remain free in Model 2, allowing mass to be redistributed between the central galaxy and host halo. """ +model_galaxies_only = model +model_with_halo = copy.deepcopy(model_galaxies_only) + +halo_mass = af.Model(al.mp.NFWSph) +halo_mass.centre = tuple(main_lens_centres[0]) +halo_mass.kappa_s = af.UniformPrior(lower_limit=0.0, upper_limit=0.5) +halo_mass.scale_radius = af.UniformPrior(lower_limit=5.0, upper_limit=50.0) + +model_with_halo.galaxies.group_halo = af.Model( + al.Galaxy, redshift=0.5, mass=halo_mass +) + +print(model_with_halo.info) + +search_with_halo = af.Nautilus( + path_prefix=Path("howtolens") / "chapter_4", + name="tutorial_4_group_scale_with_nfw_halo", + unique_tag=dataset_name, + n_live=100, + n_batch=50, + iterations_per_quick_update=2500, +) + +result_with_halo = search_with_halo.fit(model=model_with_halo, analysis=analysis) + +print(result_with_halo.info) +aplt.subplot_fit_imaging(fit=result_with_halo.max_log_likelihood_fit) + +""" +__Bayesian Model Comparison__ + +Compare the log evidences from the two fitted models. We report the difference as the NFW-halo model minus +the galaxy-only model: a positive difference favours including the NFW halo, while a negative difference favours +the galaxy-only description, under the adopted priors. + +Interpret this alongside fit diagnostics and the numerical reliability of the searches. The evidence comparison +accounts for the additional parameter space; it is not simply a comparison of the best-fitting images. +For equal prior model probabilities, the difference in log evidences is the log posterior odds between the models. + +A preference for the NFW model supports that explicit component within these model choices. A preference for the +simpler model does not demonstrate the absence of a physical dark matter halo. + +The next scaling-relation exercise returns to the galaxy-only setup, keeping the halo comparison separate from +the change in member-mass treatment. +""" +log_evidence_galaxies_only = result.samples_summary.log_evidence +log_evidence_with_halo = result_with_halo.samples_summary.log_evidence + +if ( + log_evidence_galaxies_only is not None + and log_evidence_with_halo is not None + and np.isfinite(log_evidence_galaxies_only) + and np.isfinite(log_evidence_with_halo) +): + print(f"Log evidence, galaxy-only model: {log_evidence_galaxies_only:.3f}") + print(f"Log evidence, galaxy + NFW model: {log_evidence_with_halo:.3f}") + print( + "Delta log evidence (NFW minus galaxy-only): " + f"{log_evidence_with_halo - log_evidence_galaxies_only:.3f}" + ) +else: + print("Finite evidences are unavailable; complete both nested-sampling fits before comparing the models.") + +r""" __Scaling Relation Members__ -The model above gave every member its own free `sigma`. With two members that costs two parameters -- harmless. -But groups can host dozens of members, and one free mass parameter per member quickly bloats the model, slows -the search, and asks the data to constrain masses it barely feels individually. +We now return to the galaxy-only model and change how its member galaxies are described. This keeps the +scaling-relation exercise separate from the NFW halo comparison. + +Previously, each member had an independent mass normalization, `sigma`. We now link the members through +their luminosities: -The previous tutorial's solution applies directly here: tie the members' masses to their light through a -scaling relation. More luminous galaxies are more massive, so we write each member's `sigma` and `r_cut` as -power laws of its luminosity, normalized by a single shared free parameter: +$$ +\sigma_i=\sigma_{\rm ref} +\left(\frac{L_i}{L_{\rm ref}}\right)^{0.25}, +\qquad +r_{{\rm cut},i}=r_{{\rm cut},{\rm ref}} +\left(\frac{L_i}{L_{\rm ref}}\right)^{0.7}. +$$ - - `sigma = sigma_ref * (L / L_ref) ** 0.25` - - `r_cut = r_cut_ref * (L / L_ref) ** 0.7` +The exponent 0.25 follows the approximate Faber-Jackson scaling introduced in Tutorial 3. The truncation exponent +0.7 is an adopted prescription for this example, rather than a universal property of group members. -These exponents follow the convention of modern cluster lensing analyses, and `L_ref` is a fixed reference -luminosity. The 0.25 is the previous tutorial's Faber-Jackson relation recast for velocity dispersion: -`L ~ sigma^4` inverts to `sigma ~ L^0.25`, and since `theta_E ~ sigma^2` this reproduces the `theta_E ~ L^0.5` -scaling we anchored there. Note also the change of normalization: rather than hanging the relation off an -anchor galaxy the model already fits, we normalise it with a shared free parameter at a fixed reference -luminosity. Now the *entire member population's mass* costs one free parameter (`sigma_ref`), no matter how -many members the group has, and each member's observed luminosity acts as a physically motivated prior on its -mass. +Unlike the previous tutorial's anchor-galaxy approach, we introduce a shared free normalization, `sigma_ref`, +at a fixed reference luminosity. We hold both exponents and `r_cut_ref` fixed. -For real data the luminosities come from your photometry catalogue (only luminosity ratios enter the model, so -any consistent units work). Here we compute them from the true member light profiles, using an aperture -luminosity within 3.0". +With member centres fixed and spherical mass profiles, the entire member **mass population** therefore has one +non-linear parameter, regardless of how many members we include. + +Their light parameters remain separate. Here, each member's fixed-centre linear `SersicSph` contributes two +non-linear parameters: effective radius and Sersic index. Its intensity is solved linearly. + +For this simulated example, we obtain luminosities from the known member light profiles within a 3.0" aperture +centred on each galaxy. This photometric aperture is separate from the 7.5" fitting mask. + +For real observations, use consistently measured luminosities and account for the measurement and population +assumptions discussed in Tutorial 3. """ luminosity_list = [ member_0.bulge.luminosity_within_circle_from(radius=3.0), @@ -545,44 +677,50 @@ ) """ -Note that the tied members now live in the `scaling_galaxies` collection — the home the previous tutorial -introduced for a scaling-relation population — whereas the individually-modelled members above sat in -`extra_galaxies`, like tutorial 1's interlopers. Both collections are included in the ray-tracing; the split -keeps `model.info` readable and tells the results machinery which galaxies are a tied population. +The tied members now appear under `scaling_galaxies`, while the individually modeled members previously appeared +under `extra_galaxies`. Both contribute to the ray-tracing. -The model's `info` shows that both members' `sigma` values now trace back to the single shared `sigma_ref` -prior, and the parameter count has dropped to N=18. +Inspect `model.info`: both member `sigma` expressions depend on the same `sigma_ref` prior. -A drop of one parameter looks unremarkable -- until you scale it up. A group with 20 members modeled -individually would need 20 free mass parameters; with the scaling relation it still needs exactly one. (In -practice the members' light is handled the same way, using the Multi Gaussian Expansion from earlier in the -lectures, whose fixed-centre members add almost no free parameters either -- so entire member populations can -be added to a group model almost for free.) +The model has **18 non-linear parameters**: seven for the BGG, six for the source, four for the member light +profiles and one shared member-mass normalization. -This dataset was in fact simulated with members that obey this exact scaling relation, so the model remains the -true model. +With N members, the corresponding count is 14 + 2N, because their light models still contribute two parameters +each. Only the member mass-parameter count remains constant. + +Fixed-width, fixed-centre spherical MGEs could remove those non-linear member-light parameters where that light +description is appropriate. Elliptical MGEs with fixed centres would retain two per member. + +The truncation radii also change: instead of fixing both to 10.0", we now assign luminosity-dependent values. +The comparison therefore changes both the mass-normalization freedom and the truncation prescription. """ print(model.info) """ -The tied members have moved out of `extra_galaxies` into `scaling_galaxies`, and they no longer share one -description: each member's `sigma` is no longer an independent prior but an expression, -`sigma = scaling_galaxies.1.mass.sigma.sigma_ref * `, with a different ratio for each. One -free prior, two galaxies — the scaling relation. +The figure shows the two member `sigma` values linked to one shared prior. Each is computed from `sigma_ref` +and its fixed luminosity ratio. + +Their truncation radii are also calculated from luminosity, but every input to that calculation is fixed. +Each member therefore receives a fixed `r_cut` value, which can differ between members. -`r_cut` stays fixed, as it was before. `r_cut_ref * luminosity_ratio ** 0.7` is arithmetic on plain numbers -rather than on a prior, so it yields a fixed value rather than a relation. +Replacing two independent `sigma` parameters with one shared normalization reduces the count from 19 to 18. -Nineteen free parameters fall to eighteen. One parameter is an unremarkable saving for two members, but the -saving keeps growing: however many members you add to `scaling_galaxies`, every one of their `sigma` values -points back at that single `sigma_ref`. +For a larger population, the saving grows: replacing N independent member normalizations with one shared +parameter removes N - 1 sampling dimensions, provided the other model choices remain unchanged. """ af.ModelPlotter(model).figure() print(f"Total free parameters: {model.prior_count}") """ -We fit this model with an identical search set up. +We fit the scaling-relation model using the same dataset, analysis object and search settings as the galaxy-only +fit with independently modeled members. + +Inspect the resulting parameters and residuals to assess whether the restricted member model describes the data +adequately. + +Remember that this comparison changes the truncation prescription as well as tying the mass normalizations. +Any difference in the fit cannot be attributed solely to the reduction of one parameter. """ search = af.Nautilus( path_prefix=Path("howtolens") / "chapter_4", @@ -594,14 +732,14 @@ ) print( - "The non-linear search has begun running - checkout the output/howtolens/chapter_4/" - "tutorial_4_group_scale_scaling_relation folder for live output of the results, images and model." - " This Jupyter notebook cell with progress once search has completed - this could take some time!" + "The non-linear search has begun. Check the output/howtolens/chapter_4/" + "tutorial_4_group_scale_scaling_relation folder for results and visualizations as the search progresses." + " This cell will finish when the search completes." ) result_scaling = search.fit(model=model, analysis=analysis) -print("The search has finished run - you may now continue the notebook.") +print("The search has finished — you may now continue the notebook.") print(result_scaling.info) @@ -610,53 +748,45 @@ """ __The Group Scale Sweet Spot__ -Step back and consider what this tutorial did *not* require: no new fitting machinery, no new analysis object, -no new data format. The `FitImaging`, `AnalysisImaging`, linear light profiles and `Nautilus` search of the -galaxy-scale chapters handled the group unchanged -- we just put more galaxies in the tracer, reached for the -truncated dPIE profile, and used scaling relations to keep the member population cheap. Even the pixelized -source reconstructions of the previous chapter work at group scale exactly as they do at galaxy scale, and for -real groups with complex arcs they are the recommended source model. - -This is why the group scale is the **sweet spot** of strong lens modeling. The full toolkit of galaxy-scale -modeling still applies, and the model dimensionality stays low: our individually-modeled-member fit had N=19 -free parameters and the scaling-relation fit N=18. Real group models are of this order -- a few tens of free -parameters at most (N < 30 or so) -- comfortably within reach of the non-linear searches we already know, with -run times of minutes to hours. - -Push the system any richer, however, and this toolkit breaks down. A cluster hosts hundreds of members and -lenses many sources at once; its image is too large and complex to fit pixel-by-pixel with a tracer's light -model, and its model would need hundreds of parameters. Cluster-scale modeling therefore switches to a -different tool set -- fitting the *positions* of the multiple images of many point-like sources, with member -catalogues driving the mass model -- which is the subject of the next tutorial. +Group-scale lenses let us apply much of the toolkit developed for individual galaxies to a richer mass +distribution. -__Wrap Up__ +We still use `FitImaging`, `AnalysisImaging`, linear light profiles and a non-linear search. Pixelized source +reconstructions can also be used when the lensed source has structure that a simple parametric profile does +not capture. -In this tutorial, we took the tools of the previous tutorials to the group scale. Lets recap what we learnt: +Our examples remain compact: 19 non-linear parameters for independently normalized members, 21 after adding the +illustrative NFW halo, and 18 for the galaxy-only scaling-relation model. -- **Groups in LCDM**: A galaxy group is a dark matter halo of roughly 10^13 to 10^14 solar masses hosting a - handful to a few dozen galaxies, with the brightest group galaxy (BGG) typically near its centre. The group's - halo may enter the mass model as its own component, often centred on the BGG -- but whether it is needed is - an explicit modelling choice, tested by fitting with and without it. +These counts describe our chosen examples, rather than an upper limit for group modeling. Real systems may +require more galaxies, additional sources, more flexible mass profiles or further freedom in the scaling relation. -- **Groups vs multi-galaxy lenses**: The line is blurry. All groups are multi-galaxy lenses, but not all - multi-galaxy lenses are groups -- the group's defining feature is the shared halo environment its members - orbit within. +Groups are particularly useful for studying how mass is divided between a central galaxy, satellite galaxies +and a larger dark matter halo. As throughout this chapter, that decomposition can remain uncertain even when +the lensed images are fitted well. -- **Tidal truncation and the dPIE**: Members orbiting in the group's potential have their outer dark matter - tidally stripped, so their profiles are truncated. The `dPIEMassSph` profile encodes this via its `r_cut` - truncation radius, with `sigma` setting the lensing strength and `r_core` the (usually vanishing) core. +At cluster scale, many multiply imaged sources can provide constraints across a much larger region. A common +approach is to fit their image positions, using a catalogue to describe the member population. -- **Fitting and modeling groups**: The galaxy-scale machinery works unchanged -- a tracer with more galaxies, - members with fixed centres and free `sigma`, and a `Nautilus` search over N=19 parameters. +This is the approach introduced in the next tutorial. It complements surface-brightness modeling rather than +marking a fundamental scale beyond which pixel-based fitting is impossible. -- **Scaling relations**: Tying member `sigma` and `r_cut` to luminosity via power laws with one shared free - normalization means the whole member population costs a single parameter, however many members there are. - -- **The sweet spot**: Groups are the largest systems the familiar toolkit -- including pixelized source - reconstruction -- still handles, with model dimensionality staying below a few tens of parameters. +__Wrap Up__ -In the next tutorial we climb the final rung of the ladder to galaxy clusters, where tens to hundreds of member -galaxies lens many sources simultaneously. There the toolkit changes: we will model the positions of multiply -imaged point sources rather than every pixel of the data, and drive the mass model from member catalogues via -a csv interface built on the same scaling relations we used here. +In this tutorial, we learned: + +- Group lenses combine contributions from central galaxies, members and potentially an explicitly modeled shared + dark matter halo. +- The dPIE profile provides a finite-mass description of members, with a smooth truncation scale whose + interpretation depends on the adopted model. +- Measuring member positions first and fixing centres helps keep the inference manageable. +- Comparing fitted galaxy-only and galaxy-plus-NFW models tests whether the data support a separate halo + component under the chosen priors. +- Luminosity-based scaling relations can replace independent member mass normalizations with shared parameters, + while member-light freedom must still be counted separately. +- The familiar imaging toolkit extends naturally to groups, but reliable mass decomposition requires attention + to degeneracies and modeling assumptions. + +In the next tutorial, we move to **galaxy clusters**, fitting the positions of multiple images from background +sources and building member-galaxy models from a CSV catalogue. """ diff --git a/scripts/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.py b/scripts/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.py index 0e52a72..9982c27 100644 --- a/scripts/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.py +++ b/scripts/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.py @@ -2,43 +2,35 @@ Tutorial 5: Cluster Scale ========================= -Throughout this chapter we have been climbing a ladder of scale: from a single lens galaxy with an extra -galaxy nearby, to multi-galaxy lenses, to galaxy groups whose members share a common dark matter halo. +We now extend the tools developed for galaxies and groups to **galaxy clusters**. -This tutorial climbs the final rung: **galaxy clusters**, the most massive gravitationally-bound structures in -the Universe. A cluster-scale strong lens contains: +Galaxy clusters typically inhabit dark matter halos with masses of roughly $10^{14}$-$10^{15}$ solar masses, +with the most massive systems exceeding $10^{15}$ solar masses. Within this shared halo, a cluster can contain +**hundreds of individual lens galaxies**, including a brightest cluster galaxy, other prominent galaxies and a +large population of lower-mass members. -- **30+ to hundreds of lens galaxies**: a brightest cluster galaxy (BCG) and bright satellites, plus a large - population of lower-mass member galaxies, all embedded in... +Their combined mass can produce multiple images of many background sources at different redshifts. -- **A cluster-scale dark matter halo of more than 10^14 solar masses** (the most massive exceed 10^15 solar - masses) — hundreds of times more massive than the halo of a single lens galaxy. +These systems offer two important scientific opportunities: -- **Many multiply-imaged background sources** — often tens of them — and, crucially, these sources typically - all sit at **different redshifts**. Light from each source therefore traverses a different path through the - Universe, and modeling them together requires **multi-plane ray tracing**, which we explain below. +- **Studying magnified background galaxies:** lensing can make faint sources brighter and stretch their images, + revealing details that would otherwise be difficult to observe. +- **Mapping the cluster's mass distribution:** multiple-image systems at different positions and redshifts + constrain the combined contributions of the cluster halo and its galaxies. -The science a cluster lens delivers is different from the galaxy-scale lensing of earlier chapters: +High magnification occurs near critical curves in both galaxy- and cluster-scale lenses. Clusters provide +extended regions in which many background sources can be lensed, but the magnification of an individual source +depends on its position, size and the lens model. -- **Extreme magnification**: near a cluster's critical curves, magnifications of tens to hundreds are common - (compared to the factors of a few of galaxy-scale lensing). Clusters act as natural telescopes, letting us - study intrinsically faint galaxies in the early Universe that would otherwise be invisible — many of the - most distant galaxies known were discovered behind lensing clusters. +In this tutorial, we fit **multiple-image positions** rather than the full surface-brightness distribution of +every arc. This provides a compact set of constraints for exploring the cluster mass model. -- **Mapping the cluster's mass**: every multiply-imaged source constrains the cluster's total mass - distribution along a different line of sight. With many sources, the mass model pins down the shape of the - cluster's dark matter halo and the substructure within it — the granularity of dark matter on sub-cluster - scales — providing some of the sharpest tests of the cold dark matter model. - -The modeling toolkit also changes at this scale. Fitting the extended arcs of every source, with a light -profile or pixelization each, is computationally prohibitive when there are tens of sources and hundreds of -member galaxies. The standard approach instead fits only the **positions** of each source's multiple images — -point-source modeling — and drives the mass model from spreadsheet-editable **CSV catalogues**, because -writing Python model code for hundreds of galaxies by hand is not sensible either. +We also introduce CSV catalogues for the image positions, individually modeled components and member population. +These make larger systems easier to organize while retaining the model-composition tools used earlier. __Contents__ -- **Multi-Plane Ray Tracing:** What it means for sources at different redshifts to be lensed together. +- **Multi-Plane Ray Tracing:** Distinguish multiple source planes from multiple deflecting planes. - **Dataset:** Load the simulated cluster's CCD imaging and inspect the true multi-plane tracer. - **Point Source Modeling:** Why cluster modeling fits multiple-image positions rather than extended arcs. - **Point Datasets:** The per-source multiple-image positions, loaded from a single hand-editable CSV. @@ -55,34 +47,26 @@ __Multi-Plane Ray Tracing__ -Every lens system in the tutorials so far had two planes: an image plane (the lens galaxies, all at one -redshift) and a source plane (the lensed galaxy). The lens equation was applied once, mapping image-plane -coordinates to source-plane coordinates via the deflection angles: +Our simulated cluster places all deflecting mass at redshift $z=0.5$, with background sources at $z=1.0$ and +$z=2.0$. -$\beta = \theta - \alpha(\theta)$ +This gives us **one deflecting plane and two source planes**. Each source is mapped through the same cluster +mass distribution, but with the lensing-distance factors appropriate to its redshift. -A cluster breaks this picture, because its sources sit at different redshifts. Consider our simulated cluster, -which has lens galaxies at $z = 0.5$ and two sources, at $z = 1.0$ and $z = 2.0$: +Different source redshifts therefore require different geometric scaling; they do not automatically imply that +light is deflected by mass on several planes. -- Light from the $z = 1.0$ source is deflected by the $z = 0.5$ cluster and travels to us: the familiar - two-plane system. +Genuine multi-plane deflection arises when significant mass occupies more than one redshift plane. For example, +a galaxy at $z=1.0$ could both be lensed by the cluster and deflect light from a more distant source at $z=2.0$. -- Light from the $z = 2.0$ source first passes the $z = 1.0$ plane, then the $z = 0.5$ cluster plane. If any - galaxy at $z = 1.0$ had mass, it would deflect this light too — the deflections of successive planes - accumulate, each applied at the position the ray has reached by that plane. +In that case, the ray's position at a later plane depends on the deflections accumulated at earlier planes. +The multi-plane lens equation accounts for this sequentially. -This is **multi-plane ray tracing**: the lens equation is applied recursively, plane by plane in redshift -order. There is a second, subtler effect: the strength of a deflection depends on the distances between the -observer, the deflector and the source. The same cluster bends light from a $z = 2.0$ source through a larger -effective angle than light from a $z = 1.0$ source, because the geometry of the light paths differs. The -recursive lens equation accounts for this by scaling each plane's deflections by ratios of cosmological -(angular diameter) distances. +The `Tracer` supports both situations. It organizes galaxies by redshift and computes the appropriate mappings +to each source plane. Our example uses that machinery with mass on the cluster plane only. -The maths is more bookkeeping than new physics, and the good news is that the `Tracer` handles all of it -automatically: give it galaxies at three or more redshifts and it groups them into planes, orders them, scales -their deflections and applies the recursion. Every source's redshift must simply be *correct* — hardcoding the -wrong redshift silently produces the wrong multi-plane geometry, which is why the dataset CSVs below carry a -redshift for every source. +Source redshifts are therefore essential inputs. Here they are known from the simulation; observational +redshift uncertainties must be considered when interpreting a real cluster model. """ import importlib.util @@ -110,11 +94,21 @@ """ __Dataset__ -We use a simulated cluster whose scale is kept deliberately small so it runs quickly, but which contains every -ingredient of the cluster regime: 2 main lens galaxies (a BCG and a satellite), 10 lower-mass member galaxies -on a luminosity-mass scaling relation, a 10^15.3 solar-mass dark matter halo, and 2 multiply-imaged sources at -different redshifts (z = 1.0 and z = 2.0). A real cluster simply has more of everything — and we will see that -scaling this model up to hundreds of members does not add a single free parameter. +We use a simplified simulated cluster containing: + +- Two individually modeled lens galaxies: a brightest cluster galaxy, or BCG, and a satellite. +- Ten additional member galaxies whose masses follow a luminosity-based scaling relation. +- A shared dark matter halo with input `mass_at_200` of $10^{15.3}$ solar masses. +- Two multiply imaged sources at redshifts 1.0 and 2.0. + +The cluster's deflecting components are all at redshift 0.5. + +This example demonstrates the catalogue and fitting workflow with a small member population. Adding more members +need not add non-linear mass parameters when their positions and profile properties are fixed or tied through +the same relation, although evaluating their deflections still adds computational work. + +Real clusters can require additional halos, more flexible galaxy models and further treatment of redshift or +membership uncertainties. """ dataset_name = "simple" dataset_path = Path("dataset") / "cluster" / dataset_name @@ -135,21 +129,32 @@ ) """ -We first load and plot the cluster's CCD imaging. Note the pixel scale of 0.2" and the sheer size of the -field: 100" x 100", compared to the ~6" fields of the galaxy-scale tutorials. The Einstein radius of a -10^15 solar-mass cluster is ~20-30", so its multiple images and arcs are spread across a region hundreds of -times larger in area than a galaxy-scale lens. +We first load and plot the simulated cluster image. Its pixel scale is 0.2" and its field spans 100" x 100", +allowing us to see the cluster galaxies and widely separated lensed images. + +Inspect where the multiple images lie relative to the central galaxies and member population. -The imaging is loaded for visualization only — as we discuss next, the model is not fitted to these pixels. +The angular extent of strong lensing depends on the mass distribution and source redshift, not simply the +cluster's total halo mass. + +We use this image for visualization. The fit below uses measured multiple-image positions rather than these +image pixels. """ data = al.Array2D.from_fits(file_path=dataset_path / "data.fits", pixel_scales=0.2) aplt.plot_array(array=data, title="Cluster CCD Imaging") """ -The simulator saved the true `Tracer` used to make this dataset, which we can load to inspect the multi-plane -structure described above. The tracer has three planes: the lens plane at z = 0.5 (holding all 13 lens-plane -galaxies — 2 main galaxies, 10 scaling members and the dark matter halo) and one source plane per source. +We load the `Tracer` saved by the simulator to inspect its redshift structure. + +It contains three planes: the cluster plane at $z=0.5$, followed by source planes at $z=1.0$ and $z=2.0$. + +The cluster plane contains 13 `Galaxy` objects: two main galaxies, ten scaling-relation members and one mass-only +object carrying the shared dark matter halo. The halo's use of a `Galaxy` container is an API convention; it does +not represent an additional luminous galaxy. + +All deflecting mass in this example lies on the cluster plane. The two source planes specify where we evaluate +the mappings for their respective background sources. """ tracer_true = al.from_json(file_path=dataset_path / "tracer.json") @@ -160,45 +165,39 @@ """ __Point Source Modeling__ -In every previous tutorial we fitted the data pixel-by-pixel: a model image of the lens and source light was -computed, convolved with the PSF and compared to every image pixel. For a cluster this becomes computationally -prohibitive: +We now describe each multiply imaged source using a set of image positions rather than fitting its full +surface-brightness distribution. -- Every one of the tens of sources needs its own light model (or pixelization), each adding parameters (or an - expensive linear inversion) to the fit. +For extended galaxies, these positions should identify **corresponding features** in the different images -- for +example, recognizable knots that represent the same source structure. Selecting each image's brightest pixel +independently does not necessarily identify matching features. -- The image is enormous — our modest simulated cluster already spans 500 x 500 pixels — and the deflection - angles of hundreds of member galaxies would need evaluating at every one of them, for every likelihood - evaluation. +This reduces the amount of data evaluated during the fit and avoids constructing a light-profile or pixelized +reconstruction for every source. It is a widely used approach for building cluster mass models. -The standard approach in cluster lensing therefore simplifies the data dramatically: each multiply-imaged -source is reduced to the **positions of its multiple images** — the (y,x) coordinates of the brightest pixel -of each image, measured from the imaging. The model then only has to answer a much cheaper question: does this -mass model ray-trace all of a source's observed image positions back to the same source-plane location? +The trade-off is that position fitting does not use the full information in the extended arcs. Surface-brightness +modeling can provide complementary constraints and remains possible for selected systems or more detailed analyses. -This is **point-source modeling**. We are deliberately discarding the information in the arcs' extended light -in exchange for a likelihood that is fast enough to evaluate with hundreds of galaxies and tens of sources. -(For lensed quasars and supernovae — genuine point sources — nothing is even discarded.) Extended-source -cluster modeling, where individual arcs are fitted at pixel level with the pixelizations of the previous -chapter, does exist in **PyAutoLens** as a specialised follow-up analysis — see the `autolens_workspace` -cluster examples — but position fitting is the workhorse that published cluster mass models are built on. +For genuine point sources such as quasars or supernovae, image positions are natural measurements, although +fluxes, time delays and other observables can provide additional information. __Point Datasets__ -The positions of each source's multiple images are stored in a single CSV file, `point_datasets.csv`, with -one row per observed multiple image: +We load the multiple-image measurements from `point_datasets.csv`, with one row per observed image: + +- `name`: identifies the source or matched source feature. Rows sharing a name form one multiple-image system. +- `y`, `x`: its observed image-plane coordinates in arcseconds. +- `positions_noise`: the positional uncertainty adopted by the likelihood, in arcseconds. +- `redshift`: the source redshift, shared by the rows belonging to that system. - - `name`: the source identifier (e.g. `point_0`). All rows sharing a `name` belong to the same source. - - `y`, `x`: the image-plane position of the multiple image, in arc-seconds. - - `positions_noise`: the positional uncertainty in arc-seconds — how precisely the image's centroid is - measured (for space-telescope imaging ~0.005", set by PSF-fitting precision, not the pixel scale). - - `redshift`: the source redshift, which every row of a group must share. This column is what makes the - multi-plane geometry reproducible from the file alone. +The positional uncertainty should reflect the measurement and modeling assumptions. Precise centroid measurements +do not imply that a simplified cluster mass model predicts positions to the same precision; unresolved structure +and other modeling limitations can also matter. -This CSV is the recommended input format for cluster datasets because it is hand-editable: measuring your own -cluster's multiple images means filling in a spreadsheet, not writing Python. +For this simulation, we use the supplied uncertainties. For real observations, choose and justify them rather +than adopting a universal value from the pixel scale or telescope resolution. -`al.list_from_csv` loads the file into a list of `PointDataset` objects, one per source. +`al.list_from_csv` loads the file into a list of `PointDataset` objects, one per named system. """ dataset_list = al.list_from_csv(file_path=dataset_path / "point_datasets.csv") @@ -208,10 +207,15 @@ print(f"Redshift: {dataset.redshift}") """ -Plotting each dataset shows just how sparse point-source data is: a handful of (y,x) coordinates per source. -That a full cluster mass model can be constrained by so few numbers is because each coordinate is measured to -milli-arcsecond precision, and because every source at its own redshift probes the mass distribution -differently. +Plot each dataset to inspect its multiple-image positions. + +Each system supplies a small set of coordinates that must be consistent with a common source position under the +lens model. Systems distributed across the cluster probe different parts of its deflection field, while their +redshifts determine the appropriate lensing geometry. + +The information available depends on the number and configuration of images, their uncertainties and the model's +flexibility. A small number of precise positions does not automatically determine a unique cluster mass +distribution. """ for dataset in dataset_list: aplt.plot_grid( @@ -222,36 +226,29 @@ """ __The CSV Interface__ -With hundreds of member galaxies, composing the lens model in Python — one `af.Model(al.Galaxy)` per galaxy, -as in every previous tutorial — stops being sensible. The cluster workflow therefore defines the model in CSV -files as well, which the simulator wrote alongside the data: +CSV files provide a convenient way to organize a model containing many components. They separate the measured +catalogue and profile choices from the Python code that assembles the model. + +The simulator supplies: - - `mass.csv`: every individually-modelled mass profile — the two main lens galaxies' `dPIEMassSph` profiles - and the host halo's `NFWMCRLudlowSph`. - - `light.csv`: the light profiles (not used in point-source modeling, since light does not lens). - - `point.csv`: the source galaxies' `Point` components. +- `mass.csv`: the individually described mass profiles, including the main galaxies and shared dark matter halo. +- `light.csv`: light-profile descriptions, which are not needed for this positions-only likelihood. +- `point.csv`: the source point components. -Each row of these CSVs carries: +Each profile row specifies a galaxy name, attribute name, profile class, redshift and relevant profile parameters. +Rows with the same galaxy name are assembled into one `Galaxy`. - - `galaxy`: a galaxy name (e.g. `lens_0`, `host_halo`, `source_0`). Rows sharing a name compose into one - galaxy. - - `attr_name`: the attribute the profile is bound to on the galaxy (e.g. `mass`, `dark`, `point_0`). - - `profile_class`: the profile class name (e.g. `dPIEMassSph`), looked up in `al.mp` / `al.lp` / `al.ps`. - - The profile's constructor parameters as columns (tuples like `centre` split into `y` / `x`); parameters a - row's class does not use are left blank. - - `redshift`: the galaxy's redshift. +The lower-mass member population is listed separately in `scaling_galaxies.csv`, with measured positions and +luminosities. We assign its mass profiles and shared scaling relation in Python. -The lower-mass member population lives in a fourth, simpler catalogue, `scaling_galaxies.csv`, with one row -per member and columns `y, x, luminosity`. No profile class, no mass parameters — because, as the previous -tutorial showed, the members' masses are not free parameters but derive from their luminosities via a scaling -relation. The catalogue is exactly what an observer measures: where each member is and how bright it is. +Adding members to this catalogue does not add independent mass parameters **under our fixed-centre, +spherical-profile and shared-relation assumptions**. Adding an individually modeled galaxy or halo can add +parameters, depending on which quantities we allow to vary. -This is the key scaling property of the CSV interface: modeling a richer cluster means appending rows to -`scaling_galaxies.csv` (and, for another individually-modelled galaxy or halo, to `mass.csv`) — the Python -below does not change, and the number of free parameters does not grow with the member count. +The catalogue format makes a larger model easier to assemble; the modeling assumptions determine its +dimensionality. -We load the mass and point families (`al.galaxy_models_from_csv`) and the member catalogue -(`al.galaxy_table_from_csv`): +We now load the mass and point-profile tables, followed by the member catalogue. """ mass_table = al.galaxy_models_from_csv( file_path=dataset_path / "mass.csv", family="mass" @@ -269,24 +266,37 @@ print(f"Scaling galaxies in catalogue: {len(scaling_galaxies_luminosity_list)}") """ -In a real analysis the member centres and luminosities come from light fits to the imaging data (or an -external photometric catalogue), and the main-galaxy centres in `mass.csv` are pinned to the observed light -centres. Fixing the centres to observed values is essential at cluster scale: a handful of multiple-image -positions cannot constrain hundreds of free centre coordinates, but the imaging measures them for free. +In real observations, member positions and luminosities can come from preliminary light fits or a suitable +catalogue. As in earlier tutorials, fixing member mass centres to measured light positions is a useful way to +limit the model's freedom. + +These measurements are not exact, and selected galaxies can be given positional freedom where the data and +scientific question justify it. __Point Solver__ -Point-source modeling needs one new piece of machinery: given a mass model and a source-plane (y,x) -coordinate, where in the image plane do its multiple images appear? Answering this means solving the lens -equation *backwards*, which has no analytic solution. +We met the `PointSolver` earlier when finding the multiple images of a point source, such as a lensed quasar, +behind a single lens galaxy. + +We use exactly the same tool here. Given a mass model and a source position, it solves the lens equation +numerically to locate the multiple images. The difference is that our mass model now contains a cluster halo +and many galaxies, and we repeat the calculation for sources at their respective redshifts. -The `PointSolver` solves it numerically: it tiles the image plane with triangles, ray-traces each triangle's -corners to the source plane, keeps the triangles that land on the source-plane coordinate, and subdivides -them repeatedly until the image positions are located to a precision of `pixel_scale_precision`. +Recall that the solver divides the image plane into triangles, maps them to the source plane and refines +candidate regions until the requested positional resolution is reached. -The solver's grid must span the full 100" cluster field — the multiple images sit tens of arc-seconds from -the cluster centre. The `magnification_threshold` discards heavily demagnified images (e.g. the faint central -image of a typical lens configuration, which real observations do not detect). +The grid should cover the region in which we want to search for images. Here, it spans the same approximate 100" +field as the simulated imaging. Images outside that search region will not be found. + +`pixel_scale_precision` sets the solver's numerical resolution in arcseconds; it is separate from the +observational uncertainties in `positions_noise`. + +`magnification_threshold` filters out predicted images with low absolute magnification. This is a numerical +selection rule, not a complete model of detectability, which also depends on source brightness, noise and blending. + +Unlike an image-plane position likelihood that uses the solver during fitting, our chosen cluster likelihood +back-traces the observed positions without solving for predicted images at every evaluation. We will use the +familiar `PointSolver` after fitting to check the predicted image configuration for each source. """ grid = al.Grid2D.uniform( shape_native=(100, 100), @@ -300,38 +310,30 @@ """ __Model__ -We now compose the cluster model, which has four tiers of component — the same four tiers every published -cluster mass model is built from: +Our example combines four types of component: - - **Main lens galaxies (2)**: the BCG and satellite, modelled individually with `dPIEMassSph` profiles. As - the previous tutorial on group-scale lenses discussed, the dPIE is the standard truncated profile of this - regime: members orbiting in the cluster's shared potential have their outer dark matter tidally stripped, - so their mass genuinely ends at a finite truncation radius `r_cut`. Each main galaxy has free `sigma` (its - fiducial velocity dispersion, setting the lens strength) and free `r_cut`, with its centre fixed to the - observed light centre [4 free parameters]. +- **Two main lens galaxies:** each has a spherical dPIE mass profile with fixed centre and core radius, but free + `sigma` and `r_cut`. Together they contribute **four parameters**. +- **Ten scaling-relation members:** their positions and core radii are fixed. Their velocity-dispersion + normalizations depend on one shared `sigma_ref`; their truncation radii follow a fixed luminosity prescription. + This population contributes **one parameter**. +- **One shared dark matter halo:** an `NFWMCRLudlowSph` profile with fixed centre and free `mass_at_200`. + Its mass-concentration prescription supplies additional structure without an independent concentration + parameter. It contributes **one parameter**. +- **Two background sources:** `PointSolved` components whose source positions are solved within the selected + likelihood rather than sampled independently. They contribute **zero non-linear sampling parameters**. - - **Scaling-tier members (10)**: `dPIEMassSph` profiles with centres fixed from the catalogue and `sigma` / - `r_cut` derived from each member's luminosity via the scaling relation introduced earlier in this chapter: - sigma = sigma_ref * (L / L_ref)^0.25 and r_cut = r_cut_ref * (L / L_ref)^0.7. Only the normalization - `sigma_ref` — the velocity dispersion of a member at the reference luminosity — is free. Whether the - catalogue holds 10 members or 300, the tier costs [1 free parameter]. +The total is therefore **six free non-linear parameters**. - - **Host dark matter halo (1)**: a standalone galaxy carrying the cluster's `NFWMCRLudlowSph` halo, centred - on the BCG, with a free total mass `mass_at_200` [1 free parameter]. +This small count reflects strong restrictions on the model: spherical profiles, fixed positions and redshifts, +a prescribed halo mass-concentration relation, and a deterministic member scaling relation. It is not a claim +that real cluster mass distributions generally require only six parameters. - - **Source galaxies (2)**: parameter-free `PointSolved` components. Rather than sampling each source's - (y,x) source-plane centre as free parameters, the fit solves for the centre analytically — the - precision-weighted mean of the back-traced image positions. With tens of sources this matters: it removes - two parameters per source from the search [0 free parameters]. +The model contains twelve lens galaxies, one mass-only halo component and two source objects. Adding more tied +members preserves the parameter count only while those restrictions remain in place. -**Total: N = 6 free parameters** — for a model containing 13 galaxies and 2 sources. This is the punchline of -the cluster workflow: catalogues and scaling relations decouple the model's physical richness from the -dimensionality of the non-linear search. - -`al.galaxy_af_models_from_csv_tables` converts the CSV tables into a dictionary of `af.Model(Galaxy)` objects -keyed by galaxy name, with every CSV value fixed as a default. We then selectively promote parameters to free -priors — exactly the `af.Model` customization API used throughout the earlier chapters, just applied to -models built from files instead of Python. +`al.galaxy_af_models_from_csv_tables` builds the named galaxy models from the CSV tables, initially fixing their +supplied values. We then assign priors to the particular parameters we want the search to vary. """ redshift_lens = 0.5 source_redshifts = [dataset.redshift for dataset in dataset_list] @@ -339,10 +341,17 @@ galaxy_models = al.galaxy_af_models_from_csv_tables(mass_table, point_table) """ -The main lens galaxies get free dPIE `sigma` / `r_cut`; their centres and redshifts stay fixed at the CSV -values, and `r_core` stays fixed at the CSV's 0.0 (the vanishing-core convention discussed in the previous -tutorial). The cosmology constants `H0` / `Om0` are pinned explicitly: they are model *constants*, not -parameters to sample — left unset they would inherit priors from the configuration files and float. +We give each main lens galaxy two free dPIE parameters: `sigma`, which controls its mass normalization, and +`r_cut`, which controls its outer truncation scale. + +Their centres, redshifts and zero core radii retain the values supplied by the catalogue. As in the group +tutorial, `sigma` uses the Lenstool profile convention and is not automatically identical to a measured stellar +velocity dispersion. + +We explicitly fix `H0` and `Om0`, because this example assumes a cosmology rather than attempting to infer it. + +The prior ranges below are choices for this simulated example. For real data, they should reflect the system +being studied, and results near their boundaries warrant further inspection. """ for name in ("lens_0", "lens_1"): galaxy_models[name].mass.sigma = af.UniformPrior( @@ -353,27 +362,55 @@ galaxy_models[name].mass.Om0 = 0.30966 """ -The host halo gets a free `mass_at_200`, spanning the full range of cluster masses with a log-uniform prior -(mass scales spanning orders of magnitude are sampled in log space, as we saw for intensities in earlier -chapters). +The shared dark matter halo receives a free `mass_at_200` parameter, expressed in solar masses. + +This is the mass parameter of the NFW host component, not the sum of every mass component in our cluster model. +The main galaxies and scaling-relation members contribute additional mass. + +The `NFWMCRLudlowSph` profile uses a prescribed mass-concentration relation, so changing the halo mass also changes +its associated profile structure. We do not fit concentration independently here. + +We use a log-uniform prior from $10^{14.5}$ to $10^{16}$ solar masses, assigning equal prior weight to equal +logarithmic intervals. This is a broad example range, rather than a universal prior for cluster lenses. """ galaxy_models["host_halo"].dark.mass_at_200 = af.LogUniformPrior( lower_limit=10**14.5, upper_limit=10**16.0 ) """ -Each source's `point_i` component is swapped for the parameter-free `al.ps.PointSolved`. The name pairing -(`point_0`, `point_1`) is what links each model component to the `PointDataset` with the same name — in a -multi-source cluster this pairing is what guarantees every source's positions are fitted by the correct -component. +We replace each source's point component with `PointSolved`. + +With the source-plane likelihood used below, the source position is solved from the back-traced image positions +for each proposed mass model, rather than sampled as two independent coordinates. + +This does not mean the source position is known exactly or remains fixed. It changes as the mass model changes, +and its interpretation depends on the positional uncertainties and likelihood assumptions. + +Each component name, such as `point_0`, must match the name of its `PointDataset`. We also retain the source +redshift associated with that dataset so that its images are traced to the correct plane. """ for i, dataset in enumerate(dataset_list): setattr(galaxy_models[f"source_{i}"], f"point_{i}", af.Model(al.ps.PointSolved)) -""" -The scaling tier is composed in a loop over the catalogue, exactly as in the previous tutorial: the single -shared prior `scaling_sigma_ref` is defined once outside the loop, and each member's `sigma` / `r_cut` derive -from it via that member's luminosity ratio. The truth value used by the simulator is sigma_ref = 85 km/s. +r""" +We build the member population by looping over its measured positions and luminosities, using the same approach +as in the previous tutorials. + +The shared `scaling_sigma_ref` prior is defined once, outside the loop. Each member's `sigma` is an expression +involving that prior and its fixed luminosity ratio. + +Each `r_cut`, however, is calculated entirely from fixed quantities: the reference truncation scale, luminosity +ratio and exponent. It therefore receives a fixed value, rather than depending on `scaling_sigma_ref`. + +We adopt $\sigma\propto L^{0.25}$ and $r_{\rm cut}\propto L^{0.7}$, with fixed centres and zero core radii. +These assumptions leave one free mass parameter for the entire member population. + +The simulator used `sigma_ref = 85 km/s`. We will later inspect whether the fit constrains this normalization. + +The dPIE `redshift_source` input specifies the reference source redshift used to normalize the profile's lensing +quantities. Here, we use the highest source redshift consistently for the scaling members. The tracer then +evaluates the lens mapping to each source's own plane; this does not place every source at that reference +redshift. """ scaling_sigma_ref = af.UniformPrior(lower_limit=0.0, upper_limit=200.0) scaling_sigma_exponent = 0.25 # alpha (Faber-Jackson) @@ -405,8 +442,17 @@ scaling_galaxies = af.Collection(scaling_galaxies_list) """ -The named galaxies and the scaling tier combine into the overall model. Printing `model.info` confirms the -parameter count: for all its 15 galaxies, the search explores just 6 dimensions. +We combine the individually named components and scaling-relation members into the overall model. + +The `galaxies` collection contains the two main lens galaxies, the mass-only host-halo component and the two +sources. The `scaling_galaxies` collection contains the ten additional members. + +This gives **15 `Galaxy` objects**, representing twelve lens galaxies, one shared dark matter halo and two +background sources. + +Inspect `model.info` to check the fixed values, independent priors and linked expressions. Under the assumptions +above, the model has **six free non-linear parameters**: four for the main galaxies, one for the host halo and +one shared by the scaling members. """ model = af.Collection( galaxies=af.Collection(**galaxy_models), @@ -416,36 +462,44 @@ print(model.info) """ -The same model can also be visualized as a figure, making its structure easier to understand at a glance. +The figure shows the model's independent priors, fixed values and linked expressions. + +Each main galaxy has its own free `sigma` and `r_cut`. The host halo has one free mass parameter, and the ten +scaling members share one `scaling_sigma_ref` prior. -The figure shows how the model is organized: which parameters belong to each component, and whether they are free, -fixed, shared, linked by an expression, solved during the fit, or not configured. `model.info` provides the -corresponding numerical details, including the prior assigned to each free parameter and the value of each fixed -parameter. +The source positions are solved within the selected likelihood rather than sampled independently. -Thirteen galaxies and two sources are modelled with six free parameters. That compression — main galaxies and -sources sharing priors, one halo, and a scaling relation tying ten members to a single free prior — is what makes -a cluster-scale model tractable at all. +These choices give six non-linear parameters across fifteen `Galaxy` objects. The small parameter count comes +from the restrictions and shared relations we imposed, rather than from the catalogue format itself. """ af.ModelPlotter(model).figure() """ __Analysis + Factor Graph__ -Each source's dataset gets its own `AnalysisPoint`, which defines the log likelihood for that source: how -well do the model's predictions match this source's observed image positions? +We create one `AnalysisPoint` for each source's dataset. Each analysis evaluates how well the same cluster mass +model explains that source's observed multiple-image positions. + +We select `FitPositionsSourceSolved`, which: + +1. Traces the observed image positions back to the source's redshift plane. +2. Solves for a common source position under the adopted weighting. +3. Evaluates the scatter around that position using the positional uncertainties and the likelihood's + source-plane weighting. -`fit_positions_cls=al.FitPositionsSourceSolved` selects the **solved source-plane** likelihood — the default -cluster configuration. Rather than forward-solving the lens equation for the model's image positions on every -likelihood evaluation (accurate but expensive), it ray-traces the *observed* positions back to the source -plane and measures how tightly they converge around the analytically-solved source centre, with a weighting -that maps source-plane scatter back to image-plane precision. No lens-equation solve per evaluation makes -cluster-scale inference fast; the `PointSolver` is reserved for validating the final model below. +This avoids solving for predicted image positions at every likelihood evaluation. It is a source-plane fitting +approach, rather than a direct comparison between observed and forward-solved image positions. -The analyses are then combined through a **factor graph**, the same multi-dataset machinery used for -multi-wavelength imaging: each analysis becomes a factor sharing the one global model, and the total log -likelihood is the sum over the per-source likelihoods. This is what lets every source — each at its own -redshift, each with its own multi-plane geometry — constrain the same cluster mass model simultaneously. +We will use the `PointSolver` afterwards to inspect the predicted images. That check is important because a +compact set of back-traced positions does not by itself establish that the model predicts the observed image +configuration. + +We combine the analyses using a **factor graph**. Each source contributes a likelihood factor, and all factors +share the same global mass model. + +Assuming the datasets are conditionally independent given that model, the total log likelihood is the sum of +their individual log likelihoods. The shared parameters are sampled once, with every source contributing +constraints through its own positions and redshift. """ analysis_list = [ al.AnalysisPoint( @@ -467,8 +521,13 @@ """ __Search__ -We fit the model with Nautilus. The parameter space is only 6-dimensional, so a modest number of live points -suffices; a richer cluster with several individually-modelled galaxies would warrant more. +We use `Nautilus` with 100 live points as the starting configuration for this six-parameter example. + +A low parameter count helps, but does not guarantee a simple posterior. Correlations between the halo, main +galaxies and member normalization can still make inference challenging. + +Inspect the resulting fits and posterior distributions, and assess whether important conclusions remain stable +under repeated runs or more demanding search settings. """ search = af.Nautilus( path_prefix=Path("howtolens", "chapter_4"), @@ -482,35 +541,39 @@ """ __Model Fit__ -We pass the factor graph's global model and the factor graph itself (as the analysis) to the search. Because -the likelihood involves no pixel-level computation, a full cluster point-source fit takes minutes — this is -the payoff of point-source modeling, given that a pixel-level fit of the same system would take days. -""" -print( - """ - The non-linear search has begun running. +We pass the factor graph's global model and combined analysis to the search. - This Jupyter notebook cell will progress once the search has completed - this could take a few minutes! +Each proposed parameter set defines one cluster mass model, which is evaluated against both source datasets. +Their log likelihoods combine to guide the search. - On-the-fly updates every iterations_per_quick_update are printed to the notebook. - """ +The position-based likelihood avoids constructing a full model image at each evaluation. Runtime nevertheless +depends on the model, number of images and members, hardware and search settings. + +When the search finishes, we will inspect both the global mass parameters and the fit to each source. +""" +print( + "The non-linear search has begun. " + "Progress updates are printed during the search. " + "This cell will finish when the search completes." ) result_list = search.fit(model=factor_graph.global_prior_model, analysis=factor_graph) -print("The search has finished run - you may now continue the notebook.") +print("The search has finished — you may now continue the notebook.") """ __Results__ -A cluster fit produces the most complex results object we have met: many galaxies across multiple planes, -tiers whose parameters are derived rather than sampled, and one result per source dataset. This section tours -how to pull out each quantity you will actually need — it is worth working through slowly, because navigating -results is half the practical skill of cluster modeling. +The factor-graph fit returns one result per source dataset, in the same order as `dataset_list`. + +These results come from **one joint inference**, not separate searches. They share the global mass model and +posterior, while each provides access to its own dataset and corresponding `FitPointDataset`. + +We first use one result to inspect the shared model parameters and tracer. We then loop over the results to +examine each source's inferred position and fit diagnostics. -A factor-graph fit returns one `Result` per dataset (in the same order as `dataset_list`). All results share -the same global model — and therefore the same samples and maximum likelihood model — but each carries its own -dataset and its own maximum likelihood `FitPointDataset`. +This separates two useful questions: what mass distribution describes the cluster, and how well does that +distribution explain each observed multiple-image system? """ print(f"Number of results (one per source dataset): {len(result_list)}") @@ -519,9 +582,14 @@ """ __Results: The Maximum Likelihood Instance__ -The `max_log_likelihood_instance` is the model instance with the highest likelihood found. Its structure -mirrors the model composition above: named galaxies under `.galaxies`, the scaling tier under -`.scaling_galaxies`. We can read off the best-fit parameters of every tier. +The `max_log_likelihood_instance` contains the parameter values of the highest-likelihood sample found by +the search. + +Its structure follows the model we constructed: named components appear under `.galaxies`, while the tied +members appear under `.scaling_galaxies`. + +We can inspect the main galaxies' dPIE parameters and the host halo's `mass_at_200` directly. These describe one +fitted realization; later, we use the posterior samples to examine their uncertainties and correlations. """ instance = result.max_log_likelihood_instance @@ -536,10 +604,18 @@ """ __Results: Per-Member Profiles__ -The scaling tier's single free parameter was `sigma_ref`, but the instance contains the fully-realised -`dPIEMassSph` of every member — the scaling relation has been applied, so each member carries the `sigma` and -`r_cut` its luminosity implies. This is how you would tabulate the inferred mass of every member galaxy in a -real cluster analysis. +Although the member population shares one free normalization, the fitted instance contains a complete +`dPIEMassSph` profile for every member. + +Each member's `sigma` has been calculated from the fitted shared normalization and its luminosity ratio. +Its centre, core radius and luminosity-derived truncation radius retain their fixed values. + +The loop below lists these realized profile parameters. They are not independent measurements of every member's +mass: they inherit the scaling relation and its assumptions. + +To quantify their uncertainties, evaluate the derived quantities across posterior samples. With fixed +luminosities and exponent, the members' `sigma` values vary together through their shared normalization. +Intrinsic scatter and photometric uncertainty are not included unless explicitly modeled. """ for i, member in enumerate(instance.scaling_galaxies): print( @@ -550,10 +626,19 @@ """ __Results: The Tracer__ -`max_log_likelihood_tracer` assembles every galaxy of the instance — named tiers and scaling members alike — -into the best-fit multi-plane `Tracer`. This is the object to use for any lensing calculation with the -best-fit mass model: convergence maps, deflection fields, critical curves and caustics, all computed exactly -as in the earlier chapters, but now for the full cluster. +`max_log_likelihood_tracer` assembles the named components and scaling members into a tracer for the fitted model. + +It provides the same lensing calculations used in earlier chapters, now with the full cluster mass distribution +and both source redshifts. + +Inspect the plane redshifts and number of objects in the lens plane. Remember that the host halo occupies a +mass-only `Galaxy` object alongside the twelve lens galaxies. + +When calculating quantities such as critical curves or magnifications, specify the relevant source plane: +the same cluster produces different lens mappings for sources at different redshifts. + +This tracer represents one fitted realization. Uncertainty in derived lensing quantities requires repeating +the calculation over appropriate posterior samples. """ tracer = result.max_log_likelihood_tracer @@ -565,11 +650,17 @@ """ __Results: Solved Source-Plane Positions__ -Each result's `max_log_likelihood_fit` is the `FitPointDataset` of that source. Because we fitted with the -solved source-plane likelihood, the fit's `positions` object carries the analytically-solved source-plane -centre — the model's inferred true position of the source, before lensing. Its `residual_map` lists how far -each back-traced image lands from that centre (in the source plane): for a good model these residuals are -tiny, since all images of a source originate from the same point. +Each result's `max_log_likelihood_fit` describes the fit to its own source dataset. + +With our selected likelihood, `fit.positions.source_plane_coordinate` gives the source position solved from +that system's back-traced image positions under the fitted mass model. + +The `residual_map` records their offsets from this common position in the source plane. Inspect these together +with the positional uncertainties and likelihood weighting, rather than judging the fit solely by whether +the raw offsets look small. + +The printed log likelihood is the position-likelihood contribution for that source. The joint inference combines +the contributions from all source datasets. """ for result in result_list: fit = result.max_log_likelihood_fit @@ -582,11 +673,18 @@ print(f" Log likelihood: {float(fit.positions.log_likelihood):.2f}") """ -We can perform the same back-tracing manually with the tracer, which makes explicit what the fit just did: -ray-trace each source's observed image positions through the multi-plane lens equation to that source's own -plane. `plane_index_via_redshift_from` maps a source redshift to its plane, and `traced_grid_2d_list_from` -returns the positions traced to every plane — the multi-plane generalisation of the two-plane ray tracing of -chapter 1. +We can inspect the same mapping directly using the tracer, following the ray-tracing approach introduced in +Chapter 1. + +For each dataset, we identify its source plane from its redshift and trace the observed image positions through +the model. We then select the coordinates at that source plane. + +Images identified as the same source feature should map to a common location within the accuracy allowed by the +data and model. Differences between their back-traced positions reveal where the proposed mass distribution +does not bring them into agreement. + +This calculation displays the traced coordinates. It does not reproduce the full likelihood weighting or +independently calculate the solved source position. """ for dataset in dataset_list: plane_index = tracer.plane_index_via_redshift_from(redshift=dataset.redshift) @@ -598,14 +696,15 @@ """ __Results: Magnifications__ -The magnification of each multiple image tells us how much the cluster brightens the source at that position — -the "natural telescope" number. It is computed from the local distortion of the multi-plane deflection field -(its Hessian) at each observed position, via the `LensCalc` object. `plane_j` selects the source's plane, so -each source's magnifications are evaluated through its own multi-plane chain. +We calculate the magnification at each observed image position using the fitted tracer. -At cluster scale, images near the critical curves can reach magnifications of tens to hundreds — this is -precisely the quantity you would quote when using the cluster to study an intrinsically faint background -galaxy, since the source's true luminosity is the observed luminosity divided by the magnification. +`plane_j` selects the relevant source plane, ensuring that each calculation uses the geometry appropriate to that source’s redshift. + +Magnification describes the local change in image area and, because lensing preserves surface brightness, the corresponding amplification of a sufficiently small source element. The code prints its absolute value; the sign also carries information about image parity. + +For an extended arc, the magnification can vary substantially across the image. The value at one position is therefore not necessarily the appropriate correction for the arc’s total flux. + +Near critical curves, magnifications can be large and sensitive to the mass model and source position. To infer an intrinsic luminosity, use a magnification appropriate to the measured emission and propagate the lens-model uncertainty. """ for dataset in dataset_list: plane_index = tracer.plane_index_via_redshift_from(redshift=dataset.redshift) @@ -622,11 +721,17 @@ """ __Results: Image-Plane Validation__ -The solved source-plane likelihood never solves the lens equation forwards, so it cannot tell us whether the -best-fit model predicts the *right number* of multiple images — a model that would produce an extra image, or -lose an observed one, looks the same to it. The standard final check is therefore to forward-solve the -best-fit model with the `PointSolver` and compare the predicted image positions to the observed ones, -per source. +Our source-plane likelihood compares the back-traced positions of the observed images. It does not explicitly search for every image predicted by the model. + +We therefore return to the familiar `PointSolver`. For each source, we use its solved source position and redshift to predict the image-plane positions, then compare them with the observations. + +Inspect both their positions and their number. Significant mismatches can reveal limitations that were not apparent from the source-plane residuals alone. + +The comparison also depends on the solver’s search region, numerical resolution and magnification threshold. An apparently missing predicted image may lie outside the searched region or have been filtered out. + +Conversely, an additional predicted image is not automatically ruled out by its absence from the catalogue: it may be too faint, blended with a galaxy or outside the observations. Assess its expected detectability before interpreting it as a failure of the mass model. + +This is a diagnostic of the fitted realization. Important conclusions should also be checked across the posterior and, where appropriate, with an image-plane likelihood. """ for result, dataset in zip(result_list, dataset_list): fit = result.max_log_likelihood_fit @@ -653,10 +758,17 @@ """ __Results: Samples and Errors__ -Everything above used the maximum likelihood model, but the `Samples` object gives the full posterior — the -same API as chapter 2, unchanged by the cluster's complexity. Of particular scientific interest here are the -inferred halo mass and the scaling-relation normalization `sigma_ref` (whose truth value in the simulator was -85 km/s): the marginalised errors on these are what a cluster paper reports. +The calculations above used one fitted realization. The posterior samples describe the range of model parameters supported by the data under our chosen priors and assumptions. + +We use the same `Samples` interface introduced in Chapter 2 to inspect marginal medians, credible intervals and correlations. + +Of particular interest are the host halo mass, the main galaxies’ mass-profile parameters and the shared member normalization. Examine their joint distributions: a narrow interval for one parameter does not describe all freedom in the cluster’s mass decomposition. + +The model returned by `median_pdf()` contains the marginal median of each parameter. It is a useful summary, but need not be a single sampled realization or the best-fitting combination. + +The intervals below describe posterior uncertainty within this model. They do not automatically include uncertainties associated with fixed redshifts, member luminosities, the mass–concentration relation or omitted mass structure. + +The corner plot helps reveal these parameter correlations and whether the sampled distributions approach their prior boundaries. """ samples = result_list[0].samples @@ -680,53 +792,31 @@ """ __Customization__ -This tutorial used the default point-source setup throughout: `Point` / `PointSolved` source components, the -solved source-plane likelihood, and default `PointSolver` settings. Point-source modeling has a rich set of -options beyond these — image-plane likelihoods and their pairing schemes, free source centres, fitting the -fluxes of the multiple images, fitting time delays (the observable behind lensed-quasar cosmology) — and a -dedicated workspace guide covers them extensively: - - - `autolens_workspace/scripts/point_source`: the galaxy-scale point-source examples (lensed quasars and - supernovae), including the `fit.py` guide to every fit variant and the `features` folder (fluxes, time - delays, multiple sources). - - `autolens_workspace/scripts/guides/point_solver/pairing.py`: the full matrix of position-fitting schemes - and when to use each. - - `autolens_workspace/scripts/cluster`: the cluster-scale workflow this tutorial is built on, including a - fit to real Hubble Space Telescope data of the cluster Abell 2744 with 188 catalogue members and 7 - sources, the CSV-schema guide (`csv_api.py`) and a step-by-step walkthrough of the point-source - likelihood (`likelihood_function.py`). +This tutorial used solved source positions and a source-plane position likelihood. Other analyses may require image-plane likelihoods, independently sampled source positions, flux measurements or time delays. -__Wrap Up__ +The workspace provides examples and step-by-step guides: -This tutorial reached the top of the strong-lensing mass ladder. Lets recap what we learnt: +- `autolens_workspace/scripts/point_source`: point-source modeling, including the familiar quasar examples and additional observables. +- `autolens_workspace/scripts/guides/point_solver/pairing.py`: image-position pairing schemes and their use. +- `autolens_workspace/scripts/cluster`: cluster workflows, CSV inputs and a walkthrough of the cluster point-source likelihood. -- **Clusters**: 30+ to hundreds of lens galaxies inside a dark matter halo of more than 10^14 solar masses, - lensing many background sources at once. Their science is extreme magnification — using the cluster as a - natural telescope onto the faint early Universe — and mapping the cluster's dark matter distribution. +Use these guides when adapting the tutorial to a different dataset or likelihood. -- **Multi-plane ray tracing**: cluster sources sit at different redshifts, so the lens equation is applied - recursively through the planes, with each plane's deflections scaled by cosmological distance ratios. The - `Tracer` handles this automatically, provided every source's redshift is set correctly. +__Wrap Up__ -- **Point-source modeling**: fitting the extended light of every source is computationally prohibitive at - this scale, so the standard workflow fits the positions of each source's multiple images, reducing the - likelihood to source-plane geometry that evaluates in milliseconds. +In this tutorial, we learned: -- **The CSV interface**: the data (`point_datasets.csv`), the individually-modelled galaxies (`mass.csv` / - `point.csv`) and the member catalogue (`scaling_galaxies.csv`) are all spreadsheet-editable files. Scaling - the model to a richer cluster is a row-append, not a code change. +- Cluster lenses combine a shared dark matter halo with many individual galaxies and can multiply image sources at several redshifts. +- Multiple source planes require the appropriate redshift-dependent geometry. Multiple **deflecting** planes arise when significant mass lies at different redshifts. +- Position fitting uses matched image features to constrain the mass model without reconstructing every arc’s full surface brightness. +- CSV catalogues organize the data and model components; fixed quantities and shared relations determine how many parameters remain free. +- Our restricted example has six non-linear parameters. That compactness comes from its assumptions, rather than implying that cluster mass distributions are intrinsically simple. +- A joint fit combines the source datasets while allowing us to inspect each system’s contribution separately. +- Interpreting the result requires both posterior uncertainties and checks of the predicted image configuration. Derived member masses and magnifications inherit the model’s assumptions. -- **Six parameters, fifteen galaxies**: fixed observed centres, a scaling relation for the member population - and solved source centres decouple the model's physical richness from the dimensionality of the search. +Strong lensing has now taken us from individual galaxies to groups and clusters. -- **Results access**: per-member realised profiles, the multi-plane tracer, solved source-plane centres, - per-image magnifications and forward-solved image positions — the complete toolkit for interpreting a - cluster fit. +Beyond the central region producing multiple images, the same mass distribution continues to distort background galaxies. Those distortions are often too small to identify reliably in an individual galaxy because its unlensed shape is unknown. -Strong lensing — multiple images, arcs, Einstein rings — has carried us from single galaxies to the most -massive structures in the Universe. But a cluster's gravity does not stop deflecting light at the radius -where multiple images form. Far beyond it, every background galaxy is still subtly sheared — distorted by a -percent or less — and by measuring those distortions statistically across thousands of galaxies, the -cluster's mass can be mapped out to its edges. That is **weak lensing**, a different regime with different -data and different statistics, and it is where the next tutorial takes us. +By measuring the coherent distortions across a population of background galaxies, we can constrain mass over a much wider region. This is **weak lensing**, the subject of the final tutorial in this chapter. """ diff --git a/scripts/chapter_4_scaling_up_lensing/tutorial_6_weak_lensing.py b/scripts/chapter_4_scaling_up_lensing/tutorial_6_weak_lensing.py index 8e32c59..86e59d1 100644 --- a/scripts/chapter_4_scaling_up_lensing/tutorial_6_weak_lensing.py +++ b/scripts/chapter_4_scaling_up_lensing/tutorial_6_weak_lensing.py @@ -2,58 +2,36 @@ Tutorial 6: Weak Lensing ======================== -Every tutorial in this series so far — indeed, every fit performed in all four chapters of **HowToLens** — has been -a *strong* lensing analysis. Strong lensing occurs when a background galaxy lies so close (in projection) to a -foreground mass that its light is bent into multiple images, arcs or a complete Einstein ring. These dramatic -features are what we simulated, fitted and modeled, from the single galaxy-scale lenses of chapters 1 and 2 up to -the group-scale and cluster-scale systems earlier in this chapter. - -Strong lensing is spectacular, but it is also rare and spatially confined. Multiple images only form inside (or very -near) the Einstein radius, so a strong-lensing analysis constrains the mass distribution only within that region — -a few arc-seconds for a galaxy, tens of arc-seconds for a cluster core. Outside it, the arcs and multiple images -simply do not exist, and everything we have built so far has nothing to fit. - -Yet the gravity of the foreground mass does not stop at the Einstein radius. *Every* background galaxy, however far -from the lens centre, has its shape slightly distorted — sheared — by the foreground mass it sits behind. This is -**weak lensing**: a percent-level stretching of each background galaxy's observed ellipticity, tangentially aligned -around the foreground mass. - -The catch is that we cannot see this distortion in any single galaxy. Galaxies are not intrinsically round: a -typical galaxy has a random unlensed ellipticity of ~0.25 per component, whereas the weak-lensing shear it receives -is ~0.01-0.1. The signal is buried an order of magnitude below the intrinsic "shape noise" of any one object. - -The solution is statistical. The intrinsic ellipticities of different galaxies are randomly oriented and average to -zero, whereas the lensing shear is coherent — every galaxy near a given point on the sky is sheared the same way. -Average the measured shapes of many background galaxies and the random part cancels while the lensing part remains. -This is the fundamental contrast with everything the series has done so far: strong lensing extracts an exquisite -signal from a single special system, weak lensing extracts a faint signal from the ensemble of many ordinary ones. - -This changes what the data even *is*. There is no image to fit, no PSF to convolve, no mask, no pixelized source -reconstruction. A weak-lensing dataset is a **shear catalogue**: a table of background-galaxy sky positions, each -with a measured shear estimate (two ellipticity components) and a per-galaxy uncertainty. Fitting one means -comparing a mass model's predicted shear field, evaluated at those positions, against the measured values. - -In this tutorial we simulate a weak-lensing shear catalogue around a cluster-scale lens (entirely in memory — no -files are written), visualize its shear field, fit it with a mass model whose parameters we know, and then infer -those parameters with a non-linear search. You will recognise every step: the `Tracer`, `Fit`, `Analysis` and -search workflow of the whole series, applied to a completely different kind of data. +Our modeling tutorials have concentrated on **strong lensing**: the multiple images, arcs and Einstein rings produced by galaxy, group and cluster lenses. + +In the previous tutorial, we used the positions of multiply imaged sources to constrain a cluster’s mass distribution. Those images provide particularly valuable information in the central region where they form. To measure the mass distribution over a much wider region, we can also use **weak lensing**. + +The same gravitational field distorts the shapes of background galaxies beyond the region containing prominent arcs. These distortions are usually difficult to distinguish from a galaxy’s unknown intrinsic shape: an elongated galaxy might have been elongated even without lensing. + +The signal becomes measurable statistically. Nearby background galaxies experience a coherent lensing distortion, while their intrinsic orientations contribute scatter. Measuring many galaxies allows us to estimate that coherent signal. + +This scatter is called **shape noise**. Increasing the number of usable background galaxies reduces its contribution to the uncertainty, although observational biases and correlations between intrinsic galaxy shapes also require attention in real analyses. + +You first encountered a weak-lensing dataset in Chapter 1. Here we return to its **shear catalogue**: background-galaxy positions, two components describing the estimated distortion, and their uncertainties. + +We simulate a catalogue around a cluster-scale lens, visualize it, inspect a fit using the input mass model, and then infer the model parameters with a non-linear search. The familiar `Tracer`, `Fit`, `Analysis` and search workflow remains central. This tutorial closes both this chapter and the four core chapters of **HowToLens**. __Contents__ -- **Shear Catalogues:** What a weak-lensing dataset is and where the catalogue comes from in a real analysis. -- **Mass Scales:** Why weak lensing is a cluster-scale tool, tying to the mass scales of the previous tutorials. -- **Ray Tracing:** Build a `Tracer` for a cluster-scale lens, the mass whose shear field we will measure. -- **Source Galaxy Positions:** Draw background galaxies in an annulus outside the strong-lensing core. -- **Simulate:** Create a `WeakDataset` in memory with `SimulatorShearYX`, adding realistic shape noise. -- **Visualize:** Plot the shear field as a whisker map and the dataset's 2x2 summary mosaic. -- **Mass Map:** Invert the shear catalogue into a model-independent convergence map (Kaiser-Squires). -- **Fitting:** Fit the catalogue with the true mass model via `FitWeak` and inspect its goodness-of-fit. -- **Model Fit:** Infer the mass model from the shear catalogue alone with `AnalysisWeak` and a non-linear search. -- **Result:** The inferred model, the fit mosaic and the tangential shear profile. -- **Joint Strong and Weak Lensing:** How PyAutoLens expects weak lensing to be used — combined with strong lensing. -- **Wrap Up:** The end of the chapter, and of the core HowToLens lectures. +- **Shear Catalogues:** The measurements used in a weak-lensing analysis. +- **Mass Scales:** Weak lensing around galaxies, groups and clusters. +- **Ray Tracing:** Build a simple cluster-scale mass model. +- **Source Galaxy Positions:** Sample background galaxies across the observed field. +- **Simulate:** Generate a shear catalogue with shape noise. +- **Visualize:** Inspect the shear field and dataset summary. +- **Mass Map:** Reconstruct a convergence map from the catalogue. +- **Fitting:** Inspect the likelihood and residuals for a specified mass model. +- **Model Fit:** Infer mass-model parameters with a non-linear search. +- **Result:** Inspect the inferred model and tangential shear profile. +- **Joint Strong and Weak Lensing:** Combine constraints across different radii. +- **Wrap Up:** Complete the core HowToLens lectures. """ from autolens import jax_wrapper # Sets JAX environment before other imports @@ -67,64 +45,54 @@ import autolens as al import autolens.plot as aplt -""" +r""" __Shear Catalogues__ -Before we simulate anything, lets be clear about what a real weak-lensing dataset looks like, because it is unlike -any data this series has fitted before. +A shear catalogue contains one row per background galaxy, including: + +- Its observed sky position, expressed here as `(y, x)` offsets in arc-seconds. +- Two components describing its estimated lensing distortion. +- An uncertainty that accounts for intrinsic shape dispersion and measurement noise. + +Real catalogues also require information about source redshifts, selection and calibration. The lensing signal depends on the geometry between the observer, lens and source, just as it did for the multiple source redshifts in the cluster tutorial. + +Producing these measurements begins with telescope images. Galaxies must be detected and selected, and their shapes measured while accounting for the PSF, noise and instrumental effects. The PSF can both blur galaxy shapes and introduce coherent distortions that could be mistaken for lensing. -A **shear catalogue** is a table with one row per background galaxy, containing: +We start after this shape-measurement stage. The dataset supplied to this tutorial contains catalogue measurements rather than image pixels, so our likelihood does not convolve a model image with a PSF. This does not make observational systematics disappear: their calibration and uncertainty remain part of a real weak-lensing analysis. - - The galaxy's sky position (for us, (y, x) arc-second offsets from a chosen centre). - - A measured shear estimate (gamma_1, gamma_2) — in practice the galaxy's measured ellipticity components, which - estimate the lensing shear because the intrinsic shape averages to zero over many galaxies. - - A per-galaxy uncertainty, combining the intrinsic shape dispersion (~0.25 per component) with the measurement - error, added in quadrature. +There is also an important distinction between **shear** and **reduced shear**. Galaxy-shape measurements generally estimate the reduced shear: -Producing this catalogue from raw telescope images is a substantial data-reduction task in its own right: galaxies -must be detected, stars separated from galaxies, the PSF measured and its blurring of galaxy shapes corrected -(the PSF makes every galaxy look rounder, diluting the shear signal), and calibration biases characterised. -Dedicated shape-measurement pipelines exist for exactly this job, and entire survey collaborations are built -around getting it right. +\[ +g = \frac{\gamma}{1-\kappa}. +\] -**All of that is outside PyAutoLens's scope.** PyAutoLens assumes the shear catalogue has already been produced -upstream by such a pipeline, and starts where the catalogue ends: fitting mass models to the measured shears. This -division of labour is why the weak-lensing API is so lean — no PSF, no mask, no image — the hard observational -systematics were dealt with before the data reached us. +When the convergence is sufficiently small, reduced shear is approximately equal to shear. This tutorial uses an idealized catalogue of shear measurements generated directly from the model. When working with observed catalogues, check which quantity the measurements estimate and ensure that the model predicts the same quantity. __Mass Scales__ -This chapter has climbed a ladder of mass scales, and weak lensing is its top rung. The strength of the statistical -shear signal around a lens scales with its mass, so whether weak lensing is even measurable depends on where on the -ladder we stand: +Weak lensing is useful across the mass scales explored in this chapter. - - **A single galaxy** (Einstein radius ~1-2", the lenses of chapters 1-3): the shear imprinted on background - galaxies beyond the Einstein radius is far too weak to detect around any one system — there are too few - background galaxies carrying too little shear. (Surveys recover it only by *stacking* thousands of lens - galaxies, a technique called galaxy-galaxy lensing that averages over the lens population.) +For individual galaxy lenses, the available background galaxies usually provide too little information for a precise halo measurement. **Galaxy–galaxy lensing** therefore commonly combines measurements around many foreground galaxies to constrain the average mass distribution of a population. - - **A group** (Einstein radius ~4-10", the scale of the group tutorial earlier in this chapter): the signal is - marginal — detectable for well-observed individual groups, but noisy. +Groups produce larger signals, but the precision obtainable for an individual system depends on its mass, redshift and the depth and quality of the observations. Combining groups can also improve the measurement. - - **A cluster** (Einstein radius ~10-30"+, the previous tutorial's scale): the signal is strong enough to measure - around a *single* system. Hundreds to thousands of background galaxies within a few arc-minutes each carry a - |gamma| ~ 0.01-0.2 shear, and their average traces the cluster's mass out to radii of arc-minutes — ten or more - times further out than the strong-lensing core. +Massive clusters can produce measurable coherent distortions across hundreds or thousands of background galaxies. These measurements extend well beyond the central arcs and help constrain the cluster’s extended dark matter halo. -This reach is the scientific point. The dark matter halo of a cluster extends to Mpc scales, far beyond where arcs -form. Weak lensing is the only lensing probe of that outer halo, which is why it is the tool of choice for cluster -mass measurements, and it is why this tutorial simulates a cluster-scale lens. +There is no sharp Einstein-radius boundary separating these applications. Detectability depends on the lensing geometry, the radii sampled, the number of usable sources and their shape uncertainties. + +We use a cluster-scale lens here because it provides a useful demonstration of an individual-system weak-lensing analysis. __Ray Tracing__ -We begin exactly as the series always has: with a `Tracer`. The lens is a cluster-scale `Isothermal` mass profile -with an Einstein radius of 25.0" — the same order as the previous tutorial's cluster, and a mass for which the -weak shear signal is genuinely measurable. The source galaxy carries no light profile: weak lensing measures the -lens's shear field at the background galaxies' positions, so their appearance is irrelevant — they are pure probes, -included only to give the `Tracer` its source-plane redshift. +We begin with a `Tracer`, using an elliptical `Isothermal` mass profile with an Einstein radius of 25.0 arc-seconds. + +This is a deliberately simple cluster-scale mass distribution. Real cluster analyses often use NFW dark matter halos and additional mass components, as discussed in the previous tutorial. + +The lens has no light profile because this fit uses catalogue measurements rather than an image of the lens. -Note also what the lens galaxy lacks: no light profile. A shear catalogue contains no image of the lens, so there -is no lens light to model — another simplification compared to every imaging fit in this series. +The source galaxy also has no light profile. It supplies the source-plane redshift needed to calculate the lensing geometry; it does not represent the detailed appearance of an individual background galaxy. + +For simplicity, all background galaxies in this simulation lie at redshift 1.0, behind a lens at redshift 0.5. """ lens_galaxy = al.Galaxy( redshift=0.5, @@ -142,23 +110,22 @@ """ __Source Galaxy Positions__ -Real weak-lensing measurements avoid the strong-lensing core: inside it the shear is no longer weak (the linear -shear approximation breaks down), and cluster-member galaxies contaminate the background sample. We therefore draw -our background galaxies in an **annulus**, from an inner radius of 50" (twice the Einstein radius, safely into the -weak regime) to an outer radius of 200" (over 3 arc-minutes), distributed uniformly in area. +We draw 1500 observed background-galaxy positions in an annulus extending from 50 to 200 arc-seconds from the lens centre, distributed uniformly in area. + +This excludes the central region containing the strongest lensing features. In real observations, the usable region also depends on blending, cluster-member contamination and the reliability of the shape measurements. -At 50" from this lens the shear is |gamma| ~ 0.25, and by 200" it has fallen to |gamma| ~ 0.06 — every galaxy is a -weak probe whose individual distortion is at or below the shape noise. With 1500 galaxies (a deep-survey source -density of ~45 per square arc-minute) the *ensemble* nonetheless carries a decisive signal, exactly as in a real -cluster analysis. +The annulus covers approximately 33 square arc-minutes, giving a source density of about 46 galaxies per square arc-minute. This represents a deep illustrative catalogue; the usable density in an observation depends on its depth, resolution and selection criteria. -The positions are stored as an `al.Grid2DIrregular` of (y, x) coordinates — the same irregular-grid structure the -point-source tutorials used, because a catalogue of sky positions is not a uniform pixel grid. +For comparison, a spherical isothermal lens with an Einstein radius of 25 arc-seconds has shear and convergence of 0.25 at 50 arc-seconds, falling to about 0.06 at 200 arc-seconds. Our elliptical model varies with position angle as well. + +The inner boundary is therefore outside the Einstein radius, but it does not guarantee that reduced shear is approximately equal to shear. For the spherical example, the reduced shear at 50 arc-seconds is about 0.33. Remember that our simulation generates shear directly rather than simulating observed galaxy ellipticities. + +The positions are stored in an `al.Grid2DIrregular`, using the same `(y, x)` coordinate convention as the point-source tutorials. These are observed image-plane positions at which we evaluate the lensing field, not reconstructed source-plane coordinates. """ rng = np.random.default_rng(1) n_galaxies = 1500 -radius_inner = 50.0 # arc-seconds — inside this we are in the strong-lensing core. +radius_inner = 50.0 # arc-seconds — excludes the central region of the simulated lens. radius_outer = 200.0 # arc-seconds — the edge of our simulated weak-lensing field. radii = np.sqrt(rng.uniform(radius_inner**2.0, radius_outer**2.0, n_galaxies)) @@ -171,19 +138,15 @@ """ __Simulate__ -The `SimulatorShearYX` object simulates a weak-lensing shear catalogue from a tracer: its `via_tracer_from` method -evaluates the tracer's shear field at every galaxy position (by differentiating the deflection-angle field) and -adds Gaussian shape noise to each measurement. +`SimulatorShearYX` evaluates the tracer’s shear field at each catalogue position and adds independent Gaussian noise to its two components. + +We use `noise_sigma=0.25` per component as an illustrative shape-noise dispersion. The intrinsic shapes of real galaxies produce substantial scatter, and measurement errors add further uncertainty. + +This is a simplified statistical simulation. We do not generate images of individual background galaxies or run a shape-measurement pipeline. Instead, we directly generate noisy estimates of the shear field that our likelihood will fit. -A `noise_sigma` of 0.25 per shear component is the standard intrinsic shape dispersion of real galaxies — this is -the dominant noise source in weak lensing, and it is what makes the per-galaxy signal invisible: the noise on each -measurement is several times larger than the shear it contains. +The simulator’s default configuration generates shear rather than reduced shear, matching the idealization described above. -Unlike every previous tutorial, we do not write this dataset to disk and reload it. The whole catalogue is a few -thousand numbers, so we keep it in memory and use it directly — which also mirrors how you might resimulate -catalogues on the fly when testing survey sensitivities. (This repo's `scripts/simulator/weak_lensing.py` — the -script chapter 1's data tutorial auto-ran to give you your first glimpse of a shear catalogue — shows the -disk-based version, with the same JSON output pattern as the imaging simulators.) +We keep the catalogue in memory and pass it directly to the fitting tools. The script `scripts/simulator/weak_lensing.py`, used for the weak-lensing example in Chapter 1, demonstrates saving a catalogue to disk. """ dataset_name = "weak_lensing" @@ -200,40 +163,43 @@ """ __Visualize__ -Weak-lensing data has its own visual language. The shear field is drawn as a **whisker map**: at each galaxy -position, a line segment whose length is the shear magnitude |gamma| and whose orientation is the shear's position -angle. The segments are deliberately *headless* (no arrowheads), because shear is a spin-2 quantity — rotating a -shear by 180 degrees maps it back onto itself, so a whisker has an orientation but no direction, and an arrowhead -would suggest information the data does not contain. +We display the catalogue as a **whisker map**. Each galaxy position has a line segment whose length represents the magnitude of its measured shear estimate and whose orientation represents the corresponding position angle. -Around a massive lens, the whiskers align *tangentially* — each traces a small piece of a circle around the lens -centre, the statistical echo of the rings and arcs of strong lensing. Squint at the plot below and you can see it, -though the shape noise makes it far from obvious galaxy-by-galaxy: this is what a signal an order of magnitude -below the per-object noise looks like. +The segments have no arrowheads. A shear orientation is unchanged by a rotation of 180 degrees, so a line represents it more appropriately than a directed arrow. + +Around a centrally concentrated lens, the coherent pattern is predominantly tangential: the whiskers tend to follow circles around the lens centre. Ellipticity and additional mass structure can modify that pattern. + +Shape noise introduces substantial scatter in both the lengths and orientations of the plotted whiskers. Individual measurements need not align with the underlying field, even when the ensemble constrains it well. + +The plot provides an initial view of the measurements. Later, we will compare them with a model and summarize their tangential component in radial bins. """ aplt.plot_shear_yx_2d(shear_yx=dataset.shear_yx) """ -`aplt.subplot_weak_dataset` summarises the full dataset as a 2x2 mosaic: the whisker map, the per-galaxy noise-map, -the shear magnitude |gamma| and the position angle phi at every galaxy. +`aplt.subplot_weak_dataset` summarizes the catalogue in four panels: the shear whiskers, the per-galaxy uncertainties, the measured shear magnitudes and their position angles. + +Our simulation assigns the same uncertainty to every galaxy. Real catalogues generally have varying uncertainties because galaxies differ in brightness, size and the quality of their shape measurements. + +The magnitude and position-angle panels describe the noisy measurements. They should not be interpreted as direct maps of the underlying lensing field. """ aplt.subplot_weak_dataset(dataset=dataset) """ __Mass Map__ -A remarkable property of weak lensing is that the shear catalogue can be inverted directly into a map of the -convergence `kappa` — the dimensionless projected mass density we have used throughout the series — *without -assuming any mass model at all*. In Fourier space, shear and convergence are related algebraically, so two FFTs -turn the catalogue into a "dark matter map". This is the Kaiser-Squires technique, and it produced some of the most -famous images in cosmology, such as the mass map of the Bullet Cluster showing dark matter offset from the -colliding gas. - -`aplt.plot_convergence_map` bins the catalogue onto a regular grid, applies a small Gaussian smoothing (per-cell -shears are shape-noise dominated) and plots the reconstruction. For our simulated cluster it peaks at the lens -centre at (0.0", 0.0"). Two caveats: the map's mean is unconstrained (the mass-sheet degeneracy, which chapter 3 -met in its strong-lensing form) and FFT periodicity produces edge artefacts — for quantitative masses we fit a -mass model, which is what the rest of this tutorial does. +The shear field contains information about the convergence `kappa`, the dimensionless projected mass density introduced earlier in the series. + +The **Kaiser–Squires** method uses the relationship between shear and convergence in Fourier space to reconstruct a convergence map without choosing a parametric mass profile such as an Isothermal or NFW. + +`aplt.plot_convergence_map` bins the catalogue onto a regular grid, smooths the binned shear field and performs this reconstruction. + +The resulting map provides a useful view of the projected mass structure. It traces the total lensing mass, including both dark matter and baryons; identifying a feature specifically with dark matter requires additional information. + +Avoid interpreting every peak as a real mass concentration. Shape noise, smoothing, the finite field and gaps in the catalogue all affect the reconstruction. Our catalogue has no measurements inside its central hole, so the displayed map there is not a direct local measurement. + +Shear also leaves an additive constant in the reconstructed convergence unconstrained. This is related to the mass-sheet degeneracy discussed in Chapter 3. + +Use this map as an exploratory diagnostic. Quantitative measurements require uncertainty estimates and careful treatment of the survey geometry. Here, we proceed by fitting a parametric mass model directly to the catalogue. """ aplt.plot_convergence_map( shear_yx=dataset.shear_yx, @@ -244,21 +210,21 @@ """ __Fitting__ -We now fit the catalogue, following the same pattern as every fit in this series: build a model `Tracer`, pass it -with the dataset to a `Fit` object, and inspect residuals and the log likelihood. For weak lensing the fit object -is `FitWeak`, and because we simulated the data ourselves we can hand it the *true* tracer and see what a perfect -model looks like. - -`FitWeak` evaluates the model tracer's shear field at the dataset's galaxy positions and compares it with the -measured shears, assuming each component is independently Gaussian-distributed around the model with the -per-galaxy noise. Each galaxy contributes **two** independent data points (gamma_1 and gamma_2), so the number of -degrees of freedom is 2 * n_galaxies, and for a good fit whose residuals are pure shape noise the chi-squared -should be close to that number. - -Compare this to the imaging fits of chapter 1: there, the fit convolved a model image with the PSF and compared -tens of thousands of pixels; here there is no convolution, no mask and only a few thousand numbers. A weak-lensing -likelihood is orders of magnitude cheaper — which is precisely why it is so inexpensive to add to a strong-lensing -analysis, as discussed at the end of this tutorial. +We now follow the fitting workflow introduced in Chapter 1: specify a model `Tracer`, combine it with the dataset in a fit object, and inspect the residuals and log likelihood. + +For this dataset, the fit object is `FitWeak`. It evaluates the predicted shear at each observed galaxy position and compares its two components with the catalogue measurements. + +Our likelihood assumes independent Gaussian errors for the two components, using the supplied uncertainties. This matches the way we generated this simulated catalogue. + +We first supply the input tracer used by the simulator. Its predictions describe the underlying shear field, while the residuals contain the Gaussian noise added during simulation. + +There are two measured components per galaxy, giving 3000 scalar measurements. At this fixed input model, the expected chi-squared is therefore 3000, with statistical fluctuations between noise realizations. + +This count should not be confused with the residual degrees of freedom after estimating parameters from the same data. We will shortly allow the mass parameters to vary in a non-linear search. + +Unlike an imaging likelihood, this calculation does not generate and convolve a model image or reconstruct source surface brightness. Its main task is evaluating the lensing field at the catalogue positions and calculating the likelihood. + +The computational cost depends on the catalogue size, mass model and implementation, but this makes catalogue fitting a useful complement to the imaging and point-source analyses explored earlier. """ fit = al.FitWeak(dataset=dataset, tracer=tracer) @@ -266,13 +232,18 @@ print("Fit Summary (true model)") print("------------------------") print(f"n_galaxies : {dataset.n_galaxies}") -print(f"degrees_of_freedom: {2 * dataset.n_galaxies}") +print(f"n_data_components: {2 * dataset.n_galaxies}") print(f"chi_squared : {fit.chi_squared:.3f}") print(f"log_likelihood : {fit.log_likelihood:.3f}") """ -As always, an incorrect mass model produces a worse fit. Halving the Einstein radius halves the predicted shear -everywhere, leaving coherent tangential residuals across the field, and the log likelihood drops accordingly. +We next halve the model’s Einstein radius while keeping its centre and ellipticity fixed. + +For this Isothermal profile, that change halves the predicted shear at every catalogue position. The model therefore underpredicts the coherent signal present in the simulated data. + +Compare the two printed log likelihoods. This deliberately large change illustrates how the catalogue distinguishes different mass normalizations, even though individual galaxy measurements are noisy. + +The likelihood combines information from the whole catalogue: the preference does not require every individual measurement to lie closer to the input model. """ tracer_wrong = al.Tracer( galaxies=[ @@ -295,30 +266,38 @@ print(f"log_likelihood (wrong model): {fit_wrong.log_likelihood:.3f}") """ -`aplt.subplot_fit_weak` visualises a weak-lensing fit as a 2x2 mosaic: the observed shear field, the model shear -field, the two overlaid on one axes (data in black, model in red), and the per-galaxy chi-squared map. For the true -model the overlay's residuals are short and randomly oriented — the shape-noise floor — and the chi-squared map is -spatially uniform. +`aplt.subplot_fit_weak` displays the observed shear field, the model field, an overlay of the two and the per-galaxy chi-squared contributions. + +The input model produces a smooth, coherent pattern. The observed whiskers scatter around that pattern because of shape noise, so a good fit does not require close agreement for every galaxy. + +Likewise, the chi-squared map need not look uniform. Individual galaxies can have large contributions simply because their noise realizations are large. + +Look for coherent discrepancies across the field, alongside the overall likelihood and residual statistics. Such patterns can indicate missing mass structure, an inadequate model or problems with the measurements. + +For this simulation, the input model and noise assumptions match the data-generation process, providing a reference for interpreting these diagnostics. """ aplt.subplot_fit_weak(fit=fit) """ __Model Fit__ -In a real analysis we do not know the mass model — we infer it. The workflow is the one you have used since -chapter 2: compose a model with `af.Model` and `af.Collection`, choose a non-linear search, create an `Analysis` -object and fit. For weak lensing the analysis object is `AnalysisWeak`, whose `log_likelihood_function` builds a -`Tracer` from each sampled parameter set, evaluates its shear field at the catalogue positions and returns the -Gaussian log likelihood — the same `FitWeak` machinery we just used by hand. +We now infer the mass-model parameters using the workflow introduced in Chapter 2: compose a model with `af.Model` and `af.Collection`, choose a non-linear search, create an analysis object and fit. + +`AnalysisWeak` builds a `Tracer` from each sampled parameter set and evaluates the catalogue likelihood using the same `FitWeak` calculation we inspected above. + +Our Isothermal model has five non-linear parameters: -The model is the lens's `Isothermal` mass [5 parameters]; the source galaxy again carries no components. Note the -tiny parameter space — no lens light, no source light, no shear-as-nuisance-parameter (the shear field *is* the -data here) — compared to the N=20+ models of the imaging tutorials. +- Two centre coordinates. +- Two ellipticity components. +- The Einstein radius. -One adjustment is needed, familiar from the group and cluster tutorials: the default priors are tuned for -galaxy-scale lenses (Einstein radii of 0"-8", centres within a fraction of an arc-second). Our cluster's 25" -Einstein radius lies entirely outside that prior, so we widen the priors to cluster scales — always match your -priors to the mass scale of the system you are fitting. +The lens and source redshifts remain fixed. Neither galaxy has a light profile, so there are no light-profile parameters or source reconstructions to fit. + +Earlier in this chapter, we often fixed individual galaxy centres to their measured centres of light. Here, the mass profile represents the cluster as a whole, and we allow its centre to vary. A cluster’s overall mass centre need not coincide exactly with the light centre of its brightest galaxy. + +We assign an Einstein-radius prior spanning 0–60 arc-seconds and Gaussian centre priors with a width of 20 arc-seconds around the origin. These are illustrative choices suited to this simulated system. + +As in the group and cluster tutorials, check that the priors describe the scale and plausible configurations of the system being analyzed. Inspect the resulting posterior to determine whether the data constrain these parameters within their allowed ranges. """ mass = af.Model(al.mp.Isothermal) mass.einstein_radius = af.UniformPrior(lower_limit=0.0, upper_limit=60.0) @@ -334,23 +313,24 @@ print(model.info) """ -The same model can also be visualized as a figure, making its structure easier to understand at a glance. +The model figure summarizes this structure: one lens mass profile with five free parameters and a source galaxy supplying a fixed redshift. -The figure shows how the model is organized: which parameters belong to each component, and whether they are free, -fixed, shared, linked by an expression, solved during the fit, or not configured. `model.info` provides the -corresponding numerical details, including the prior assigned to each free parameter and the value of each fixed -parameter. +Use it alongside `model.info`, which lists the priors and fixed values. -In weak lensing the source galaxies are the *data*, a catalogue of measured shapes, so there is no source light -to fit and the source galaxy in this model carries no light profile at all. +The single source galaxy in this model does not mean that the catalogue contains only one background galaxy. It supplies the common source-plane redshift assumed for all 1500 catalogue entries. + +Their individual observed positions and shear estimates belong to the dataset; we do not introduce a separate light profile or free source position for each entry. """ af.ModelPlotter(model).figure() """ -We fit the model with the nested sampling algorithm Nautilus, as throughout the series. A weak-lensing likelihood -evaluation takes milliseconds (one shear-field evaluation at 1500 positions plus a chi-squared sum), so this -5-parameter fit completes in minutes on an ordinary CPU — a refreshing contrast to the imaging fits of the earlier -chapters. +We use Nautilus to sample the posterior, as in the earlier tutorials, and pass the catalogue to `AnalysisWeak`. + +Each likelihood evaluation predicts the shear field at the 1500 galaxy positions and compares it with the measurements. There is no image convolution or source reconstruction in this calculation. + +This is a compact five-parameter example, but its runtime still depends on the implementation, hardware and number of likelihood evaluations required by the search. + +Use the search outputs to monitor progress and assess convergence before interpreting the inferred parameters. The familiar output directory contains the model information, samples and fit diagnostics. """ search = af.Nautilus( path_prefix=Path("howtolens", "chapter_4"), @@ -363,35 +343,51 @@ analysis = al.AnalysisWeak(dataset=dataset) print( - "The non-linear search has begun running - checkout the output/howtolens/chapter_4/tutorial_6_weak_lensing" - " folder for live output of the results, images and model." - " This Jupyter notebook cell with progress once search has completed - this could take some time!" + "The non-linear search has begun. Check " + "output/howtolens/chapter_4/tutorial_6_weak_lensing " + "for live results, images and model information. " + "Continue once the search has completed." ) result = search.fit(model=model, analysis=analysis) -print("The search has finished run - you may now continue the notebook.") +print("The search has finished. You may now continue the notebook.") """ __Result__ -The result's `info` attribute confirms the search recovers the input mass model — Einstein radius, ellipticity and -centre — from nothing but the statistically-averaged shapes of background galaxies. No arc, no ring, no multiple -images: the ensemble alone constrains the cluster's mass. +Inspect `result.info` to see the inferred parameters and their uncertainties. + +Because we simulated this catalogue, we can compare them with the input Einstein radius of 25 arc-seconds, axis ratio of 0.8, position angle of 45 degrees and centre at the origin. + +The code parameterizes ellipticity using two components, so convert between those components and axis ratio and position angle when making that comparison. + +Noise means that the inferred values need not equal the inputs exactly. Consider the posterior intervals and parameter correlations, rather than judging recovery from a single fitted realization. + +The fit subplot below displays the maximum-likelihood realization found by the search. Compare its coherent shear pattern with the noisy measurements, using the diagnostics discussed above. + +These constraints are conditional on our chosen mass profile, fixed redshifts and noise assumptions. A real cluster may require a more flexible mass distribution and additional treatment of observational uncertainties. """ print(result.info) aplt.subplot_fit_weak(fit=result.max_log_likelihood_fit) """ -Cluster weak-lensing measurements are conventionally presented as the **tangential shear profile**: the mean -tangential shear gamma_t of background galaxies in radial bins about the lens centre, which traces the projected -mass profile. `aplt.plot_shear_profile` bins our catalogue and, given the fit, overlays the model's profile as a -line. - -The plot also shows the *cross* component gamma_x — the shear rotated by 45 degrees. Gravitational lensing produces -no cross component at leading order, so cross points scattering around zero is the standard "B-mode" null test of a -weak-lensing measurement: a systematic contaminating the shapes would show up there. +Weak-lensing measurements around clusters are often summarized using a **tangential shear profile**. + +For each background galaxy, we resolve its shear into components defined relative to a chosen centre. The tangential component describes the tendency for images to stretch around that centre. + +`aplt.plot_shear_profile` groups the catalogue into radial bins and plots the mean tangential component with uncertainties. Passing a fit also overlays the model’s binned tangential profile. + +Here we use eight bins around the simulation’s input centre, `(0.0, 0.0)`. This plotting choice does not fix the mass centre in the fit: the model still has two free centre coordinates. + +The plot is a summary of the fitted catalogue. Our likelihood used both shear components at every galaxy position, retaining angular information that radial averaging can hide. + +The second set of points shows the **cross component**, defined at 45 degrees to the tangential component. Its azimuthal average is expected to be consistent with zero for the ideal lensing signal and suitable angular sampling. + +A significant cross signal therefore motivates checks of the measurements, angular coverage and model geometry. However, a cross profile consistent with zero does not establish that all systematic errors are absent; some biases can change the tangential signal without producing a cross signal. + +Use the radial profiles together with the two-dimensional fit diagnostics and posterior uncertainties. """ aplt.plot_shear_profile( result.max_log_likelihood_fit, @@ -402,69 +398,60 @@ """ __Joint Strong and Weak Lensing__ -We fitted this catalogue on its own, and weak-lensing-only fits of real catalogues are a fully supported PyAutoLens -workflow. But the way PyAutoLens really expects weak lensing to be used is **jointly with strong lensing**, because -the two probes are perfectly complementary: +We fitted the weak-lensing catalogue on its own. When a system also has strong-lensing observations, combining the two can constrain its mass distribution across a wider range of radii. + +**Strong lensing** provides detailed information where multiple images and arcs form. It often tightly constrains the enclosed projected mass near the Einstein radius, while the inferred density profile and division between mass components remain subject to degeneracies. + +**Weak lensing** adds measurements over a larger field, extending our sensitivity to the outer dark matter halo. Its constraining power depends on the background-source density, redshifts, shape uncertainties and area observed. + +These are complementary measurements of the same gravitational field. Strong lensing does not become insensitive to all mass outside the Einstein radius, and weak lensing does not independently determine every feature of the outer halo. + +A joint analysis uses shared mass-model parameters to predict both datasets. We combine an imaging or point-source analysis with `AnalysisWeak`, following the multi-dataset approach used earlier in this chapter. - - **Strong lensing** (everything before this tutorial) pins the mass in the inner region with exquisite precision — - the positions of multiple images and arcs nail the Einstein mass and the inner density profile — but says - nothing beyond the Einstein radius. +For datasets whose measurement errors can be treated as independent, their log likelihoods add. Each analysis retains its own data model and uncertainties, while the shared mass parameters must explain both sets of observations. - - **Weak lensing** (this tutorial) constrains the mass profile out to arc-minute radii — the outskirts of the dark - matter halo — but its centre and inner profile are only weakly pinned by the field's geometry. +The source populations need not have the same redshift. Each prediction must use the geometry appropriate to its sources, just as in the previous cluster tutorial. -Fit both datasets simultaneously with a single mass model — one analysis for the imaging or point-source data, one -`AnalysisWeak` for the shear catalogue, combined exactly as the multi-dataset fits earlier in this chapter combined -their analyses — and the model is anchored at the centre by strong lensing while its outer profile is measured by -weak lensing. This hybrid is the state of the art for cluster mass measurements, used across systems like the -Frontier Fields clusters, and PyAutoLens's shared `Tracer` infrastructure makes it natural: the same mass profiles -that ray-traced arcs in the previous tutorial produce the shear field fitted here. +For example, strong-lensing images can constrain the central mass distribution while a weak-lensing catalogue helps constrain the mass and concentration of an extended NFW halo. Combining them can reduce degeneracies, although the result still depends on the chosen mass components and observational assumptions. -The workspace's `autolens_workspace/*/weak` package has the complete treatment: +Inspect the contributions from both datasets separately. A satisfactory joint fit should describe both, and a disagreement can reveal missing mass structure, calibration problems or overly restrictive assumptions. - - `weak/start_here.py`: fits a real shear catalogue of the merging cluster Abell 2744 ("Pandora's Cluster") — - download, quality cuts, mass map, NFW halo fit. - - `weak/simulator.py`, `weak/fit.py`, `weak/modeling.py`: the disk-based versions of this tutorial's workflow. - - `weak/likelihood_function.py`: a step-by-step walkthrough of the weak-lensing likelihood. - - `weak/features/strong_lensing`: the joint strong-plus-weak fits described above. +The `autolens_workspace/scripts/weak` directory provides examples for continuing this work: + +- [start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/start_here.py): an introduction using a real galaxy-shape catalogue for Abell 2744. +- [simulator.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/simulator.py), [fit.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/fit.py) and [modeling.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/modeling.py): simulation, fitting and inference examples. +- [likelihood_function.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/likelihood_function.py): a step-by-step explanation of the weak-lensing likelihood. +- [features/strong_lensing](https://github.com/PyAutoLabs/autolens_workspace/tree/main/scripts/weak/features/strong_lensing): examples combining strong- and weak-lensing measurements. __Wrap Up__ -This tutorial completed the chapter's journey up the mass ladder, and with it the four core chapters of -**HowToLens**. Lets take stock of how far we have come. +This tutorial completes Chapter 4 and the four core chapters of **HowToLens**. + +We have learned how to: + +- Represent weak-lensing measurements as a catalogue of positions, shear estimates and uncertainties. +- Simulate an idealized catalogue and understand how shape noise affects its measurements. +- Visualize the shear field and construct an exploratory convergence map. +- Evaluate a catalogue likelihood and infer mass-model parameters using the familiar search workflow. +- Interpret fit diagnostics and posterior uncertainties, and understand the motivation for joint strong- and weak-lensing analyses. + +The distinction between shear and reduced shear matters when moving from this idealized simulation to observed galaxy shapes. So do source redshifts, calibration, selection and the flexibility of the mass model. -Chapter 1 built lensing from first principles: grids, light and mass profiles, ray tracing, the lens equation, and -fitting imaging data with a `Tracer`. Chapter 2 turned fitting into inference — non-linear searches, priors, -Bayesian model comparison — so we could *infer* lens models rather than guess them. Chapter 3 replaced analytic -sources with pixelized reconstructions, letting the data itself reveal the source's morphology. +Across the series, the same ideas have supported increasingly complex analyses. -This chapter then scaled those tools up through every regime nature offers, and in this tutorial: +**Chapter 1** introduced grids, light and mass profiles, ray tracing and fitting data. These calculations came together as a likelihood function. -- **Weak Lensing:** Outside the strong-lensing region every background galaxy is still weakly sheared; the signal - is invisible per galaxy beneath intrinsic shape noise but emerges statistically over an ensemble. +**Chapter 2** used that likelihood for inference: defining priors, running non-linear searches, examining posterior uncertainties and comparing models. -- **Shear Catalogues:** The weak-lensing dataset is a catalogue of galaxy positions, measured shear estimates and - uncertainties, produced upstream by a dedicated shape-measurement pipeline — PyAutoLens fits mass models to it - and leaves the shape measurement to those pipelines. +**Chapter 3** introduced pixelized source reconstructions, allowing more flexible descriptions of source morphology while controlling that flexibility through regularization. -- **Mass Scales:** The statistical signal is hopeless around a single galaxy, marginal around a group and - measurable around a cluster — and it probes the dark matter halo to radii far beyond the reach of arcs. +**Chapter 4** extended the modeling to additional galaxies, shared scaling relations, groups, clusters and weak lensing. We saw how fixed measurements and shared relations can make large models tractable, while also shaping the conclusions we can draw from them. -- **The Same Workflow:** `SimulatorShearYX`, `FitWeak` and `AnalysisWeak` slot into the identical - simulate-fit-model pattern the series has used since chapter 1, and a non-linear search recovered the cluster's - mass from galaxy shapes alone. +You now have a foundation for building lens models, understanding their likelihoods and assessing their results. Applying those tools to a scientific question means choosing an appropriate model, checking the data and testing which conclusions remain robust when assumptions change. -- **Joint Fits:** Strong lensing pins the inner mass, weak lensing measures the outskirts; fitting both with one - model is the expected PyAutoLens workflow for cluster and group science. +The next step is the [autolens_workspace](https://github.com/PyAutoLabs/autolens_workspace). Start with the example closest to your dataset, then use its feature examples and likelihood guides to build up the analysis you need. -And that is the series: from a single lens galaxy, to lenses with extra galaxies, to multi-galaxy lenses, to -scaling relations that keep many-galaxy models tractable, to group-scale and cluster-scale systems, and finally -beyond the Einstein radius altogether into the weak-lensing regime. You have every conceptual tool the modern -lensing literature uses, and you have used each one on data. +The workspace covers imaging, interferometry, point sources, groups, clusters and weak lensing, alongside tools such as the automated SLaM pipelines. -Where next? The `autolens_workspace` is the destination for real science. Its `imaging`, `point_source`, `group`, -`cluster` and `weak` packages hold the production-ready versions of everything taught here — including the -`start_here.py` scripts that are each topic's canonical, always-current reference — plus the features this series -could only gesture at: multi-wavelength fits, interferometry, automated SLaM pipelines and more. Take your own -data there, and good luck with your science! +Bring your own data, keep inspecting what the model is doing, and enjoy exploring the Universe through gravitational lensing! """ diff --git a/workspace_index.json b/workspace_index.json index c6c567a..e643b29 100644 --- a/workspace_index.json +++ b/workspace_index.json @@ -556,7 +556,7 @@ "cross_refs": [], "notebook": "notebooks/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.ipynb", "path": "scripts/chapter_4_scaling_up_lensing/tutorial_1_extra_galaxies.py", - "summary": "Welcome to chapter 4 of **HowToLens**, where we scale up lens modeling beyond a single lens galaxy.", + "summary": "Welcome to chapter 4 of **HowToLens**, where we scale up lens modeling beyond a single dominant lens galaxy.", "title": "Tutorial 1: Extra Galaxies" }, { @@ -573,10 +573,12 @@ "Three Lens Galaxies", "Wrap Up" ], - "cross_refs": [], + "cross_refs": [ + "//github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_4_scaling_up_lensing/tutorial_4_group_scale.ipynb" + ], "notebook": "notebooks/chapter_4_scaling_up_lensing/tutorial_2_multi_galaxy.ipynb", "path": "scripts/chapter_4_scaling_up_lensing/tutorial_2_multi_galaxy.py", - "summary": "In the previous tutorial, we learned how to deal with extra galaxies near a strong lens \u2014 nuisance objects whose light contaminates the data but which play no meaningful role in the lensing itself. We removed their emission from the analysis, or gave them a heavily restricted model, and the single dominant lens galaxy remained the star of the show.", + "summary": "In the previous tutorial, we modeled a system with one dominant lens galaxy and a smaller nearby galaxy. We saw that the extra galaxy's light and gravitational deflections required separate consideration.", "title": "Tutorial 2: Multi-Galaxy Lenses" }, { @@ -601,7 +603,7 @@ "cross_refs": [], "notebook": "notebooks/chapter_4_scaling_up_lensing/tutorial_3_scaling_relation.ipynb", "path": "scripts/chapter_4_scaling_up_lensing/tutorial_3_scaling_relation.py", - "summary": "The previous tutorial ended on a warning: every deflector we add to a lens model brings its own free parameters. Two galaxies were manageable, but each one cost us a mass profile's worth of dimensions, and the arithmetic only gets worse. A group-scale lens may have ten member galaxies, a cluster hundreds. If every member keeps its own free mass, the parameter space explodes \u2014 a 100-galaxy cluster with 5 free mass parameters per galaxy is a 500-dimensional model, which no non-linear search can sample and no dataset can constrain anyway.", + "summary": "In the previous tutorial, we saw how adding significant deflectors increases both the number of parameters and the degeneracies between galaxy masses. Independently fitting the mass of every member becomes increasingly demanding for groups and clusters.", "title": "Tutorial 3: Scaling Relations" }, { @@ -613,6 +615,8 @@ "Fitting a Group", "A Group Halo?", "Model Fit", + "Fit With a Shared NFW Dark Matter Halo", + "Bayesian Model Comparison", "Scaling Relation Members", "The Group Scale Sweet Spot", "Wrap Up" @@ -620,7 +624,7 @@ "cross_refs": [], "notebook": "notebooks/chapter_4_scaling_up_lensing/tutorial_4_group_scale.ipynb", "path": "scripts/chapter_4_scaling_up_lensing/tutorial_4_group_scale.py", - "summary": "In the previous tutorials we took our first steps beyond the single lens galaxy: we included extra galaxies near the lens in the model, we modeled systems where two or more galaxies of comparable mass share the lensing, and we introduced scaling relations, which tie the mass of a galaxy to its light so that adding more galaxies to a model does not mean adding more free parameters.", + "summary": "The previous tutorials introduced nearby galaxies, multiple significant deflectors and scaling relations. We now combine these ideas to model a **group-scale lens**.", "title": "Tutorial 4: Group Scale" }, { @@ -640,14 +644,11 @@ "Wrap Up" ], "cross_refs": [ - "autolens_workspace/scripts/guides/point_solver/pairing.py", - "csv_api.py", - "fit.py", - "likelihood_function.py" + "autolens_workspace/scripts/guides/point_solver/pairing.py" ], "notebook": "notebooks/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.ipynb", "path": "scripts/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.py", - "summary": "Throughout this chapter we have been climbing a ladder of scale: from a single lens galaxy with an extra galaxy nearby, to multi-galaxy lenses, to galaxy groups whose members share a common dark matter halo.", + "summary": "We now extend the tools developed for galaxies and groups to **galaxy clusters**.", "title": "Tutorial 5: Cluster Scale" }, { @@ -666,17 +667,21 @@ "Wrap Up" ], "cross_refs": [ + "//github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/fit.py", + "//github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/likelihood_function.py", + "//github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/modeling.py", + "//github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/simulator.py", + "//github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/weak/start_here.py", + "fit.py", + "likelihood_function.py", + "modeling.py", "scripts/simulator/weak_lensing.py", - "start_here.py", - "weak/fit.py", - "weak/likelihood_function.py", - "weak/modeling.py", - "weak/simulator.py", - "weak/start_here.py" + "simulator.py", + "start_here.py" ], "notebook": "notebooks/chapter_4_scaling_up_lensing/tutorial_6_weak_lensing.ipynb", "path": "scripts/chapter_4_scaling_up_lensing/tutorial_6_weak_lensing.py", - "summary": "Every tutorial in this series so far \u2014 indeed, every fit performed in all four chapters of **HowToLens** \u2014 has been a *strong* lensing analysis. Strong lensing occurs when a background galaxy lies so close (in projection) to a foreground mass that its light is bent into multiple images, arcs or a complete Einstein ring. These dramatic features are what we simulated, fitted and modeled, from the single galaxy-scale lenses of chapters 1 and 2 up to the group-scale and cluster-scale systems earlier in this chapter.", + "summary": "Our modeling tutorials have concentrated on **strong lensing**: the multiple images, arcs and Einstein rings produced by galaxy, group and cluster lenses.", "title": "Tutorial 6: Weak Lensing" }, {