diff --git a/README.md b/README.md index 583af4f..6c670c1 100644 --- a/README.md +++ b/README.md @@ -85,17 +85,14 @@ for the chapter 1 tutorials listed with a `markdown` link below; every other tut - Tutorial 3: Fitting — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_3_fitting.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_3_fitting.md)) - Tutorial 4: Methods — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_4_methods.ipynb)) - Tutorial 5: Summary — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_1_introduction/tutorial_5_summary.ipynb) / [markdown](markdown/chapter_1_introduction/tutorial_5_summary.md)) -- **[Chapter 2: Modeling](scripts/chapter_2_modeling/README.md)** — Bayesian inference, non-linear searches, galaxy modeling, search chaining, and prior passing. - - Tutorial 1: Non-linear Search — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb)) - - Tutorial 2: Practicalities — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb)) - - Tutorial 3: Realism and Complexity — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_3_realism_and_complexity.ipynb)) - - Tutorial 4: Dealing with Failure — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_4_dealing_with_failure.ipynb)) - - Tutorial 5: Linear Profiles — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_5_linear_profiles.ipynb)) - - Tutorial 6: Masking — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_6_masking.ipynb)) - - Tutorial 7: Results — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_7_results.ipynb)) - - Tutorial 8: Need for Speed — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_8_need_for_speed.ipynb)) - - Tutorial 9: Search Chaining — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_9_search_chaining.ipynb)) - - Tutorial 10: Prior Passing — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_10_prior_passing.ipynb)) +- **[Chapter 2: Modeling](scripts/chapter_2_modeling/README.md)** — Practical galaxy models, data and likelihoods, linear profiles and search chaining. + - Tutorial 1: Non-linear Search — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb)) + - Tutorial 2: Practicalities — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb)) + - Tutorial 3: Why Modeling Is Hard — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_3_why_modeling_is_hard.ipynb)) + - Tutorial 4: Linear Profiles — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_4_linear_profiles.ipynb)) + - Tutorial 5: Data and Likelihoods — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_5_data_and_likelihoods.ipynb)) + - Tutorial 6: Search Chaining — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_6_search_chaining.ipynb)) + - Tutorial 7: Summary — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_7_summary.ipynb)) - **[Chapter 3: Pixelizations](scripts/chapter_3_pixelizations/README.md)** — Indexed mappings, inversions, regularization and MGE search chaining. - Tutorial 1: Pixelizations — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_1_pixelizations.ipynb)) - Tutorial 2: Bayesian Regularization — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_3_pixelizations/tutorial_2_bayesian_regularization.ipynb)) @@ -106,7 +103,9 @@ for the chapter 1 tutorials listed with a `markdown` link below; every other tut - Tutorial 2: Multi Galaxy — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy.ipynb)) - Tutorial 3: Cluster — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_4_scaling_up_galaxies/tutorial_3_cluster.ipynb)) - **[Optional Tutorials](scripts/chapter_optional/)** — Alternative non-linear searches and advanced topics. - - Tutorial Optional: Searches — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_optional/tutorial_searches.ipynb)) + - Alternative Searches — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_optional/tutorial_searches.ipynb)) + - Need for Speed — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_optional/tutorial_need_for_speed.ipynb)) + - Historical Prior Passing — ([Colab](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_optional/tutorial_prior_passing.ipynb)); not required reading. Model-fits can run faster on a GPU. In Colab, enable one via *Runtime* → *Change runtime type* → *Hardware accelerator* before running a notebook. diff --git a/llms-full.txt b/llms-full.txt index efd7ad6..e003cdb 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -24,25 +24,19 @@ AUTO-GENERATED by PyAutoHands — do not edit by hand; regenerate with generate. ## chapter_2_modeling -- [Tutorial 10: Prior Passing](scripts/chapter_2_modeling/tutorial_10_prior_passing.py): In the previous tutorial, we used non-linear search chaining to break the model-fitting procedure down into two non-linear searches. This used an initial search to fit a simple model, whose results were used to tune and initialize the priors of a more complex model that was fitted by the second search. - - Contents: Initial Setup, Dataset Auto-Simulation, Model, Search, Result (Search 1), Prior Passing, Result, Wrap Up, Detailed Explanation Of Prior Passing, EXAMPLE -- [Tutorial 1: Non-linear Search](scripts/chapter_2_modeling/tutorial_1_non_linear_search.py): The starting point for most scientific analysis conducted by an Astronomer is that they have observations of a galaxy using a telescope like the Hubble Space Telescope, and seek to learn about the galaxy and the Universe from these observations. With **PyAutoGalaxy**, we seek to learn about the galaxy's structure and morphology, asking questions like how big is the galaxy, is it disky or bulgy, and how is its light distributed? - - Contents: Parameter Space, Non-Linear Search, Search Types, Deeper Background, Data, Model, Priors, Analysis, Searches, Maximum Likelihood Estimation (MLE), Markov Chain Monte Carlo (MCMC), Nested Sampling, Result, Samples, Customizing Searches, Wrap Up -- [Tutorial 2: Practicalities](scripts/chapter_2_modeling/tutorial_2_practicalities.py): In the last tutorial, we introduced foundational statistical concepts essential for model-fitting, such as parameter spaces, likelihoods, priors, and non-linear searches. Understanding these statistical concepts is crucial for performing model fits effectively. -- [Tutorial 3: Realism and Complexity](scripts/chapter_2_modeling/tutorial_3_realism_and_complexity.py): In the previous two tutorials, we fitted a fairly basic model: the galaxy's light was a single bulge component. In real observations we know that galaxies are observed to have multiple different morphological structures. - - Contents: Initial Setup, Model + Search + Analysis, Result, Global and Local Maxima, Wrap Up -- [Tutorial 4: Dealing With Failure](scripts/chapter_2_modeling/tutorial_4_dealing_with_failure.py): In the previous tutorial we intentionally made our non-linear search infer a local maxima solution and therefore return a physically incorrect model. In this tutorial, we will pretend that we have modeled our galaxy and inferred a local maxima. We introduce three approaches one can take that changes how we fit the model, all of which have the aim of ensuring we infer the global maxima: - - Contents: Initial Setup, Approach 1: Prior Tuning, Approach 2: Reducing Complexity, Approach 3: Look Harder -- [Tutorial 5: Linear Profiles](scripts/chapter_2_modeling/tutorial_5_linear_profiles.py): In the previous tutorial we learned how to balance model complexity with our non-linear search in order to infer accurate model solutions and avoid failure. We saw how in order to fit a model accurately one may have to parameterize and fit a simpler model with fewer non-linear parameters, at the expense of fitting the data less accurately. - - Contents: Initial Setup, Linear Light Profiles, Run Time, Result, Intensities, Visualization, Basis, Model Fit, Disk MGE, Multi Gaussian Expansion Benefits, Positive Only Solver, Other Basis Functions, Wrap Up -- [Tutorial 6: Masking](scripts/chapter_2_modeling/tutorial_6_masking.py): We have learnt everything we need to know about non-linear searches to model a galaxy and infer a good model solution. Now, lets consider masking in more detail, something we have not given much consideration previously. We'll also learn a neat trick to improve the speed and accuracy of a non-linear search. - - Contents: Initial Setup, Mask, Model + Search + Analysis, Discussion, Wrap Up -- [Tutorial 7: Results](scripts/chapter_2_modeling/tutorial_7_results.py): In the previous tutorials, each search returned a `Result` object, which we used to plot the maximum log likelihood fit of each model-fit. In this tutorial, we'll take a look at the result object in a little more detail. - - Contents: Initial Setup, Galaxies & Fit, Samples, Workspace, Database, Wrap Up -- [Tutorial 8: Need For Speed](scripts/chapter_2_modeling/tutorial_8_need_for_speed.py): In this chapter, we have learnt how to model galaxies and how to balance complexity and realism to ensure that we infer a good model. - - Contents: Searching Non-linear Parameter Space, Cost Per Evaluation, JAX, Run Time Estimation, Data Quantity, Wrap Up -- [Tutorial 9: Search Chaining](scripts/chapter_2_modeling/tutorial_9_search_chaining.py): Throughout this chapter, we have fitted the data using just one non-linear search. The previous tutorial discussed the run-time cost of doing this: with a single search, the dimensionality of the model, the priors on its parameters and the search settings must all be juggled at once, leaving us little flexibility to trade them off against one another. - - Contents: Initial Setup, Dataset Auto-Simulation, Model, Search + Analysis, Result, Prior Passing, Result, Wrap Up +- [Tutorial 1: Non-linear Search](scripts/chapter_2_modeling/tutorial_1_non_linear_search.py): In chapter 1, you adjusted a galaxy model by hand and inspected how well its image matched the data. Now we will ask a search to do this for us. Our aim is still to learn about the galaxy: its size, shape and concentration. + - Contents: Parameter Space, Dataset and Mask, Model and Priors, Analysis, Nested Sampling, Result +- [Tutorial 2: Practicalities](scripts/chapter_2_modeling/tutorial_2_practicalities.py): A galaxy can contain a compact bulge and an extended disk. We now fit both, while learning how to run a search, manage its memory use and inspect its output. These practical skills let us assess a model as the fit progresses. + - Contents: Dataset and Mask, Model, Search Settings, Analysis and Run Times, VRAM Use, Output Folder, Unique Identifier, Results and Configuration +- [Tutorial 3: Why Modeling Is Hard](scripts/chapter_2_modeling/tutorial_3_why_modeling_is_hard.py): The bulge and disk in tutorial 2 made our model more realistic, but also harder to fit. Their centres, shapes, brightnesses and sizes can trade off. A search can find a plausible galaxy without finding the best explanation available within the model. + - Contents: A Reference Fit, An Inadequate Search, Local Maxima, Prior Tuning, Reducing Complexity, Look Harder, Benefits and Weaknesses +- [Tutorial 4: Linear Profiles](scripts/chapter_2_modeling/tutorial_4_linear_profiles.py): In tutorial 3, simplifying the bulge and disk geometry made the search easier but restricted the galaxies it could represent. Linear light profiles offer a different opportunity: keep the same profile shapes and solve their intensities directly, removing those dimensions from the non-linear search. + - Contents: Linear Light Profiles, Results and Intensities, Galaxy Structure, Basis, Two Gaussian Groups, Benefits and Limitations +- [Tutorial 5: Data and Likelihoods](scripts/chapter_2_modeling/tutorial_5_data_and_likelihoods.py): So far we have changed the galaxy model and the search. Now consider the other side of the fit: the measurements we include and how they are compared with a prediction. The data, model and Analysis object have distinct jobs. This separation lets the same modelling tools work with different observations and likelihood functions. + - Contents: Masking, Extra Galaxy Noise Scaling, Analysis, Interferometer Data, Multiple Datasets +- [Tutorial 6: Search Chaining](scripts/chapter_2_modeling/tutorial_6_search_chaining.py): A neighbouring galaxy can complicate the fit to our target. We need to describe its light, but repeatedly searching all its parameters while refining the target can waste effort and introduce difficult degeneracies. Search chaining lets us fit different parts of the scene in stages. + - Contents: Dataset, Search 1, Inspect Before Chaining, Search 2, Limits and Pipelines +- [Tutorial 7: Summary](scripts/chapter_2_modeling/tutorial_7_summary.py): (no summary in script docstring) ## chapter_3_pixelizations @@ -64,8 +58,12 @@ AUTO-GENERATED by PyAutoHands — do not edit by hand; regenerate with generate. ## chapter_optional -- [Tutorial: Alternative Searches](scripts/chapter_optional/tutorial_searches.py): Up to now, we've always used the non-linear search Nautilus and not considered the input parameters that control its sampling. In this tutorial, we'll consider how we can change these setting to balance finding the global maxima solution with fast run time. - - Contents: Nested Sampling, Optimizers, MCMC +- [Optional Tutorial: Need for Speed](scripts/chapter_optional/tutorial_need_for_speed.py): Return to this tutorial when a fit is too slow for your scientific needs. Faster likelihood calculations help, but a well-organised model and search often matter just as much. Hardware cannot make an inappropriate model fit. + - Contents: Search Effort, Likelihood Cost, JAX and Batching, Measuring Runtime, Data Quantity +- [Optional Historical Tutorial: Prior Passing](scripts/chapter_optional/tutorial_prior_passing.py): This is historical background, not part of the recommended HowToGalaxy learning path. Older versions of the PyAutoGalaxy / PyAutoLens workflow automatically narrowed priors between searches. That default behaviour has been disabled. New readers are discouraged from investing time in the old prior-passing recipes: learn the component-separation approach in chapter 2 tutorial 6 instead. + - Contents: Historical Behaviour, Current Behaviour, Why It Is Optional +- [Optional Tutorial: Alternative Searches](scripts/chapter_optional/tutorial_searches.py): You can complete HowToGalaxy using Nautilus without studying search algorithms in detail. Return here if you want to understand the fast Prodigy stage of search chaining, or compare alternative approaches for your own work. + - Contents: Optimisation, Nested Sampling, MCMC ## simulators diff --git a/llms.txt b/llms.txt index b702b74..f7f9ef5 100644 --- a/llms.txt +++ b/llms.txt @@ -25,7 +25,7 @@ real analysis?" below). ## The learning path (chapters in order) - **Chapter 1 — Introduction** → [scripts/chapter_1_introduction/](scripts/chapter_1_introduction/): Galaxies from first principles: grids & galaxies, light profiles, simulating data, and fitting data. The conceptual foundation. -- **Chapter 2 — Modeling** → [scripts/chapter_2_modeling/](scripts/chapter_2_modeling/): Fitting a galaxy model to data with a non-linear search — parameter spaces, priors, dealing with failure, linear light profiles, masking, and reading results. +- **Chapter 2 — Modeling** → [scripts/chapter_2_modeling/](scripts/chapter_2_modeling/): Fitting a galaxy model to data with a non-linear search — practicalities, difficult fits, linear profiles, data and likelihoods, and component-based search chaining. - **Chapter 3 — Pixelizations** → [scripts/chapter_3_pixelizations/](scripts/chapter_3_pixelizations/): Reconstructing galaxy structure on a mesh — indexed mappings, inversions, Bayesian regularization and combined MGE/pixelization search chaining. - **Chapter 4 — Scaling Up Galaxies** → [scripts/chapter_4_scaling_up_galaxies/](scripts/chapter_4_scaling_up_galaxies/): Beyond a single galaxy — extra galaxies, blended multi-galaxy systems, and cluster fields. @@ -34,9 +34,9 @@ real analysis?" below). - **What is a light profile / how is a galaxy's light described?** → [scripts/chapter_1_introduction/tutorial_1_grids_and_galaxies.py](scripts/chapter_1_introduction/tutorial_1_grids_and_galaxies.py): Sersic profiles, geometry, projecting light in 1D. - **How does a telescope image (and noise/PSF) get simulated?** → [scripts/chapter_1_introduction/tutorial_2_data.py](scripts/chapter_1_introduction/tutorial_2_data.py): Optics blurring, Poisson noise, background sky, the simulator API. - **What does "fitting" a galaxy mean?** → [scripts/chapter_1_introduction/tutorial_3_fitting.py](scripts/chapter_1_introduction/tutorial_3_fitting.py): Masking, model images, residuals and the log likelihood. -- **How does a non-linear search find a model?** → [scripts/chapter_2_modeling/tutorial_1_non_linear_search.py](scripts/chapter_2_modeling/tutorial_1_non_linear_search.py): Parameter space, priors, MLE / MCMC / nested sampling. -- **My fit found a wrong (local-maxima) solution — what do I do?** → [scripts/chapter_2_modeling/tutorial_4_dealing_with_failure.py](scripts/chapter_2_modeling/tutorial_4_dealing_with_failure.py): Prior tuning, reducing complexity, and looking harder. -- **What are linear light profiles / MGE?** → [scripts/chapter_2_modeling/tutorial_5_linear_profiles.py](scripts/chapter_2_modeling/tutorial_5_linear_profiles.py): Solving intensities linearly; the Multi-Gaussian Expansion basis. +- **How does a non-linear search find a model?** → [scripts/chapter_2_modeling/tutorial_1_non_linear_search.py](scripts/chapter_2_modeling/tutorial_1_non_linear_search.py): Parameter space, priors and nested sampling with Nautilus. +- **My fit found a wrong (local-maxima) solution — what do I do?** → [scripts/chapter_2_modeling/tutorial_3_why_modeling_is_hard.py](scripts/chapter_2_modeling/tutorial_3_why_modeling_is_hard.py): Prior tuning, reducing complexity, and looking harder. +- **What are linear light profiles / MGE?** → [scripts/chapter_2_modeling/tutorial_4_linear_profiles.py](scripts/chapter_2_modeling/tutorial_4_linear_profiles.py): Solving intensities linearly; the Multi-Gaussian Expansion basis. - **How do I model an image with two galaxies?** → [scripts/chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy.py](scripts/chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy.py): Joint fitting of blended galaxies and their degeneracies. - **How do I reconstruct irregular structure on a pixel grid?** → [scripts/chapter_3_pixelizations/tutorial_1_pixelizations.py](scripts/chapter_3_pixelizations/tutorial_1_pixelizations.py) through [tutorial_3_model_fit.py](scripts/chapter_3_pixelizations/tutorial_3_model_fit.py). diff --git a/notebooks/README.md b/notebooks/README.md index 3ade191..e54ca64 100644 --- a/notebooks/README.md +++ b/notebooks/README.md @@ -3,7 +3,7 @@ The `HowToGalaxy` folder contains **HowToGalaxy** lectures, which teach a new us # Folders - `chapter_1_introduction`: An introduction to galaxy morphology and structure using **PyAutoGalaxy**. -- `chapter_2_modeling`: How to model galaxies, including a primer on Bayesian non-linear analysis. +- `chapter_2_modeling`: How to model galaxies, with data, models, Analysis objects and searches. - `chapter_3_pixelizations`: How to perform pixelized reconstructions of a galaxy. - `chapter_4_scaling_up_galaxies`: How to scale up modeling to multiple galaxies, from blended pairs to cluster fields. - `chapter_optional`: Optional tutorials. @@ -77,9 +77,9 @@ In chapter 1, we'll learn about galaxy structure and **PyAutoGalaxy**. At the en # OVERVIEW OF CHAPTER 2 (Beginner) -**Bayesian Inference and Non-linear Searches** +**Practical Galaxy Modeling** -In chapter 2, we'll cover Bayesian inference and model-fitting via a non-linear search. We will use these tools to +In chapter 2, we'll learn practical model-fitting via a non-linear search. We will use these tools to fit CCD imaging data of a galaxy with a model. At the end, you'll understand: 1. The concept of a non-linear search and non-linear parameter space. @@ -87,7 +87,7 @@ fit CCD imaging data of a galaxy with a model. At the end, you'll understand: 3. The trade-off between realism and complexity when choosing a model. 4. Why an incorrect model may be inferred and how to prevent this from happening. 5. The challenges that are involved in inferring a robust model in a computationally reasonable run-time. -6. How to chain non-linear searches together to build automated modeling pipelines with prior passing. +6. How to chain searches to fit components separately and simplify later fits. **Once completed, you'll be ready to model your own galaxies with PyAutoGalaxy!** diff --git a/notebooks/chapter_1_introduction/tutorial_2_data.ipynb b/notebooks/chapter_1_introduction/tutorial_2_data.ipynb index 9801c52..cbe9cf6 100644 --- a/notebooks/chapter_1_introduction/tutorial_2_data.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_2_data.ipynb @@ -635,8 +635,8 @@ "script if it does not exist on your hard-disk, using the same auto-simulation idiom as later tutorials) and plot\n", "its dirty images \u2014 the closest an interferometer dataset comes to the CCD images we simulated above.\n", "\n", - "HowToGalaxy will not cover interferometry any further than this. The lecture series teaches galaxy modeling using\n", - "CCD imaging, and everything you learn transfers to visibility-space fitting. If you need to model interferometer\n", + "HowToGalaxy teaches model fitting using CCD imaging, with a brief reminder of visibility-space likelihoods in\n", + "chapter 2. The modelling tools transfer to visibility-space fitting. If you need to model interferometer\n", "data, go to the `autogalaxy_workspace/scripts/interferometer` package, which is the dedicated resource for\n", "uv-plane galaxy modeling." ] diff --git a/notebooks/chapter_2_modeling/README.md b/notebooks/chapter_2_modeling/README.md index df3547d..dffcad1 100644 --- a/notebooks/chapter_2_modeling/README.md +++ b/notebooks/chapter_2_modeling/README.md @@ -1,26 +1,17 @@ -In chapter 2, we'll take you through how to model galaxies using a non-linear search, ending with how -searches are chained together into automated modeling pipelines. +Chapter 2 brings together data, models, Analysis objects and searches to teach practical galaxy modelling. -**Colab** links to every tutorial are included. +- [Tutorial 1: Non-linear Search](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb) — Fit a galaxy using Nautilus. -# Files +- [Tutorial 2: Practicalities](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb) — Run a realistic model and inspect output, memory use and results. -- [Tutorial 1: Non-linear Search](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb) — How a non-linear search is used to fit a model and the concepts of a parameter space and priors. +- [Tutorial 3: Why Modeling Is Hard](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_3_why_modeling_is_hard.ipynb) — Use visual inspection to diagnose and improve difficult fits. -- [Tutorial 2: Practicalities](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb) — Practicalities of performing model-fitting, like how to inspect the results on your hard-disk. +- [Tutorial 4: Linear Profiles](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_4_linear_profiles.ipynb) — Solve intensities and represent galaxy structure with MGEs. -- [Tutorial 3: Realism and Complexity](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_3_realism_and_complexity.ipynb) — Finding a balance between realism and complexity when composing and fitting a model. +- [Tutorial 5: Data and Likelihoods](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_5_data_and_likelihoods.ipynb) — Choose measurements and connect data to models through Analysis objects. -- [Tutorial 4: Dealing with Failure](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_4_dealing_with_failure.ipynb) — What to do when PyAutoGalaxy finds an inaccurate model. +- [Tutorial 6: Search Chaining](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_6_search_chaining.ipynb) — Fit components in stages with Prodigy and Nautilus. -- [Tutorial 5: Linear Profiles](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_5_linear_profiles.ipynb) — Light profiles which capture complex morphologies in a reduced number of non-linear parameters. +- [Tutorial 7: Summary](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_7_summary.ipynb) — Review the chapter and choose the next step. -- [Tutorial 6: Masking](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_6_masking.ipynb) — How to mask your data to improve the model. - -- [Tutorial 7: Results](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_7_results.ipynb) — Overview of the results available after successfully fitting a model. - -- [Tutorial 8: Need for Speed](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_8_need_for_speed.ipynb) — How to fit complex models whilst balancing efficiency and run-time. - -- [Tutorial 9: Search Chaining](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_9_search_chaining.ipynb) — Breaking the modeling procedure into a chained sequence of model-fits. - -- [Tutorial 10: Prior Passing](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_10_prior_passing.ipynb) — How the results of earlier searches are passed to later searches. +Alternative searches and performance guidance are in `../chapter_optional`. Prior passing is historical background, not required reading. diff --git a/notebooks/chapter_2_modeling/tutorial_10_prior_passing.ipynb b/notebooks/chapter_2_modeling/tutorial_10_prior_passing.ipynb deleted file mode 100644 index 790d12f..0000000 --- a/notebooks/chapter_2_modeling/tutorial_10_prior_passing.ipynb +++ /dev/null @@ -1,562 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 10: Prior Passing\n", - "==========================\n", - "\n", - "In the previous tutorial, we used non-linear search chaining to break the model-fitting procedure down into two\n", - "non-linear searches. This used an initial search to fit a simple model, whose results were used to tune and\n", - "initialize the priors of a more complex model that was fitted by the second search.\n", - "\n", - "However, the results were passed between searches manually. I explicitly wrote out every result as a prior\n", - "containing the values inferred in the first search. **PyAutoGalaxy** has an API for passing priors in a more generalized\n", - "way, which is the topic of this tutorial.\n", - "\n", - "__Contents__\n", - "\n", - "- **Initial Setup:** Load the dataset and apply a mask.\n", - "- **Dataset Auto-Simulation:** Simulate the dataset via its simulator script if it is not on your hard-disk.\n", - "- **Model:** Compose the model for the first search.\n", - "- **Search:** Run the first search.\n", - "- **Result (Search 1):** Inspect the result of the first search.\n", - "- **Prior Passing:** Use the prior passing API to pass results to the second search.\n", - "- **Result:** Inspect the final result of the chained search.\n", - "- **Wrap Up:** Summary of the prior passing API.\n", - "- **Detailed Explanation Of Prior Passing:** In-depth explanation of how priors are passed between searches.\n", - "- **EXAMPLE:** A worked example of prior passing for a Sersic sersic_index parameter." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Google Colab Setup__\n", - "\n", - "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "jupyter": { - "source_hidden": true - } - }, - "outputs": [], - "source": [ - "# @title Set up Google Colab { display-mode: \"form\" }\n", - "try:\n", - " import google.colab\n", - "except ImportError:\n", - " from autogalaxy import setup_colab as _setup_colab\n", - "else:\n", - " import importlib\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.check_call(\n", - " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", - " )\n", - " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", - "\n", - "_setup_colab.setup(\"howtogalaxy\")" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autogalaxy import setup_notebook; setup_notebook()\n", - "\n", - "import numpy as np\n", - "from pathlib import Path\n", - "import autogalaxy as ag\n", - "import autogalaxy.plot as aplt\n", - "import autofit as af" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Initial Setup__\n", - "\n", - "we'll use the same galaxy data as the previous tutorial, where:\n", - "\n", - " - The galaxy's bulge is a `Sersic`.\n", - " - The galaxy's disk is an `Exponential`.\n", - " \n", - "All the usual steps for setting up a model fit (masking, analysis, etc.) are included below." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "dataset_name = \"simple\"\n", - "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Dataset Auto-Simulation__\n", - "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "if ag.util.dataset.should_simulate(str(dataset_path)):\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulators/simple.py\"],\n", - " check=True,\n", - " )\n", - "\n", - "\n", - "dataset = ag.Imaging.from_fits(\n", - " data_path=dataset_path / \"data.fits\",\n", - " noise_map_path=dataset_path / \"noise_map.fits\",\n", - " psf_path=dataset_path / \"psf.fits\",\n", - " pixel_scales=0.1,\n", - ")\n", - "\n", - "mask = ag.Mask2D.circular(\n", - " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5\n", - ")\n", - "\n", - "dataset = dataset.apply_mask(mask=mask)\n", - "\n", - "over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n", - " grid=dataset.grid,\n", - " sub_size_list=[8, 4, 2],\n", - " radial_list=[0.3, 0.6],\n", - " centre_list=[(0.0, 0.0)],\n", - ")\n", - "\n", - "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n", - "\n", - "aplt.subplot_imaging_dataset(dataset=dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Model__\n", - "\n", - "We are going to use the same result of search 1 from the previous tutorial. Thus, we set up an identical model such \n", - "that we instantly load the result from hard-disk." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge = af.Model(ag.lp_linear.Sersic)\n", - "disk = af.Model(ag.lp_linear.Exponential)\n", - "\n", - "bulge.centre_0 = 0.0\n", - "bulge.centre_1 = 0.0\n", - "disk.centre_0 = 0.0\n", - "disk.centre_1 = 0.0\n", - "\n", - "disk.ell_comps = bulge.ell_comps\n", - "\n", - "bulge.sersic_index = 4.0\n", - "\n", - "galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n", - "\n", - "model_1 = af.Collection(galaxies=af.Collection(galaxy=galaxy))" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `info` attribute shows the model in a readable format." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(model_1.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Search__\n", - "\n", - "We also create the same search as the previous tutorial, using the same name to ensure we use the same results, and \n", - "run it." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "analysis_1 = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", - "\n", - "search_1 = af.Nautilus(\n", - " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", - " name=\"tutorial_9_search_chaining_1\",\n", - " unique_tag=dataset_name,\n", - " n_live=100,\n", - " n_batch=50, # GPU batching and VRAM use explained in tutorial 2 of this chapter.\n", - ")\n", - "\n", - "result_1 = search_1.fit(model=model_1, analysis=analysis_1)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Result (Search 1)__\n", - "\n", - "The results which are used for prior passing are summarised in the `info` attribute." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result_1.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Prior Passing__\n", - "\n", - "We are now going to use the prior passing API to pass these results, in a way which does not require us to manually \n", - "write out the inferred parameter values of each component. The details of how prior passing is performed will be \n", - "expanded upon at the end of the tutorial.\n", - "\n", - "We start with the bulge, which in the previous search was a `Sersic` with its centre fixed to (0.0, 0.0) \n", - "and its `sersic_index` fixed to 4.0. The API for passing priors is shown below and there are two things worth noting:\n", - "\n", - " 1) We pass the priors using the `model` attribute of the result. This informs **PyAutoGalaxy** to pass the result as a\n", - " model component that is to be fitted for in the next search, using priors that are initialized from the previous\n", - " search's result. Note, if we pass as a `model` a parameter that was fixed in search 1 (e.g. the `sersic_index`) it \n", - " will be fixed to the same value in search 2.\n", - "\n", - " 2) We do not pass the `centre` or `sersic_index` using `model`, because it would be fixed to the values that it was in \n", - " the first search. By omitting the centre, it uses the default priors on a galaxy, whereas we manually tell the \n", - " Sersic index to use a `TruncatedGaussianPrior` centred on 4.0. " - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge = af.Model(ag.lp_linear.Sersic)\n", - "\n", - "bulge.ell_comps = result_1.model.galaxies.galaxy.bulge.ell_comps\n", - "bulge.effective_radius = result_1.model.galaxies.galaxy.bulge.effective_radius\n", - "bulge.sersic_index = af.TruncatedGaussianPrior(\n", - " mean=4.0, sigma=2.0, lower_limit=0.0, upper_limit=5.0\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For the disk, we are passing the result of an `Exponential` to a `Sersic`.\n", - "\n", - "We do not pass the `ell_comps` because this would pair them to the `bulge`, as was performed in the first \n", - "model-fit." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "disk = af.Model(ag.lp_linear.Sersic)\n", - "\n", - "disk.effective_radius = result_1.model.galaxies.galaxy.disk.effective_radius\n", - "disk.sersic_index = af.TruncatedGaussianPrior(\n", - " mean=1.0, sigma=2.0, lower_limit=0.0, upper_limit=5.0\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now compose the model with these components that have had their priors customized. " - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n", - "\n", - "model_2 = af.Collection(galaxies=af.Collection(galaxy=galaxy))" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `info` attribute shows the model, including how all priors are updated via prior passing." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(model_2.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Search__\n", - "\n", - "Lets setup and run the search. I have given it a different name to the previous tutorial so we can compare the priors\n", - "that were passed." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "analysis_2 = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", - "\n", - "search_2 = af.Nautilus(\n", - " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", - " name=\"tutorial_10_prior_passing_2\",\n", - " unique_tag=dataset_name,\n", - " n_live=100,\n", - " n_batch=50, # GPU batching and VRAM use explained in tutorial 2 of this chapter.\n", - ")\n", - "\n", - "print(\n", - " \"The non-linear search has begun running - checkout the output/howtogalaxy/chapter_2\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell will progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", - "result_2 = search_2.fit(model=model_2, analysis=analysis_2)\n", - "\n", - "print(\"Search has finished run - you may now continue the notebook.\")\n" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Result__\n", - "\n", - "We can again inspect the results via the `info` attribute." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result_2.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And a plot of the image shows we get a good model again!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_fit_imaging(fit=result_2.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Wrap Up__\n", - "\n", - "This tutorial has covered the core of the prior passing API; the chaining example in the `autogalaxy_workspace`\n", - "(`autogalaxy_workspace/scripts/guides/modeling/chaining.py`) expands on it further. The main thing to note is that\n", - "we can pass entire profiles or galaxies using prior passing, if their model does not change (which for the bulge\n", - "and disk above, was not true). The API to pass a whole profile or galaxy is as follows:\n", - "\n", - " bulge = result_1.model.galaxies.galaxy.bulge\n", - " galaxy = result_1.model.galaxies.galaxy\n", - "\n", - "We can also pass priors using an `instance` instead of a `model`. When an `instance` is used, the maximum likelihood\n", - "parameter values are passed as fixed values that are therefore not fitted for by the non-linear search (reducing its\n", - "dimensionality). Chained fits often use this to fix one galaxy's light to the best-fit model of an early search\n", - "before fitting a second galaxy alongside it \u2014 chapter 4 of **HowToGalaxy**, which scales up to modeling multiple\n", - "galaxies, and the workspace's chaining example show this in action.\n", - " \n", - "Lets now think about how priors are passed. Checkout the `model.info` file of the second search of this tutorial. The \n", - "parameters do not use the default priors we saw in search 1 (which are typically broad UniformPriors). Instead, \n", - "they use GaussianPrior`s where:\n", - "\n", - " - The mean values are the median PDF results of every parameter in search 1.\n", - " - The sigma values are specified in the `width_modifier` field of the profile's entry in the `config/priors`\n", - " config files (we will discuss why this is used in a moment).\n", - "\n", - "Like the manual `GaussianPrior`'s that were used in the previous tutorial, the prior passing API sets up the prior on each\n", - "parameter with a `GaussianPrior` centred on the high likelihood regions of parameter space!\n", - "\n", - "__Detailed Explanation Of Prior Passing__\n", - "\n", - "To end, I provide a detailed overview of how prior passing works and illustrate tools that can be used to customize\n", - "its behaviour. It is up to you whether you want read this, or move on to the summary that concludes the chapter!\n", - "\n", - "Lets say I chain two parameters as follows:\n", - " \n", - " `bulge.effective_radius = result_1.model.galaxies.galaxy.bulge.effective_radius`\n", - "\n", - "By invoking the `model` attribute, the prior is passed following 3 rules:\n", - "\n", - " 1) The new parameter, in this case the effective radius, uses a `GaussianPrior`. This is ideal, as the 1D pdf results\n", - " we compute at the end of a search are easily summarised as a Gaussian.\n", - "\n", - " 2) The mean of the `GaussianPrior` is the median PDF value of the parameter estimated in search 1.\n", - " \n", - " This ensures that the initial sampling of the new search's non-linear starts by searching the region of non-linear \n", - " parameter space that correspond to highest log likelihood solutions in the previous search. Our priors therefore \n", - " correspond to the `correct` regions of parameter space.\n", - "\n", - " 3) The sigma of the Gaussian uses the value specified for the profile in the `config/priors/*.yaml` config file's\n", - " `width_modifier` field (check these files out now).\n", - "\n", - "The idea here is simple. We want a value of sigma that gives a `GaussianPrior` wide enough to search a broad \n", - "region of parameter space, so that the model can change if a better solution is nearby. However, we want it \n", - "to be narrow enough that we don't search too much of parameter space, as this will be slow or risk leading us \n", - "into an incorrect solution! \n", - "\n", - "The `width_modifier` values in the priors config file have been chosen based on our experience as being a good\n", - "balance of broadly sampling parameter space but not being so narrow that important solutions are missed.\n", - " \n", - "There are two ways a value is specified using the priors/width file:\n", - "\n", - " 1) Absolute: In this case, the error assumed on the parameter is the value given in the config file. \n", - " For example, if for the width on centre_0 of a light profile, the width modifier reads \"Absolute\" with a value \n", - " 0.05. This means if the error on the parameter centre_0 was less than 0.05 in the previous search, the sigma of \n", - " its `GaussianPrior` in this search will be 0.05.\n", - " \n", - " 2) Relative: In this case, the error assumed on the parameter is the % of the value of the estimated value given in \n", - " the config file. For example, if the intensity estimated in the previous search was 2.0, and the relative error in \n", - " the config file reads \"Relative\" with a value 0.5, then the sigma of the `GaussianPrior` will be 50% of this \n", - " value, i.e. sigma = 0.5 * 2.0 = 1.0.\n", - "\n", - "We use absolute and relative values for different parameters, depending on their properties. For example, using the \n", - "relative value of a parameter like the `Profile` centre makes no sense. If our galaxy is centred at (0.0, 0.0), \n", - "the relative error will always be tiny and thus poorly defined. Therefore, the default configs in **PyAutoGalaxy** use \n", - "absolute errors on the centre.\n", - "\n", - "However, there are parameters where using an absolute value does not make sense. Intensity is a good example of this. \n", - "The intensity of an image depends on its units, S/N, galaxy brightness, etc. There is no single absolute value that \n", - "one can use to generically chain the intensity of any two profiles. Thus, it makes more sense to chain them using\n", - "the relative value from a previous search.\n", - "\n", - "__EXAMPLE__\n", - "\n", - "Lets go through an example using a real parameter. Lets say in search 1 we fit the galaxy's light with an \n", - "elliptical Sersic profile, and we estimate that its sersic index is equal to 4.0.\n", - " \n", - "To pass this as a prior to search 2 we write:\n", - "\n", - " galaxy.bulge.sersic_index = result_1.model.galaxy.bulge.sersic_index\n", - "\n", - "The prior on the galaxy's bulge sersic index in search 2 would thus be a `GaussianPrior` with mean=4.0. \n", - "\n", - "The value of the Sersic index `width_modifier` in the priors config file sets sigma. The prior config file specifies\n", - "that we use an \"Absolute\" value of 1.5 to chain this prior. Thus, the `GaussianPrior` in search 2 would have a\n", - "mean=4.0 and sigma=1.5.\n", - "\n", - "If the prior config file had instead specified that we use a relative value of 0.8, the GaussianPrior in search 2 would\n", - "have a mean=4.0 and sigma = 4.0 * 0.8 = 3.2.\n", - "\n", - "And with that, we're done. Chaining priors is a bit of an art form, but one that works really well. " - ] - } - ], - "metadata": { - "anaconda-cloud": {}, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - }, - "colab": { - "aiContexts": { - "24c2f562-da24-50bb-8eb9-5a887505fe54": { - "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", - "name": "PyAutoGalaxy assistant", - "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_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\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_2_modeling/tutorial_10_prior_passing.ipynb in HowToGalaxy).\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 PyAutoGalaxy 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 PyAutoGalaxy docs (https://pyautogalaxy.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) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. 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 galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_chain_searches\n\n---\nname: ag_chain_searches\ndescription: Break one hard fit into a sequence of easier non-linear searches, using each result to initialize the next. Covers when chaining beats a single search and when it does not, passing a whole profile or galaxy with `result.model` (which preserves the original priors) versus narrowing them with `result.model_centred` and its absolute, relative and bounded variants, the `TruncatedGaussianPrior` those produce and where its sigma comes from in the `priors` config `width_modifier`, fixing a component with `result.instance` to remove its dimensions, and the output-path convention that keeps a chain's searches together. Use when a model is too complex for one search, when an early search should use cheap settings and a later one accurate ones, or when several galaxies must be added one at a time. Not for choosing a single search (`ag_configure_search`), not for driving one fit (`ag_run_search`), and not for combining several datasets (`ag_multi_dataset`).\n---\n\n# Chaining searches\n\nEvery other modelling skill in this workspace composes one model and hands it to one search.\nChaining is the alternative shape: split the problem into a sequence of searches, and use what\neach one learned to tell the next where to look.\n\nThe reason is statistical, not cosmetic. A non-linear search has to map a parameter space it knows\nnothing about, and the cost of doing that grows sharply with dimensionality while the risk of\nsettling in a local maximum grows with multi-modality. A galaxy model with a bulge, a disk, a sky\nlevel and two blended neighbours has both problems at once. Fit the bulge alone and the space is\nsmall, unimodal and mapped in minutes; then the disk only has to be added to a galaxy whose size\nand centre are already known. Each search in a chain solves a problem that is easy *because* of\nthe one before it.\n\nThree distinct benefits, and they are worth separating because they justify chaining in different\nsituations:\n\n- **Lower dimensionality per search.** Earlier searches fit simpler models with a parameter space\n that can be sampled properly, which reduces the chance of an incorrect local maximum in the\n final one.\n- **Cheap settings early, accurate settings late.** An early search only needs to find the high-\n likelihood region, so it can use a fast optimizer or a small `n_live`. Only the final search\n needs settings good enough to quantify errors.\n- **Cheap approximations early.** An early search can use a smaller mask, coarser over-sampling\n or a simplified component, and revert to the accurate-but-expensive settings at the end. The\n approximation costs some fidelity in the early result, which is fine when that result is only\n being used to place a prior.\n\nThis skill has **one** grounding script: `autogalaxy_workspace:scripts/guides/modeling/chaining.py`.\nIt is deliberately an API overview rather than a library of pipelines, and this skill is scoped to\nmatch it \u2014 the mechanics of prior passing, done honestly, rather than a catalogue of recipes that\ndo not exist upstream. The end of chapter 2 of the HowToGalaxy lecture series (tutorials 9-10) is where the pedagogy lives.\nRead [`../wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md) for\nhow run time scales with the model, which is the quantity chaining exists to manage.\n\n## Ask\n\n- *\"What makes this fit hard \u2014 too many parameters, or a search that keeps landing somewhere\n wrong?\"* Both are chaining's territory, but they suggest different splits: dimensionality\n suggests adding components one at a time, multi-modality suggests fixing the thing the search\n keeps getting wrong.\n- *\"What would you fit first if you had to pick one component?\"* Usually the brightest and\n simplest. If the user cannot name one, chaining may not be the right tool \u2014 see the branch on\n when not to chain.\n- *\"Is a single search actually failing, or just slow?\"* A slow-but-correct search is often better\n served by a faster sampler or JAX than by a chain, because a chain adds a whole class of\n failure: a wrong early result confidently narrowing a later prior.\n\n## Branch \u2014 the two-search chain\n\nThe deliverable is one script containing the whole chain, so it can be re-run end to end. Adapted\nfrom `autogalaxy_workspace:scripts/guides/modeling/chaining.py`.\n\n```python\n\"\"\"\nGalaxy Structure: Chained Searches\n=================================\n\nFit a galaxy's bulge alone, then add a disk with the bulge's parameters initialized from the\nfirst fit. Splitting the fit this way lets each search sample a parameter space it can actually\nmap, and makes the two-component decomposition a refinement of a known galaxy rather than a\nfourteen-dimensional search from broad priors.\n\n__Contents__\n\n- **Imports:** JAX environment first, then the standard trio.\n- **Dataset:** Load, mask and over-sample the imaging once, for every search.\n- **Paths:** One output prefix shared by every search in the chain.\n- **Model (Search 1):** A single linear Sersic bulge.\n- **Model-Fit (Search 1):** Fit it, cheaply.\n- **Model Chaining:** Pass the bulge into search 2 and add a disk.\n- **Model-Fit (Search 2):** Fit the two-component model with accurate settings.\n- **Result:** Read the final model back.\n\"\"\"\nfrom autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\n\"\"\"\n__Dataset__\n\nLoaded, masked and over-sampled once. Every search in the chain shares one `analysis`, which is\nwhat makes their likelihoods comparable \u2014 if search 2 used a different mask, its log likelihood\nwould not be on the same scale as search 1's, and the priors passed between them would refer to a\ndifferent dataset.\n\"\"\"\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"\"\n\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=0.1,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=3.0,\n)\n\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\n\"\"\"\n__Paths__\n\nOne `path_prefix` for the whole chain, with each search distinguished only by `name`. This keeps\nevery stage of one chain in one directory tree, which matters when you come back to a fit and\nneed to see what search 1 actually inferred before trusting search 2.\n\"\"\"\npath_prefix = Path(\"imaging\") / \"chaining\" / \"\"\n\n\"\"\"\n__Model (Search 1)__\n\nThe bulge alone. A linear `Sersic` solves its own `intensity`, so this is a compact space the\nsearch can map quickly (`PyAutoGalaxy:autogalaxy/profiles/light/linear/sersic.py`).\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel_1 = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model_1.info)\n\n\"\"\"\n__Model-Fit (Search 1)__\n\nCheap settings on purpose: this search only has to find the high-likelihood region, not measure\nerrors. Inspect its result before relying on it \u2014 a chain built on a bad first search propagates\nthat error into every subsequent prior, with more confidence at every step.\n\"\"\"\nsearch_1 = af.Nautilus(\n path_prefix=path_prefix,\n name=\"search[1]__bulge\",\n unique_tag=\"\",\n n_live=100,\n)\n\nresult_1 = search_1.fit(model=model_1, analysis=analysis)\n\nprint(result_1.info)\n\n\"\"\"\n__Model Chaining__\n\n`result_1.model_centred` returns the search-1 model with every free parameter replaced by a\n`TruncatedGaussianPrior` centred on that parameter's median from search 1\n(`PyAutoFit:autofit/non_linear/result.py`,\n`PyAutoFit:autofit/mapper/prior/truncated_gaussian.py`). Search 2 therefore starts sampling in\nthe region search 1 found, rather than from broad priors.\n\nNote the attribute: `result_1.model` passes the component through with its **original** priors\nunchanged, which is useful when you want the structure of a previous model but not its\nconstraints. `model_centred` is the one that narrows.\n\"\"\"\nbulge = result_1.model_centred.galaxies.galaxy.bulge\ndisk = af.Model(ag.lp_linear.Exponential)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n\nmodel_2 = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model_2.info)\n\n\"\"\"\n__Model-Fit (Search 2)__\n\nThe accurate search. Read search 2's `model.info` in the output folder to confirm the priors\narrived as intended before trusting the result.\n\"\"\"\nsearch_2 = af.Nautilus(\n path_prefix=path_prefix,\n name=\"search[2]__bulge_disk\",\n unique_tag=\"\",\n n_live=150,\n)\n\nresult_2 = search_2.fit(model=model_2, analysis=analysis)\n\n\"\"\"\n__Result__\n\"\"\"\nprint(result_2.info)\n\nPLOT_DIR = Path(\"scripts\") / \"scratch\" / \"\" / \"chained\"\n\naplt.subplot_fit_imaging(\n fit=result_2.max_log_likelihood_fit,\n output_path=str(PLOT_DIR),\n output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nWhole components pass, not just single parameters: `result_1.model_centred.galaxies.galaxy.bulge`\ncarries every one of the bulge's parameters across in one expression, provided the component's\n*type* has not changed. A single parameter passes the same way \u2014\n`galaxy.bulge.effective_radius = result_1.model_centred.galaxies.galaxy.bulge.effective_radius` \u2014\nwhich is how you narrow some parameters and leave others broad.\n\n## Branch \u2014 `model`, `model_centred`, and `instance`\n\nThis is the part to get right, and the distinction is sharper than the workspace script's prose\nsuggests. Three attributes on a `Result`, three different things:\n\n**`result.model`** \u2014 the same model with the **same priors it had before**. On the released stack\nthis attribute preserves the priors rather than narrowing them\n(`PyAutoFit:autofit/non_linear/result.py`), so a component passed this way brings its structure\nacross but no information from the fit. That is occasionally exactly what you want \u2014 reuse the\ncomposition, refit from scratch \u2014 but it is *not* prior passing, and reading the workspace\nscript's older description of it as producing narrowed Gaussians will mislead you. Check what you\nactually got:\n\n```python\nprint(type(model_2.galaxies.galaxy.bulge.sersic_index).__name__)\n```\n\n**`result.model_centred`** \u2014 the narrowing one. Every free parameter becomes a\n`TruncatedGaussianPrior` whose `mean` is that parameter's median from the previous search and whose\n`sigma` comes from the parameter's `width_modifier` in the `priors` config. Three further variants\nlet you override that width:\n\n| Attribute | Prior produced | `sigma` |\n|---|---|---|\n| `result.model_centred` | `TruncatedGaussianPrior` | from the parameter's config `width_modifier` |\n| `result.model_centred_absolute(a=0.1)` | `TruncatedGaussianPrior` | exactly `a`, for every parameter |\n| `result.model_centred_relative(r=0.2)` | `TruncatedGaussianPrior` | `r \u00d7 mean`, per parameter |\n| `result.model_centred_max_lh_bounded(b=0.3)` | `UniformPrior` | bounds at `mean \u00b1 b` |\n\n**`result.instance`** \u2014 the maximum-likelihood *values*, as fixed numbers. A component passed this\nway has no free parameters at all, so search 2's dimensionality drops by that component's\nparameter count. This is the lever for \"fit the bulge, freeze it, then fit the disk against a\nfixed bulge\", and it is much stronger medicine than a narrow prior: the later search cannot\nrevisit the frozen component even if the added component would have changed it.\n\n```python\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=result_1.instance.galaxies.galaxy.bulge, # fixed, contributes 0 parameters\n disk=af.Model(ag.lp_linear.Exponential),\n)\n```\n\nThe common three-stage pattern uses all of it: fit the bulge; fix it and fit the disk; then free\nboth from the second result's narrowed priors for a final search where everything moves together.\nFreezing permanently is a real bias risk, because a bulge fitted without a disk absorbs some of\nthe disk's light \u2014 so the third stage is not optional if the decomposition is the result you are\nquoting.\n\n## Branch \u2014 where `sigma` comes from, and its two traps\n\n`model_centred` reads each parameter's width from the `width_modifier` field of its entry in the\n`priors` config (`autogalaxy_assistant:config/priors/`, mapped in\n[`../wiki/core/api/configuration.md`](../wiki/core/api/configuration.md)). Two forms:\n\n- **Absolute** \u2014 `sigma` is the config value directly. For a linear `Sersic`, `sersic_index`\n carries `Absolute: 1.5`, each `centre` component `Absolute: 0.05`, and each `ell_comps`\n component `Absolute: 0.2`.\n- **Relative** \u2014 `sigma` is that fraction of the inferred value. `effective_radius` carries\n `Relative: 1.0`.\n\nThe reasoning behind which is which is worth understanding, because it tells you when to override.\nA relative width on a centre makes no sense: a galaxy centred near `(0.0, 0.0)` would get a sigma\nnear zero and the next search could not move it at all. An absolute width on an `intensity` makes\nno sense either, because intensity depends on units, exposure and brightness, so no single number\ngeneralises. Hence absolute centres and relative radii.\n\nTwo traps follow directly, and both are worth stating to a user before they hit them:\n\n**Relative widths break on parameters that can be negative or zero.**\n`model_centred_relative(r=...)` applies one relative width to *every* parameter, including\n`ell_comps`, whose median is legitimately near zero and often negative. That yields a negative\n`sigma` and raises rather than silently misbehaving \u2014 which is the good outcome, but it does mean\nthe blanket relative form is unusable on a general light-profile model. Use `model_centred`\n(per-parameter config widths), or `model_centred_absolute` where a single absolute width is\ndefensible for the parameters you are passing.\n\n**The bounded variant does not inherit the parameter's physical limits.**\n`model_centred_max_lh_bounded(b=...)` builds a `UniformPrior` at `mean \u00b1 b` regardless of the\nparameter's configured limits, so a `sersic_index` inferred near its ceiling of 5.0 can come back\nwith an upper limit above 5.0. Set the bound with the parameter's range in mind, or clamp the\nprior yourself afterwards.\n\nThe width you want is a genuine trade-off with no default that is right everywhere: wide enough\nthat a better nearby solution can still be found, narrow enough that the search is not doing\nsearch-1's work over again. The shipped `width_modifier` values are a considered balance rather\nthan a physical truth, and overriding them for one parameter you understand well is normal.\n\n## Branch \u2014 when chaining is the wrong tool\n\nChaining adds a failure mode that a single search does not have: **a wrong early result narrows a\nlater prior around the wrong place, and the later search never looks anywhere else.** The final\nposterior then looks tight and well-behaved and is simply wrong. Three situations where a single\nsearch is better:\n\n- **The single search works and is merely slow.** Reach for a faster sampler, a linear light\n profile, JAX or a GPU first ([`ag_configure_search`](./ag_configure_search.md),\n [`ag_run_search`](./ag_run_search.md)). Complexity you do not need is complexity that can be\n wrong.\n- **The early model is not a subset of the late one.** Prior passing assumes the parameter means\n something similar in both searches. Passing a `Sersic`'s parameters into an `Exponential`, or a\n parametric component's into a pixelised one, is either an error or meaningless.\n- **The parameter you fixed early is the one you are measuring.** If a bulge fitted without a disk\n is the number going in the paper, do not chain to a frozen bulge \u2014 chain to a narrowed one and\n let the final search move it.\n\nAlways inspect the intermediate result rather than trusting the chain. `result_1.info`, and\n`model.info` inside search 2's output folder, are the two things to read before believing the\nfinal number.\n\n## Branch \u2014 the practical mechanics\n\n**One analysis, reused.** Build the `ag.AnalysisImaging` once, before search 1, and pass the same\nobject to every search \u2014 unless you are deliberately changing the data between stages (a smaller\nmask early, the full one late), in which case say so explicitly, because the log likelihoods are\nthen not comparable across stages.\n\n**Naming.** One `path_prefix` for the chain, and `name=\"search[1]__\"` per stage. The bracket\nconvention is the workspace's and it sorts correctly; the `__` suffix is what makes an\noutput tree readable a month later.\n\n**`unique_tag`.** Keep it identical across the chain's searches, since it identifies the *dataset*.\nEach stage still lands in its own folder because `name` differs. And the identifier trap from\n[`ag_configure_search`](./ag_configure_search.md) applies to every stage: it does not hash your\ndata's pixel values, so if you swap datasets without changing `unique_tag`, every search in the\nchain silently returns the previous galaxy's result.\n\n**Smoke test the whole chain, not one search.** A chain's characteristic bug is a mis-typed\nattribute path in the passing expression, and that only fires at the second search:\n\n```bash\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/chained_fit.py\n```\n\nLevel 1 rather than level 2 here: level 1 runs a real (tiny) search at each stage, so a `Result`\nexists with samples for the next stage to pass from. Level 2 bypasses the sampler and leaves the\nchain nothing meaningful to narrow around. The levels are\n[`../wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md), and the priors a\ntest-mode chain produces are wiring evidence only \u2014 never quote them.\n\n## Combine\n\n- [`ag_configure_search`](./ag_configure_search.md) \u2014 cheap settings for early searches and\n accurate ones for the last; also the `unique_tag` semantics every stage inherits.\n- [`ag_run_search`](./ag_run_search.md) \u2014 driving each stage and reading its output folder.\n- [`ag_build_imaging_model`](./ag_build_imaging_model.md) \u2014 composing the models the chain steps\n between, including prior customisation by hand when you want to override a passed width.\n- [`ag_multi_galaxy_and_cluster`](./ag_multi_galaxy_and_cluster.md) \u2014 adding galaxies one at a\n time is the most common real use of chaining.\n- [`ag_multi_dataset`](./ag_multi_dataset.md) \u2014 its one-by-one branch is a chain across datasets\n rather than across model complexity.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) \u2014 when a single search lands somewhere\n unphysical, which is the diagnosis that most often leads here.\n- `ag_pixelization` \u2014 a smooth-profile fit chained into a pixelised one is a natural pairing,\n because the pixelisation wants a decent light model to start from.\n\nWhen a chain is worth keeping, offer (default-yes) to record it in a dated\n`wiki/project/YYYY-MM-DD-.md` entry: why the fit was split, what each stage fitted, what was\npassed as a narrowed prior versus fixed as an instance, and the shared output prefix \u2014 per\n[`_style.md`](./_style.md) property #5. The split and the passing decisions are the reasoning a\nreader will want, and they are invisible in the final `model.results`.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [HowToGalaxy: Search chaining](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_9_search_chaining.ipynb):\n the first chaining tutorial at the end of chapter 2, which builds the idea from a fit that fails\n without it; `tutorial_10_prior_passing` then walks the prior mechanics, and\n `chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy` applies the ideas to blended galaxies.\n- **General reference** \u2014 [RTD: Configs](https://pyautogalaxy.readthedocs.io/en/latest/general/configs.html):\n how the config files are laid out and looked up \u2014 the `priors` tree is where each parameter's\n `width_modifier` lives, and hence where a passed prior's `sigma` comes from.\n- **Experienced PyAutoGalaxy user** \u2014 [workspace: guides/modeling/chaining.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/guides/modeling/chaining.py):\n the API overview this skill is grounded in, with its own long discussion of absolute versus\n relative widths.\n\n## Agent procedural checklist\n\n1. Ask whether the single search is failing or merely slow; recommend a faster search before a\n chain when it is only slow.\n2. Choose the split with the user and say what each stage buys \u2014 dimensionality, settings, or a\n cheap approximation.\n3. Build the dataset and one `ag.AnalysisImaging` before search 1 and reuse it, or state\n explicitly why a stage uses different data.\n4. Write the whole chain into one script under one `path_prefix`, with `search[N]__` names.\n5. Use `result.model_centred` (or a `model_centred_*` variant) to narrow, `result.instance` to\n fix, and `result.model` only when you deliberately want the original priors back.\n6. Verify what you built: print the passed prior's type, and read `model.info` in the later\n search's output folder.\n7. Do not use `model_centred_relative` on a model containing `ell_comps` or a centre \u2014 it raises\n on a negative median.\n8. Inspect `result_1.info` before trusting anything downstream of it.\n9. If a component is frozen mid-chain, plan the final stage that frees it again before quoting its\n parameters.\n10. Validate the whole chain with `PYAUTO_TEST_MODE=1` (not 2 \u2014 the chain needs samples to pass).\n11. Offer the `wiki/project/` entry recording the split and the passing decisions.\n" - } - }, - "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file diff --git a/notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb b/notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb index 2b1a3ba..4d16c17 100644 --- a/notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb +++ b/notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb @@ -7,164 +7,37 @@ "Tutorial 1: Non-linear Search\n", "=============================\n", "\n", - "The starting point for most scientific analysis conducted by an Astronomer is that they have observations of a galaxy\n", - "using a telescope like the Hubble Space Telescope, and seek to learn about the galaxy and the Universe from these\n", - "observations. With **PyAutoGalaxy**, we seek to learn about the galaxy's structure and morphology, asking questions like\n", - "how big is the galaxy, is it disky or bulgy, and how is its light distributed?\n", + "In chapter 1, you adjusted a galaxy model by hand and inspected how well its image matched the data. Now we will\n", + "ask a search to do this for us. Our aim is still to learn about the galaxy: its size, shape and concentration.\n", "\n", - "To answer these questions, we must therefore fit the dataset with a model of the galaxy, where the model defines the\n", - "light profile that make up the galaxy we fit. Our goal is the find the combination of light profile parameters that\n", - "best-fit the data, such that the model represents the galaxy, and therefore the Universe, as well as possible.\n", - "\n", - "This process is called model-fitting, or \"modeling\" for short, and we actually did our first example of this in the\n", - "previous chapter. If you recall, in the fitting tutorial we set up a fit to a simulated dataset where the parameter\n", - "used to simulate the data were unknown, and you guessed the values of the parameters that best fit the data. You\n", - "iteratively improved the model-fit by guessing new parameters, over and over, finding solutions which produced\n", - "higher `log_likelihood` values.\n", - "\n", - "However, this approach was not optimal: it was manual and slow, we had no certainty that we had found the best\n", - "(e.g. maximum likelihood) solution and for more complex models, with more parameters and light profiles, it would\n", - "have been completely unfeasible.\n", - "\n", - "In this chapter, we perform modeling as a scientist would actually do it, and introduce the statistical inference\n", - "techniques that will ultimately allow us to fit complex models made of many light profiles to real galaxy data,\n", - "and begin learning about real galaxies in the Universe.\n", - "\n", - "This first tutorial introduces a number of key statistical concepts that are fundamental to understanding how\n", - "model-fitting works, both for **PyAutoGalaxy** and in general.\n", - "\n", - "__Overview__\n", - "\n", - "In this tutorial, we will use a non-linear search to fit a single Sersic light profile to simulated imaging of a\n", - "galaxy. We will:\n", - "\n", - "- Introduce concept like a \"parameter space\", \"likelihood surface\" and \"priors\", and relate them to how a non-linear\n", - " search works.\n", - "\n", - "- Introduce the `Analysis` class, which defines the `log_likelihood_function` that quantifies the goodness of fit of a\n", - " model instance to the data.\n", - "\n", - "- Fit datasets with different non-linear searches, including a maximum likelihood estimator (MLE),\n", - " Markov Chain Monte Carlo (MCMC) and nested sampling.\n", + "We will fit one Sersic profile using Nautilus, a nested sampler. You do not need to learn several kinds of search\n", + "to start modelling galaxies. Alternative searches are covered in the optional searches tutorial.\n", "\n", "__Contents__\n", "\n", - "This tutorial is split into the following sections:\n", - "\n", - "- **Parameter Space**: Introduce the concept of a \"parameter space\" and how it relates to model-fitting.\n", - "- **Non-Linear Search**: Introduce the concept of a \"non-linear search\" and how it fits models to data.\n", - "- **Search Types**: Introduce the maximum likelihood estimator (MLE), Markov Chain Monte Carlo (MCMC) and nested sampling search algorithms used in this tutorial.\n", - "- **Deeper Background**: Provide links to resources that more thoroughly describe the statistical principles that underpin non-linear searches.\n", - "- **Data**: Load and plot the galaxy dataset we'll fit.\n", - "- **Model**: Introduce the galaxy model we'll fit to the data.\n", - "- **Priors**: Introduce priors and how they are used to define the parameter space and guide the non-linear search.\n", - "- **Analysis**: Introduce the `Analysis` class, which contains the `log_likelihood_function` used to fit the model to the data.\n", - "- **Searches**: An overview of the searches used in this tutorial.\n", - "- **Maximum Likelihood Estimation (MLE)**: Perform a model-fit using the MLE search.\n", - "- **Markov Chain Monte Carlo (MCMC)**: Perform a model-fit using the MCMC search.\n", - "- **Nested Sampling**: Perform a model-fit using the nested sampling search.\n", - "- **Result**: The result of the model-fit, including the maximum likelihood model.\n", - "- **Samples**: The samples of the non-linear search, used to compute parameter estimates and uncertainties.\n", - "- **Customizing Searches**: How to customize the settings of the non-linear search.\n", - "- **Wrap Up**: A summary of the concepts introduced in this tutorial.\n", + "- **Parameter Space:** The galaxy models we can explore.\n", + "- **Dataset and Mask:** The observation we will fit.\n", + "- **Model and Priors:** The components and possible parameter values.\n", + "- **Analysis:** The interface between a model and the data.\n", + "- **Nested Sampling:** Use Nautilus to explore possible models.\n", + "- **Result:** Inspect the fit and the uncertainty in its parameters.\n", "\n", "__Parameter Space__\n", "\n", - "In mathematics, a function is defined by its parameters, which map inputs to outputs. For example, consider the simple function:\n", - "\n", - "\\[\n", - "f(x) = x^2\n", - "\\]\n", - "\n", - "Here, \\(x\\) is the input parameter, and \\(f(x)\\) returns the output \\(x^2\\). This relationship defines\n", - "the \"parameter space\" of the function, which in this case forms a parabola.\n", - "\n", - "Functions can also have multiple parameters, such as:\n", - "\n", - "\\[\n", - "f(x, y, z) = x + y^2 - z^3\n", - "\\]\n", - "\n", - "This defines a parameter space in three dimensions, representing the relationships between \\(x\\), \\(y\\), \\(z\\),\n", - "and the output \\(f(x, y, z)\\).\n", - "\n", - "This concept of parameter space is closely related to how we approach model-fitting. For instance, in chapter 1,\n", - "we created instances of a `Galaxy` object with\n", - "parameters like \\( (\\text{`centre_0`}, \\text{`centre_1`}, \\text{`ell_comps_0`}, \\text{`ell_comps_1`}, \\text{`intensity`}, \\text{`effective_radius`}, \\text{`sersic_index`}) \\).\n", - "These parameters were used to fit data and compute a log likelihood.\n", - "\n", - "We can think of this process as analogous to the function \\(f(\\( (\\text{`centre_0`}, \\text{`centre_1`}, \\text{`ell_comps_0`}, \\text{`ell_comps_1`}, \\text{`intensity`}, \\text{`effective_radius`}, \\text{`sersic_index`}) \\))\\),\n", - "where the output is the log likelihood. This function, which maps parameter values to a log likelihood, is known\n", - "as the \"likelihood function\" in statistical inference. To be explicit, we\u2019ll refer to it as the `log_likelihood_function`\n", - "since it deals with the log of the likelihood function.\n", - "\n", - "By framing the likelihood this way, we can think of our model as having its own parameter space\u2014a multidimensional\n", - "surface defined by all possible values of the\n", - "parameters \\( (\\text{`centre_0`}, \\text{`centre_1`}, \\text{`ell_comps_0`}, \\text{`ell_comps_1`}, \\text{`intensity`}, \\text{`effective_radius`}, \\text{`sersic_index`}) \\).\n", - "This surface, known as the \"likelihood surface,\" represents how the log likelihood changes across different parameter\n", - "values. During model-fitting, our goal is to find the peak of this surface, where the fit to the data is optimal.\n", - "\n", - "This parameter space is \"non-linear,\" meaning the relationship between the model parameters and the log likelihood is\n", - "not a simple linear one. Because of this non-linearity, we cannot predict the log likelihood from a given set of model\n", - "parameters without actually performing a fit to the data, as we did in the fitting tutorial of chapter 1.\n", - "\n", - "__Non-Linear Search__\n", - "\n", - "Now that we understand our problem in terms of a non-linear parameter space with a likelihood surface, we can\n", - "introduce the method used to fit the model to the data \u2014- the \"non-linear search\".\n", - "\n", - "Previously, our approach involved manually guessing models until finding one with a good fit and high log likelihood.\n", - "Surprisingly, this random guessing forms the basis of how model-fitting using a non-linear search actually works!\n", + "Imagine changing only the galaxy's size and concentration. Each pair of values describes a different galaxy.\n", + "All those possible pairs form a two-dimensional parameter space. Adding its centre and shape adds more dimensions.\n", + "A point in this space is one particular model, with a number assigned to every free parameter.\n", "\n", - "A non-linear search involves systematically guessing many models while tracking their log likelihoods. As the\n", - "algorithm progresses, it tends to favor models with parameter combinations that have previously yielded higher\n", - "log likelihoods. This iterative refinement helps to efficiently explore the vast parameter space.\n", + "The likelihood function gives each point a score by comparing the model prediction with the data and its noise.\n", + "Plotting that score over parameter space would give a likelihood surface. High regions describe better fits;\n", + "the parameter space is the set of possible inputs, while the likelihood surface describes their scores.\n", "\n", - "There are two key differences between guessing random models and using a non-linear search:\n", + "__Non-linear Search__\n", "\n", - "- **Computational Efficiency**: The non-linear search can evaluate the log likelihood of a model parameter\n", - " combinations in milliseconds and therefore many thousands of models in minutes. This computational speed enables\n", - " it to thoroughly sample potential solutions, which would be impractical for a human.\n", - "\n", - "- **Effective Sampling**: The search algorithm maintains a robust memory of previously guessed models and their log\n", - " likelihoods. This allows it to sample potential solutions more thoroughly and converge on the highest\n", - " likelihood solutions more efficiently, which is again impractical for a human.\n", - "\n", - "Think of the non-linear search as systematically exploring parameter space to pinpoint regions with the highest log\n", - "likelihood values. Its primary goal is to identify and converge on the parameter values that best describe the data.\n", - "\n", - "__Search Types__\n", - "\n", - "There are different types of non-linear searches, each of which explores parameter space in a unique way.\n", - "In this example, we will use three types of searches, which broadly represent the various approaches to non-linear\n", - "searches used in statistical inference.\n", - "\n", - "These are:\n", - "\n", - "- **Maximum Likelihood Estimation (MLE)**: This method aims to find the model that maximizes the likelihood function.\n", - " It does so by testing nearby models and adjusting parameters in the direction that increases the likelihood.\n", - "\n", - "- **Markov Chain Monte Carlo (MCMC)**: This approach uses a group of \"walkers\" that explore parameter space randomly.\n", - " The likelihood at each walker's position influences the probability of the walker moving to a new position.\n", - "\n", - "- **Nested Sampling**: This technique samples points from the parameter space iteratively. Lower likelihood points\n", - " are replaced by higher likelihood ones, gradually concentrating the samples in regions of high likelihood.\n", - "\n", - "We will provide more details on each of these searches below.\n", - "\n", - "__Deeper Background__\n", - "\n", - "**The descriptions of how searches work in this example are simplified and phenomenological and do not give a full\n", - "description of how they work at a deep statistical level. The goal is to provide you with an intuition for how to use\n", - "them and when different searches are appropriate for different problems. Later tutorials will provide a more formal\n", - "description of how these searches work.**\n", - "\n", - "If you're interested in learning more about these principles, you can explore resources such as:\n", - "\n", - "- [Markov Chain Monte Carlo (MCMC)](https://en.wikipedia.org/wiki/Markov_chain_Monte_Carlo)\n", - "- [Introduction to MCMC Sampling](https://twiecki.io/blog/2015/11/10/mcmc-sampling/)\n", - "- [Nested Sampling](https://www.imperial.ac.uk/media/imperial-college/research-centres-and-groups/astrophysics/public/icic/data-analysis-workshop/2016/NestedSampling_JRP.pdf)\n", - "- [A Zero-Math Introduction to MCMC Methods](https://towardsdatascience.com/a-zero-math-introduction-to-markov-chain-monte-carlo-methods-dcba889e0c50)" + "A search tries many parameter combinations, evaluates their likelihoods and uses what it learns to explore\n", + "promising regions. This automates the repeated guesses you made in chapter 1. Relationships between parameters\n", + "make the task difficult: a larger, dimmer galaxy may resemble a smaller, brighter one. A search must explore\n", + "these possibilities, rather than adjust each parameter independently." ] }, { @@ -213,6 +86,8 @@ "from autogalaxy import setup_notebook; setup_notebook()\n", "\n", "from pathlib import Path\n", + "import numpy as np\n", + "import autofit as af\n", "import autogalaxy as ag\n", "import autogalaxy.plot as aplt" ], @@ -223,77 +98,24 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__PyAutoFit__\n", - "\n", - "Modeling uses the probabilistic programming language\n", - "[PyAutoFit](https://github.com/PyAutoLabs/PyAutoFit), an open-source project that allows complex model\n", - "fitting techniques to be straightforwardly integrated into scientific modeling software. \n", + "__Dataset and Mask__\n", "\n", - "**PyAutoFit** is actually a spin-off project of **PyAutoGalaxy**, whereby we found that the statistical techniques and\n", - "methods we applied to model galaxies could be used in a more general setting to many different scientific \n", - "problems. Check it out if you are interested in developing your own software to perform advanced model-fitting!\n", - "\n", - "We import this library separately from **PyAutoGalaxy**." + "Load the imaging data and retain the region inside the circular mask. The simulator creates the data if needed.\n", + "The image, noise map and PSF together describe the observation; none specifies which galaxy model we must fit." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "import autofit as af" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Initial Setup__\n", - "\n", - "Let's first load the `Imaging` dataset, which we will use to fit a model with a non-linear search.\n", - "\n", - "The galaxy in this image was generated using a `Sersic` light profile, which we'll also use in our model fitting \n", - "in this tutorial. This means the model we are going to fit is identical to the one used to simulate the data, \n", - "allowing us to assess the fitting process under controlled conditions.\n", "\n", - "The dataset, as well as all subsequent datasets used in future tutorials, is stored in \n", - "the `HowToGalaxy/dataset/imaging` folder. " - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ "dataset_name = \"simple__sersic\"\n", - "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Dataset Auto-Simulation__\n", - "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ + "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name\n", "if ag.util.dataset.should_simulate(str(dataset_path)):\n", " import subprocess\n", " import sys\n", "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulators/sersic.py\"],\n", - " check=True,\n", - " )\n", - "\n", + " subprocess.run([sys.executable, \"scripts/simulators/sersic.py\"], check=True)\n", "\n", "dataset = ag.Imaging.from_fits(\n", " data_path=dataset_path / \"data.fits\",\n", @@ -301,32 +123,10 @@ " psf_path=dataset_path / \"psf.fits\",\n", " pixel_scales=0.1,\n", ")\n", - "\n", - "aplt.subplot_imaging_dataset(dataset=dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Mask__\n", - "\n", - "The fit requires a mask, which we define as a 3.0\" circle." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ "mask = ag.Mask2D.circular(\n", " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=3.0\n", ")\n", - "\n", - "dataset = dataset.apply_mask(mask=mask)\n", - "\n", - "aplt.subplot_imaging_dataset(dataset=dataset)" + "dataset = dataset.apply_mask(mask=mask)" ], "outputs": [], "execution_count": null @@ -335,45 +135,25 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Model__\n", - "\n", - "To compose a model, we will set up a `Galaxy` using a `af.Model`. Instead of manually specifying every parameter \n", - "for the galaxy's light profiles (as we did before), we will now define the galaxy using only the class of each \n", - "profile. Using a `Model` object tells **PyAutoGalaxy** that the parameters of the profiles should be fitted for \n", - "during the non-linear search.\n", + "__Over Sampling__\n", "\n", - "In this case, we'll model the galaxy with an elliptical Sersic light profile, which is linear and represents \n", - "its bulge component (the same profile used to simulate the galaxy). " + "The bright centre changes rapidly across a pixel. Adaptive over sampling evaluates it on a finer grid so that\n", + "numerical inaccuracies do not masquerade as poor models. The outskirts need fewer evaluations." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "galaxy_model = af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp_linear.Sersic)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now input the model component into a `Collection` object, which groups all the model components used to fit the data.\n", - "\n", - "As with profiles, we give galaxies descriptive names like `bulge`, or `disk`. Since this model has only one \n", - "galaxy, we'll simply refer to it as `galaxy` throughout the tutorials.\n", "\n", - "It may seem odd that we define two `Collections`, with the `Collection` in the outer loop only having a `galaxies`\n", - "attribute. In future tutorials, we'll see that we can add additional model-components to a model other than just\n", - "galaxies, and the API below therefore makes it simple to extend the model to include these components." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "model = af.Collection(galaxies=af.Collection(galaxy=galaxy_model))" + "over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n", + " grid=dataset.grid,\n", + " sub_size_list=[8, 4, 2],\n", + " radial_list=[0.3, 0.6],\n", + " centre_list=[(0.0, 0.0)],\n", + ")\n", + "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n", + "aplt.subplot_imaging_dataset(dataset=dataset)" ], "outputs": [], "execution_count": null @@ -382,21 +162,23 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The `info` attribute shows the model in a readable format.\n", + "__Model__\n", "\n", - "[The `info` below may not display optimally on your computer screen, for example the whitespace between parameter\n", - "names on the left and parameter priors on the right may lead them to appear across multiple lines. This is a\n", - "common issue in Jupyter notebooks.\n", + "PyAutoFit supplies the model and search tools; PyAutoGalaxy supplies the galaxy physics and data analysis.\n", + "Passing a profile class to `af.Model` makes its parameters quantities to infer. This differs from the fixed\n", + "profile instances we created in chapter 1.\n", "\n", - "The`info_whitespace_length` parameter in the file `config/general.yaml` in the [output] section can be changed to \n", - "increase or decrease the amount of whitespace (The Jupyter notebook kernel will need to be reset for this change to \n", - "appear in a notebook).]" + "We use a linear Sersic profile. Its intensity is still fitted, but is calculated directly for each trial shape\n", + "instead of being another parameter for Nautilus to search. Tutorial 4 explains this in detail." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", + "galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp_linear.Sersic)\n", + "model = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n", "print(model.info)" ], "outputs": [], @@ -408,72 +190,21 @@ "source": [ "__Priors__\n", "\n", - "When we examine the `.info` of our model, we notice that each parameter (like `centre`, `effective_radius`, \n", - "and `sersic_index` in our `Sersic` model) is associated with priors, such as `UniformPrior`. Priors define the \n", - "range of permissible values that each parameter can assume during the model fitting process, for example a uniform\n", - "prior means that a parameter is equally likely to be any value within the given range, but cannot be outside of it.\n", - "\n", - "The priors displayed above use default values defined in the `config/priors` directory. These default values have\n", - "been chosen to be broad, and contain the breadth of plausible solutions one should expect when fitting light\n", - "profiles to a real galaxy.\n", - "\n", - "For instance, consider the `centre` parameter of our `Sersic` light profile. In theory, it could take on any value from \n", - "negative to positive infinity. However, imaging datasets are typically reduced such that the galaxy centre is close \n", - "to (0.0\", 0.0\"). Therefore, a `GaussianPrior` with `mean=0.0` and `sigma=0.1` is a good description of where the\n", - "galaxy `centre` is. \n", - "\n", - "If the galaxy had a different centre in the dataset, we would change the mean of the prior to reflect this.\n", - "However, in general, we advise all galaxy images are reduced such that the galaxy is at (0.0\", 0.0\").\n", - "\n", - "Priors serve two primary purposes:\n", + "The model summary lists a prior for every free parameter. A prior describes which values we allow and how much\n", + "weight we give them before the fit. A uniform prior assigns equal weight within its limits. A Gaussian prior\n", + "favours values near its mean, with its width set by `sigma`.\n", "\n", - "**Defining Valid Parameter Space:** Priors specify the range of parameter values that constitute valid solutions. \n", - "This ensures that our model explores only those solutions that are consistent with our observed data and physical \n", - "constraints.\n", - "\n", - "**Incorporating Prior Knowledge:** Priors also encapsulate our prior beliefs or expectations about the model \n", - "parameters. For instance, if we have previously fitted a similar model to another dataset and obtained certain \n", - "parameter values, we can incorporate this knowledge into our priors for a new dataset. This approach guides the \n", - "model fitting process towards parameter values that are more probable based on our prior understanding.\n", - "\n", - "Below, we manually specify the priors on all parameter in our `Sersic` model. The custom priors below are\n", - "close to the default priors drawn via configfiles, with the main purpose of the code below to show you how to\n", - "customize priors yourself." + "The defaults come from `config/priors`. They cover a broad range of galaxies. Our cutout places the bright centre\n", + "near (0.0, 0.0), so a prior concentrated around that position is sensible. We can customise it as follows:" ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "model.galaxies.galaxy.bulge.centre.centre_0 = af.GaussianPrior(mean=0.0, sigma=0.1)\n", "model.galaxies.galaxy.bulge.centre.centre_1 = af.GaussianPrior(mean=0.0, sigma=0.1)\n", - "model.galaxies.galaxy.bulge.ell_comps.ell_comps_0 = af.UniformPrior(\n", - " lower_limit=-1.0, upper_limit=1.0\n", - ")\n", - "model.galaxies.galaxy.bulge.ell_comps.ell_comps_1 = af.UniformPrior(\n", - " lower_limit=-1.0, upper_limit=1.0\n", - ")\n", - "model.galaxies.galaxy.bulge.effective_radius = af.UniformPrior(\n", - " lower_limit=0.0, upper_limit=10.0\n", - ")\n", - "model.galaxies.galaxy.bulge.sersic_index = af.UniformPrior(\n", - " lower_limit=0.8, upper_limit=8.0\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "By reprinting the `model.info`, we can see that the priors have been updated to the values we specified." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ "print(model.info)" ], "outputs": [], @@ -483,348 +214,27 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Analysis__\n", - "\n", - "The `AnalysisImaging` object defines how an instance of a model, consisting of a set of parameters values for the \n", - "light profiles, is fitted to the `Imaging` dataset.\n", - "\n", - "The fit is performed using the analysis class's `log_likelihood_function`, which in model-fitting is a commonly used \n", - "term to describe a function that given a model and data, fits the model to the data to return a value of log \n", - "likelihood. \n", - "\n", - "In the fitting tutorial in chapter 1 you essentially performed this likelihood function yourself by hand, when you \n", - "entered different models to a `FitImaging` object and used its `log_likelihood` property to quantify how well it \n", - "fitted the data.\n", - "\n", - "A detailed step-by-step visual guide of the likelihood function is provided \n", - "at `autogalaxy_workspace/*/imaging/likelihood_function.ipynb`." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Searches__\n", - "\n", - "To perform a non-linear search, we create an instance of a `NonLinearSearch` object. **PyAutoFit** offers many options \n", - "for this. A detailed description of each search method and guidance on when to use them can be found in \n", - "the [search cookbook](https://pyautofit.readthedocs.io/en/latest/cookbooks/search.html).\n", - "\n", - "In this tutorial, we\u2019ll focus on three searches that represent different approaches to model fitting:\n", - "\n", - "1. **Maximum Likelihood Estimation (MLE)** using the `LBFGS` non-linear search.\n", - "2. **Markov Chain Monte Carlo (MCMC)** using the `Emcee` non-linear search.\n", - "3. **Nested Sampling** using the `Nautilus` non-linear search.\n", - "\n", - "In this example, non-linear search results are stored in memory rather than written to hard disk because the fits\n", - "are fast and can therefore be easily regenerated. The next tutorial will perform fits which write results to the\n", - "hard-disk and discuss the outputs that are generated.\n", - "\n", - "__Maximum Likelihood Estimation (MLE)__\n", - "\n", - "Maximum likelihood estimation (MLE) is the most straightforward type of non-linear search. Here is a simplified \n", - "overview of how it works:\n", - "\n", - "1. Starts at a point in parameter space with a set of initial values for the model parameters.\n", - "2. Calculates the likelihood of the model at this starting point.\n", - "3. Evaluates the likelihood at nearby points to estimate the gradient, determining the direction in which to move \"up\" in parameter space.\n", - "4. Moves to a new point where, based on the gradient, the likelihood is higher.\n", - "\n", - "This process repeats until the search finds a point where the likelihood can no longer be improved, indicating that \n", - "the maximum likelihood has been reached.\n", - "\n", - "The `LBFGS` search is an example of an MLE algorithm that follows this iterative procedure. Let\u2019s see how it \n", - "performs on our Sersic model.\n", - "\n", - "In the example below, we do not specify a starting point for the MLE, so it begins at the center of the prior \n", - "range for each parameter." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search = af.LBFGS()" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To begin the model-fit via the non-linear search, we pass it our model and analysis and begin the fit.\n", - "\n", - "The fit will take a minute or so to run." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(\n", - " \"\"\"\n", - " The non-linear search has begun running.\n", - " This Jupyter notebook cell will progress once the search has completed - this could take a few minutes!\n", - " \"\"\"\n", - ")\n", - "\n", - "model = af.Collection(galaxies=af.Collection(galaxy=galaxy_model))\n", - "\n", - "result = search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"The search has finished run - you may now continue the notebook.\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Upon completion the non-linear search returns a `Result` object, which contains information about the model-fit.\n", - "\n", - "The `info` attribute shows the result in a readable format.\n", - "\n", - "[Above, we discussed that the `info_whitespace_length` parameter in the config files could be changed to make\n", - "the `model.info` attribute display optimally on your computer. This attribute also controls the whitespace of the\n", - "`result.info` attribute.]" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result.info)\n" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "One thing the result contains we'll use now is the `FitImaging` object that corresponds to the set of model\n", - "parameters that gave the maximum log likelihood solution. \n", + "A narrow prior can help a search, but can also exclude a good explanation of the data. Priors should reflect\n", + "reasonable knowledge and assumptions, not force the answer we hope to find. Tutorial 3 explores this balance.\n", "\n", - "We plot this object to inspect how good our fit was." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The fit quality is poor, with significant residuals, meaning that the MLE failed to identify the correct model.\n", - "\n", - "This happened because the starting point of the search was a poor match to the data, placing it far from the true \n", - "solution in parameter space. As a result, after moving \"up\" the likelihood gradient several times, the search \n", - "settled into a \"local maximum\", a local peak in the likelihood surface that was better than models that surrounded\n", - "it in parameter space, but far from the global maximum solution.\n", - "\n", - "To achieve a better fit with MLE, the search needs to begin in a region of parameter space where the log likelihood \n", - "is higher. This process is known as \"initialization\" and it involves providing the search with an \n", - "appropriate \"starting point\" in parameter space.\n", - "\n", - "The code below shows how we can customize the starting point of the search to provide a better initialization,\n", - "with the values input below close to the true values used to simulate the dataset." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "initializer = af.InitializerParamStartPoints(\n", - " {\n", - " model.galaxies.galaxy.bulge.centre.centre_0: 0.0,\n", - " model.galaxies.galaxy.bulge.centre.centre_1: 0.0,\n", - " model.galaxies.galaxy.bulge.ell_comps.ell_comps_0: 0.1,\n", - " model.galaxies.galaxy.bulge.ell_comps.ell_comps_1: 0.05,\n", - " model.galaxies.galaxy.bulge.effective_radius: 1.0,\n", - " model.galaxies.galaxy.bulge.sersic_index: 3.7,\n", - " }\n", - ")\n", - "\n", - "search = af.LBFGS(initializer=initializer)\n", - "\n", - "print(\n", - " \"\"\"\n", - " The non-linear search has begun running.\n", - " This Jupyter notebook cell will progress once the search has completed - this could take a few minutes!\n", - " \"\"\"\n", - ")\n", - "\n", - "model = af.Collection(galaxies=af.Collection(galaxy=galaxy_model))\n", - "\n", - "result = search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"The search has finished run - you may now continue the notebook.\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "By printing `result.info` and looking at the maximum log likelihood model, we can confirm the search provided a\n", - "good model fit with a much higher likelihood than the incorrect model above." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result.info)\n", - "\n", - "aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The MLE is a great starting point for model-fitting because it\u2019s fast, conceptually simple, and often yields \n", - "accurate results. It is especially effective if you can provide a good initialization, allowing it to find the \n", - "best-fit solution quickly.\n", - "\n", - "However, MLE has its limitations. As seen above, it can get \"stuck\" in a local maximum, particularly if the \n", - "starting point is poorly chosen. In complex model-fitting problems, providing a suitable starting point can be \n", - "challenging. While MLE performed well in the example with just six parameters, it struggles with models that have\n", - "many parameters, as the complexity of the likelihood surface makes simply moving \"up\" the gradient less effective.\n", - "\n", - "The MLE also does not provide any information on the errors on the parameters, which is a significant limitation.\n", - "The next two types of searches \"map out\" the likelihood surface, such that they not only infer the maximum likelihood\n", - "solution but also quantify the errors on the parameters.\n", - "\n", - "__Markov Chain Monte Carlo (MCMC)__\n", - "\n", - "Markov Chain Monte Carlo (MCMC) is a more powerful method for model-fitting, though it is also more computationally \n", - "intensive and conceptually complex. Here\u2019s a simplified overview:\n", - "\n", - "1. Place a set of \"walkers\" in parameter space, each with random parameter values.\n", - "2. Calculate the likelihood of each walker's position.\n", - "3. Move the walkers to new positions, guided by the likelihood of their current positions. Walkers in high-likelihood \n", - "regions encourage those in lower regions to move closer to them.\n", - "\n", - "This process repeats, with the walkers converging on the highest-likelihood regions of parameter space.\n", - "\n", - "Unlike MLE, MCMC thoroughly explores parameter space. While MLE moves a single point up the likelihood gradient, \n", - "MCMC uses many walkers to explore high-likelihood regions, making it more effective at finding the global maximum, \n", - "though slower. \n", - "\n", - "There is a reduced risk of getting stuck in local maxima, because whilst some walkers may temporarily get stuck in \n", - "one, other walkers will explore other regions of parameter space and encourage the walker in local maxima to move \n", - "away from it and head towards higher likelihood regions.\n", - "\n", - "In the example below, we use the `Emcee` MCMC search to fit the galaxy. The search starts with walkers \n", - "initialized in a \"ball\" around the center of the model\u2019s priors, similar to the MLE search that failed earlier." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search = af.Emcee(\n", - " nwalkers=20, # The number of walkers we'll use to sample parameter space.\n", - " nsteps=300, # The number of steps each walker takes, after which 20 * 300 = 6000 steps the non-linear search ends.\n", - ")\n", - "\n", - "print(\n", - " \"\"\"\n", - " The non-linear search has begun running.\n", - " This Jupyter notebook cell will progress once the search has completed - this could take a few minutes!\n", - " \"\"\"\n", - ")\n", - "\n", - "model = af.Collection(galaxies=af.Collection(galaxy=galaxy_model))\n", - "\n", - "result = search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"The search has finished run - you may now continue the notebook.\")\n", - "\n", - "print(result.info)\n", - "\n", - "aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The MCMC search succeeded, finding the same high-likelihood model that the MLE search with a good starting point \n", - "identified, even without a good initialization. Its use of multiple walkers exploring parameter space allowed it to \n", - "avoid the local maxima that had trapped the MLE search.\n", - "\n", - "A major advantage of MCMC is that it provides estimates of parameter uncertainties by \"mapping out\" the likelihood \n", - "surface, unlike MLE, which only finds the maximum likelihood solution. These error estimates are accessible in \n", - "the `result.info` string and through the `result.samples` object, which is explained fully in tutorial 7.\n", - "\n", - "While a good starting point wasn't necessary for this simple model, it becomes essential for efficiently mapping the \n", - "likelihood surface in more complex models with many parameters. The code below shows an MCMC fit using a good starting \n", - "point, with two key differences from the MLE initialization:\n", + "__Analysis__\n", "\n", - "1. Instead of single starting values, we provide bounds for each parameter. MCMC initializes each walker in a \n", - "small \"ball\" in parameter space, requiring a defined range for each parameter from which values are randomly drawn.\n", + "The data and model have separate jobs. The data describe what we measured and its uncertainty; the model describes\n", + "possible galaxies. An `Analysis` object connects them. It takes a trial model instance, predicts its image,\n", + "convolves it with the PSF and compares it with the measured image using the noise map. Its\n", + "`log_likelihood_function` returns the score that guides the search.\n", "\n", - "2. We do not specify a starting point for the `ell_comps` parameters, allowing its initial values to be drawn from its \n", - "priors. This illustrates that with MCMC, it\u2019s not necessary to know a good starting point for every parameter." + "This is the same comparison you performed using `FitImaging` in chapter 1, now repeated automatically.\n", + "`use_jax=True` enables the numerical engine that accelerates these repeated calculations on a CPU or a compatible\n", + "GPU. You do not need to know how JAX works to use it." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "initializer = af.InitializerParamBounds(\n", - " {\n", - " model.galaxies.galaxy.bulge.centre.centre_0: (-0.01, 0.01),\n", - " model.galaxies.galaxy.bulge.centre.centre_1: (-0.01, 0.01),\n", - " model.galaxies.galaxy.bulge.effective_radius: (0.0, 2.0),\n", - " model.galaxies.galaxy.bulge.sersic_index: (3.0, 5.0),\n", - " }\n", - ")\n", - "\n", - "search = af.Emcee(\n", - " nwalkers=20, # The number of walkers we'll use to sample parameter space.\n", - " nsteps=300, # The number of steps each walker takes, after which 20 * 300 = 6000 steps the non-linear search ends.\n", - " initializer=initializer,\n", - ")\n", - "\n", - "print(\n", - " \"\"\"\n", - " The non-linear search has begun running.\n", - " This Jupyter notebook cell will progress once the search has completed - this could take a few minutes!\n", - " \"\"\"\n", - ")\n", - "\n", - "model = af.Collection(galaxies=af.Collection(galaxy=galaxy_model))\n", - "\n", - "result = search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"The search has finished run - you may now continue the notebook.\")\n", "\n", - "print(result.info)" + "analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)" ], "outputs": [], "execution_count": null @@ -833,47 +243,24 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "MCMC is a powerful tool for model-fitting, providing accurate parameter estimates and uncertainties. For simple models\n", - "without a starting point, MCMC can still find the correct solution, and if a good starting point is provided, it can\n", - "efficiently scale to more complex models with more parameters.\n", - "\n", - "The main limitation of MCMC is that one has to supply the number of steps the walkers take (`nsteps`). If this value \n", - "is too low, the walkers may not explore the likelihood surface sufficiently. It can be challenging to know the right \n", - "number of steps, especially if models of different complexity are being fitted or if datasets of varying quality are \n", - "used. One often ends up having to perform \"trial and error\" to verify a sufficient number of steps are used.\n", - "\n", - "MCMC can perform badly in parameter spaces with certain types of complexity, for example when there are\n", - "are many local maxima \"peaks\" that many of the walkers can become stuck walking around them, so many walkers that\n", - "when they communicate with one another they cannot gain enough information to move away from the local peak.\n", - "\n", "__Nested Sampling__\n", "\n", - "**Nested Sampling** is an advanced method for model-fitting that excels in handling complex models with intricate \n", - "parameter spaces. Here\u2019s a simplified overview of its process:\n", - "\n", - "1. Start with a set of \"live points\" in parameter space, each initialized with random parameter values drawn from their respective priors.\n", - "\n", - "2. Compute the log likelihood for each live point.\n", + "Nautilus starts by drawing trial models from the priors. These are called live points. As it explores, it focuses\n", + "on regions containing higher-likelihood models. The samples describe both good-fitting parameter values and the\n", + "range of values consistent with the data under our model assumptions.\n", "\n", - "3. Draw a new point based on the likelihood of the current live points, favoring regions of higher likelihood.\n", - "\n", - "4. If the new point has a higher likelihood than any existing live point, it becomes a live point, and the lowest likelihood live point is discarded.\n", - "\n", - "This iterative process continues, gradually focusing the live points around higher likelihood regions of parameter \n", - "space until they converge on the highest likelihood solution.\n", - "\n", - "Like MCMC, Nested Sampling effectively maps out parameter space, providing accurate estimates of parameters and \n", - "their uncertainties." + "The `n_live` setting controls how thoroughly the search explores. We use 100 for this introductory example;\n", + "it is not a guarantee of a correct fit. Tutorial 2 explains practical search settings, including `n_batch`.\n", + "Nautilus has stopping criteria, so we do not have to prescribe a fixed number of trial models." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "search = af.Nautilus(\n", - " n_live=100,\n", - " n_batch=50, # Explained in next tutorial\n", - ")" + "\n", + "search = af.Nautilus(n_live=100, n_batch=50)\n", + "result = search.fit(model=model, analysis=analysis)" ], "outputs": [], "execution_count": null @@ -882,30 +269,19 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "To begin the model-fit via the non-linear search, we pass it our model and analysis and begin the fit.\n", + "__Result__\n", "\n", - "The fit will take a minute or so to run." + "The result summary reports inferred parameter values and uncertainties. For example, a range of plausible\n", + "half-light radii tells us how precisely the data constrain the galaxy's size, given this model and its priors.\n", + "A best-fitting value alone does not tell us this." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(\n", - " \"\"\"\n", - " The non-linear search has begun running.\n", - " This Jupyter notebook cell will progress once the search has completed - this could take a few minutes!\n", - " \"\"\"\n", - ")\n", - "\n", - "model = af.Collection(galaxies=af.Collection(galaxy=galaxy_model))\n", - "\n", - "result = search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"The search has finished run - you may now continue the notebook.\")\n", "\n", "print(result.info)\n", - "\n", "aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit)" ], "outputs": [], @@ -915,85 +291,18 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The **Nested Sampling** search was successful, identifying the same high-likelihood model as the MLE and MCMC searches. \n", - "One of the main benefits of Nested Sampling is its ability to provide accurate parameter estimates and uncertainties, \n", - "similar to MCMC. Additionally, it features a built-in stopping criterion, which eliminates the need for users to \n", - "specify the number of steps the search should take. \n", - "\n", - "This method also excels in handling complex parameter spaces, particularly those with multiple local peaks. This is because\n", - "the live points will identify each peak and converge around them, but then begin to be discarded from a peak if higher\n", - "likelihood points are found elsewhere in parameter space. In MCMC, the walkers can get stuck indefinitely in\n", - "peaks, causing the method to stall.\n", - "\n", - "Another significant advantage is that Nested Sampling estimates an important statistical quantity \n", - "known as \"evidence.\" This value quantifies how well the model fits the data while considering the model's complexity,\n", - "making it essential for Bayesian model comparison, which will be covered in later tutorials. \n", - "\n", - "Nested sampling cannot use a starting point, as it always samples parameter space from scratch by drawing live points\n", - "from the priors. This is both good and bad, depending on if you have access to a good starting point or not. If you do\n", - "not, your MCMC / MLE fit will likely struggle with initialization compared to Nested Sampling. Conversely, if you do \n", - "possess a robust starting point, it can significantly enhance the performance of MCMC, allowing it to begin closer to \n", - "the highest likelihood regions of parameter space. This proximity can lead to faster convergence and more reliable results.\n", - "\n", - "However, Nested Sampling does have limitations; it often scales poorly with increased model complexity. For example, \n", - "once a model has around 50 or more parameters, Nested Sampling can become very slow, whereas MCMC remains efficient \n", - "even in such complex parameter spaces.\n", - "\n", - "__What is The Best Search To Use?__\n", - "\n", - "In statistical inference, the choice of the best search method depends on several factors specific to the problem, \n", - "such as model complexity, availability of a starting point, and whether error estimates are required. More subtle \n", - "aspects, like the shape of the likelihood surface and the presence of multiple peaks, also play a role, as you'll \n", - "explore in later tutorials.\n", - "\n", - "When approaching a model-fitting problem, it's usually advisable to try various search methods to find the most \n", - "effective one. \n", + "Look at the data, model image and residuals together. Does the model reproduce the central brightness and faint\n", + "outskirts? Residuals consistent with noise are encouraging; coherent bright or dark structures need investigation.\n", + "A search finishing is not evidence by itself that it found an adequate model or explored all good solutions.\n", "\n", - "However, after extensive testing within **PyAutoGalaxy**, a clear recommendation has emerged for fitting galaxy light \n", - "profiles and studying galaxy structure. The nested sampling method `Nautilus` consistently proves to be the most \n", - "effective. It requires fewer iterations than MCMC or MLE methods (when no starting point is used), provides robust \n", - "sampling even for complex models, includes a built-in stopping criterion, and delivers reliable error estimates.\n", - "\n", - "All examples in the `autogalaxy_workspace` use the `Nautilus` search, and future tutorials in the **HowToGalaxy** \n", - "series will also use it. We strongly recommend using `Nautilus` from now on.\n", - "\n", - "That said, MLE and MCMC searches can still be effective, and you're encouraged to experiment with them. If you have \n", - "a reliable starting point, MLE and MCMC can outperform `Nautilus` in terms of speed and efficiency. Additionally, \n", - "for very complex models (e.g., with 30+ parameters), `Nautilus` may struggle, while MCMC might handle the complexity \n", - "better\u2014though you're unlikely to encounter that level of complexity soon.\n", - "\n", - "Lastly, MLE, MCMC, and nested sampling are just three categories of non-linear searches, each containing different \n", - "algorithms with their own strengths and weaknesses. Exploring these options could help you find the best approach \n", - "for your model-fitting needs. For more details on each method, see the [search cookbook](https://pyautofit.readthedocs.io/en/latest/cookbooks/search.html).\n", + "The samples are available through `result.samples`. For now, inspecting the fit and summary is enough. Tutorial 2\n", + "introduces saved output and points to the workspace for detailed results analysis.\n", "\n", "__Wrap Up__\n", "\n", - "This tutorial has laid the foundation with several fundamental concepts in model fitting and statistical inference:\n", - "\n", - "1. **Parameter Space**: This refers to the range of possible values that each parameter in a model can take. It \n", - "defines the dimensions over which the likelihood of different parameter values is evaluated.\n", - "\n", - "2. **Likelihood Function**: This function receives as input a model with specific parameter values and returns a\n", - "log likelihood value that quantifies how well the model describes the data.\n", - "\n", - "3. **Likelihood Surface**: This surface represents how the likelihood of the model varies across the parameter space. \n", - "It helps in identifying the best-fit parameters that maximize the likelihood of the model given the data.\n", - "\n", - "4. **Non-linear Search**: This is an optimization technique used to explore the parameter space and find the \n", - "combination of parameter values that best describe the data. It iteratively adjusts the parameters to maximize the \n", - "likelihood. Many different search algorithms exist, each with their own strengths and weaknesses, and this tutorial\n", - "used the MLE, MCMC, and nested sampling searches.\n", - "\n", - "5. **Priors**: Priors are probabilities assigned to different values of parameters before considering the data. \n", - "They encapsulate our prior knowledge or assumptions about the parameter values. Priors can constrain the parameter \n", - "space, making the search more efficient and realistic.\n", - "\n", - "6. **Model Fitting**: The process of adjusting model parameters to minimize the difference between model predictions \n", - "and observed data, quantified by the likelihood function.\n", - "\n", - "Understanding these concepts is crucial as they form the backbone of model fitting and parameter estimation in \n", - "scientific research and data analysis. In the next tutorials, these concepts will be further expanded upon to \n", - "deepen your understanding and provide more advanced techniques for model fitting and analysis." + "We supplied data, a model and an Analysis object, then asked Nautilus to explore the model's parameter space.\n", + "The next tutorial uses these same ingredients for a more realistic galaxy and explains the practicalities of\n", + "running and inspecting a fit." ] } ], @@ -1021,7 +330,7 @@ "24c2f562-da24-50bb-8eb9-5a887505fe54": { "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", "name": "PyAutoGalaxy assistant", - "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_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\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb in HowToGalaxy).\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 PyAutoGalaxy 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 PyAutoGalaxy docs (https://pyautogalaxy.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) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. 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 galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_run_search\n\n---\nname: ag_run_search\ndescription: Run the fit \u2014 take a composed model, an analysis and a configured search and drive `search.fit(model=model, analysis=analysis)` to completion, then read what it wrote. Covers the output-folder anatomy and the on-the-fly announcement, the unique-identifier resume behaviour and when it silently reuses a stale fit, `iterations_per_quick_update` and `live_visual_update`, JAX/GPU acceleration and when it actually pays, VRAM checks before a long GPU run, the `PYAUTO_TEST_MODE` smoke levels, and the `if __name__ == \"__main__\"` parallelisation fix. Use once `ag_build_imaging_model` and `ag_configure_search` have produced `model`, `analysis` and `search` objects, or when a fit is running and the user wants to know what to watch. Not for composing the model or choosing the search (those two skills), not for interpreting the finished posterior (`ag_load_results`), and not for diagnosing a fit that ran but converged somewhere unphysical (`ag_debug_fit_failure`).\n---\n\n# Running the fit\n\nThis is the moment the inference actually happens. Everything before it was preparation:\na `model` says which morphological parameters are free and what priors they carry, an\n`analysis` binds that model to one dataset and knows how to turn a parameter vector into a\nlog likelihood, and a `search` knows how to explore the parameter space. One call joins\nthem:\n\n```python\nresult = search.fit(model=model, analysis=analysis)\n```\n\nStatistically, that call is sampling (or optimising) the posterior\n$P(\\theta | d) \\propto \\mathcal{L}(d | \\theta) P(\\theta)$, where the likelihood is the\nGaussian-noise chi-squared of the PSF-convolved model image against the data \u2014 walked\nline by line in `autogalaxy_workspace:scripts/imaging/likelihood_function.py`. Scientifically,\nit is where a Sersic index, an effective radius or a bulge-to-total ratio stops being a guess\nand becomes a measurement with errors. What this skill adds is everything *around* the call:\nhow to watch it, how long to expect, how to make it fast, and how to prove the script works\nbefore committing hours to it.\n\nTwo wiki pages carry the background this skill assumes. Read\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md) for\nwhat each sampler does and how run time scales with the model, and\n[`wiki/core/api/analysis_objects.md`](../wiki/core/api/analysis_objects.md) for what the\nreturned `Result` contains.\n\n## Ask\n\nThree questions, and the answers change the branch:\n\n- *\"Do you already have `model`, `analysis` and `search`?\"* If not, route to\n [`ag_build_imaging_model`](./ag_build_imaging_model.md) and\n [`ag_configure_search`](./ag_configure_search.md) first. A fit assembled from a\n half-remembered model is the most expensive mistake available here.\n- *\"Smoke test first, or straight to the production run?\"* Almost always smoke test first \u2014\n it takes seconds and answers \"does this script execute end to end?\", which is a different\n question from \"is this galaxy's Sersic index 3.2?\". The smoke branch is below.\n- *\"How long can this run, and on what?\"* A `MultiStartProdigy` fit is minutes; a `Nautilus`\n fit of a smooth model is tens of minutes on a GPU and can be hours on a CPU; a pixelised\n fit can be far longer. That answer decides foreground vs background, laptop vs cluster,\n and whether `live_visual_update` is worth switching on.\n\nIf the data is real observational imaging, the inspection gate in\n[`../AGENTS.md`](../AGENTS.md) applies before you get here at all \u2014 contaminants and mask\nextent are settled in [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md), not\nretrospectively.\n\n## Branch \u2014 the production run\n\nThe deliverable is one script in `scripts/` the user can re-run and edit. Adapted from\n`autogalaxy_workspace:scripts/imaging/start_here.py` (the fit and result sections) and\n`autogalaxy_workspace:scripts/imaging/modeling.py` (the Nautilus configuration and the VRAM\ncheck):\n\n```python\n\"\"\"\nGalaxy Structure: Run the Fit\n=============================\n\nFit a galaxy's surface-brightness profile to CCD imaging: load and mask the data, compose a\nlinear Sersic bulge, and sample the posterior with Nautilus so the inferred effective radius\nand Sersic index come with errors.\n\n__Contents__\n\n- **Imports:** JAX environment first, then the standard trio.\n- **Dataset:** Load imaging, mask it, and apply adaptive over-sampling.\n- **Model:** Compose the galaxy's light profile.\n- **Search:** Configure Nautilus and its update cadence.\n- **Analysis:** Bind the model to the data and choose the JAX backend.\n- **Model-Fit:** Run the search and announce the output folder.\n- **Result:** Read the best-fit model back.\n\"\"\"\nfrom autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\n\"\"\"\n__Dataset__\n\nGalaxy modeling needs three ingredients: the image in CCD counts, a per-pixel RMS noise-map,\nand the PSF. The PSF is forward-modelled rather than divided out, which is what separates a\ngenuinely compact bulge from a seeing-broadened one. `pixel_scales` converts pixels to\narcseconds and must match the instrument (`ag.Imaging.from_fits`,\n`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe mask sets which pixels enter the likelihood, and its radius is a science choice, not a\ndefault: truncate the outer isophotes and the effective radius and Sersic index are biased\ndirectly. Over-sampling evaluates the light profile several times per pixel where the\ngradient is steep, which matters most in the central few tenths of an arcsecond\n(`ag.util.over_sample.over_sample_size_via_radial_bins_from`).\n\"\"\"\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"\"\nMASK_RADIUS = 2.5\n\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n pixel_scales=0.1,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\n\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n\n\"\"\"\n__Model__\n\nA linear `Sersic` bulge: the `intensity` is solved by linear inversion each iteration rather\nthan sampled, so the search explores one fewer dimension per component for free\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Linear Light Profiles__`).\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\n\n\"\"\"\n__Search__\n\n`Nautilus` is nested sampling: it returns the full posterior \u2014 every parameter's density,\nits errors, and the correlations between them. `n_live` trades accuracy against run time and\n200 covers the vast majority of galaxy models. `unique_tag` is conventionally the dataset\nname, which is what keeps the same model fitted to different data in different folders\n(`PyAutoFit:autofit/non_linear/search/nest/nautilus/search.py`).\n\"\"\"\nsearch = af.Nautilus(\n path_prefix=Path(\"imaging\"),\n name=\"sersic\",\n unique_tag=\"\",\n n_live=200,\n iterations_per_quick_update=10000,\n live_visual_update=False,\n)\n\n\"\"\"\n__Analysis__\n\n`ag.AnalysisImaging` defines the `log_likelihood_function` the search calls, and defaults to\n`use_jax=True` when JAX is installed (`PyAutoGalaxy:autogalaxy/imaging/model/analysis.py`).\n\"\"\"\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\n\"\"\"\n__Model-Fit__\n\nResults are written to the output folder on the fly, from the best model found so far, so the\nfolder is worth opening the moment the search starts.\n\"\"\"\nprint(f\"Output folder: {search.paths.output_path.resolve()}\")\n\nresult = search.fit(model=model, analysis=analysis)\n\n\"\"\"\n__Result__\n\"\"\"\nprint(result.info)\nprint(result.max_log_likelihood_instance)\n```\n\nRun it with writable caches if the default locations are not writable \u2014 a sandbox, CI, or an\ninstall imported from a Windows mount under WSL\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)):\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\n`search.fit` itself is `PyAutoFit:autofit/non_linear/search/abstract_search.py`.\n\n## Branch \u2014 what the output folder contains, and when to look\n\n**Announce the folder at launch, not at the end.** Quote\n`search.paths.output_path.resolve()` once the fit is running and say plainly that\n`model.results` and `image/fit.png` refresh as the search goes \u2014 there is nothing to wait\nfor. Users new to the stack sit watching a silent terminal because nobody told them.\n\nThe annotated tree of `files/`, `image/`, `model.info`, `model.results`, `search.summary`\nand the `` folder is `__Output Folder Layout__` in\n[`autogalaxy_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/modeling.py);\nthe same section appears in the `interferometer`, `multi_dataset`, `multi_galaxy` and\n`cluster` `modeling.py` scripts. Link it rather than copying the tree into the conversation,\nwhere it would rot. The condensed version is also in\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n\"The output folder\".\n\nName what to open first, in this order:\n\n1. `model.results` \u2014 the human-readable fit summary, parameters with errors.\n2. `image/fit.png` \u2014 data, model image, residuals and chi-squared map in one figure.\n3. `search.log` \u2014 tail it if you want to watch progress from a terminal.\n\nDepth follows [`_style.md`](./_style.md) \"Adaptive depth\": for a newcomer, or in teacher\nmode, walk all three. For a returning user, quoting the path is enough.\n\n## Branch \u2014 resuming, and the trap inside it\n\n`` is derived from the model, the search settings and the dataset identifier, so\nre-running an identical configuration **resumes** the existing fit rather than restarting it\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Unique Identifier__`). That is a\nfeature \u2014 an interrupted overnight run picks up where it stopped.\n\nIt is also the sharpest edge in the workflow. **The identifier does not hash the pixel\nvalues of your data.** Swap `data.fits` for a different galaxy, keep the model, the search\nand the `unique_tag` identical, and the next run finds a completed fit at the same path and\nreturns it \u2014 silently, in seconds, with the previous galaxy's parameters. If the data\nchanges, change the `unique_tag`. If you are unsure whether a result is stale, delete the\n`` folder and re-run rather than reasoning about it.\n\nTest mode namespaces its output separately: any active `PYAUTO_TEST_MODE` level inserts a\n`test_mode` segment straight after the output root, so a smoke run lands in\n`output/test_mode//...` and cannot short-circuit a later real fit\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## Branch \u2014 the update cadence and the live view\n\nTwo settings control what you see while the fit runs, both on the search\n(`PyAutoFit:autofit/non_linear/search/abstract_search.py`):\n\n- **`iterations_per_quick_update`** \u2014 how often the current best model is visualised and\n written to disk. The unit depends on the search: likelihood evaluations for `Nautilus`\n (hence the large `10000` in `modeling.py`), gradient steps for `MultiStartProdigy` (hence\n the much smaller `50` in `start_here.py`). Each update costs roughly ten seconds, so too\n low a value and output dominates the run time; too high and you cannot see progress. If\n the log is constantly reporting that it is outputting results, raise it.\n- **`live_visual_update`** \u2014 additionally push the quick-update image to a live surface: a\n matplotlib window that refreshes in a plain script, or a self-updating cell in Jupyter and\n Colab. The `fit.png` disk write happens either way. Leave it `False` on anything headless\n \u2014 an HPC node, a background process, CI.\n\nIf the search configuration already records the choice, don't re-ask; that decision belongs\nto [`ag_configure_search`](./ag_configure_search.md).\n\n## Branch \u2014 JAX, GPUs, and when the acceleration pays\n\nImaging fits run through JAX by default. Installing the extra (`pip install autogalaxy[jax]`)\nis all that is required: `ag.AnalysisImaging` then defaults to `use_jax=True`, and the search\ndriver wraps the likelihood in `jax.vmap(jax.jit(...))` so a whole batch of parameter vectors\nevaluates in one call. You will see a one-time log line as the JIT compile starts; every\nevaluation after that re-uses the compiled trace. This is described in\n`autogalaxy_workspace:scripts/guides/using_jax.py` `__Auto-Enabled Modeling__`, and if JAX is\nabsent the analysis warns once and falls back to NumPy.\n\n**When it pays.** The gain scales with how much array work each likelihood evaluation does,\nso it is largest for big masks, fine over-sampling, many-component bases and pixelised\nreconstructions, and smallest for a tiny mask with one smooth profile. GPU gains dwarf CPU\ngains: `autogalaxy_workspace:scripts/imaging/modeling.py` `__JAX__` quotes roughly ten\nminutes on a GPU against an hour on a CPU for its example, with a CPU still gaining from\nmultithreading. Gradient-based searches like `MultiStartProdigy` are not merely faster under\nJAX \u2014 they are only possible with it, because JAX is what supplies the likelihood's\nderivatives and evaluates all the parallel starts in one batched call\n(`autogalaxy_workspace:scripts/imaging/start_here.py` `__Multi Start Gradient Optimization__`).\n\n**Check VRAM before a long GPU run.** A JAX fit must fit inside the GPU's memory, and it\nfails at JIT-compile time or on the first likelihood call if it does not:\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py` `__VRAM Use__`. It takes\ntwenty or thirty seconds, so comment it out once you know your model's footprint. Batch size\nis the lever: larger batches cut wall-clock time and raise VRAM, smaller batches the reverse.\nA smooth-profile fit on a modest dataset is tens of megabytes; a pixelised reconstruction on\nhigh-resolution data can exceed ten gigabytes.\n\n**Turn JAX off to debug.** `ag.AnalysisImaging(dataset=dataset, use_jax=False)`, or\n`PYAUTO_DISABLE_JAX=1` to force it globally without editing code. NumPy stack traces are far\neasier to read, and you can drop a debugger or a `print` into code JAX would otherwise\ncompile. That is the first lever to pull when deciding whether a failure is a JAX problem at\nall \u2014 see [`ag_debug_fit_failure`](./ag_debug_fit_failure.md).\n\nFor running on a cluster \u2014 SLURM array jobs, one galaxy per task, the CPU and GPU batch\nscripts, and `number_of_cores` read from `SLURM_CPUS_PER_TASK` \u2014 read\n[`../wiki/core/operations/hpc.md`](../wiki/core/operations/hpc.md) for the concepts and\n[`../wiki/core/operations/hpc_infrastructure.md`](../wiki/core/operations/hpc_infrastructure.md)\nfor the `hpc/` templates and `sync` CLI this repo ships; the upstream ground truth behind both\nis `autogalaxy_workspace:scripts/guides/hpc/example_cpu_and_gpu.py`. The Python modeling code\nis identical for a GPU run; only the batch script changes.\n\n## Branch \u2014 the smoke test, before you spend hours\n\nEvery script gets one fast structural run before a real one. `PYAUTO_TEST_MODE` has four\nlevels ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)), and the\nchoice between them matters more than it looks:\n\n```bash\n# Level 1 \u2014 sampler runs with minimal iterations. A real (tiny) search: writes\n# model.results, image/fit.png and a samples.csv you can load back.\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n\n# Level 2 \u2014 sampler bypassed, likelihood called exactly once. The fastest proof that\n# the model composes and the likelihood evaluates.\nPYAUTO_TEST_MODE=2 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\n**Level 2 does not write the fit products.** A level-2 run returns a `Result`, proving the\nwiring, but leaves no `model.results` and no `image/fit.png` behind \u2014 so if the next thing\nyou want to do is plot or load the fit, use level 1. Level 3 skips the likelihood call as\nwell, which is only useful for checking that a script's non-fitting scaffolding runs.\n\n**The parameter values from any test-mode run are meaningless.** The sampler was truncated or\nmocked. Never quote a structural parameter measured in test mode; say explicitly that the\nnumber is a wiring check.\n\nFor the fastest possible loop, combine test mode with the dataset and output short-circuits:\n\n```bash\nPYAUTO_TEST_MODE=2 PYAUTO_SKIP_FIT_OUTPUT=1 PYAUTO_SKIP_VISUALIZATION=1 \\\n PYAUTO_SMALL_DATASETS=1 PYAUTO_FAST_PLOTS=1 python scripts/run_fit.py\n```\n\n`PYAUTO_SMALL_DATASETS=1` caps every array, mask and grid to 16 \u00d7 16 pixels \u2014 so delete any\npreviously simulated `dataset/` when you toggle it, or a full-resolution dataset on disk will\nbe reused and mismatch the capped grids.\n\n## Branch \u2014 the error that appears the moment the search starts\n\nOn some combinations of operating system and Python version, a script raises as soon as the\nsearch begins, from Python's process spawning rather than from anything about your model. The\nfix is to wrap the whole fit in a function and call it under a main guard:\n\n```python\ndef fit():\n from autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\n import autofit as af\n import autogalaxy as ag\n\n # ... dataset, model, search, analysis as above ...\n result = search.fit(model=model, analysis=analysis)\n\n\nif __name__ == \"__main__\":\n fit()\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/modeling/bug_fix.py`, which is the same\n`modeling.py` fit with this one structural change. It works for every dataset type, so adopt\nit for any modeling script that hits the error. If parallelisation still will not work after\nthe fix, that script points at the project's support channel.\n\n## Combine\n\n- [`ag_plot_fit`](./ag_plot_fit.md) \u2014 render the fit yourself, at whatever scaling and\n cropping the science needs, rather than reading the auto-generated `image/fit.png`.\n- [`ag_load_results`](./ag_load_results.md) \u2014 pull the posterior, the best-fit galaxies and\n the derived quantities back into Python, in-session or from disk later.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) \u2014 the fit finished but the residuals or\n the parameters are wrong.\n- [`ag_configure_search`](./ag_configure_search.md) \u2014 the fit is too slow, or the sampler is\n the wrong one for the model.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) \u2014 build a controlled dataset with known\n truth and fit that first, which is the cleanest way to separate a model problem from a\n data problem.\n\nWhen the script and its fit are worth keeping, offer (default-yes) to record the run in a\ndated `wiki/project/YYYY-MM-DD-.md` entry: the science question, what was inferred and\nwith what search, and the output path \u2014 per [`_style.md`](./_style.md) property #5.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [HowToGalaxy: Practicalities](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running a fit \u2014 output structure, reviewing results as they appear,\n and managing run times.\n- **General reference** \u2014 [RTD: New user guide](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n the decision tree for which fit to run first, by system scale and dataset type.\n- **Experienced PyAutoGalaxy user** \u2014 [workspace: imaging/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit, with the JAX and quick-update sections this skill\n mirrors.\n\n## Agent procedural checklist\n\n1. Confirm `model`, `analysis` and `search` exist; if not, route to the model-building and\n search-configuration skills.\n2. On real observational data, confirm the inspection gate has been satisfied.\n3. Write the script to `scripts/` in the generated-script style; never leave it inline only.\n4. Validate it with `PYAUTO_TEST_MODE=1` (level 2 if you only need the likelihood proved),\n with the cache variables set if the environment needs them.\n5. Launch the production run; **quote the absolute output path immediately** and say results\n refresh on the fly.\n6. Name `model.results` and `image/fit.png` as the first two things to open.\n7. If the data changed but the model did not, confirm the `unique_tag` changed too.\n8. On a GPU, run the VRAM check before a long fit.\n9. On completion, hand off to the results-loading or fit-plotting skill rather than\n interpreting the numbers inline.\n10. Offer the `wiki/project/` entry.\n" + "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_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\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb in HowToGalaxy).\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 PyAutoGalaxy 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 PyAutoGalaxy docs (https://pyautogalaxy.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) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. 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 galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_run_search\n\n---\nname: ag_run_search\ndescription: Run the fit — take a composed model, an analysis and a configured search and drive `search.fit(model=model, analysis=analysis)` to completion, then read what it wrote. Covers the output-folder anatomy and the on-the-fly announcement, the unique-identifier resume behaviour and when it silently reuses a stale fit, `iterations_per_quick_update` and `live_visual_update`, JAX/GPU acceleration and when it actually pays, VRAM checks before a long GPU run, the `PYAUTO_TEST_MODE` smoke levels, and the `if __name__ == \"__main__\"` parallelisation fix. Use once `ag_build_imaging_model` and `ag_configure_search` have produced `model`, `analysis` and `search` objects, or when a fit is running and the user wants to know what to watch. Not for composing the model or choosing the search (those two skills), not for interpreting the finished posterior (`ag_load_results`), and not for diagnosing a fit that ran but converged somewhere unphysical (`ag_debug_fit_failure`).\n---\n\n# Running the fit\n\nThis is the moment the inference actually happens. Everything before it was preparation:\na `model` says which morphological parameters are free and what priors they carry, an\n`analysis` binds that model to one dataset and knows how to turn a parameter vector into a\nlog likelihood, and a `search` knows how to explore the parameter space. One call joins\nthem:\n\n```python\nresult = search.fit(model=model, analysis=analysis)\n```\n\nStatistically, that call is sampling (or optimising) the posterior\n$P(\\theta | d) \\propto \\mathcal{L}(d | \\theta) P(\\theta)$, where the likelihood is the\nGaussian-noise chi-squared of the PSF-convolved model image against the data — walked\nline by line in `autogalaxy_workspace:scripts/imaging/likelihood_function.py`. Scientifically,\nit is where a Sersic index, an effective radius or a bulge-to-total ratio stops being a guess\nand becomes a measurement with errors. What this skill adds is everything *around* the call:\nhow to watch it, how long to expect, how to make it fast, and how to prove the script works\nbefore committing hours to it.\n\nTwo wiki pages carry the background this skill assumes. Read\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md) for\nwhat each sampler does and how run time scales with the model, and\n[`wiki/core/api/analysis_objects.md`](../wiki/core/api/analysis_objects.md) for what the\nreturned `Result` contains.\n\n## Ask\n\nThree questions, and the answers change the branch:\n\n- *\"Do you already have `model`, `analysis` and `search`?\"* If not, route to\n [`ag_build_imaging_model`](./ag_build_imaging_model.md) and\n [`ag_configure_search`](./ag_configure_search.md) first. A fit assembled from a\n half-remembered model is the most expensive mistake available here.\n- *\"Smoke test first, or straight to the production run?\"* Almost always smoke test first —\n it takes seconds and answers \"does this script execute end to end?\", which is a different\n question from \"is this galaxy's Sersic index 3.2?\". The smoke branch is below.\n- *\"How long can this run, and on what?\"* A `MultiStartProdigy` fit is minutes; a `Nautilus`\n fit of a smooth model is tens of minutes on a GPU and can be hours on a CPU; a pixelised\n fit can be far longer. That answer decides foreground vs background, laptop vs cluster,\n and whether `live_visual_update` is worth switching on.\n\nIf the data is real observational imaging, the inspection gate in\n[`../AGENTS.md`](../AGENTS.md) applies before you get here at all — contaminants and mask\nextent are settled in [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md), not\nretrospectively.\n\n## Branch — the production run\n\nThe deliverable is one script in `scripts/` the user can re-run and edit. Adapted from\n`autogalaxy_workspace:scripts/imaging/start_here.py` (the fit and result sections) and\n`autogalaxy_workspace:scripts/imaging/modeling.py` (the Nautilus configuration and the VRAM\ncheck):\n\n```python\n\"\"\"\nGalaxy Structure: Run the Fit\n=============================\n\nFit a galaxy's surface-brightness profile to CCD imaging: load and mask the data, compose a\nlinear Sersic bulge, and sample the posterior with Nautilus so the inferred effective radius\nand Sersic index come with errors.\n\n__Contents__\n\n- **Imports:** JAX environment first, then the standard trio.\n- **Dataset:** Load imaging, mask it, and apply adaptive over-sampling.\n- **Model:** Compose the galaxy's light profile.\n- **Search:** Configure Nautilus and its update cadence.\n- **Analysis:** Bind the model to the data and choose the JAX backend.\n- **Model-Fit:** Run the search and announce the output folder.\n- **Result:** Read the best-fit model back.\n\"\"\"\nfrom autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\n\"\"\"\n__Dataset__\n\nGalaxy modeling needs three ingredients: the image in CCD counts, a per-pixel RMS noise-map,\nand the PSF. The PSF is forward-modelled rather than divided out, which is what separates a\ngenuinely compact bulge from a seeing-broadened one. `pixel_scales` converts pixels to\narcseconds and must match the instrument (`ag.Imaging.from_fits`,\n`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe mask sets which pixels enter the likelihood, and its radius is a science choice, not a\ndefault: truncate the outer isophotes and the effective radius and Sersic index are biased\ndirectly. Over-sampling evaluates the light profile several times per pixel where the\ngradient is steep, which matters most in the central few tenths of an arcsecond\n(`ag.util.over_sample.over_sample_size_via_radial_bins_from`).\n\"\"\"\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"\"\nMASK_RADIUS = 2.5\n\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n pixel_scales=0.1,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\n\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n\n\"\"\"\n__Model__\n\nA linear `Sersic` bulge: the `intensity` is solved by linear inversion each iteration rather\nthan sampled, so the search explores one fewer dimension per component for free\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Linear Light Profiles__`).\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\n\n\"\"\"\n__Search__\n\n`Nautilus` is nested sampling: it returns the full posterior — every parameter's density,\nits errors, and the correlations between them. `n_live` trades accuracy against run time and\n200 covers the vast majority of galaxy models. `unique_tag` is conventionally the dataset\nname, which is what keeps the same model fitted to different data in different folders\n(`PyAutoFit:autofit/non_linear/search/nest/nautilus/search.py`).\n\"\"\"\nsearch = af.Nautilus(\n path_prefix=Path(\"imaging\"),\n name=\"sersic\",\n unique_tag=\"\",\n n_live=200,\n iterations_per_quick_update=10000,\n live_visual_update=False,\n)\n\n\"\"\"\n__Analysis__\n\n`ag.AnalysisImaging` defines the `log_likelihood_function` the search calls, and defaults to\n`use_jax=True` when JAX is installed (`PyAutoGalaxy:autogalaxy/imaging/model/analysis.py`).\n\"\"\"\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\n\"\"\"\n__Model-Fit__\n\nResults are written to the output folder on the fly, from the best model found so far, so the\nfolder is worth opening the moment the search starts.\n\"\"\"\nprint(f\"Output folder: {search.paths.output_path.resolve()}\")\n\nresult = search.fit(model=model, analysis=analysis)\n\n\"\"\"\n__Result__\n\"\"\"\nprint(result.info)\nprint(result.max_log_likelihood_instance)\n```\n\nRun it with writable caches if the default locations are not writable — a sandbox, CI, or an\ninstall imported from a Windows mount under WSL\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)):\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\n`search.fit` itself is `PyAutoFit:autofit/non_linear/search/abstract_search.py`.\n\n## Branch — what the output folder contains, and when to look\n\n**Announce the folder at launch, not at the end.** Quote\n`search.paths.output_path.resolve()` once the fit is running and say plainly that\n`model.results` and `image/fit.png` refresh as the search goes — there is nothing to wait\nfor. Users new to the stack sit watching a silent terminal because nobody told them.\n\nThe annotated tree of `files/`, `image/`, `model.info`, `model.results`, `search.summary`\nand the `` folder is `__Output Folder Layout__` in\n[`autogalaxy_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/modeling.py);\nthe same section appears in the `interferometer`, `multi_dataset`, `multi_galaxy` and\n`cluster` `modeling.py` scripts. Link it rather than copying the tree into the conversation,\nwhere it would rot. The condensed version is also in\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n\"The output folder\".\n\nName what to open first, in this order:\n\n1. `model.results` — the human-readable fit summary, parameters with errors.\n2. `image/fit.png` — data, model image, residuals and chi-squared map in one figure.\n3. `search.log` — tail it if you want to watch progress from a terminal.\n\nDepth follows [`_style.md`](./_style.md) \"Adaptive depth\": for a newcomer, or in teacher\nmode, walk all three. For a returning user, quoting the path is enough.\n\n## Branch — resuming, and the trap inside it\n\n`` is derived from the model, the search settings and the dataset identifier, so\nre-running an identical configuration **resumes** the existing fit rather than restarting it\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Unique Identifier__`). That is a\nfeature — an interrupted overnight run picks up where it stopped.\n\nIt is also the sharpest edge in the workflow. **The identifier does not hash the pixel\nvalues of your data.** Swap `data.fits` for a different galaxy, keep the model, the search\nand the `unique_tag` identical, and the next run finds a completed fit at the same path and\nreturns it — silently, in seconds, with the previous galaxy's parameters. If the data\nchanges, change the `unique_tag`. If you are unsure whether a result is stale, delete the\n`` folder and re-run rather than reasoning about it.\n\nTest mode namespaces its output separately: any active `PYAUTO_TEST_MODE` level inserts a\n`test_mode` segment straight after the output root, so a smoke run lands in\n`output/test_mode//...` and cannot short-circuit a later real fit\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## Branch — the update cadence and the live view\n\nTwo settings control what you see while the fit runs, both on the search\n(`PyAutoFit:autofit/non_linear/search/abstract_search.py`):\n\n- **`iterations_per_quick_update`** — how often the current best model is visualised and\n written to disk. The unit depends on the search: likelihood evaluations for `Nautilus`\n (hence the large `10000` in `modeling.py`), gradient steps for `MultiStartProdigy` (hence\n the much smaller `50` in `start_here.py`). Each update costs roughly ten seconds, so too\n low a value and output dominates the run time; too high and you cannot see progress. If\n the log is constantly reporting that it is outputting results, raise it.\n- **`live_visual_update`** — additionally push the quick-update image to a live surface: a\n matplotlib window that refreshes in a plain script, or a self-updating cell in Jupyter and\n Colab. The `fit.png` disk write happens either way. Leave it `False` on anything headless\n — an HPC node, a background process, CI.\n\nIf the search configuration already records the choice, don't re-ask; that decision belongs\nto [`ag_configure_search`](./ag_configure_search.md).\n\n## Branch — JAX, GPUs, and when the acceleration pays\n\nImaging fits run through JAX by default. Installing the extra (`pip install autogalaxy[jax]`)\nis all that is required: `ag.AnalysisImaging` then defaults to `use_jax=True`, and the search\ndriver wraps the likelihood in `jax.vmap(jax.jit(...))` so a whole batch of parameter vectors\nevaluates in one call. You will see a one-time log line as the JIT compile starts; every\nevaluation after that re-uses the compiled trace. This is described in\n`autogalaxy_workspace:scripts/guides/using_jax.py` `__Auto-Enabled Modeling__`, and if JAX is\nabsent the analysis warns once and falls back to NumPy.\n\n**When it pays.** The gain scales with how much array work each likelihood evaluation does,\nso it is largest for big masks, fine over-sampling, many-component bases and pixelised\nreconstructions, and smallest for a tiny mask with one smooth profile. GPU gains dwarf CPU\ngains: `autogalaxy_workspace:scripts/imaging/modeling.py` `__JAX__` quotes roughly ten\nminutes on a GPU against an hour on a CPU for its example, with a CPU still gaining from\nmultithreading. Gradient-based searches like `MultiStartProdigy` are not merely faster under\nJAX — they are only possible with it, because JAX is what supplies the likelihood's\nderivatives and evaluates all the parallel starts in one batched call\n(`autogalaxy_workspace:scripts/imaging/start_here.py` `__Multi Start Gradient Optimization__`).\n\n**Check VRAM before a long GPU run.** A JAX fit must fit inside the GPU's memory, and it\nfails at JIT-compile time or on the first likelihood call if it does not:\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py` `__VRAM Use__`. It takes\ntwenty or thirty seconds, so comment it out once you know your model's footprint. Batch size\nis the lever: larger batches cut wall-clock time and raise VRAM, smaller batches the reverse.\nA smooth-profile fit on a modest dataset is tens of megabytes; a pixelised reconstruction on\nhigh-resolution data can exceed ten gigabytes.\n\n**Turn JAX off to debug.** `ag.AnalysisImaging(dataset=dataset, use_jax=False)`, or\n`PYAUTO_DISABLE_JAX=1` to force it globally without editing code. NumPy stack traces are far\neasier to read, and you can drop a debugger or a `print` into code JAX would otherwise\ncompile. That is the first lever to pull when deciding whether a failure is a JAX problem at\nall — see [`ag_debug_fit_failure`](./ag_debug_fit_failure.md).\n\nFor running on a cluster — SLURM array jobs, one galaxy per task, the CPU and GPU batch\nscripts, and `number_of_cores` read from `SLURM_CPUS_PER_TASK` — read\n[`../wiki/core/operations/hpc.md`](../wiki/core/operations/hpc.md) for the concepts and\n[`../wiki/core/operations/hpc_infrastructure.md`](../wiki/core/operations/hpc_infrastructure.md)\nfor the `hpc/` templates and `sync` CLI this repo ships; the upstream ground truth behind both\nis `autogalaxy_workspace:scripts/guides/hpc/example_cpu_and_gpu.py`. The Python modeling code\nis identical for a GPU run; only the batch script changes.\n\n## Branch — the smoke test, before you spend hours\n\nEvery script gets one fast structural run before a real one. `PYAUTO_TEST_MODE` has four\nlevels ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)), and the\nchoice between them matters more than it looks:\n\n```bash\n# Level 1 — sampler runs with minimal iterations. A real (tiny) search: writes\n# model.results, image/fit.png and a samples.csv you can load back.\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n\n# Level 2 — sampler bypassed, likelihood called exactly once. The fastest proof that\n# the model composes and the likelihood evaluates.\nPYAUTO_TEST_MODE=2 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\n**Level 2 does not write the fit products.** A level-2 run returns a `Result`, proving the\nwiring, but leaves no `model.results` and no `image/fit.png` behind — so if the next thing\nyou want to do is plot or load the fit, use level 1. Level 3 skips the likelihood call as\nwell, which is only useful for checking that a script's non-fitting scaffolding runs.\n\n**The parameter values from any test-mode run are meaningless.** The sampler was truncated or\nmocked. Never quote a structural parameter measured in test mode; say explicitly that the\nnumber is a wiring check.\n\nFor the fastest possible loop, combine test mode with the dataset and output short-circuits:\n\n```bash\nPYAUTO_TEST_MODE=2 PYAUTO_SKIP_FIT_OUTPUT=1 PYAUTO_SKIP_VISUALIZATION=1 \\\n PYAUTO_SMALL_DATASETS=1 PYAUTO_FAST_PLOTS=1 python scripts/run_fit.py\n```\n\n`PYAUTO_SMALL_DATASETS=1` caps every array, mask and grid to 16 × 16 pixels — so delete any\npreviously simulated `dataset/` when you toggle it, or a full-resolution dataset on disk will\nbe reused and mismatch the capped grids.\n\n## Branch — the error that appears the moment the search starts\n\nOn some combinations of operating system and Python version, a script raises as soon as the\nsearch begins, from Python's process spawning rather than from anything about your model. The\nfix is to wrap the whole fit in a function and call it under a main guard:\n\n```python\ndef fit():\n from autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\n import autofit as af\n import autogalaxy as ag\n\n # ... dataset, model, search, analysis as above ...\n result = search.fit(model=model, analysis=analysis)\n\n\nif __name__ == \"__main__\":\n fit()\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/modeling/bug_fix.py`, which is the same\n`modeling.py` fit with this one structural change. It works for every dataset type, so adopt\nit for any modeling script that hits the error. If parallelisation still will not work after\nthe fix, that script points at the project's support channel.\n\n## Combine\n\n- [`ag_plot_fit`](./ag_plot_fit.md) — render the fit yourself, at whatever scaling and\n cropping the science needs, rather than reading the auto-generated `image/fit.png`.\n- [`ag_load_results`](./ag_load_results.md) — pull the posterior, the best-fit galaxies and\n the derived quantities back into Python, in-session or from disk later.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) — the fit finished but the residuals or\n the parameters are wrong.\n- [`ag_configure_search`](./ag_configure_search.md) — the fit is too slow, or the sampler is\n the wrong one for the model.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) — build a controlled dataset with known\n truth and fit that first, which is the cleanest way to separate a model problem from a\n data problem.\n\nWhen the script and its fit are worth keeping, offer (default-yes) to record the run in a\ndated `wiki/project/YYYY-MM-DD-.md` entry: the science question, what was inferred and\nwith what search, and the output path — per [`_style.md`](./_style.md) property #5.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Practicalities](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running a fit — output structure, reviewing results as they appear,\n and managing run times.\n- **General reference** — [RTD: New user guide](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n the decision tree for which fit to run first, by system scale and dataset type.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit, with the JAX and quick-update sections this skill\n mirrors.\n\n## Agent procedural checklist\n\n1. Confirm `model`, `analysis` and `search` exist; if not, route to the model-building and\n search-configuration skills.\n2. On real observational data, confirm the inspection gate has been satisfied.\n3. Write the script to `scripts/` in the generated-script style; never leave it inline only.\n4. Validate it with `PYAUTO_TEST_MODE=1` (level 2 if you only need the likelihood proved),\n with the cache variables set if the environment needs them.\n5. Launch the production run; **quote the absolute output path immediately** and say results\n refresh on the fly.\n6. Name `model.results` and `image/fit.png` as the first two things to open.\n7. If the data changed but the model did not, confirm the `unique_tag` changed too.\n8. On a GPU, run the VRAM check before a long fit.\n9. On completion, hand off to the results-loading or fit-plotting skill rather than\n interpreting the numbers inline.\n10. Offer the `wiki/project/` entry.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb b/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb index 1495003..43650c9 100644 --- a/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb +++ b/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb @@ -7,39 +7,19 @@ "Tutorial 2: Practicalities\n", "==========================\n", "\n", - "In the last tutorial, we introduced foundational statistical concepts essential for model-fitting, such as parameter\n", - "spaces, likelihoods, priors, and non-linear searches. Understanding these statistical concepts is crucial for\n", - "performing model fits effectively.\n", - "\n", - "However, achieving successful model-fitting also requires practical skills, including how to manage outputs,\n", - "review results, interpret model quality, and ensure run-times are efficient enough for your scientific needs.\n", - "\n", - "This tutorial will focus on these practical aspects of model-fitting, including:\n", - "\n", - "- How to save results to your hard disk.\n", - "- How to navigate the output folder and examine model-fit results to assess quality.\n", - "- How to estimate the run-time of a model-fit before initiating it, and change settings to make it faster or run the analysis in parallel.\n", + "A galaxy can contain a compact bulge and an extended disk. We now fit both, while learning how to run a search,\n", + "manage its memory use and inspect its output. These practical skills let us assess a model as the fit progresses.\n", "\n", "__Contents__\n", "\n", - "This tutorial is split into the following sections:\n", - "\n", - " **PyAutoFit:** The parent package of PyAutoGalaxy, which handles practicalities of model-fitting.\n", - " **Initial Setup:** Load the dataset we'll fit a model to using a non-linear search.\n", - " **Mask:** Apply a mask to the dataset.\n", - " **Over Sampling:** Apply adaptive over sampling to the dataset.\n", - " **Model:** Introduce the model we will fit to the data.\n", - " **Search:** Setup the non-linear search, Nautilus, used to fit the model to the data.\n", - " **Search Settings:** Discuss the settings of the non-linear search, including the number of live points.\n", - " **Iterations Per Update:** How often the non-linear search outputs the current results to hard-disk.\n", - " **Analysis:** Create the Analysis object which contains the `log_likelihood_function` that the non-linear search calls.\n", - " **Run Times:** Estimate the run-time of the model-fit before initiating it.\n", - " **Model-Fit:** Fit the model to the data.\n", - " **Result Info:** Print the results of the model-fit to the terminal.\n", - " **Output Folder:** Inspect the output folder where results are stored.\n", - " **Unique Identifier:** Discussion of the unique identifier of the model-fit which names the folder in the output directory.\n", - " **Output Folder Contents:** What is output to the output folder (model results, visualization, etc.).\n", - " **Result:** Plot the best-fit model to the data." + "- **Dataset and Mask:** Inspect a galaxy with a bulge and disk.\n", + "- **Model:** Make the model more realistic.\n", + "- **Search Settings:** Balance exploration, batching and output updates.\n", + "- **Analysis and Run Times:** Understand the cost of a fit.\n", + "- **VRAM Use:** Check memory before fitting.\n", + "- **Output Folder:** Find summaries, images and saved results.\n", + "- **Unique Identifier:** Understand separate fits and resuming.\n", + "- **Results and Configuration:** Inspect the fit and find further tools." ] }, { @@ -88,6 +68,8 @@ "from autogalaxy import setup_notebook; setup_notebook()\n", "\n", "from pathlib import Path\n", + "import numpy as np\n", + "import autofit as af\n", "import autogalaxy as ag\n", "import autogalaxy.plot as aplt" ], @@ -98,70 +80,24 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__PyAutoFit__\n", - "\n", - "Modeling uses the probabilistic programming language\n", - "[PyAutoFit](https://github.com/PyAutoLabs/PyAutoFit), an open-source project that allows complex model\n", - "fitting techniques to be straightforwardly integrated into scientific modeling software. \n", + "__Dataset and Mask__\n", "\n", - "The majority of tools that make model-fitting practical are provided by PyAutoFit, for example it handles\n", - "all output of the non-linear search to hard-disk, the visualization of results and the estimation of run-times." + "Load the imaging data and retain the region inside the circular mask. The simulator creates the data if needed.\n", + "The image, noise map and PSF together describe the observation; none specifies which galaxy model we must fit." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "import autofit as af" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Initial Setup__\n", - "\n", - "Lets first load the `Imaging` dataset we'll fit a model with using a non-linear search. \n", "\n", - "This is the same dataset we fitted in the previous tutorial, and we'll repeat the same fit, as we simply want\n", - "to illustrate the practicalities of model-fitting in this tutorial." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "dataset_name = \"simple__sersic\"\n", - "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Dataset Auto-Simulation__\n", - "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ + "dataset_name = \"simple\"\n", + "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name\n", "if ag.util.dataset.should_simulate(str(dataset_path)):\n", " import subprocess\n", " import sys\n", "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulators/sersic.py\"],\n", - " check=True,\n", - " )\n", - "\n", + " subprocess.run([sys.executable, \"scripts/simulators/simple.py\"], check=True)\n", "\n", "dataset = ag.Imaging.from_fits(\n", " data_path=dataset_path / \"data.fits\",\n", @@ -169,32 +105,10 @@ " psf_path=dataset_path / \"psf.fits\",\n", " pixel_scales=0.1,\n", ")\n", - "\n", - "aplt.subplot_imaging_dataset(dataset=dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Mask__\n", - "\n", - "We again apply a 3.0\" mask to the dataset." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ "mask = ag.Mask2D.circular(\n", - " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=3.0\n", + " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5\n", ")\n", - "\n", - "dataset = dataset.apply_mask(mask=mask)\n", - "\n", - "aplt.subplot_imaging_dataset(dataset=dataset)" + "dataset = dataset.apply_mask(mask=mask)" ], "outputs": [], "execution_count": null @@ -205,28 +119,23 @@ "source": [ "__Over Sampling__\n", "\n", - "Over sampling is a numerical technique where the images of light profiles and galaxies are evaluated \n", - "on a higher resolution grid than the image data to ensure the calculation is accurate. \n", - "\n", - "For a new user, the details of over-sampling are not important, therefore just be aware that below we make it so that \n", - "all calculations use an adaptive over sampling scheme which ensures high accuracy and precision.\n", - "\n", - "Once you are more experienced, you should read up on over-sampling in more detail via \n", - "the `autogalaxy_workspace/*/guides/advanced/over_sampling.ipynb` notebook." + "The bright centre changes rapidly across a pixel. Adaptive over sampling evaluates it on a finer grid so that\n", + "numerical inaccuracies do not masquerade as poor models. The outskirts need fewer evaluations." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n", " grid=dataset.grid,\n", " sub_size_list=[8, 4, 2],\n", " radial_list=[0.3, 0.6],\n", " centre_list=[(0.0, 0.0)],\n", ")\n", - "\n", - "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n" + "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n", + "aplt.subplot_imaging_dataset(dataset=dataset)" ], "outputs": [], "execution_count": null @@ -237,19 +146,22 @@ "source": [ "__Model__\n", "\n", - "We compose the model using the same API as the previous tutorial.\n", + "Look at the bright central light and the more extended emission around it. A single Sersic profile need not\n", + "capture both structures. We represent the bulge with a Sersic and the disk with an Exponential profile, as in the\n", + "simulator. Real galaxies need not separate this neatly, but this controlled example lets us practise modelling.\n", "\n", - "This model is the same as the previous tutorial, a single `Galaxy` with a `Sersic` light profile." + "Here we use ordinary light profiles, so both intensities are searched along with the shapes. There are 13 free\n", + "parameters: seven for the bulge and six for the disk. Greater realism has also given the search more to explore.\n", + "Tutorial 4 returns to linear profiles and shows how to reduce this burden." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "galaxy_model = af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp_linear.Sersic)\n", - "\n", - "model = af.Collection(galaxies=af.Collection(galaxy=galaxy_model))\n", "\n", + "galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp.Sersic, disk=ag.lp.Exponential)\n", + "model = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n", "print(model.info)" ], "outputs": [], @@ -259,69 +171,39 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Search__\n", - "\n", - "To fit the model, we now create the non-linear search object, selecting the nested sampling algorithm, Nautilus, \n", - "as recommended in the previous tutorial.\n", - "\n", - "We set up the `Nautilus` object with these parameters:\n", - "\n", - "- **`path_prefix`**: specifies the output directory, here set to `HowToGalaxy/output/howtogalaxy/chapter_2`.\n", - " \n", - "- **`name`**: gives the search a descriptive name, which creates the full output path \n", - "as `HowToGalaxy/output/howtogalaxy/chapter_2/tutorial_2_practicalities`.\n", - "\n", - "- **`n_live`**: controls the number of live points Nautilus uses to sample parameter space.\n", - "\n", "__Search Settings__\n", "\n", - "Nautilus samples parameter space by placing \"live points\" representing different galaxy models. Each point has an \n", - "associated `log_likelihood` that reflects how well it fits the data. By mapping where high-likelihood solutions are \n", - "located, it can focus on searching those regions.\n", - "\n", - "The main setting to balance is the **number of live points**. More live points allow Nautilus to map parameter space \n", - "more thoroughly, increasing accuracy but also runtime. Fewer live points reduce run-time but may make the search less \n", - "reliable, possibly getting stuck in local maxima.\n", + "We use 200 live points for this more complex model. More live points generally improve exploration at the cost\n", + "of more work; fewer may be faster but can miss good solutions. The appropriate value depends on the model and\n", + "data, and must be judged from the results rather than a universal rule.\n", "\n", - "The ideal number of live points depends on model complexity. More parameters generally require more live points, but\n", - "the default of 3000 is more than sufficient for most galaxy models. Lower values can still yield reliable results, particularly\n", - "for simpler models. For this example (6 parameters), we reduce the live points to 80 to speed up runtime without \n", - "compromising accuracy.\n", + "`n_batch=50` lets the search evaluate batches of trial models using the accelerated likelihood. This can make good\n", + "use of a GPU, but larger batches need more memory. Batching does not replace adequate exploration with live points.\n", "\n", - "Tuning non-linear search settings (e.g., the number of live points) to match model complexity is essential. We aim \n", - "for enough live points to ensure accurate results (i.e., finding a global maximum) but not so many that runtime \n", - "is excessive.\n", - "\n", - "In practice, the optimal number of live points is often found through trial and error, guided by summary statistics \n", - "on how well the search is performing, which we\u2019ll cover below. For this single Sersic model with a linear light \n", - "profile, 80 live points is sufficient to achieve reliable results.\n", + "`path_prefix` groups related fits, `name` identifies this tutorial and `unique_tag` identifies the dataset.\n", + "Together they organise the output folders described below.\n", "\n", "__Iterations Per Update__\n", "\n", - "Every N iterations, the non-linear search outputs the current results to the folder `HowToGalaxy/output`,\n", - "which includes producing visualization. \n", - "\n", - "Depending on how long it takes for the model to be fitted to the data (see discussion about run times below), \n", - "this can take up a large fraction of the run-time of the non-linear search.\n", - "\n", - "For this fit, the fit is very fast, thus we set a high value of `iterations_per_quick_update=2500` to ensure these updates\n", - "do not slow down the overall speed of the model-fit.\n", + "`iterations_per_quick_update=2500` controls quick output updates after roughly this many likelihood evaluations.\n", + "Full updates have their own setting, `iterations_per_full_update`. The two update types do different amounts of\n", + "work, so this does not mean that every saved product is regenerated every 2500 evaluations.\n", "\n", - "**If the iteration per update is too low, the model-fit may be significantly slowed down by the time it takes to\n", - "output results and visualization frequently to hard-disk. If your fit is consistent displaying a log saying that it\n", - "is outputting results, try increasing this value to ensure the model-fit runs efficiently.**" + "Frequent plotting and disk writes can dominate a fast fit. Increase the update interval if output takes too much\n", + "of the runtime; decrease it if you need more frequent feedback while diagnosing a fit." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "search = af.Nautilus(\n", " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", " name=\"tutorial_2_practicalities\",\n", " unique_tag=dataset_name,\n", - " n_live=80,\n", - " n_batch=50, # GPU model fits are batched and run simultaneously, see the run times section below.\n", + " n_live=200,\n", + " n_batch=50,\n", " iterations_per_quick_update=2500,\n", ")" ], @@ -334,14 +216,15 @@ "source": [ "__Analysis__\n", "\n", - "We again create the `AnalysisImaging` object which contains the `log_likelihood_function` that the non-linear search\n", - "calls to fit the model to the data." + "The model defines possible bulges and disks; `AnalysisImaging` compares their predicted light with this masked\n", + "dataset. The search itself does not need to know how a galaxy image is calculated." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)" ], "outputs": [], @@ -353,69 +236,27 @@ "source": [ "__Run Times__\n", "\n", - "Another key practicality in model-fitting is the run-time of the model-fit. Modeling can be a computationally \n", - "expensive process, whereby the fitting of complex models to high resolution datasets run times may be of order hours, \n", - "days or weeks.\n", - "\n", - "Run times are dictated by two factors:\n", - "\n", - " - **The log likelihood evaluation time:** the time it takes for a single `instance` of the model to be fitted to \n", - " the dataset such that a log likelihood is returned.\n", - "\n", - " - **The number of iterations (e.g. log likelihood evaluations) performed by the non-linear search:** more complex\n", - " models require more iterations to converge to a solution (and as discussed above, settings like the number of live\n", - " points also control this).\n", - "\n", - "For this analysis, the log likelihood evaluation time is ~0.05 seconds, which is extremely fast for model fitting. \n", + "Two important costs are how expensive the likelihood is to evaluate and how many evaluations the search needs.\n", + "More pixels, finer over sampling and more elaborate models can increase the first; difficult parameter spaces\n", + "and more thorough search settings can increase the second.\n", "\n", - "The more advanced fitting techniques discussed later in this chapter (e.g. multi Gaussian expansions, shapelets) and\n", - "the pixelizations of chapter 3 have longer log likelihood evaluation times. However, on GPU, they can be so fast that\n", - "they may not produce significantly longer overall run-times.\n", + "With JAX, compilation adds an initial cost, after which compiled calculations are reused. Batches can evaluate\n", + "several models together, so timing one ordinary `FitImaging` call is not a reliable prediction of search runtime.\n", + "Use a representative run on your own machine and inspect `search.summary`, allowing for compilation, search work\n", + "and output overhead. There is no fixed runtime or evaluations-per-parameter rule that applies to every fit.\n", "\n", - "To estimate the expected overall run time of the model-fit we multiply the log likelihood evaluation time by an \n", - "estimate of the number of iterations the non-linear search will perform, which is around 50000 to 100000 for this model.\n", + "__VRAM Use__\n", "\n", - "Tests thus far reveal CPU run times are around 30 minutes, and GPU run times around 10 minutes.\n", - "\n", - "__Model-Fit__\n", - "\n", - "To begin the model-fit, we pass the model and analysis objects to the search, which performs a non-linear search to \n", - "identify models that best fit the data.\n", - "\n", - "Running model fits via non-linear search can take significant time. While the fit in this tutorial should \n", - "complete in a few minutes, more complex models may require longer run times. In Jupyter notebooks, this can be \n", - "limiting, as the notebook cell will only complete once the fit finishes, preventing you from advancing through the \n", - "tutorial or running additional code.\n", - "\n", - "To work around this, we recommend running tutorial scripts as standalone Python scripts, found \n", - "in the `scripts/` folder of the HowToGalaxy repository. These scripts mirror the notebook tutorials but run independently of \n", - "Jupyter notebooks. For example, you can start a script with:\n", - "\n", - "`python3 scripts/chapter_2_modeling/tutorial_2_practicalities.py`\n", - "\n", - "Using scripts allows results to be saved to the hard drive in the `output` folder, enabling you to inspect results \n", - "immediately once the script completes. When rerun, the script loads results directly from disk, so any Jupyter \n", - "notebook cells will quickly load and display the complete model-fit results if they\u2019re already saved.\n", - "\n", - "This approach not only avoids the slowdowns associated with notebook cells during lengthy runs but is also essential \n", - "for using super-computers for fitting tasks, as they require separate Python scripts.\n", - "\n", - "For tasks like loading results, inspecting data, plotting, and interpreting results, Jupyter notebooks remain ideal." + "A GPU has a finite amount of memory, often called VRAM. Larger datasets, models and batches need more of it.\n", + "The following estimates memory for the likelihood calculation at the chosen batch size:" ] }, { "cell_type": "code", "metadata": {}, "source": [ - "print(\n", - " \"The non-linear search has begun running - checkout the HowToGalaxy/output/\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell will progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", - "result = search.fit(model=model, analysis=analysis)\n", "\n", - "print(\"Search has finished run - you may now continue the notebook.\")" + "analysis.print_vram_use(model=model, batch_size=search.batch_size)" ], "outputs": [], "execution_count": null @@ -424,19 +265,24 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Result Info__\n", + "This is a likelihood estimate, not a promise about the total memory required by the process. Compilation,\n", + "other arrays and other programs also need space. On a CPU, available system memory is the relevant limit.\n", + "If memory is tight, try reducing `n_batch` from 50 to 10 before removing useful data or simplifying the science.\n", "\n", - "A concise readable summary of the results is given by printing its `info` attribute.\n", + "__Model Fit__\n", "\n", - "[Above, we discussed that the `info_whitespace_length` parameter in the config files could be changed to make\n", - "the `model.info` attribute display optimally on your computer. This attribute also controls the whitespace of the\n", - "`result.info` attribute.]" + "Run the fit below. A notebook cell waits until it finishes, but output appears on disk while it runs.\n", + "You can instead run `python scripts/chapter_2_modeling/tutorial_2_practicalities.py` from the repository root.\n", + "Scripts and notebooks save to the same output location when run with the same settings and working directory.\n", + "A script does not inherently make the inference faster; it is often more convenient for long unattended fits." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", + "result = search.fit(model=model, analysis=analysis)\n", "print(result.info)" ], "outputs": [], @@ -448,71 +294,63 @@ "source": [ "__Output Folder__\n", "\n", - "Now checkout the `HowToGalaxy/output` folder.\n", + "Open `output` in the repository root. The layout below shows the main products of a completed fit; the exact\n", + "images and optional files depend on configuration and which updates have run.\n", + "\n", + "```text\n", + "output/\n", + "+-- howtogalaxy/\n", + " +-- chapter_2/\n", + " +-- simple/ # unique_tag\n", + " +-- tutorial_2_practicalities/ # name\n", + " +-- /\n", + " +-- model.info\n", + " +-- model.results\n", + " +-- search.summary\n", + " +-- search.log\n", + " +-- image/\n", + " | +-- dataset.png\n", + " | +-- dataset.fits\n", + " | +-- fit.png\n", + " | +-- fit.fits\n", + " +-- files/\n", + " +-- model.json\n", + " +-- galaxies.json\n", + " +-- search.json\n", + " +-- samples.csv\n", + " +-- samples_info.json\n", + " +-- samples_summary.json\n", + " +-- covariance.csv\n", + " +-- dataset_identity.json\n", + " +-- search_internal/\n", + "```\n", + "\n", + "`model.info` records the model and priors. `model.results` summarises inferred parameters and uncertainties.\n", + "`image/fit.png` lets you inspect the current best fit without writing Python. `search.summary` helps assess search\n", + "progress and runtime, while `search.log` records messages. The `files` directory stores machine-readable results;\n", + "search-specific checkpoint files support resuming an interrupted fit.\n", "\n", - "This is where the results of the search are written to hard-disk (in the `tutorial_2_practicalities` folder). \n", + "__Unique Identifier__\n", "\n", - "Once completed images, results and information about the fit appear in this folder, meaning that you don't need \n", - "to keep running Python code to see the result.\n", + "The identifier is derived from identifying model and search settings, including the tag. It is not a random name.\n", + "Repeating the same setup finds the same output, allowing an interrupted search to resume when its checkpoint is\n", + "intact, or a completed result to load rather than run again. Changing identifying settings creates another folder.\n", "\n", - "__Unique Identifier__\n", + "`unique_tag=dataset_name` keeps datasets separate. The identifier does not automatically hash every data pixel,\n", + "mask choice or Analysis setting. If you change these while keeping the same model and search, use a new name or\n", + "tag so that you cannot accidentally reuse an old result. Keep enough information to reproduce each analysis.\n", + "\n", + "__Results__\n", "\n", - "In the output folder, you will note that results are in a folder which is a collection of random characters. This acts \n", - "as a `unique_identifier` of the model-fit, where this identifier is generated based on the model, search and dataset \n", - "that are used in the fit.\n", - " \n", - "An identical combination of model, search and dataset generates the same identifier, meaning that rerunning the\n", - "script will use the existing results to resume the model-fit. In contrast, if you change the model, search or dataset,\n", - "a new unique identifier will be generated, ensuring that the model-fit results are output into a separate folder. \n", - "\n", - "We additionally want the unique identifier to be specific to the dataset fitted, so that if we fit different datasets\n", - "with the same model and search results are output to a different folder. We achieved this for the fit above by passing \n", - "the `dataset_name` to the search's `unique_tag`.\n", - "\n", - "__Output Folder Contents__\n", - "\n", - "Now this is running you should checkout the `HowToGalaxy/output` folder. This is where the results of the\n", - "search are written to hard-disk (in the `tutorial_2_practicalities` folder), where all outputs are human readable\n", - "(e.g. as .json, .csv or text files).\n", - "\n", - "As the fit progresses, results are written to the `output` folder on the fly using the highest likelihood model found\n", - "by the non-linear search so far. This means you can inspect the results of the model-fit as it runs, without having to\n", - "wait for the non-linear search to terminate.\n", - " \n", - "The `output` folder includes:\n", - "\n", - " - `model.info`: Summarizes the model, its parameters and their priors discussed in the next tutorial.\n", - " \n", - " - `model.results`: Summarizes the highest likelihood model inferred so far including errors.\n", - " \n", - " - `images`: Visualization of the highest likelihood model-fit to the dataset, (e.g. a fit subplot showing the \n", - " galaxies, model data and residuals).\n", - " \n", - " - `files`: A folder containing .fits files of the dataset, the model as a human-readable .json file, \n", - " a `.csv` table of every non-linear search sample and other files containing information about the model-fit.\n", - " \n", - " - `search.summary`: A file providing summary statistics on the performance of the non-linear search.\n", - " \n", - " - `search_internal`: Internal files of the non-linear search (in this case Nautilus) used for resuming the fit and\n", - " visualizing the search.\n", - "\n", - "__Result__\n", - "\n", - "The `search.fit` method produces a `result` object, packed with useful information about the model fit that we\u2019ll \n", - "explore in detail in a later tutorial.\n", - "\n", - "One component of the `result` object we\u2019ll use now is the `FitImaging` object, which corresponds to the set of model \n", - "parameters that yielded the maximum log-likelihood solution. Plotting this object lets us visually inspect how well \n", - "the model fits the data.\n", - "\n", - "In this example, the fit to the data is excellent, with residuals near zero, as expected since the same model was \n", - "used both to simulate and fit the data." + "The result gives us the maximum-likelihood fit and galaxies, plus samples from which parameter estimates and\n", + "uncertainties are calculated. For this course, our priority is learning to obtain reliable fits." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit)" ], "outputs": [], @@ -522,58 +360,37 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The Probability Density Functions (PDF's) of the results can be plotted using Nautilus's in-built visualization \n", - "library, which is wrapped via the `corner_anesthetic` function.\n", - "\n", - "The PDF shows the 1D and 2D probabilities estimated for every parameter after the model-fit. The two dimensional \n", - "figures can show the degeneracies between different parameters, for example how increasing the intensity $I$ of the\n", - "galaxy and decreasing its effective radius $R_{Eff}$ lead to similar likelihoods and probabilities.\n", - "\n", - "This PDF will be discussed more in the next tutorial.\n", + "Inspect the central bulge, disk and residuals. A visually good fit is encouraging, but another search may find a\n", + "better solution. The next tutorial explores that failure mode.\n", "\n", - "The plot is labeled with short hand parameter names (e.g. `sersic_index` is mapped to the short hand\n", - "parameter `n`). These mappings are specified in the `config/notation.yaml` file and can be customized by users.\n", + "Once you can fit real data reliably, use `autogalaxy_workspace/scripts/guides/results/start_here.py` to learn\n", + "how to load, manipulate and combine results, including database tools for larger samples.\n", "\n", - "The superscripts of labels are the path of names each component was given in the model (e.g. for the `Sersic`\n", - "bulge, `galaxy.bulge`: the galaxy's name `galaxy` and its name `bulge` defined when making the `Model` above).\n", + "__Parameter Plots__\n", "\n", - "Components in different named galaxy or profile paths can be distinguished by their superscripts. Profiles within\n", - "the same path, such as Gaussians in a basis, can share a superscript. When the model has more than one top-level\n", - "component, each also gets its own\n", - "corner plot in the output folder (`corner_anesthetic_.png`, switched in `config/visualize/plots_search.yaml`).\n", + "The output also includes corner plots showing ranges of plausible parameters and relationships between them.\n", + "For example, the bulge's intensity and effective radius can trade off while producing similar images.\n", + "The `corner_anesthetic` plotting function can show these distributions. With `latent=True`, it displays derived\n", + "quantities such as axis ratio and position angle instead of the sampled elliptical components.\n", "\n", - "The parameters a model is sampled in are not always the ones it is read in: a profile's elliptical components are an\n", - "axis ratio and a position angle. Passing `latent=True` to `corner_anesthetic` plots these latent parameters instead.\n", - "The same figure is written to the output folder as `corner_anesthetic_latent.png` when `corner_anesthetic_latent`\n", - "is switched on in `config/visualize/plots_search.yaml` (off by default), once the fit is complete. With\n", - "`latent_model_parameters` enabled, full-sample latent output (`latent_draw_via_pdf: false`) writes these columns\n", - "to `files/latent/samples.csv`. Only the plot recentres periodic angles; saved values keep the conversion's range.\n", + "Labels are controlled by `config/notation.yaml`. Component names become superscripts, distinguishing the bulge\n", + "from the disk. Search plot switches, including the optional latent corner plot, are in\n", + "`config/visualize/plots_search.yaml`. These plots become useful once you have checked the fit itself.\n", "\n", - "__Other Practicalities__\n", + "__Configuration and Storage__\n", "\n", - "The following are examples of other practicalities which I will document fully in this example script in the future,\n", - "but so far have no found the time:\n", + "The `config` directory controls defaults for priors, search settings, plotting and output. The\n", + "`info_whitespace_length` setting in `config/general.yaml` adjusts the spacing of model and result summaries.\n", + "Restart a notebook kernel when changing configuration that is loaded at startup.\n", "\n", - "- `config`: The files in `HowToGalaxy/config` which control many aspects of how PyAutoGalaxy runs,\n", - " including visualization, the non-linear search settings.\n", - "\n", - "- `config/priors`: Folder containing the default priors on all model components.\n", - "\n", - "- `results`: How to load the results of a model-fit from the output folder to a Python script or Jupyter notebook.\n", - "\n", - "- `output.yaml`: What files are output to control file size.\n", + "`config/output.yaml` controls which products are retained. In particular, `search_internal: false` removes\n", + "search internals after completion to save space; keep them if you need the search-specific state later.\n", + "Do not remove the checkpoints of an unfinished fit you intend to resume.\n", "\n", "__Wrap Up__\n", "\n", - "This tutorial has illustrated how to handle a number of practicalities that are key to performing model-fitting\n", - "effectively. These include:\n", - "\n", - "- How to save results to your hard disk.\n", - "\n", - "- How to navigate the output folder and examine model-fit results to assess quality.\n", - "\n", - "- How to estimate the run-time of a model-fit before initiating it, and change settings to make it faster or run the\n", - " analysis in parallel." + "We have fitted a more realistic model and learnt where to inspect its progress, results and resource use.\n", + "Now we will deliberately give the search too little exploration and learn how to diagnose and improve the fit." ] } ], @@ -601,7 +418,7 @@ "24c2f562-da24-50bb-8eb9-5a887505fe54": { "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", "name": "PyAutoGalaxy assistant", - "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_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\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb in HowToGalaxy).\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 PyAutoGalaxy 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 PyAutoGalaxy docs (https://pyautogalaxy.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) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. 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 galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_run_search\n\n---\nname: ag_run_search\ndescription: Run the fit \u2014 take a composed model, an analysis and a configured search and drive `search.fit(model=model, analysis=analysis)` to completion, then read what it wrote. Covers the output-folder anatomy and the on-the-fly announcement, the unique-identifier resume behaviour and when it silently reuses a stale fit, `iterations_per_quick_update` and `live_visual_update`, JAX/GPU acceleration and when it actually pays, VRAM checks before a long GPU run, the `PYAUTO_TEST_MODE` smoke levels, and the `if __name__ == \"__main__\"` parallelisation fix. Use once `ag_build_imaging_model` and `ag_configure_search` have produced `model`, `analysis` and `search` objects, or when a fit is running and the user wants to know what to watch. Not for composing the model or choosing the search (those two skills), not for interpreting the finished posterior (`ag_load_results`), and not for diagnosing a fit that ran but converged somewhere unphysical (`ag_debug_fit_failure`).\n---\n\n# Running the fit\n\nThis is the moment the inference actually happens. Everything before it was preparation:\na `model` says which morphological parameters are free and what priors they carry, an\n`analysis` binds that model to one dataset and knows how to turn a parameter vector into a\nlog likelihood, and a `search` knows how to explore the parameter space. One call joins\nthem:\n\n```python\nresult = search.fit(model=model, analysis=analysis)\n```\n\nStatistically, that call is sampling (or optimising) the posterior\n$P(\\theta | d) \\propto \\mathcal{L}(d | \\theta) P(\\theta)$, where the likelihood is the\nGaussian-noise chi-squared of the PSF-convolved model image against the data \u2014 walked\nline by line in `autogalaxy_workspace:scripts/imaging/likelihood_function.py`. Scientifically,\nit is where a Sersic index, an effective radius or a bulge-to-total ratio stops being a guess\nand becomes a measurement with errors. What this skill adds is everything *around* the call:\nhow to watch it, how long to expect, how to make it fast, and how to prove the script works\nbefore committing hours to it.\n\nTwo wiki pages carry the background this skill assumes. Read\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md) for\nwhat each sampler does and how run time scales with the model, and\n[`wiki/core/api/analysis_objects.md`](../wiki/core/api/analysis_objects.md) for what the\nreturned `Result` contains.\n\n## Ask\n\nThree questions, and the answers change the branch:\n\n- *\"Do you already have `model`, `analysis` and `search`?\"* If not, route to\n [`ag_build_imaging_model`](./ag_build_imaging_model.md) and\n [`ag_configure_search`](./ag_configure_search.md) first. A fit assembled from a\n half-remembered model is the most expensive mistake available here.\n- *\"Smoke test first, or straight to the production run?\"* Almost always smoke test first \u2014\n it takes seconds and answers \"does this script execute end to end?\", which is a different\n question from \"is this galaxy's Sersic index 3.2?\". The smoke branch is below.\n- *\"How long can this run, and on what?\"* A `MultiStartProdigy` fit is minutes; a `Nautilus`\n fit of a smooth model is tens of minutes on a GPU and can be hours on a CPU; a pixelised\n fit can be far longer. That answer decides foreground vs background, laptop vs cluster,\n and whether `live_visual_update` is worth switching on.\n\nIf the data is real observational imaging, the inspection gate in\n[`../AGENTS.md`](../AGENTS.md) applies before you get here at all \u2014 contaminants and mask\nextent are settled in [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md), not\nretrospectively.\n\n## Branch \u2014 the production run\n\nThe deliverable is one script in `scripts/` the user can re-run and edit. Adapted from\n`autogalaxy_workspace:scripts/imaging/start_here.py` (the fit and result sections) and\n`autogalaxy_workspace:scripts/imaging/modeling.py` (the Nautilus configuration and the VRAM\ncheck):\n\n```python\n\"\"\"\nGalaxy Structure: Run the Fit\n=============================\n\nFit a galaxy's surface-brightness profile to CCD imaging: load and mask the data, compose a\nlinear Sersic bulge, and sample the posterior with Nautilus so the inferred effective radius\nand Sersic index come with errors.\n\n__Contents__\n\n- **Imports:** JAX environment first, then the standard trio.\n- **Dataset:** Load imaging, mask it, and apply adaptive over-sampling.\n- **Model:** Compose the galaxy's light profile.\n- **Search:** Configure Nautilus and its update cadence.\n- **Analysis:** Bind the model to the data and choose the JAX backend.\n- **Model-Fit:** Run the search and announce the output folder.\n- **Result:** Read the best-fit model back.\n\"\"\"\nfrom autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\n\"\"\"\n__Dataset__\n\nGalaxy modeling needs three ingredients: the image in CCD counts, a per-pixel RMS noise-map,\nand the PSF. The PSF is forward-modelled rather than divided out, which is what separates a\ngenuinely compact bulge from a seeing-broadened one. `pixel_scales` converts pixels to\narcseconds and must match the instrument (`ag.Imaging.from_fits`,\n`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe mask sets which pixels enter the likelihood, and its radius is a science choice, not a\ndefault: truncate the outer isophotes and the effective radius and Sersic index are biased\ndirectly. Over-sampling evaluates the light profile several times per pixel where the\ngradient is steep, which matters most in the central few tenths of an arcsecond\n(`ag.util.over_sample.over_sample_size_via_radial_bins_from`).\n\"\"\"\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"\"\nMASK_RADIUS = 2.5\n\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n pixel_scales=0.1,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\n\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n\n\"\"\"\n__Model__\n\nA linear `Sersic` bulge: the `intensity` is solved by linear inversion each iteration rather\nthan sampled, so the search explores one fewer dimension per component for free\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Linear Light Profiles__`).\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\n\n\"\"\"\n__Search__\n\n`Nautilus` is nested sampling: it returns the full posterior \u2014 every parameter's density,\nits errors, and the correlations between them. `n_live` trades accuracy against run time and\n200 covers the vast majority of galaxy models. `unique_tag` is conventionally the dataset\nname, which is what keeps the same model fitted to different data in different folders\n(`PyAutoFit:autofit/non_linear/search/nest/nautilus/search.py`).\n\"\"\"\nsearch = af.Nautilus(\n path_prefix=Path(\"imaging\"),\n name=\"sersic\",\n unique_tag=\"\",\n n_live=200,\n iterations_per_quick_update=10000,\n live_visual_update=False,\n)\n\n\"\"\"\n__Analysis__\n\n`ag.AnalysisImaging` defines the `log_likelihood_function` the search calls, and defaults to\n`use_jax=True` when JAX is installed (`PyAutoGalaxy:autogalaxy/imaging/model/analysis.py`).\n\"\"\"\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\n\"\"\"\n__Model-Fit__\n\nResults are written to the output folder on the fly, from the best model found so far, so the\nfolder is worth opening the moment the search starts.\n\"\"\"\nprint(f\"Output folder: {search.paths.output_path.resolve()}\")\n\nresult = search.fit(model=model, analysis=analysis)\n\n\"\"\"\n__Result__\n\"\"\"\nprint(result.info)\nprint(result.max_log_likelihood_instance)\n```\n\nRun it with writable caches if the default locations are not writable \u2014 a sandbox, CI, or an\ninstall imported from a Windows mount under WSL\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)):\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\n`search.fit` itself is `PyAutoFit:autofit/non_linear/search/abstract_search.py`.\n\n## Branch \u2014 what the output folder contains, and when to look\n\n**Announce the folder at launch, not at the end.** Quote\n`search.paths.output_path.resolve()` once the fit is running and say plainly that\n`model.results` and `image/fit.png` refresh as the search goes \u2014 there is nothing to wait\nfor. Users new to the stack sit watching a silent terminal because nobody told them.\n\nThe annotated tree of `files/`, `image/`, `model.info`, `model.results`, `search.summary`\nand the `` folder is `__Output Folder Layout__` in\n[`autogalaxy_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/modeling.py);\nthe same section appears in the `interferometer`, `multi_dataset`, `multi_galaxy` and\n`cluster` `modeling.py` scripts. Link it rather than copying the tree into the conversation,\nwhere it would rot. The condensed version is also in\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n\"The output folder\".\n\nName what to open first, in this order:\n\n1. `model.results` \u2014 the human-readable fit summary, parameters with errors.\n2. `image/fit.png` \u2014 data, model image, residuals and chi-squared map in one figure.\n3. `search.log` \u2014 tail it if you want to watch progress from a terminal.\n\nDepth follows [`_style.md`](./_style.md) \"Adaptive depth\": for a newcomer, or in teacher\nmode, walk all three. For a returning user, quoting the path is enough.\n\n## Branch \u2014 resuming, and the trap inside it\n\n`` is derived from the model, the search settings and the dataset identifier, so\nre-running an identical configuration **resumes** the existing fit rather than restarting it\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Unique Identifier__`). That is a\nfeature \u2014 an interrupted overnight run picks up where it stopped.\n\nIt is also the sharpest edge in the workflow. **The identifier does not hash the pixel\nvalues of your data.** Swap `data.fits` for a different galaxy, keep the model, the search\nand the `unique_tag` identical, and the next run finds a completed fit at the same path and\nreturns it \u2014 silently, in seconds, with the previous galaxy's parameters. If the data\nchanges, change the `unique_tag`. If you are unsure whether a result is stale, delete the\n`` folder and re-run rather than reasoning about it.\n\nTest mode namespaces its output separately: any active `PYAUTO_TEST_MODE` level inserts a\n`test_mode` segment straight after the output root, so a smoke run lands in\n`output/test_mode//...` and cannot short-circuit a later real fit\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## Branch \u2014 the update cadence and the live view\n\nTwo settings control what you see while the fit runs, both on the search\n(`PyAutoFit:autofit/non_linear/search/abstract_search.py`):\n\n- **`iterations_per_quick_update`** \u2014 how often the current best model is visualised and\n written to disk. The unit depends on the search: likelihood evaluations for `Nautilus`\n (hence the large `10000` in `modeling.py`), gradient steps for `MultiStartProdigy` (hence\n the much smaller `50` in `start_here.py`). Each update costs roughly ten seconds, so too\n low a value and output dominates the run time; too high and you cannot see progress. If\n the log is constantly reporting that it is outputting results, raise it.\n- **`live_visual_update`** \u2014 additionally push the quick-update image to a live surface: a\n matplotlib window that refreshes in a plain script, or a self-updating cell in Jupyter and\n Colab. The `fit.png` disk write happens either way. Leave it `False` on anything headless\n \u2014 an HPC node, a background process, CI.\n\nIf the search configuration already records the choice, don't re-ask; that decision belongs\nto [`ag_configure_search`](./ag_configure_search.md).\n\n## Branch \u2014 JAX, GPUs, and when the acceleration pays\n\nImaging fits run through JAX by default. Installing the extra (`pip install autogalaxy[jax]`)\nis all that is required: `ag.AnalysisImaging` then defaults to `use_jax=True`, and the search\ndriver wraps the likelihood in `jax.vmap(jax.jit(...))` so a whole batch of parameter vectors\nevaluates in one call. You will see a one-time log line as the JIT compile starts; every\nevaluation after that re-uses the compiled trace. This is described in\n`autogalaxy_workspace:scripts/guides/using_jax.py` `__Auto-Enabled Modeling__`, and if JAX is\nabsent the analysis warns once and falls back to NumPy.\n\n**When it pays.** The gain scales with how much array work each likelihood evaluation does,\nso it is largest for big masks, fine over-sampling, many-component bases and pixelised\nreconstructions, and smallest for a tiny mask with one smooth profile. GPU gains dwarf CPU\ngains: `autogalaxy_workspace:scripts/imaging/modeling.py` `__JAX__` quotes roughly ten\nminutes on a GPU against an hour on a CPU for its example, with a CPU still gaining from\nmultithreading. Gradient-based searches like `MultiStartProdigy` are not merely faster under\nJAX \u2014 they are only possible with it, because JAX is what supplies the likelihood's\nderivatives and evaluates all the parallel starts in one batched call\n(`autogalaxy_workspace:scripts/imaging/start_here.py` `__Multi Start Gradient Optimization__`).\n\n**Check VRAM before a long GPU run.** A JAX fit must fit inside the GPU's memory, and it\nfails at JIT-compile time or on the first likelihood call if it does not:\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py` `__VRAM Use__`. It takes\ntwenty or thirty seconds, so comment it out once you know your model's footprint. Batch size\nis the lever: larger batches cut wall-clock time and raise VRAM, smaller batches the reverse.\nA smooth-profile fit on a modest dataset is tens of megabytes; a pixelised reconstruction on\nhigh-resolution data can exceed ten gigabytes.\n\n**Turn JAX off to debug.** `ag.AnalysisImaging(dataset=dataset, use_jax=False)`, or\n`PYAUTO_DISABLE_JAX=1` to force it globally without editing code. NumPy stack traces are far\neasier to read, and you can drop a debugger or a `print` into code JAX would otherwise\ncompile. That is the first lever to pull when deciding whether a failure is a JAX problem at\nall \u2014 see [`ag_debug_fit_failure`](./ag_debug_fit_failure.md).\n\nFor running on a cluster \u2014 SLURM array jobs, one galaxy per task, the CPU and GPU batch\nscripts, and `number_of_cores` read from `SLURM_CPUS_PER_TASK` \u2014 read\n[`../wiki/core/operations/hpc.md`](../wiki/core/operations/hpc.md) for the concepts and\n[`../wiki/core/operations/hpc_infrastructure.md`](../wiki/core/operations/hpc_infrastructure.md)\nfor the `hpc/` templates and `sync` CLI this repo ships; the upstream ground truth behind both\nis `autogalaxy_workspace:scripts/guides/hpc/example_cpu_and_gpu.py`. The Python modeling code\nis identical for a GPU run; only the batch script changes.\n\n## Branch \u2014 the smoke test, before you spend hours\n\nEvery script gets one fast structural run before a real one. `PYAUTO_TEST_MODE` has four\nlevels ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)), and the\nchoice between them matters more than it looks:\n\n```bash\n# Level 1 \u2014 sampler runs with minimal iterations. A real (tiny) search: writes\n# model.results, image/fit.png and a samples.csv you can load back.\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n\n# Level 2 \u2014 sampler bypassed, likelihood called exactly once. The fastest proof that\n# the model composes and the likelihood evaluates.\nPYAUTO_TEST_MODE=2 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\n**Level 2 does not write the fit products.** A level-2 run returns a `Result`, proving the\nwiring, but leaves no `model.results` and no `image/fit.png` behind \u2014 so if the next thing\nyou want to do is plot or load the fit, use level 1. Level 3 skips the likelihood call as\nwell, which is only useful for checking that a script's non-fitting scaffolding runs.\n\n**The parameter values from any test-mode run are meaningless.** The sampler was truncated or\nmocked. Never quote a structural parameter measured in test mode; say explicitly that the\nnumber is a wiring check.\n\nFor the fastest possible loop, combine test mode with the dataset and output short-circuits:\n\n```bash\nPYAUTO_TEST_MODE=2 PYAUTO_SKIP_FIT_OUTPUT=1 PYAUTO_SKIP_VISUALIZATION=1 \\\n PYAUTO_SMALL_DATASETS=1 PYAUTO_FAST_PLOTS=1 python scripts/run_fit.py\n```\n\n`PYAUTO_SMALL_DATASETS=1` caps every array, mask and grid to 16 \u00d7 16 pixels \u2014 so delete any\npreviously simulated `dataset/` when you toggle it, or a full-resolution dataset on disk will\nbe reused and mismatch the capped grids.\n\n## Branch \u2014 the error that appears the moment the search starts\n\nOn some combinations of operating system and Python version, a script raises as soon as the\nsearch begins, from Python's process spawning rather than from anything about your model. The\nfix is to wrap the whole fit in a function and call it under a main guard:\n\n```python\ndef fit():\n from autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\n import autofit as af\n import autogalaxy as ag\n\n # ... dataset, model, search, analysis as above ...\n result = search.fit(model=model, analysis=analysis)\n\n\nif __name__ == \"__main__\":\n fit()\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/modeling/bug_fix.py`, which is the same\n`modeling.py` fit with this one structural change. It works for every dataset type, so adopt\nit for any modeling script that hits the error. If parallelisation still will not work after\nthe fix, that script points at the project's support channel.\n\n## Combine\n\n- [`ag_plot_fit`](./ag_plot_fit.md) \u2014 render the fit yourself, at whatever scaling and\n cropping the science needs, rather than reading the auto-generated `image/fit.png`.\n- [`ag_load_results`](./ag_load_results.md) \u2014 pull the posterior, the best-fit galaxies and\n the derived quantities back into Python, in-session or from disk later.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) \u2014 the fit finished but the residuals or\n the parameters are wrong.\n- [`ag_configure_search`](./ag_configure_search.md) \u2014 the fit is too slow, or the sampler is\n the wrong one for the model.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) \u2014 build a controlled dataset with known\n truth and fit that first, which is the cleanest way to separate a model problem from a\n data problem.\n\nWhen the script and its fit are worth keeping, offer (default-yes) to record the run in a\ndated `wiki/project/YYYY-MM-DD-.md` entry: the science question, what was inferred and\nwith what search, and the output path \u2014 per [`_style.md`](./_style.md) property #5.\n\n## Further reading\n\n- **Student / new to galaxy morphology** \u2014 [HowToGalaxy: Practicalities](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running a fit \u2014 output structure, reviewing results as they appear,\n and managing run times.\n- **General reference** \u2014 [RTD: New user guide](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n the decision tree for which fit to run first, by system scale and dataset type.\n- **Experienced PyAutoGalaxy user** \u2014 [workspace: imaging/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit, with the JAX and quick-update sections this skill\n mirrors.\n\n## Agent procedural checklist\n\n1. Confirm `model`, `analysis` and `search` exist; if not, route to the model-building and\n search-configuration skills.\n2. On real observational data, confirm the inspection gate has been satisfied.\n3. Write the script to `scripts/` in the generated-script style; never leave it inline only.\n4. Validate it with `PYAUTO_TEST_MODE=1` (level 2 if you only need the likelihood proved),\n with the cache variables set if the environment needs them.\n5. Launch the production run; **quote the absolute output path immediately** and say results\n refresh on the fly.\n6. Name `model.results` and `image/fit.png` as the first two things to open.\n7. If the data changed but the model did not, confirm the `unique_tag` changed too.\n8. On a GPU, run the VRAM check before a long fit.\n9. On completion, hand off to the results-loading or fit-plotting skill rather than\n interpreting the numbers inline.\n10. Offer the `wiki/project/` entry.\n" + "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_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\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb in HowToGalaxy).\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 PyAutoGalaxy 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 PyAutoGalaxy docs (https://pyautogalaxy.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) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. 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 galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_run_search\n\n---\nname: ag_run_search\ndescription: Run the fit — take a composed model, an analysis and a configured search and drive `search.fit(model=model, analysis=analysis)` to completion, then read what it wrote. Covers the output-folder anatomy and the on-the-fly announcement, the unique-identifier resume behaviour and when it silently reuses a stale fit, `iterations_per_quick_update` and `live_visual_update`, JAX/GPU acceleration and when it actually pays, VRAM checks before a long GPU run, the `PYAUTO_TEST_MODE` smoke levels, and the `if __name__ == \"__main__\"` parallelisation fix. Use once `ag_build_imaging_model` and `ag_configure_search` have produced `model`, `analysis` and `search` objects, or when a fit is running and the user wants to know what to watch. Not for composing the model or choosing the search (those two skills), not for interpreting the finished posterior (`ag_load_results`), and not for diagnosing a fit that ran but converged somewhere unphysical (`ag_debug_fit_failure`).\n---\n\n# Running the fit\n\nThis is the moment the inference actually happens. Everything before it was preparation:\na `model` says which morphological parameters are free and what priors they carry, an\n`analysis` binds that model to one dataset and knows how to turn a parameter vector into a\nlog likelihood, and a `search` knows how to explore the parameter space. One call joins\nthem:\n\n```python\nresult = search.fit(model=model, analysis=analysis)\n```\n\nStatistically, that call is sampling (or optimising) the posterior\n$P(\\theta | d) \\propto \\mathcal{L}(d | \\theta) P(\\theta)$, where the likelihood is the\nGaussian-noise chi-squared of the PSF-convolved model image against the data — walked\nline by line in `autogalaxy_workspace:scripts/imaging/likelihood_function.py`. Scientifically,\nit is where a Sersic index, an effective radius or a bulge-to-total ratio stops being a guess\nand becomes a measurement with errors. What this skill adds is everything *around* the call:\nhow to watch it, how long to expect, how to make it fast, and how to prove the script works\nbefore committing hours to it.\n\nTwo wiki pages carry the background this skill assumes. Read\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md) for\nwhat each sampler does and how run time scales with the model, and\n[`wiki/core/api/analysis_objects.md`](../wiki/core/api/analysis_objects.md) for what the\nreturned `Result` contains.\n\n## Ask\n\nThree questions, and the answers change the branch:\n\n- *\"Do you already have `model`, `analysis` and `search`?\"* If not, route to\n [`ag_build_imaging_model`](./ag_build_imaging_model.md) and\n [`ag_configure_search`](./ag_configure_search.md) first. A fit assembled from a\n half-remembered model is the most expensive mistake available here.\n- *\"Smoke test first, or straight to the production run?\"* Almost always smoke test first —\n it takes seconds and answers \"does this script execute end to end?\", which is a different\n question from \"is this galaxy's Sersic index 3.2?\". The smoke branch is below.\n- *\"How long can this run, and on what?\"* A `MultiStartProdigy` fit is minutes; a `Nautilus`\n fit of a smooth model is tens of minutes on a GPU and can be hours on a CPU; a pixelised\n fit can be far longer. That answer decides foreground vs background, laptop vs cluster,\n and whether `live_visual_update` is worth switching on.\n\nIf the data is real observational imaging, the inspection gate in\n[`../AGENTS.md`](../AGENTS.md) applies before you get here at all — contaminants and mask\nextent are settled in [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md), not\nretrospectively.\n\n## Branch — the production run\n\nThe deliverable is one script in `scripts/` the user can re-run and edit. Adapted from\n`autogalaxy_workspace:scripts/imaging/start_here.py` (the fit and result sections) and\n`autogalaxy_workspace:scripts/imaging/modeling.py` (the Nautilus configuration and the VRAM\ncheck):\n\n```python\n\"\"\"\nGalaxy Structure: Run the Fit\n=============================\n\nFit a galaxy's surface-brightness profile to CCD imaging: load and mask the data, compose a\nlinear Sersic bulge, and sample the posterior with Nautilus so the inferred effective radius\nand Sersic index come with errors.\n\n__Contents__\n\n- **Imports:** JAX environment first, then the standard trio.\n- **Dataset:** Load imaging, mask it, and apply adaptive over-sampling.\n- **Model:** Compose the galaxy's light profile.\n- **Search:** Configure Nautilus and its update cadence.\n- **Analysis:** Bind the model to the data and choose the JAX backend.\n- **Model-Fit:** Run the search and announce the output folder.\n- **Result:** Read the best-fit model back.\n\"\"\"\nfrom autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\n\"\"\"\n__Dataset__\n\nGalaxy modeling needs three ingredients: the image in CCD counts, a per-pixel RMS noise-map,\nand the PSF. The PSF is forward-modelled rather than divided out, which is what separates a\ngenuinely compact bulge from a seeing-broadened one. `pixel_scales` converts pixels to\narcseconds and must match the instrument (`ag.Imaging.from_fits`,\n`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe mask sets which pixels enter the likelihood, and its radius is a science choice, not a\ndefault: truncate the outer isophotes and the effective radius and Sersic index are biased\ndirectly. Over-sampling evaluates the light profile several times per pixel where the\ngradient is steep, which matters most in the central few tenths of an arcsecond\n(`ag.util.over_sample.over_sample_size_via_radial_bins_from`).\n\"\"\"\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"\"\nMASK_RADIUS = 2.5\n\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n pixel_scales=0.1,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\n\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n\n\"\"\"\n__Model__\n\nA linear `Sersic` bulge: the `intensity` is solved by linear inversion each iteration rather\nthan sampled, so the search explores one fewer dimension per component for free\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Linear Light Profiles__`).\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\n\n\"\"\"\n__Search__\n\n`Nautilus` is nested sampling: it returns the full posterior — every parameter's density,\nits errors, and the correlations between them. `n_live` trades accuracy against run time and\n200 covers the vast majority of galaxy models. `unique_tag` is conventionally the dataset\nname, which is what keeps the same model fitted to different data in different folders\n(`PyAutoFit:autofit/non_linear/search/nest/nautilus/search.py`).\n\"\"\"\nsearch = af.Nautilus(\n path_prefix=Path(\"imaging\"),\n name=\"sersic\",\n unique_tag=\"\",\n n_live=200,\n iterations_per_quick_update=10000,\n live_visual_update=False,\n)\n\n\"\"\"\n__Analysis__\n\n`ag.AnalysisImaging` defines the `log_likelihood_function` the search calls, and defaults to\n`use_jax=True` when JAX is installed (`PyAutoGalaxy:autogalaxy/imaging/model/analysis.py`).\n\"\"\"\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\n\"\"\"\n__Model-Fit__\n\nResults are written to the output folder on the fly, from the best model found so far, so the\nfolder is worth opening the moment the search starts.\n\"\"\"\nprint(f\"Output folder: {search.paths.output_path.resolve()}\")\n\nresult = search.fit(model=model, analysis=analysis)\n\n\"\"\"\n__Result__\n\"\"\"\nprint(result.info)\nprint(result.max_log_likelihood_instance)\n```\n\nRun it with writable caches if the default locations are not writable — a sandbox, CI, or an\ninstall imported from a Windows mount under WSL\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)):\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\n`search.fit` itself is `PyAutoFit:autofit/non_linear/search/abstract_search.py`.\n\n## Branch — what the output folder contains, and when to look\n\n**Announce the folder at launch, not at the end.** Quote\n`search.paths.output_path.resolve()` once the fit is running and say plainly that\n`model.results` and `image/fit.png` refresh as the search goes — there is nothing to wait\nfor. Users new to the stack sit watching a silent terminal because nobody told them.\n\nThe annotated tree of `files/`, `image/`, `model.info`, `model.results`, `search.summary`\nand the `` folder is `__Output Folder Layout__` in\n[`autogalaxy_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/modeling.py);\nthe same section appears in the `interferometer`, `multi_dataset`, `multi_galaxy` and\n`cluster` `modeling.py` scripts. Link it rather than copying the tree into the conversation,\nwhere it would rot. The condensed version is also in\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n\"The output folder\".\n\nName what to open first, in this order:\n\n1. `model.results` — the human-readable fit summary, parameters with errors.\n2. `image/fit.png` — data, model image, residuals and chi-squared map in one figure.\n3. `search.log` — tail it if you want to watch progress from a terminal.\n\nDepth follows [`_style.md`](./_style.md) \"Adaptive depth\": for a newcomer, or in teacher\nmode, walk all three. For a returning user, quoting the path is enough.\n\n## Branch — resuming, and the trap inside it\n\n`` is derived from the model, the search settings and the dataset identifier, so\nre-running an identical configuration **resumes** the existing fit rather than restarting it\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Unique Identifier__`). That is a\nfeature — an interrupted overnight run picks up where it stopped.\n\nIt is also the sharpest edge in the workflow. **The identifier does not hash the pixel\nvalues of your data.** Swap `data.fits` for a different galaxy, keep the model, the search\nand the `unique_tag` identical, and the next run finds a completed fit at the same path and\nreturns it — silently, in seconds, with the previous galaxy's parameters. If the data\nchanges, change the `unique_tag`. If you are unsure whether a result is stale, delete the\n`` folder and re-run rather than reasoning about it.\n\nTest mode namespaces its output separately: any active `PYAUTO_TEST_MODE` level inserts a\n`test_mode` segment straight after the output root, so a smoke run lands in\n`output/test_mode//...` and cannot short-circuit a later real fit\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## Branch — the update cadence and the live view\n\nTwo settings control what you see while the fit runs, both on the search\n(`PyAutoFit:autofit/non_linear/search/abstract_search.py`):\n\n- **`iterations_per_quick_update`** — how often the current best model is visualised and\n written to disk. The unit depends on the search: likelihood evaluations for `Nautilus`\n (hence the large `10000` in `modeling.py`), gradient steps for `MultiStartProdigy` (hence\n the much smaller `50` in `start_here.py`). Each update costs roughly ten seconds, so too\n low a value and output dominates the run time; too high and you cannot see progress. If\n the log is constantly reporting that it is outputting results, raise it.\n- **`live_visual_update`** — additionally push the quick-update image to a live surface: a\n matplotlib window that refreshes in a plain script, or a self-updating cell in Jupyter and\n Colab. The `fit.png` disk write happens either way. Leave it `False` on anything headless\n — an HPC node, a background process, CI.\n\nIf the search configuration already records the choice, don't re-ask; that decision belongs\nto [`ag_configure_search`](./ag_configure_search.md).\n\n## Branch — JAX, GPUs, and when the acceleration pays\n\nImaging fits run through JAX by default. Installing the extra (`pip install autogalaxy[jax]`)\nis all that is required: `ag.AnalysisImaging` then defaults to `use_jax=True`, and the search\ndriver wraps the likelihood in `jax.vmap(jax.jit(...))` so a whole batch of parameter vectors\nevaluates in one call. You will see a one-time log line as the JIT compile starts; every\nevaluation after that re-uses the compiled trace. This is described in\n`autogalaxy_workspace:scripts/guides/using_jax.py` `__Auto-Enabled Modeling__`, and if JAX is\nabsent the analysis warns once and falls back to NumPy.\n\n**When it pays.** The gain scales with how much array work each likelihood evaluation does,\nso it is largest for big masks, fine over-sampling, many-component bases and pixelised\nreconstructions, and smallest for a tiny mask with one smooth profile. GPU gains dwarf CPU\ngains: `autogalaxy_workspace:scripts/imaging/modeling.py` `__JAX__` quotes roughly ten\nminutes on a GPU against an hour on a CPU for its example, with a CPU still gaining from\nmultithreading. Gradient-based searches like `MultiStartProdigy` are not merely faster under\nJAX — they are only possible with it, because JAX is what supplies the likelihood's\nderivatives and evaluates all the parallel starts in one batched call\n(`autogalaxy_workspace:scripts/imaging/start_here.py` `__Multi Start Gradient Optimization__`).\n\n**Check VRAM before a long GPU run.** A JAX fit must fit inside the GPU's memory, and it\nfails at JIT-compile time or on the first likelihood call if it does not:\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py` `__VRAM Use__`. It takes\ntwenty or thirty seconds, so comment it out once you know your model's footprint. Batch size\nis the lever: larger batches cut wall-clock time and raise VRAM, smaller batches the reverse.\nA smooth-profile fit on a modest dataset is tens of megabytes; a pixelised reconstruction on\nhigh-resolution data can exceed ten gigabytes.\n\n**Turn JAX off to debug.** `ag.AnalysisImaging(dataset=dataset, use_jax=False)`, or\n`PYAUTO_DISABLE_JAX=1` to force it globally without editing code. NumPy stack traces are far\neasier to read, and you can drop a debugger or a `print` into code JAX would otherwise\ncompile. That is the first lever to pull when deciding whether a failure is a JAX problem at\nall — see [`ag_debug_fit_failure`](./ag_debug_fit_failure.md).\n\nFor running on a cluster — SLURM array jobs, one galaxy per task, the CPU and GPU batch\nscripts, and `number_of_cores` read from `SLURM_CPUS_PER_TASK` — read\n[`../wiki/core/operations/hpc.md`](../wiki/core/operations/hpc.md) for the concepts and\n[`../wiki/core/operations/hpc_infrastructure.md`](../wiki/core/operations/hpc_infrastructure.md)\nfor the `hpc/` templates and `sync` CLI this repo ships; the upstream ground truth behind both\nis `autogalaxy_workspace:scripts/guides/hpc/example_cpu_and_gpu.py`. The Python modeling code\nis identical for a GPU run; only the batch script changes.\n\n## Branch — the smoke test, before you spend hours\n\nEvery script gets one fast structural run before a real one. `PYAUTO_TEST_MODE` has four\nlevels ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)), and the\nchoice between them matters more than it looks:\n\n```bash\n# Level 1 — sampler runs with minimal iterations. A real (tiny) search: writes\n# model.results, image/fit.png and a samples.csv you can load back.\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n\n# Level 2 — sampler bypassed, likelihood called exactly once. The fastest proof that\n# the model composes and the likelihood evaluates.\nPYAUTO_TEST_MODE=2 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\n**Level 2 does not write the fit products.** A level-2 run returns a `Result`, proving the\nwiring, but leaves no `model.results` and no `image/fit.png` behind — so if the next thing\nyou want to do is plot or load the fit, use level 1. Level 3 skips the likelihood call as\nwell, which is only useful for checking that a script's non-fitting scaffolding runs.\n\n**The parameter values from any test-mode run are meaningless.** The sampler was truncated or\nmocked. Never quote a structural parameter measured in test mode; say explicitly that the\nnumber is a wiring check.\n\nFor the fastest possible loop, combine test mode with the dataset and output short-circuits:\n\n```bash\nPYAUTO_TEST_MODE=2 PYAUTO_SKIP_FIT_OUTPUT=1 PYAUTO_SKIP_VISUALIZATION=1 \\\n PYAUTO_SMALL_DATASETS=1 PYAUTO_FAST_PLOTS=1 python scripts/run_fit.py\n```\n\n`PYAUTO_SMALL_DATASETS=1` caps every array, mask and grid to 16 × 16 pixels — so delete any\npreviously simulated `dataset/` when you toggle it, or a full-resolution dataset on disk will\nbe reused and mismatch the capped grids.\n\n## Branch — the error that appears the moment the search starts\n\nOn some combinations of operating system and Python version, a script raises as soon as the\nsearch begins, from Python's process spawning rather than from anything about your model. The\nfix is to wrap the whole fit in a function and call it under a main guard:\n\n```python\ndef fit():\n from autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\n import autofit as af\n import autogalaxy as ag\n\n # ... dataset, model, search, analysis as above ...\n result = search.fit(model=model, analysis=analysis)\n\n\nif __name__ == \"__main__\":\n fit()\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/modeling/bug_fix.py`, which is the same\n`modeling.py` fit with this one structural change. It works for every dataset type, so adopt\nit for any modeling script that hits the error. If parallelisation still will not work after\nthe fix, that script points at the project's support channel.\n\n## Combine\n\n- [`ag_plot_fit`](./ag_plot_fit.md) — render the fit yourself, at whatever scaling and\n cropping the science needs, rather than reading the auto-generated `image/fit.png`.\n- [`ag_load_results`](./ag_load_results.md) — pull the posterior, the best-fit galaxies and\n the derived quantities back into Python, in-session or from disk later.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) — the fit finished but the residuals or\n the parameters are wrong.\n- [`ag_configure_search`](./ag_configure_search.md) — the fit is too slow, or the sampler is\n the wrong one for the model.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) — build a controlled dataset with known\n truth and fit that first, which is the cleanest way to separate a model problem from a\n data problem.\n\nWhen the script and its fit are worth keeping, offer (default-yes) to record the run in a\ndated `wiki/project/YYYY-MM-DD-.md` entry: the science question, what was inferred and\nwith what search, and the output path — per [`_style.md`](./_style.md) property #5.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Practicalities](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running a fit — output structure, reviewing results as they appear,\n and managing run times.\n- **General reference** — [RTD: New user guide](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n the decision tree for which fit to run first, by system scale and dataset type.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit, with the JAX and quick-update sections this skill\n mirrors.\n\n## Agent procedural checklist\n\n1. Confirm `model`, `analysis` and `search` exist; if not, route to the model-building and\n search-configuration skills.\n2. On real observational data, confirm the inspection gate has been satisfied.\n3. Write the script to `scripts/` in the generated-script style; never leave it inline only.\n4. Validate it with `PYAUTO_TEST_MODE=1` (level 2 if you only need the likelihood proved),\n with the cache variables set if the environment needs them.\n5. Launch the production run; **quote the absolute output path immediately** and say results\n refresh on the fly.\n6. Name `model.results` and `image/fit.png` as the first two things to open.\n7. If the data changed but the model did not, confirm the `unique_tag` changed too.\n8. On a GPU, run the VRAM check before a long fit.\n9. On completion, hand off to the results-loading or fit-plotting skill rather than\n interpreting the numbers inline.\n10. Offer the `wiki/project/` entry.\n" } }, "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" diff --git a/notebooks/chapter_2_modeling/tutorial_3_realism_and_complexity.ipynb b/notebooks/chapter_2_modeling/tutorial_3_realism_and_complexity.ipynb deleted file mode 100644 index fa3a415..0000000 --- a/notebooks/chapter_2_modeling/tutorial_3_realism_and_complexity.ipynb +++ /dev/null @@ -1,464 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 3: Realism and Complexity\n", - "==================================\n", - "\n", - "In the previous two tutorials, we fitted a fairly basic model: the galaxy's light was a single bulge component.\n", - "In real observations we know that galaxies are observed to have multiple different morphological structures.\n", - "\n", - "In this tutorial, we'll use a more realistic model, which consists of the following light profiles:\n", - "\n", - " - A `Sersic` light profile for the galaxy's bulge [7 parameters].\n", - " - An `Exponential` light profile for the galaxy's disk [6 parameters]\n", - "\n", - "This model has 13 free parameters, meaning that the parameter space and likelihood function it defines has a\n", - "dimensionality of N=13. This is over double the number of parameters and dimensions of the models we fitted in the\n", - "previous tutorials and in future exercises, we will fit even more complex models with some 13+ parameters.\n", - "\n", - "Therefore, take note, as we make our model more realistic, we also make its parameter space more complex, this is\n", - "an important concept to keep in mind for the remainder of this chapter!\n", - "\n", - "__Contents__\n", - "\n", - "- **Initial Setup:** Load the dataset and apply a mask.\n", - "- **Model + Search + Analysis:** Compose a bulge+disk model and fit it using Nautilus.\n", - "- **Result:** Inspect the result and compare to the true model.\n", - "- **Global and Local Maxima:** Demonstrate how the search can infer incorrect local maxima solutions.\n", - "- **Wrap Up:** Summary of the challenges of fitting more complex and realistic models." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Google Colab Setup__\n", - "\n", - "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "jupyter": { - "source_hidden": true - } - }, - "outputs": [], - "source": [ - "# @title Set up Google Colab { display-mode: \"form\" }\n", - "try:\n", - " import google.colab\n", - "except ImportError:\n", - " from autogalaxy import setup_colab as _setup_colab\n", - "else:\n", - " import importlib\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.check_call(\n", - " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", - " )\n", - " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", - "\n", - "_setup_colab.setup(\"howtogalaxy\")" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autogalaxy import setup_notebook; setup_notebook()\n", - "\n", - "from pathlib import Path\n", - "import autogalaxy as ag\n", - "import autogalaxy.plot as aplt\n", - "import autofit as af" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Initial Setup__\n", - "\n", - "we'll use new imaging data of a galaxy, where:\n", - "\n", - " - The galaxy's bulge is a `Sersic`.\n", - " - The galaxy's disk is an `Exponential`." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "dataset_name = \"simple\"\n", - "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Dataset Auto-Simulation__\n", - "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "if ag.util.dataset.should_simulate(str(dataset_path)):\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulators/simple.py\"],\n", - " check=True,\n", - " )\n", - "\n", - "\n", - "dataset = ag.Imaging.from_fits(\n", - " data_path=dataset_path / \"data.fits\",\n", - " noise_map_path=dataset_path / \"noise_map.fits\",\n", - " psf_path=dataset_path / \"psf.fits\",\n", - " pixel_scales=0.1,\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Mask__\n", - "\n", - "We'll create and use a 2.5\" `Mask2D`, which is slightly smaller than the masks we used in previous tutorials." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mask = ag.Mask2D.circular(\n", - " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5\n", - ")\n", - "\n", - "dataset = dataset.apply_mask(mask=mask)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Over Sampling__\n", - "\n", - "Apply adaptive over sampling to ensure the calculation is accurate, you can read up on over-sampling in more detail via \n", - "the `autogalaxy_workspace/*/guides/advanced/over_sampling.ipynb` notebook." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n", - " grid=dataset.grid,\n", - " sub_size_list=[8, 4, 2],\n", - " radial_list=[0.3, 0.6],\n", - " centre_list=[(0.0, 0.0)],\n", - ")\n", - "\n", - "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "When plotted, the galaxy's bulge and disk are clearly visible in the centre of the image." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_imaging_dataset(dataset=dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Model + Search + Analysis__\n", - "\n", - "Now lets fit the dataset using a search." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "model = af.Collection(\n", - " galaxies=af.Collection(\n", - " galaxy=af.Model(\n", - " ag.Galaxy, redshift=0.5, bulge=ag.lp.Sersic, disk=ag.lp.Exponential\n", - " )\n", - " )\n", - ")\n", - "\n", - "search = af.Nautilus(\n", - " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", - " name=\"tutorial_3_realism_and_complexity\",\n", - " unique_tag=dataset_name,\n", - " n_live=100,\n", - " n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2.\n", - ")\n", - "\n", - "analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", - "\n", - "print(\n", - " \"The non-linear search has begun running - checkout the HowToGalaxy/output/howtogalaxy/chapter_2/tutorial_3_realism_and_complexity\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell will progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", - "result = search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"Search has finished run - you may now continue the notebook.\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Result__\n", - "\n", - "Inspection of the `info` summary of the result suggests the model has gone to reasonable values." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And lets look at how well the model fits the imaging data, which as we are used to fits the data brilliantly!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Global and Local Maxima__\n", - "\n", - "Up to now, all of our non-linear searches have been successes. They find a model that provides a visibly good fit\n", - "to the data, minimizing the residuals and inferring a high log likelihood value. \n", - "\n", - "These solutions are called 'global maxima', they correspond to the highest likelihood regions over all of parameter \n", - "space. There are no other models in parameter space that would give higher likelihoods, this is the model we want \n", - "to always infer!\n", - "\n", - "However, non-linear searches may not always successfully locate the global maxima models. They may instead infer \n", - "a 'local maxima', a solution which has a high log likelihood value relative to the models near it in parameter \n", - "space, but where the log likelihood is significantly below the global maxima solution located somewhere else in \n", - "parameter space. \n", - "\n", - "Why does a non-linear search infer these local maxima solutions? As discussed previously, the search guesses many \n", - "models over and over, guessing more models in regions of parameter space where previous guesses gave the highest \n", - "likelihood solutions. The search gradually 'converges' around any solution that gives a higher likelihood than the \n", - "models nearby it in parameter space. If the search is not thorough enough, it may converge around a solution that \n", - "appears to give a high likelihood (compared to the models around it) but, as discussed, is only a local maxima over \n", - "all of parameter space.\n", - "\n", - "Inferring such solutions is essentially a failure of our non-linear search and it is something we do not want to\n", - "happen! Lets infer a local maxima, by reducing the number of live points, `n_live`, nautilus uses to map out \n", - "parameter space. We are going to use so few that the initial search over parameter space has an extremely low \n", - "probability of getting close the global maxima, meaning it converges on a local maxima. " - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search = af.Nautilus(\n", - " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", - " name=\"tutorial_3_realism_and_complexity__local_maxima\",\n", - " unique_tag=dataset_name,\n", - " n_live=50,\n", - " n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2.\n", - ")\n", - "\n", - "print(\n", - " \"The non-linear search has begun running - checkout the HowToGalaxy/output/howtogalaxy/chapter_2/tutorial_3_realism_and_complexity__local_maxima\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell will progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", - "result_local_maxima = search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"Search has finished run - you may now continue the notebook.\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Result__\n", - "\n", - "Inspection of the `info` summary of the result suggests certain parameters have gone to different values to the fit\n", - "performed above." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result_local_maxima.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Lets look at the fit to the `Imaging` data, which is clearly worse than our original fit above." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_fit_imaging(fit=result_local_maxima.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Finally, just to be sure we hit a local maxima, lets compare the maximum log likelihood values of the two results \n", - "\n", - "The local maxima value is significantly lower, confirming that our non-linear search simply failed to locate galaxy\n", - "models which fit the data better when it searched parameter space." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(\"Likelihood of Global Model:\")\n", - "print(result.max_log_likelihood_fit.log_likelihood)\n", - "print(\"Likelihood of Local Model:\")\n", - "print(result_local_maxima.max_log_likelihood_fit.log_likelihood)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Wrap Up__\n", - "\n", - "In this example, we intentionally made our non-linear search fail, by using so few live points it had no hope of \n", - "sampling parameter space thoroughly. For modeling real galaxies we wouldn't do this intentionally, but the risk of \n", - "inferring a local maxima is still very real, especially as we make our model more complex.\n", - "\n", - "Lets think about *complexity*. As we make our model more realistic, we also made it more complex. For this \n", - "tutorial, our non-linear parameter space went from 6 dimensions to 13. This means there was a much larger *volume* of\n", - "parameter space to search. As this volume grows, there becomes a higher chance that our non-linear search gets lost \n", - "and infers a local maxima, especially if we don't set it up with enough live points!\n", - "\n", - "At its core, modeling is all about learning how to get a non-linear search to find the global maxima region of \n", - "parameter space, even when the model is complex. This will be the main theme throughout the rest of this chapter,\n", - "culminating in the 'search chaining' technique that closes it.\n", - "\n", - "In the next exercise, we'll learn how to deal with failure and begin thinking about how we can ensure our non-linear \n", - "search finds the global-maximum log likelihood solution. First, think about the following:\n", - "\n", - " 1) When you look at an image of a galaxy, do you get a sense of roughly what values certain model \n", - " parameters are?\n", - " \n", - " 2) The non-linear search failed because parameter space was too complex. Could we make it less complex, whilst \n", - " still keeping our model fairly realistic?\n", - " \n", - " 3) The galaxy in this example had only 13 non-linear parameters. Real galaxies may have multiple components (e.g. a\n", - " disk, bulge, bar, star-forming knot) and there may even be more than 1 galaxy! Do you think there is any hope of\n", - " us navigating a parameter space if the galaxies contribute 30+ parameters?" - ] - } - ], - "metadata": { - "anaconda-cloud": {}, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - }, - "colab": { - "aiContexts": { - "24c2f562-da24-50bb-8eb9-5a887505fe54": { - "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", - "name": "PyAutoGalaxy assistant", - "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_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\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_2_modeling/tutorial_3_realism_and_complexity.ipynb in HowToGalaxy).\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 PyAutoGalaxy 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 PyAutoGalaxy docs (https://pyautogalaxy.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) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. 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 galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_run_search\n\n---\nname: ag_run_search\ndescription: Run the fit — take a composed model, an analysis and a configured search and drive `search.fit(model=model, analysis=analysis)` to completion, then read what it wrote. Covers the output-folder anatomy and the on-the-fly announcement, the unique-identifier resume behaviour and when it silently reuses a stale fit, `iterations_per_quick_update` and `live_visual_update`, JAX/GPU acceleration and when it actually pays, VRAM checks before a long GPU run, the `PYAUTO_TEST_MODE` smoke levels, and the `if __name__ == \"__main__\"` parallelisation fix. Use once `ag_build_imaging_model` and `ag_configure_search` have produced `model`, `analysis` and `search` objects, or when a fit is running and the user wants to know what to watch. Not for composing the model or choosing the search (those two skills), not for interpreting the finished posterior (`ag_load_results`), and not for diagnosing a fit that ran but converged somewhere unphysical (`ag_debug_fit_failure`).\n---\n\n# Running the fit\n\nThis is the moment the inference actually happens. Everything before it was preparation:\na `model` says which morphological parameters are free and what priors they carry, an\n`analysis` binds that model to one dataset and knows how to turn a parameter vector into a\nlog likelihood, and a `search` knows how to explore the parameter space. One call joins\nthem:\n\n```python\nresult = search.fit(model=model, analysis=analysis)\n```\n\nStatistically, that call is sampling (or optimising) the posterior\n$P(\\theta | d) \\propto \\mathcal{L}(d | \\theta) P(\\theta)$, where the likelihood is the\nGaussian-noise chi-squared of the PSF-convolved model image against the data — walked\nline by line in `autogalaxy_workspace:scripts/imaging/likelihood_function.py`. Scientifically,\nit is where a Sersic index, an effective radius or a bulge-to-total ratio stops being a guess\nand becomes a measurement with errors. What this skill adds is everything *around* the call:\nhow to watch it, how long to expect, how to make it fast, and how to prove the script works\nbefore committing hours to it.\n\nTwo wiki pages carry the background this skill assumes. Read\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md) for\nwhat each sampler does and how run time scales with the model, and\n[`wiki/core/api/analysis_objects.md`](../wiki/core/api/analysis_objects.md) for what the\nreturned `Result` contains.\n\n## Ask\n\nThree questions, and the answers change the branch:\n\n- *\"Do you already have `model`, `analysis` and `search`?\"* If not, route to\n [`ag_build_imaging_model`](./ag_build_imaging_model.md) and\n [`ag_configure_search`](./ag_configure_search.md) first. A fit assembled from a\n half-remembered model is the most expensive mistake available here.\n- *\"Smoke test first, or straight to the production run?\"* Almost always smoke test first —\n it takes seconds and answers \"does this script execute end to end?\", which is a different\n question from \"is this galaxy's Sersic index 3.2?\". The smoke branch is below.\n- *\"How long can this run, and on what?\"* A `MultiStartProdigy` fit is minutes; a `Nautilus`\n fit of a smooth model is tens of minutes on a GPU and can be hours on a CPU; a pixelised\n fit can be far longer. That answer decides foreground vs background, laptop vs cluster,\n and whether `live_visual_update` is worth switching on.\n\nIf the data is real observational imaging, the inspection gate in\n[`../AGENTS.md`](../AGENTS.md) applies before you get here at all — contaminants and mask\nextent are settled in [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md), not\nretrospectively.\n\n## Branch — the production run\n\nThe deliverable is one script in `scripts/` the user can re-run and edit. Adapted from\n`autogalaxy_workspace:scripts/imaging/start_here.py` (the fit and result sections) and\n`autogalaxy_workspace:scripts/imaging/modeling.py` (the Nautilus configuration and the VRAM\ncheck):\n\n```python\n\"\"\"\nGalaxy Structure: Run the Fit\n=============================\n\nFit a galaxy's surface-brightness profile to CCD imaging: load and mask the data, compose a\nlinear Sersic bulge, and sample the posterior with Nautilus so the inferred effective radius\nand Sersic index come with errors.\n\n__Contents__\n\n- **Imports:** JAX environment first, then the standard trio.\n- **Dataset:** Load imaging, mask it, and apply adaptive over-sampling.\n- **Model:** Compose the galaxy's light profile.\n- **Search:** Configure Nautilus and its update cadence.\n- **Analysis:** Bind the model to the data and choose the JAX backend.\n- **Model-Fit:** Run the search and announce the output folder.\n- **Result:** Read the best-fit model back.\n\"\"\"\nfrom autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\n\"\"\"\n__Dataset__\n\nGalaxy modeling needs three ingredients: the image in CCD counts, a per-pixel RMS noise-map,\nand the PSF. The PSF is forward-modelled rather than divided out, which is what separates a\ngenuinely compact bulge from a seeing-broadened one. `pixel_scales` converts pixels to\narcseconds and must match the instrument (`ag.Imaging.from_fits`,\n`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe mask sets which pixels enter the likelihood, and its radius is a science choice, not a\ndefault: truncate the outer isophotes and the effective radius and Sersic index are biased\ndirectly. Over-sampling evaluates the light profile several times per pixel where the\ngradient is steep, which matters most in the central few tenths of an arcsecond\n(`ag.util.over_sample.over_sample_size_via_radial_bins_from`).\n\"\"\"\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"\"\nMASK_RADIUS = 2.5\n\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n pixel_scales=0.1,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\n\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n\n\"\"\"\n__Model__\n\nA linear `Sersic` bulge: the `intensity` is solved by linear inversion each iteration rather\nthan sampled, so the search explores one fewer dimension per component for free\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Linear Light Profiles__`).\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\n\n\"\"\"\n__Search__\n\n`Nautilus` is nested sampling: it returns the full posterior — every parameter's density,\nits errors, and the correlations between them. `n_live` trades accuracy against run time and\n200 covers the vast majority of galaxy models. `unique_tag` is conventionally the dataset\nname, which is what keeps the same model fitted to different data in different folders\n(`PyAutoFit:autofit/non_linear/search/nest/nautilus/search.py`).\n\"\"\"\nsearch = af.Nautilus(\n path_prefix=Path(\"imaging\"),\n name=\"sersic\",\n unique_tag=\"\",\n n_live=200,\n iterations_per_quick_update=10000,\n live_visual_update=False,\n)\n\n\"\"\"\n__Analysis__\n\n`ag.AnalysisImaging` defines the `log_likelihood_function` the search calls, and defaults to\n`use_jax=True` when JAX is installed (`PyAutoGalaxy:autogalaxy/imaging/model/analysis.py`).\n\"\"\"\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\n\"\"\"\n__Model-Fit__\n\nResults are written to the output folder on the fly, from the best model found so far, so the\nfolder is worth opening the moment the search starts.\n\"\"\"\nprint(f\"Output folder: {search.paths.output_path.resolve()}\")\n\nresult = search.fit(model=model, analysis=analysis)\n\n\"\"\"\n__Result__\n\"\"\"\nprint(result.info)\nprint(result.max_log_likelihood_instance)\n```\n\nRun it with writable caches if the default locations are not writable — a sandbox, CI, or an\ninstall imported from a Windows mount under WSL\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)):\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\n`search.fit` itself is `PyAutoFit:autofit/non_linear/search/abstract_search.py`.\n\n## Branch — what the output folder contains, and when to look\n\n**Announce the folder at launch, not at the end.** Quote\n`search.paths.output_path.resolve()` once the fit is running and say plainly that\n`model.results` and `image/fit.png` refresh as the search goes — there is nothing to wait\nfor. Users new to the stack sit watching a silent terminal because nobody told them.\n\nThe annotated tree of `files/`, `image/`, `model.info`, `model.results`, `search.summary`\nand the `` folder is `__Output Folder Layout__` in\n[`autogalaxy_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/modeling.py);\nthe same section appears in the `interferometer`, `multi_dataset`, `multi_galaxy` and\n`cluster` `modeling.py` scripts. Link it rather than copying the tree into the conversation,\nwhere it would rot. The condensed version is also in\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n\"The output folder\".\n\nName what to open first, in this order:\n\n1. `model.results` — the human-readable fit summary, parameters with errors.\n2. `image/fit.png` — data, model image, residuals and chi-squared map in one figure.\n3. `search.log` — tail it if you want to watch progress from a terminal.\n\nDepth follows [`_style.md`](./_style.md) \"Adaptive depth\": for a newcomer, or in teacher\nmode, walk all three. For a returning user, quoting the path is enough.\n\n## Branch — resuming, and the trap inside it\n\n`` is derived from the model, the search settings and the dataset identifier, so\nre-running an identical configuration **resumes** the existing fit rather than restarting it\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Unique Identifier__`). That is a\nfeature — an interrupted overnight run picks up where it stopped.\n\nIt is also the sharpest edge in the workflow. **The identifier does not hash the pixel\nvalues of your data.** Swap `data.fits` for a different galaxy, keep the model, the search\nand the `unique_tag` identical, and the next run finds a completed fit at the same path and\nreturns it — silently, in seconds, with the previous galaxy's parameters. If the data\nchanges, change the `unique_tag`. If you are unsure whether a result is stale, delete the\n`` folder and re-run rather than reasoning about it.\n\nTest mode namespaces its output separately: any active `PYAUTO_TEST_MODE` level inserts a\n`test_mode` segment straight after the output root, so a smoke run lands in\n`output/test_mode//...` and cannot short-circuit a later real fit\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## Branch — the update cadence and the live view\n\nTwo settings control what you see while the fit runs, both on the search\n(`PyAutoFit:autofit/non_linear/search/abstract_search.py`):\n\n- **`iterations_per_quick_update`** — how often the current best model is visualised and\n written to disk. The unit depends on the search: likelihood evaluations for `Nautilus`\n (hence the large `10000` in `modeling.py`), gradient steps for `MultiStartProdigy` (hence\n the much smaller `50` in `start_here.py`). Each update costs roughly ten seconds, so too\n low a value and output dominates the run time; too high and you cannot see progress. If\n the log is constantly reporting that it is outputting results, raise it.\n- **`live_visual_update`** — additionally push the quick-update image to a live surface: a\n matplotlib window that refreshes in a plain script, or a self-updating cell in Jupyter and\n Colab. The `fit.png` disk write happens either way. Leave it `False` on anything headless\n — an HPC node, a background process, CI.\n\nIf the search configuration already records the choice, don't re-ask; that decision belongs\nto [`ag_configure_search`](./ag_configure_search.md).\n\n## Branch — JAX, GPUs, and when the acceleration pays\n\nImaging fits run through JAX by default. Installing the extra (`pip install autogalaxy[jax]`)\nis all that is required: `ag.AnalysisImaging` then defaults to `use_jax=True`, and the search\ndriver wraps the likelihood in `jax.vmap(jax.jit(...))` so a whole batch of parameter vectors\nevaluates in one call. You will see a one-time log line as the JIT compile starts; every\nevaluation after that re-uses the compiled trace. This is described in\n`autogalaxy_workspace:scripts/guides/using_jax.py` `__Auto-Enabled Modeling__`, and if JAX is\nabsent the analysis warns once and falls back to NumPy.\n\n**When it pays.** The gain scales with how much array work each likelihood evaluation does,\nso it is largest for big masks, fine over-sampling, many-component bases and pixelised\nreconstructions, and smallest for a tiny mask with one smooth profile. GPU gains dwarf CPU\ngains: `autogalaxy_workspace:scripts/imaging/modeling.py` `__JAX__` quotes roughly ten\nminutes on a GPU against an hour on a CPU for its example, with a CPU still gaining from\nmultithreading. Gradient-based searches like `MultiStartProdigy` are not merely faster under\nJAX — they are only possible with it, because JAX is what supplies the likelihood's\nderivatives and evaluates all the parallel starts in one batched call\n(`autogalaxy_workspace:scripts/imaging/start_here.py` `__Multi Start Gradient Optimization__`).\n\n**Check VRAM before a long GPU run.** A JAX fit must fit inside the GPU's memory, and it\nfails at JIT-compile time or on the first likelihood call if it does not:\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py` `__VRAM Use__`. It takes\ntwenty or thirty seconds, so comment it out once you know your model's footprint. Batch size\nis the lever: larger batches cut wall-clock time and raise VRAM, smaller batches the reverse.\nA smooth-profile fit on a modest dataset is tens of megabytes; a pixelised reconstruction on\nhigh-resolution data can exceed ten gigabytes.\n\n**Turn JAX off to debug.** `ag.AnalysisImaging(dataset=dataset, use_jax=False)`, or\n`PYAUTO_DISABLE_JAX=1` to force it globally without editing code. NumPy stack traces are far\neasier to read, and you can drop a debugger or a `print` into code JAX would otherwise\ncompile. That is the first lever to pull when deciding whether a failure is a JAX problem at\nall — see [`ag_debug_fit_failure`](./ag_debug_fit_failure.md).\n\nFor running on a cluster — SLURM array jobs, one galaxy per task, the CPU and GPU batch\nscripts, and `number_of_cores` read from `SLURM_CPUS_PER_TASK` — read\n[`../wiki/core/operations/hpc.md`](../wiki/core/operations/hpc.md) for the concepts and\n[`../wiki/core/operations/hpc_infrastructure.md`](../wiki/core/operations/hpc_infrastructure.md)\nfor the `hpc/` templates and `sync` CLI this repo ships; the upstream ground truth behind both\nis `autogalaxy_workspace:scripts/guides/hpc/example_cpu_and_gpu.py`. The Python modeling code\nis identical for a GPU run; only the batch script changes.\n\n## Branch — the smoke test, before you spend hours\n\nEvery script gets one fast structural run before a real one. `PYAUTO_TEST_MODE` has four\nlevels ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)), and the\nchoice between them matters more than it looks:\n\n```bash\n# Level 1 — sampler runs with minimal iterations. A real (tiny) search: writes\n# model.results, image/fit.png and a samples.csv you can load back.\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n\n# Level 2 — sampler bypassed, likelihood called exactly once. The fastest proof that\n# the model composes and the likelihood evaluates.\nPYAUTO_TEST_MODE=2 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\n**Level 2 does not write the fit products.** A level-2 run returns a `Result`, proving the\nwiring, but leaves no `model.results` and no `image/fit.png` behind — so if the next thing\nyou want to do is plot or load the fit, use level 1. Level 3 skips the likelihood call as\nwell, which is only useful for checking that a script's non-fitting scaffolding runs.\n\n**The parameter values from any test-mode run are meaningless.** The sampler was truncated or\nmocked. Never quote a structural parameter measured in test mode; say explicitly that the\nnumber is a wiring check.\n\nFor the fastest possible loop, combine test mode with the dataset and output short-circuits:\n\n```bash\nPYAUTO_TEST_MODE=2 PYAUTO_SKIP_FIT_OUTPUT=1 PYAUTO_SKIP_VISUALIZATION=1 \\\n PYAUTO_SMALL_DATASETS=1 PYAUTO_FAST_PLOTS=1 python scripts/run_fit.py\n```\n\n`PYAUTO_SMALL_DATASETS=1` caps every array, mask and grid to 16 × 16 pixels — so delete any\npreviously simulated `dataset/` when you toggle it, or a full-resolution dataset on disk will\nbe reused and mismatch the capped grids.\n\n## Branch — the error that appears the moment the search starts\n\nOn some combinations of operating system and Python version, a script raises as soon as the\nsearch begins, from Python's process spawning rather than from anything about your model. The\nfix is to wrap the whole fit in a function and call it under a main guard:\n\n```python\ndef fit():\n from autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\n import autofit as af\n import autogalaxy as ag\n\n # ... dataset, model, search, analysis as above ...\n result = search.fit(model=model, analysis=analysis)\n\n\nif __name__ == \"__main__\":\n fit()\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/modeling/bug_fix.py`, which is the same\n`modeling.py` fit with this one structural change. It works for every dataset type, so adopt\nit for any modeling script that hits the error. If parallelisation still will not work after\nthe fix, that script points at the project's support channel.\n\n## Combine\n\n- [`ag_plot_fit`](./ag_plot_fit.md) — render the fit yourself, at whatever scaling and\n cropping the science needs, rather than reading the auto-generated `image/fit.png`.\n- [`ag_load_results`](./ag_load_results.md) — pull the posterior, the best-fit galaxies and\n the derived quantities back into Python, in-session or from disk later.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) — the fit finished but the residuals or\n the parameters are wrong.\n- [`ag_configure_search`](./ag_configure_search.md) — the fit is too slow, or the sampler is\n the wrong one for the model.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) — build a controlled dataset with known\n truth and fit that first, which is the cleanest way to separate a model problem from a\n data problem.\n\nWhen the script and its fit are worth keeping, offer (default-yes) to record the run in a\ndated `wiki/project/YYYY-MM-DD-.md` entry: the science question, what was inferred and\nwith what search, and the output path — per [`_style.md`](./_style.md) property #5.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Practicalities](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running a fit — output structure, reviewing results as they appear,\n and managing run times.\n- **General reference** — [RTD: New user guide](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n the decision tree for which fit to run first, by system scale and dataset type.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit, with the JAX and quick-update sections this skill\n mirrors.\n\n## Agent procedural checklist\n\n1. Confirm `model`, `analysis` and `search` exist; if not, route to the model-building and\n search-configuration skills.\n2. On real observational data, confirm the inspection gate has been satisfied.\n3. Write the script to `scripts/` in the generated-script style; never leave it inline only.\n4. Validate it with `PYAUTO_TEST_MODE=1` (level 2 if you only need the likelihood proved),\n with the cache variables set if the environment needs them.\n5. Launch the production run; **quote the absolute output path immediately** and say results\n refresh on the fly.\n6. Name `model.results` and `image/fit.png` as the first two things to open.\n7. If the data changed but the model did not, confirm the `unique_tag` changed too.\n8. On a GPU, run the VRAM check before a long fit.\n9. On completion, hand off to the results-loading or fit-plotting skill rather than\n interpreting the numbers inline.\n10. Offer the `wiki/project/` entry.\n" - } - }, - "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file diff --git a/notebooks/chapter_2_modeling/tutorial_3_why_modeling_is_hard.ipynb b/notebooks/chapter_2_modeling/tutorial_3_why_modeling_is_hard.ipynb new file mode 100644 index 0000000..666dedd --- /dev/null +++ b/notebooks/chapter_2_modeling/tutorial_3_why_modeling_is_hard.ipynb @@ -0,0 +1,592 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Tutorial 3: Why Modeling Is Hard\n", + "================================\n", + "\n", + "The bulge and disk in tutorial 2 made our model more realistic, but also harder to fit. Their centres, shapes,\n", + "brightnesses and sizes can trade off. A search can find a plausible galaxy without finding the best explanation\n", + "available within the model.\n", + "\n", + "Here we deliberately make exploration inadequate, then try three ways to improve it: tune priors, simplify the\n", + "model and search more thoroughly. Keep the images in view throughout. They tell us what the search is getting\n", + "right, what it is missing and which assumptions might help.\n", + "\n", + "__Contents__\n", + "\n", + "- **A Reference Fit:** Repeat the practicalities model for comparison.\n", + "- **An Inadequate Search:** Explore the same model with only 14 live points.\n", + "- **Local Maxima:** Understand how an apparently plausible fit can be wrong.\n", + "- **Prior Tuning:** Use visual impressions to guide exploration.\n", + "- **Reducing Complexity:** Test shared bulge and disk geometry.\n", + "- **Look Harder:** Give the full model more thorough exploration.\n", + "- **Benefits and Weaknesses:** Balance realism, reliability and runtime." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Google Colab Setup__\n", + "\n", + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, + "outputs": [], + "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", + "try:\n", + " import google.colab\n", + "except ImportError:\n", + " from autogalaxy import setup_colab as _setup_colab\n", + "else:\n", + " import importlib\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.check_call(\n", + " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", + " )\n", + " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", + "\n", + "_setup_colab.setup(\"howtogalaxy\")" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from autogalaxy import setup_notebook; setup_notebook()\n", + "\n", + "from pathlib import Path\n", + "import numpy as np\n", + "import autofit as af\n", + "import autogalaxy as ag\n", + "import autogalaxy.plot as aplt" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Dataset and Mask__\n", + "\n", + "Load the imaging data and retain the region inside the circular mask. The simulator creates the data if needed.\n", + "The image, noise map and PSF together describe the observation; none specifies which galaxy model we must fit." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "dataset_name = \"simple\"\n", + "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name\n", + "if ag.util.dataset.should_simulate(str(dataset_path)):\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.run([sys.executable, \"scripts/simulators/simple.py\"], check=True)\n", + "\n", + "dataset = ag.Imaging.from_fits(\n", + " data_path=dataset_path / \"data.fits\",\n", + " noise_map_path=dataset_path / \"noise_map.fits\",\n", + " psf_path=dataset_path / \"psf.fits\",\n", + " pixel_scales=0.1,\n", + ")\n", + "mask = ag.Mask2D.circular(\n", + " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5\n", + ")\n", + "dataset = dataset.apply_mask(mask=mask)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Over Sampling__\n", + "\n", + "The bright centre changes rapidly across a pixel. Adaptive over sampling evaluates it on a finer grid so that\n", + "numerical inaccuracies do not masquerade as poor models. The outskirts need fewer evaluations." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n", + " grid=dataset.grid,\n", + " sub_size_list=[8, 4, 2],\n", + " radial_list=[0.3, 0.6],\n", + " centre_list=[(0.0, 0.0)],\n", + ")\n", + "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n", + "aplt.subplot_imaging_dataset(dataset=dataset)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__A Reference Fit__\n", + "\n", + "The bright centre and extended disk are both visible. We repeat tutorial 2's model and search settings, so an\n", + "existing completed fit can be loaded. Treat this as a reference to compare against, not a proven global optimum.\n", + "On real data we would not know the correct parameter values in advance." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "model = af.Collection(\n", + " galaxies=af.Collection(\n", + " galaxy=af.Model(\n", + " ag.Galaxy, redshift=0.5, bulge=ag.lp.Sersic, disk=ag.lp.Exponential\n", + " )\n", + " )\n", + ")\n", + "analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", + "search = af.Nautilus(\n", + " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", + " name=\"tutorial_2_practicalities\",\n", + " unique_tag=dataset_name,\n", + " n_live=200,\n", + " n_batch=50,\n", + " iterations_per_quick_update=2500,\n", + ")\n", + "result_reference = search.fit(model=model, analysis=analysis)\n", + "aplt.subplot_fit_imaging(fit=result_reference.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__An Inadequate Search__\n", + "\n", + "Now reduce the search to `n_live=14`, leaving the data and model unchanged. Fourteen is the minimum allowed\n", + "for this 13-parameter model: ten live points would be rejected before sampling. This deliberately poor setting makes\n", + "missing good solutions much more likely. Random searches differ between runs, so it cannot guarantee failure.\n", + "If it happens to find a good fit, that does not make 14 live points a reliable choice for this model." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "search = af.Nautilus(\n", + " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", + " name=\"tutorial_3_inadequate\",\n", + " unique_tag=dataset_name,\n", + " n_live=14,\n", + " n_batch=50,\n", + ")\n", + "result_inadequate = search.fit(model=model, analysis=analysis)\n", + "print(result_inadequate.info)\n", + "aplt.subplot_fit_imaging(fit=result_inadequate.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Compare the Fits__\n", + "\n", + "Look for a centre that is too bright or too faint, or residual light following the disk. A reasonable-looking\n", + "parameter summary can conceal these failures. Compare the log likelihoods as well as the plots; here the data,\n", + "mask and likelihood definition are the same, so higher values mean a better fit." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "print(\"Reference:\", result_reference.max_log_likelihood_fit.log_likelihood)\n", + "print(\"14 live points:\", result_inadequate.max_log_likelihood_fit.log_likelihood)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Global and Local Maxima__\n", + "\n", + "A local maximum is a solution better than nearby alternatives, with a better solution elsewhere in parameter\n", + "space. The global maximum is the highest likelihood available in that model. A search can concentrate around a\n", + "local peak and miss another: improving the fit nearby does not prove there is nowhere better to look.\n", + "\n", + "If the reference has a higher likelihood, it directly demonstrates that the inadequate search missed better\n", + "models. It does not prove that the reference is the global maximum. If the two agree, inspect repeated runs and\n", + "more thorough searches before concluding the exploration is reliable.\n", + "\n", + "Adding physical components increases the combinations we must explore. This is the central challenge of modelling:\n", + "we want enough flexibility to describe a real galaxy, while still exploring the model reliably.\n", + "\n", + "__Approach 1: Prior Tuning__\n", + "\n", + "Return to the image before changing settings. We can see roughly where the galaxy sits, its orientation and how\n", + "far its light extends. The default priors must cover many different galaxies; our visual impressions can guide a\n", + "search of this particular image. Below we create the bulge and disk separately to make those choices easy to read." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "bulge = af.Model(ag.lp.Sersic)\n", + "disk = af.Model(ag.lp.Exponential)\n" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The light peaks at the centre of the cutout. This suggests that both component centres lie close to (0.0, 0.0).\n", + "We use a narrow range around that position, leaving room for a small offset. This judgement comes from the image,\n", + "not from looking up the simulator's answer. On real data, first check the coordinate origin and any bright contaminants." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "bulge.centre_0 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05)\n", + "bulge.centre_1 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05)\n", + "disk.centre_0 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05)\n", + "disk.centre_1 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05)\n" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The central light is fairly round, while the outer disk is more elongated. The central contours suggest an angle\n", + "around 45 degrees; the outer contours lie closer to 30 degrees. The bulge's angle is less obvious because it is\n", + "rounder. These are rough impressions, not precise measurements, so our priors allow variation around them.\n", + "\n", + "We convert approximate axis ratios of 0.9 and 0.7 and those angles into elliptical components. Allowing each\n", + "component its own shape matters: forcing them to agree would erase the visual distinction we are trying to model." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "bulge_ell_comps = ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0)\n", + "disk_ell_comps = ag.convert.ell_comps_from(axis_ratio=0.7, angle=30.0)\n", + "\n", + "bulge.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior(\n", + " mean=bulge_ell_comps[0], sigma=0.1, lower_limit=-1.0, upper_limit=1.0\n", + ")\n", + "bulge.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior(\n", + " mean=bulge_ell_comps[1], sigma=0.1, lower_limit=-1.0, upper_limit=1.0\n", + ")\n", + "\n", + "disk.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior(\n", + " mean=disk_ell_comps[0], sigma=0.1, lower_limit=-1.0, upper_limit=1.0\n", + ")\n", + "disk.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior(\n", + " mean=disk_ell_comps[1], sigma=0.1, lower_limit=-1.0, upper_limit=1.0\n", + ")\n" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The visible galaxy occupies only a few arcseconds. A half-light radius of tens of arcseconds would be a poor\n", + "starting guess for this cutout. We favour a compact bulge and a more extended disk, while retaining broad tails.\n", + "\n", + "The half-light radius encloses half the profile's total light. It is not the radius where the image disappears\n", + "into the noise, so visual extent gives guidance rather than an exact radius. Positive limits exclude unphysical\n", + "sizes; the width of each prior leaves room for the data to refine our impression." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "bulge.effective_radius = af.TruncatedGaussianPrior(\n", + " mean=0.8, sigma=0.5, lower_limit=0.0, upper_limit=np.inf\n", + ")\n", + "disk.effective_radius = af.TruncatedGaussianPrior(\n", + " mean=1.5, sigma=0.8, lower_limit=0.0, upper_limit=np.inf\n", + ")\n" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The bright, concentrated centre motivates a bulge with a Sersic index around 3, whereas the disk's Exponential\n", + "profile has index 1. Neither a bright centre nor a fitted index uniquely identifies a galaxy's physical history.\n", + "This is a modelling assumption to test against the residuals, not a morphological classification imposed by eye." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "bulge.sersic_index = af.TruncatedGaussianPrior(\n", + " mean=3.0, sigma=1.0, lower_limit=0.0, upper_limit=np.inf\n", + ")\n" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now compose the model from these customised components. The names and physical profiles are unchanged;\n", + "we have changed the ranges and relative weights assigned to possible parameter values." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n", + "\n", + "model = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n", + "\n", + "\n", + "print(model.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Run with 75 live points. This is fewer than the reference's 200, but more than the deliberately inadequate 14.\n", + "We are testing a practical remedy, changing both the priors and search effort; it is not an isolated experiment\n", + "measuring the effect of priors alone. Check whether the central and outer residuals improve." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "search = af.Nautilus(\n", + " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", + " name=\"tutorial_3_tuned_priors\",\n", + " unique_tag=dataset_name,\n", + " n_live=75,\n", + " n_batch=50,\n", + ")\n", + "result_tuned = search.fit(model=model, analysis=analysis)\n", + "print(result_tuned.info)\n", + "aplt.subplot_fit_imaging(fit=result_tuned.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Approach 2: Reducing Complexity__\n", + "\n", + "The bulge and disk overlap and have similar centres, so sharing a centre is plausible. We go further and also\n", + "force them to have identical elliptical components. This removes four free parameters, leaving nine.\n", + "\n", + "The image already hints at the risk: the outer disk looks flatter than the central bulge. An easier model to\n", + "search can still be a worse description of the galaxy. We deliberately test this assumption and inspect its cost.\n", + "Use fresh profiles so the tuned priors above do not carry into this separate experiment." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "bulge = af.Model(ag.lp.Sersic)\n", + "disk = af.Model(ag.lp.Exponential)\n", + "bulge.centre = disk.centre\n", + "bulge.ell_comps = disk.ell_comps\n", + "model = af.Collection(\n", + " galaxies=af.Collection(\n", + " galaxy=af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n", + " )\n", + ")\n", + "print(model.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Use 75 live points again. Inspect the residuals around the centre and along the disk. This simulation has\n", + "components with different shapes, so the shared-geometry model cannot reproduce both exactly, even with a\n", + "perfect search. Persistent structure can signal an inadequate model rather than inadequate exploration." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "search = af.Nautilus(\n", + " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", + " name=\"tutorial_3_reduced_complexity\",\n", + " unique_tag=dataset_name,\n", + " n_live=75,\n", + " n_batch=50,\n", + ")\n", + "result_reduced = search.fit(model=model, analysis=analysis)\n", + "print(result_reduced.info)\n", + "aplt.subplot_fit_imaging(fit=result_reduced.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Approach 3: Look Harder__\n", + "\n", + "We can retain the original model and broad priors, and give Nautilus more live points. This is straightforward\n", + "and does not require deciding by eye how each galaxy should look. It costs more computation, and still cannot\n", + "guarantee that every good region will be found.\n", + "\n", + "The optional fit below uses 300 live points. Uncomment it to run the more thorough comparison. It is left out of\n", + "the default execution because the earlier experiments already involve several fits." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "model = af.Collection(\n", + " galaxies=af.Collection(\n", + " galaxy=af.Model(\n", + " ag.Galaxy, redshift=0.5, bulge=ag.lp.Sersic, disk=ag.lp.Exponential\n", + " )\n", + " )\n", + ")\n", + "search = af.Nautilus(\n", + " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", + " name=\"tutorial_3_look_harder\",\n", + " unique_tag=dataset_name,\n", + " n_live=300,\n", + " n_batch=50,\n", + ")\n", + "# result_thorough = search.fit(model=model, analysis=analysis)\n", + "# aplt.subplot_fit_imaging(fit=result_thorough.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Benefits and Weaknesses__\n", + "\n", + "| Approach | Benefit | Weakness |\n", + "| --- | --- | --- |\n", + "| Tune priors (75 live points) | Use visible structure to avoid implausible regions. | Incorrect or overly narrow choices can bias the fit; individual tuning takes time for large samples. |\n", + "| Reduce complexity (75 live points) | Fewer dimensions can make exploration easier and faster. | Shared geometry can prevent the model from describing real differences between components. |\n", + "| Look harder (300 live points) | Keep the flexible model and apply the same approach to many galaxies. | More computation can become expensive and does not repair an unsuitable model. |\n", + "\n", + "The 14-live-point run is deliberately inadequate; the 200-live-point practicalities run is our reference.\n", + "Compare actual residuals and likelihoods rather than expecting these settings to produce identical outcomes on\n", + "every run. These experiments illustrate choices, not a controlled ranking of runtime.\n", + "\n", + "__Model Limitations__\n", + "\n", + "Even a well-explored Sersic-plus-Exponential model cannot reproduce every real galaxy. A bar, spiral structure,\n", + "dust or bright star-forming knots can leave residuals no adjustment of these two smooth profiles will remove.\n", + "Look at the shape and location of those residuals before deciding that the search simply needs longer.\n", + "\n", + "__Wrap Up__\n", + "\n", + "Search chaining is especially useful because it helps strike a balance between realistic models, reliable\n", + "exploration and manageable runtimes. It is a central tool for moving beyond isolated, hand-tuned fits. Tutorial 6\n", + "shows it in practice; first, linear profiles give us another way to simplify exploration while retaining flexibility." + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.1" + }, + "colab": { + "aiContexts": { + "24c2f562-da24-50bb-8eb9-5a887505fe54": { + "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", + "name": "PyAutoGalaxy assistant", + "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_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\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_2_modeling/tutorial_3_why_modeling_is_hard.ipynb in HowToGalaxy).\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 PyAutoGalaxy 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 PyAutoGalaxy docs (https://pyautogalaxy.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) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. 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 galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_run_search\n\n---\nname: ag_run_search\ndescription: Run the fit — take a composed model, an analysis and a configured search and drive `search.fit(model=model, analysis=analysis)` to completion, then read what it wrote. Covers the output-folder anatomy and the on-the-fly announcement, the unique-identifier resume behaviour and when it silently reuses a stale fit, `iterations_per_quick_update` and `live_visual_update`, JAX/GPU acceleration and when it actually pays, VRAM checks before a long GPU run, the `PYAUTO_TEST_MODE` smoke levels, and the `if __name__ == \"__main__\"` parallelisation fix. Use once `ag_build_imaging_model` and `ag_configure_search` have produced `model`, `analysis` and `search` objects, or when a fit is running and the user wants to know what to watch. Not for composing the model or choosing the search (those two skills), not for interpreting the finished posterior (`ag_load_results`), and not for diagnosing a fit that ran but converged somewhere unphysical (`ag_debug_fit_failure`).\n---\n\n# Running the fit\n\nThis is the moment the inference actually happens. Everything before it was preparation:\na `model` says which morphological parameters are free and what priors they carry, an\n`analysis` binds that model to one dataset and knows how to turn a parameter vector into a\nlog likelihood, and a `search` knows how to explore the parameter space. One call joins\nthem:\n\n```python\nresult = search.fit(model=model, analysis=analysis)\n```\n\nStatistically, that call is sampling (or optimising) the posterior\n$P(\\theta | d) \\propto \\mathcal{L}(d | \\theta) P(\\theta)$, where the likelihood is the\nGaussian-noise chi-squared of the PSF-convolved model image against the data — walked\nline by line in `autogalaxy_workspace:scripts/imaging/likelihood_function.py`. Scientifically,\nit is where a Sersic index, an effective radius or a bulge-to-total ratio stops being a guess\nand becomes a measurement with errors. What this skill adds is everything *around* the call:\nhow to watch it, how long to expect, how to make it fast, and how to prove the script works\nbefore committing hours to it.\n\nTwo wiki pages carry the background this skill assumes. Read\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md) for\nwhat each sampler does and how run time scales with the model, and\n[`wiki/core/api/analysis_objects.md`](../wiki/core/api/analysis_objects.md) for what the\nreturned `Result` contains.\n\n## Ask\n\nThree questions, and the answers change the branch:\n\n- *\"Do you already have `model`, `analysis` and `search`?\"* If not, route to\n [`ag_build_imaging_model`](./ag_build_imaging_model.md) and\n [`ag_configure_search`](./ag_configure_search.md) first. A fit assembled from a\n half-remembered model is the most expensive mistake available here.\n- *\"Smoke test first, or straight to the production run?\"* Almost always smoke test first —\n it takes seconds and answers \"does this script execute end to end?\", which is a different\n question from \"is this galaxy's Sersic index 3.2?\". The smoke branch is below.\n- *\"How long can this run, and on what?\"* A `MultiStartProdigy` fit is minutes; a `Nautilus`\n fit of a smooth model is tens of minutes on a GPU and can be hours on a CPU; a pixelised\n fit can be far longer. That answer decides foreground vs background, laptop vs cluster,\n and whether `live_visual_update` is worth switching on.\n\nIf the data is real observational imaging, the inspection gate in\n[`../AGENTS.md`](../AGENTS.md) applies before you get here at all — contaminants and mask\nextent are settled in [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md), not\nretrospectively.\n\n## Branch — the production run\n\nThe deliverable is one script in `scripts/` the user can re-run and edit. Adapted from\n`autogalaxy_workspace:scripts/imaging/start_here.py` (the fit and result sections) and\n`autogalaxy_workspace:scripts/imaging/modeling.py` (the Nautilus configuration and the VRAM\ncheck):\n\n```python\n\"\"\"\nGalaxy Structure: Run the Fit\n=============================\n\nFit a galaxy's surface-brightness profile to CCD imaging: load and mask the data, compose a\nlinear Sersic bulge, and sample the posterior with Nautilus so the inferred effective radius\nand Sersic index come with errors.\n\n__Contents__\n\n- **Imports:** JAX environment first, then the standard trio.\n- **Dataset:** Load imaging, mask it, and apply adaptive over-sampling.\n- **Model:** Compose the galaxy's light profile.\n- **Search:** Configure Nautilus and its update cadence.\n- **Analysis:** Bind the model to the data and choose the JAX backend.\n- **Model-Fit:** Run the search and announce the output folder.\n- **Result:** Read the best-fit model back.\n\"\"\"\nfrom autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\n\"\"\"\n__Dataset__\n\nGalaxy modeling needs three ingredients: the image in CCD counts, a per-pixel RMS noise-map,\nand the PSF. The PSF is forward-modelled rather than divided out, which is what separates a\ngenuinely compact bulge from a seeing-broadened one. `pixel_scales` converts pixels to\narcseconds and must match the instrument (`ag.Imaging.from_fits`,\n`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe mask sets which pixels enter the likelihood, and its radius is a science choice, not a\ndefault: truncate the outer isophotes and the effective radius and Sersic index are biased\ndirectly. Over-sampling evaluates the light profile several times per pixel where the\ngradient is steep, which matters most in the central few tenths of an arcsecond\n(`ag.util.over_sample.over_sample_size_via_radial_bins_from`).\n\"\"\"\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"\"\nMASK_RADIUS = 2.5\n\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n pixel_scales=0.1,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\n\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n\n\"\"\"\n__Model__\n\nA linear `Sersic` bulge: the `intensity` is solved by linear inversion each iteration rather\nthan sampled, so the search explores one fewer dimension per component for free\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Linear Light Profiles__`).\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\n\n\"\"\"\n__Search__\n\n`Nautilus` is nested sampling: it returns the full posterior — every parameter's density,\nits errors, and the correlations between them. `n_live` trades accuracy against run time and\n200 covers the vast majority of galaxy models. `unique_tag` is conventionally the dataset\nname, which is what keeps the same model fitted to different data in different folders\n(`PyAutoFit:autofit/non_linear/search/nest/nautilus/search.py`).\n\"\"\"\nsearch = af.Nautilus(\n path_prefix=Path(\"imaging\"),\n name=\"sersic\",\n unique_tag=\"\",\n n_live=200,\n iterations_per_quick_update=10000,\n live_visual_update=False,\n)\n\n\"\"\"\n__Analysis__\n\n`ag.AnalysisImaging` defines the `log_likelihood_function` the search calls, and defaults to\n`use_jax=True` when JAX is installed (`PyAutoGalaxy:autogalaxy/imaging/model/analysis.py`).\n\"\"\"\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\n\"\"\"\n__Model-Fit__\n\nResults are written to the output folder on the fly, from the best model found so far, so the\nfolder is worth opening the moment the search starts.\n\"\"\"\nprint(f\"Output folder: {search.paths.output_path.resolve()}\")\n\nresult = search.fit(model=model, analysis=analysis)\n\n\"\"\"\n__Result__\n\"\"\"\nprint(result.info)\nprint(result.max_log_likelihood_instance)\n```\n\nRun it with writable caches if the default locations are not writable — a sandbox, CI, or an\ninstall imported from a Windows mount under WSL\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)):\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\n`search.fit` itself is `PyAutoFit:autofit/non_linear/search/abstract_search.py`.\n\n## Branch — what the output folder contains, and when to look\n\n**Announce the folder at launch, not at the end.** Quote\n`search.paths.output_path.resolve()` once the fit is running and say plainly that\n`model.results` and `image/fit.png` refresh as the search goes — there is nothing to wait\nfor. Users new to the stack sit watching a silent terminal because nobody told them.\n\nThe annotated tree of `files/`, `image/`, `model.info`, `model.results`, `search.summary`\nand the `` folder is `__Output Folder Layout__` in\n[`autogalaxy_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/modeling.py);\nthe same section appears in the `interferometer`, `multi_dataset`, `multi_galaxy` and\n`cluster` `modeling.py` scripts. Link it rather than copying the tree into the conversation,\nwhere it would rot. The condensed version is also in\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n\"The output folder\".\n\nName what to open first, in this order:\n\n1. `model.results` — the human-readable fit summary, parameters with errors.\n2. `image/fit.png` — data, model image, residuals and chi-squared map in one figure.\n3. `search.log` — tail it if you want to watch progress from a terminal.\n\nDepth follows [`_style.md`](./_style.md) \"Adaptive depth\": for a newcomer, or in teacher\nmode, walk all three. For a returning user, quoting the path is enough.\n\n## Branch — resuming, and the trap inside it\n\n`` is derived from the model, the search settings and the dataset identifier, so\nre-running an identical configuration **resumes** the existing fit rather than restarting it\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Unique Identifier__`). That is a\nfeature — an interrupted overnight run picks up where it stopped.\n\nIt is also the sharpest edge in the workflow. **The identifier does not hash the pixel\nvalues of your data.** Swap `data.fits` for a different galaxy, keep the model, the search\nand the `unique_tag` identical, and the next run finds a completed fit at the same path and\nreturns it — silently, in seconds, with the previous galaxy's parameters. If the data\nchanges, change the `unique_tag`. If you are unsure whether a result is stale, delete the\n`` folder and re-run rather than reasoning about it.\n\nTest mode namespaces its output separately: any active `PYAUTO_TEST_MODE` level inserts a\n`test_mode` segment straight after the output root, so a smoke run lands in\n`output/test_mode//...` and cannot short-circuit a later real fit\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## Branch — the update cadence and the live view\n\nTwo settings control what you see while the fit runs, both on the search\n(`PyAutoFit:autofit/non_linear/search/abstract_search.py`):\n\n- **`iterations_per_quick_update`** — how often the current best model is visualised and\n written to disk. The unit depends on the search: likelihood evaluations for `Nautilus`\n (hence the large `10000` in `modeling.py`), gradient steps for `MultiStartProdigy` (hence\n the much smaller `50` in `start_here.py`). Each update costs roughly ten seconds, so too\n low a value and output dominates the run time; too high and you cannot see progress. If\n the log is constantly reporting that it is outputting results, raise it.\n- **`live_visual_update`** — additionally push the quick-update image to a live surface: a\n matplotlib window that refreshes in a plain script, or a self-updating cell in Jupyter and\n Colab. The `fit.png` disk write happens either way. Leave it `False` on anything headless\n — an HPC node, a background process, CI.\n\nIf the search configuration already records the choice, don't re-ask; that decision belongs\nto [`ag_configure_search`](./ag_configure_search.md).\n\n## Branch — JAX, GPUs, and when the acceleration pays\n\nImaging fits run through JAX by default. Installing the extra (`pip install autogalaxy[jax]`)\nis all that is required: `ag.AnalysisImaging` then defaults to `use_jax=True`, and the search\ndriver wraps the likelihood in `jax.vmap(jax.jit(...))` so a whole batch of parameter vectors\nevaluates in one call. You will see a one-time log line as the JIT compile starts; every\nevaluation after that re-uses the compiled trace. This is described in\n`autogalaxy_workspace:scripts/guides/using_jax.py` `__Auto-Enabled Modeling__`, and if JAX is\nabsent the analysis warns once and falls back to NumPy.\n\n**When it pays.** The gain scales with how much array work each likelihood evaluation does,\nso it is largest for big masks, fine over-sampling, many-component bases and pixelised\nreconstructions, and smallest for a tiny mask with one smooth profile. GPU gains dwarf CPU\ngains: `autogalaxy_workspace:scripts/imaging/modeling.py` `__JAX__` quotes roughly ten\nminutes on a GPU against an hour on a CPU for its example, with a CPU still gaining from\nmultithreading. Gradient-based searches like `MultiStartProdigy` are not merely faster under\nJAX — they are only possible with it, because JAX is what supplies the likelihood's\nderivatives and evaluates all the parallel starts in one batched call\n(`autogalaxy_workspace:scripts/imaging/start_here.py` `__Multi Start Gradient Optimization__`).\n\n**Check VRAM before a long GPU run.** A JAX fit must fit inside the GPU's memory, and it\nfails at JIT-compile time or on the first likelihood call if it does not:\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py` `__VRAM Use__`. It takes\ntwenty or thirty seconds, so comment it out once you know your model's footprint. Batch size\nis the lever: larger batches cut wall-clock time and raise VRAM, smaller batches the reverse.\nA smooth-profile fit on a modest dataset is tens of megabytes; a pixelised reconstruction on\nhigh-resolution data can exceed ten gigabytes.\n\n**Turn JAX off to debug.** `ag.AnalysisImaging(dataset=dataset, use_jax=False)`, or\n`PYAUTO_DISABLE_JAX=1` to force it globally without editing code. NumPy stack traces are far\neasier to read, and you can drop a debugger or a `print` into code JAX would otherwise\ncompile. That is the first lever to pull when deciding whether a failure is a JAX problem at\nall — see [`ag_debug_fit_failure`](./ag_debug_fit_failure.md).\n\nFor running on a cluster — SLURM array jobs, one galaxy per task, the CPU and GPU batch\nscripts, and `number_of_cores` read from `SLURM_CPUS_PER_TASK` — read\n[`../wiki/core/operations/hpc.md`](../wiki/core/operations/hpc.md) for the concepts and\n[`../wiki/core/operations/hpc_infrastructure.md`](../wiki/core/operations/hpc_infrastructure.md)\nfor the `hpc/` templates and `sync` CLI this repo ships; the upstream ground truth behind both\nis `autogalaxy_workspace:scripts/guides/hpc/example_cpu_and_gpu.py`. The Python modeling code\nis identical for a GPU run; only the batch script changes.\n\n## Branch — the smoke test, before you spend hours\n\nEvery script gets one fast structural run before a real one. `PYAUTO_TEST_MODE` has four\nlevels ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)), and the\nchoice between them matters more than it looks:\n\n```bash\n# Level 1 — sampler runs with minimal iterations. A real (tiny) search: writes\n# model.results, image/fit.png and a samples.csv you can load back.\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n\n# Level 2 — sampler bypassed, likelihood called exactly once. The fastest proof that\n# the model composes and the likelihood evaluates.\nPYAUTO_TEST_MODE=2 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\n**Level 2 does not write the fit products.** A level-2 run returns a `Result`, proving the\nwiring, but leaves no `model.results` and no `image/fit.png` behind — so if the next thing\nyou want to do is plot or load the fit, use level 1. Level 3 skips the likelihood call as\nwell, which is only useful for checking that a script's non-fitting scaffolding runs.\n\n**The parameter values from any test-mode run are meaningless.** The sampler was truncated or\nmocked. Never quote a structural parameter measured in test mode; say explicitly that the\nnumber is a wiring check.\n\nFor the fastest possible loop, combine test mode with the dataset and output short-circuits:\n\n```bash\nPYAUTO_TEST_MODE=2 PYAUTO_SKIP_FIT_OUTPUT=1 PYAUTO_SKIP_VISUALIZATION=1 \\\n PYAUTO_SMALL_DATASETS=1 PYAUTO_FAST_PLOTS=1 python scripts/run_fit.py\n```\n\n`PYAUTO_SMALL_DATASETS=1` caps every array, mask and grid to 16 × 16 pixels — so delete any\npreviously simulated `dataset/` when you toggle it, or a full-resolution dataset on disk will\nbe reused and mismatch the capped grids.\n\n## Branch — the error that appears the moment the search starts\n\nOn some combinations of operating system and Python version, a script raises as soon as the\nsearch begins, from Python's process spawning rather than from anything about your model. The\nfix is to wrap the whole fit in a function and call it under a main guard:\n\n```python\ndef fit():\n from autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\n import autofit as af\n import autogalaxy as ag\n\n # ... dataset, model, search, analysis as above ...\n result = search.fit(model=model, analysis=analysis)\n\n\nif __name__ == \"__main__\":\n fit()\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/modeling/bug_fix.py`, which is the same\n`modeling.py` fit with this one structural change. It works for every dataset type, so adopt\nit for any modeling script that hits the error. If parallelisation still will not work after\nthe fix, that script points at the project's support channel.\n\n## Combine\n\n- [`ag_plot_fit`](./ag_plot_fit.md) — render the fit yourself, at whatever scaling and\n cropping the science needs, rather than reading the auto-generated `image/fit.png`.\n- [`ag_load_results`](./ag_load_results.md) — pull the posterior, the best-fit galaxies and\n the derived quantities back into Python, in-session or from disk later.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) — the fit finished but the residuals or\n the parameters are wrong.\n- [`ag_configure_search`](./ag_configure_search.md) — the fit is too slow, or the sampler is\n the wrong one for the model.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) — build a controlled dataset with known\n truth and fit that first, which is the cleanest way to separate a model problem from a\n data problem.\n\nWhen the script and its fit are worth keeping, offer (default-yes) to record the run in a\ndated `wiki/project/YYYY-MM-DD-.md` entry: the science question, what was inferred and\nwith what search, and the output path — per [`_style.md`](./_style.md) property #5.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Practicalities](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running a fit — output structure, reviewing results as they appear,\n and managing run times.\n- **General reference** — [RTD: New user guide](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n the decision tree for which fit to run first, by system scale and dataset type.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit, with the JAX and quick-update sections this skill\n mirrors.\n\n## Agent procedural checklist\n\n1. Confirm `model`, `analysis` and `search` exist; if not, route to the model-building and\n search-configuration skills.\n2. On real observational data, confirm the inspection gate has been satisfied.\n3. Write the script to `scripts/` in the generated-script style; never leave it inline only.\n4. Validate it with `PYAUTO_TEST_MODE=1` (level 2 if you only need the likelihood proved),\n with the cache variables set if the environment needs them.\n5. Launch the production run; **quote the absolute output path immediately** and say results\n refresh on the fly.\n6. Name `model.results` and `image/fit.png` as the first two things to open.\n7. If the data changed but the model did not, confirm the `unique_tag` changed too.\n8. On a GPU, run the VRAM check before a long fit.\n9. On completion, hand off to the results-loading or fit-plotting skill rather than\n interpreting the numbers inline.\n10. Offer the `wiki/project/` entry.\n" + } + }, + "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file diff --git a/notebooks/chapter_2_modeling/tutorial_4_dealing_with_failure.ipynb b/notebooks/chapter_2_modeling/tutorial_4_dealing_with_failure.ipynb deleted file mode 100644 index f2c662c..0000000 --- a/notebooks/chapter_2_modeling/tutorial_4_dealing_with_failure.ipynb +++ /dev/null @@ -1,759 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 4: Dealing With Failure\n", - "================================\n", - "\n", - "In the previous tutorial we intentionally made our non-linear search infer a local maxima solution and therefore return\n", - "a physically incorrect model. In this tutorial, we will pretend that we have modeled our galaxy and inferred a local\n", - "maxima. We introduce three approaches one can take that changes how we fit the model, all of which have the aim of\n", - "ensuring we infer the global maxima:\n", - "\n", - " 1) Prior Tuning: Tell the non-linear search where to search parameter space.\n", - " 2) Reduce Complexity: Fit a model with fewer parameters and therefore a simpler parameter space.\n", - " 3) Look Harder: Brute force a global maxima by telling the non-linear search to sample parameter space more thoroughly.\n", - "\n", - "Each approach has its benefits and disadvantages and we will discuss them in detail.\n", - "\n", - "In the previous tutorial, when we inferred a local maxima we knew that we had done so. For modeling a real galaxy,\n", - "we do not know the true model and it may be unclear if the solution we inferred is a global or local maxima. The\n", - "methods we learn in this tutorial are therefore equally important for verifying that a solution that looks like a\n", - "global maxima solution is in indeed the global maxima.\n", - "\n", - "__Contents__\n", - "\n", - "- **Initial Setup:** Load the dataset and apply a mask.\n", - "- **Approach 1: Prior Tuning:** Narrow the priors to guide the search to the correct region of parameter space.\n", - "- **Approach 2: Reducing Complexity:** Simplify the model to reduce the dimensionality of parameter space.\n", - "- **Approach 3: Look Harder:** Increase the thoroughness of the non-linear search sampling." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Google Colab Setup__\n", - "\n", - "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "jupyter": { - "source_hidden": true - } - }, - "outputs": [], - "source": [ - "# @title Set up Google Colab { display-mode: \"form\" }\n", - "try:\n", - " import google.colab\n", - "except ImportError:\n", - " from autogalaxy import setup_colab as _setup_colab\n", - "else:\n", - " import importlib\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.check_call(\n", - " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", - " )\n", - " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", - "\n", - "_setup_colab.setup(\"howtogalaxy\")" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autogalaxy import setup_notebook; setup_notebook()\n", - "\n", - "import numpy as np\n", - "from pathlib import Path\n", - "import autogalaxy as ag\n", - "import autogalaxy.plot as aplt\n", - "import autofit as af" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Initial Setup__\n", - "\n", - "we'll use the same galaxy data as the previous tutorial, where:\n", - "\n", - " - The galaxy's bulge is a `Sersic`.\n", - " - The galaxy's disk is an `Exponential`." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "dataset_name = \"simple\"\n", - "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Dataset Auto-Simulation__\n", - "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "if ag.util.dataset.should_simulate(str(dataset_path)):\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulators/simple.py\"],\n", - " check=True,\n", - " )\n", - "\n", - "\n", - "dataset = ag.Imaging.from_fits(\n", - " data_path=dataset_path / \"data.fits\",\n", - " noise_map_path=dataset_path / \"noise_map.fits\",\n", - " psf_path=dataset_path / \"psf.fits\",\n", - " pixel_scales=0.1,\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Mask__\n", - "\n", - "we'll create and use a smaller 2.5\" `Mask2D` again." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mask = ag.Mask2D.circular(\n", - " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5\n", - ")\n", - "\n", - "dataset = dataset.apply_mask(mask=mask)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Over Sampling__\n", - "\n", - "Apply adaptive over sampling to ensure the calculation is accurate, you can read up on over-sampling in more detail via \n", - "the `autogalaxy_workspace/*/guides/advanced/over_sampling.ipynb` notebook." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n", - " grid=dataset.grid,\n", - " sub_size_list=[8, 4, 2],\n", - " radial_list=[0.3, 0.6],\n", - " centre_list=[(0.0, 0.0)],\n", - ")\n", - "\n", - "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "When plotted, the galaxy's bulge and disk are clearly visible in the centre of the image." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_imaging_dataset(dataset=dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Approach 1: Prior Tuning__\n", - "\n", - "First, we are going to try giving our non-linear search a helping hand. Our priors tell the non-linear search where \n", - "to look in parameter space. If we tell it to look in the right place (that is, 'tune' our priors), this might mean \n", - "the search finds the global solution when it previously found a local maxima.\n", - "\n", - "We saw in a previous tutorial that we can fully customize priors in **PyAutoGalaxy**, so lets give it a go. I've set up \n", - "a custom search below and specified priors that give the non-linear search a better chance of inferring the global \n", - "maxima solution, alongside discussing how I have changed each prior from the default values specified by the \n", - "`config/priors` config files.\n", - "\n", - "In a previous tutorial, we customized the priors of a model by creating a `Galaxy` as a `Model` and customizing each\n", - "prior:" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp.Sersic, disk=ag.lp.Exponential)\n", - "\n", - "galaxy.bulge.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", - "galaxy.bulge.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", - "galaxy.disk.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", - "galaxy.disk.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can alternatively create the light and bulge profiles as a `Model` and customize their parameters, and then pass them\n", - "to the model galaxy and overall model. These two approaches are equivalent, but in this example the style below \n", - "provides more concise and readable code. We will therefore switch to this code style in this tutorial, but may swap \n", - "back and forth between the two styles throughout **HowToGalaxy** depending on what is more readable." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge = af.Model(ag.lp.Sersic)\n", - "disk = af.Model(ag.lp.Exponential)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "By default, the prior on the $(y,x)$ coordinates of a `LightProfile` is a GaussianPrior with\n", - "`mean=0.0` and `sigma=0.3`. However, visual inspection of our galaxy image tells us that its centre (based on the\n", - "galaxy's luminous emission) is at x = 0.0\" and y = 0.0\", so lets replace this prior with a narrow `UniformPrior`, so\n", - "the non-linear search looks over a very narrow range of `centre` values in parameter space." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge.centre_0 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05)\n", - "bulge.centre_1 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05)\n", - "disk.centre_0 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05)\n", - "disk.centre_1 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "By default, the elliptical components of our galaxy's elliptical `LightProfile` are `TruncatedGaussianPrior`'s\n", - "with `mean=0.0` and `sigma=0.3`. Note that the solution `ell_comps=(0.0, 0.0)` corresponds to a spherical system\n", - "and that all physical solutions (e.g. with axis-ratios running from 0.0 -> 1.0 and position angles 0.0 -> 180.0 degrees) \n", - "are encapsulated for solutions where each component runs from -1.0 -> 1.0). \n", - "\n", - "However, through visual inspection of the image we can often determine the position angle of the galaxy's light, which \n", - "for this data is clearly 45.0 degrees counter-clockwise from the x-axis. We can update the priors on our elliptical \n", - "components to reflect this. The `lower_limit` and `upper_limit` on a `TruncatedGaussianPrior` ensure the solutions cannot go\n", - "outside the physically plausible range -1.0 -> 1.0." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior(\n", - " mean=0.333333, sigma=0.1, lower_limit=-1.0, upper_limit=1.0\n", - ")\n", - "bulge.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior(\n", - " mean=0.0, sigma=0.1, lower_limit=-1.0, upper_limit=1.0\n", - ")\n", - "\n", - "disk.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior(\n", - " mean=0.333333, sigma=0.1, lower_limit=-1.0, upper_limit=1.0\n", - ")\n", - "disk.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior(\n", - " mean=0.0, sigma=0.1, lower_limit=-1.0, upper_limit=1.0\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `effective_radius` of light profile is its 'half-light' radius, the radius at which 50% of its total luminosity \n", - "is internal to a circle defined within that radius. **PyAutoGalaxy** assumes a `UniformPrior` on this quantity between \n", - "0.0\" and 30.0\". This large range of values is required to cover the size of all possible galaxies that can be \n", - "observed in the Universe.\n", - "\n", - "However, inspection of this image shows the galaxy's light does not extend anywhere near 30.0\", so lets reduce its\n", - "value for both bulge and disk components.\n", - "\n", - "We retain an `upper_limit=np.inf`, which means that the maximum physical value that the effective radius \n", - "can go to is infinity, as it is in the real Universe. Equally, the `lower_limit=0.0` ensures unphysical negative\n", - "values are not sampled.\n", - "\n", - "However, the inputs `mean=1.0` and `sigma=0.8` ensure the majority of samples are drawn around much lower values \n", - "between 0.0\" -> 2.0\"." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge.effective_radius = af.TruncatedGaussianPrior(\n", - " mean=1.0, sigma=0.8, lower_limit=0.0, upper_limit=np.inf\n", - ")\n", - "disk.effective_radius = af.TruncatedGaussianPrior(\n", - " mean=1.0, sigma=0.8, lower_limit=0.0, upper_limit=np.inf\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `sersic_index` defines how concentrated the light profile is. In galaxy structure studies, values of Sersic index\n", - "around 1.0 indicate a disk galaxy (which is the value the `Exponential` uses). \n", - "\n", - "Higher values of 3 or 4 indicate an elliptical galaxy. **PyAutoGalaxy** assumes a `UniformPrior` between 0.8 and 5.0\n", - "by default on this parameter, as a user could model galaxies\n", - "where the galaxy is of any morphology.\n", - "\n", - "We are assuming the `bulge` component is a bulge, thus we can change its prior on the `sersic_index` to a value near 3." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge.sersic_index = af.TruncatedGaussianPrior(\n", - " mean=3.0, sigma=1.0, lower_limit=0.0, upper_limit=np.inf\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now compose the overall model, where the galaxy model uses the `Model` components above which had their\n", - "priors customized." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n", - "\n", - "model = af.Collection(galaxies=af.Collection(galaxy=galaxy))" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `info` attribute shows the model, including the priors specified above." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(model.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can now create this custom search and run it. Our non-linear search will now start by sampling higher likelihood \n", - "regions of parameter space, given our improved and more informed priors." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search = af.Nautilus(\n", - " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", - " name=\"tutorial_4_custom_priors\",\n", - " unique_tag=dataset_name,\n", - " n_live=100,\n", - " n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2.\n", - ")\n", - "\n", - "analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", - "\n", - "print(\n", - " \"The non-linear search has begun running - checkout the HowToGalaxy/output/howtogalaxy/chapter_2/tutorial_4_custom_priors\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell will progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", - "result_custom_priors = search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"Search has finished run - you may now continue the notebook.\")\n", - "\n", - "print(result_custom_priors.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Result__\n", - "\n", - "Bam! We get a good model, which corresponds to the global maxima. By giving our non-linear search a helping hand and \n", - "informing it of where to sample parameter space, we can increase the odds that we find the global maxima solution." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_fit_imaging(fit=result_custom_priors.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Discussion__\n", - "\n", - "By tuning our priors to the galaxy we fit we increase the chance of inferring the global maxima model. The search\n", - "may also fit the model a lot faster, given it spends less time searches regions of parameter space that do not\n", - "correspond to good solutions. \n", - "\n", - "Before moving onto the next approach, lets think about the advantages and disadvantages of prior tuning:\n", - "\n", - "Advantages: \n", - "\n", - " - We have a higher chance of finding the globally maximum log likelihood solutions in parameter space.\n", - " - The search took less time to run because the non-linear search explored less of parameter space.\n", - "\n", - "Disadvantages: \n", - "\n", - " - If we specified a prior incorrectly the non-linear search will infer an incorrect solution.\n", - " - The priors for the search were tailored to the specific galaxy we fitted. If we are fitting multiple galaxies,\n", - " we would have to customize the priors for every single fit, for large samples of galaxies this would take a lot of time!\n", - "\n", - "__Approach 2: Reducing Complexity__\n", - "\n", - "The non-linear search may fail because the model is too complex, making its parameter space too difficult to \n", - "sample accurately. Can we can make the model less complex, whilst keeping it realistic enough to perform our \n", - "scientific study? What assumptions can we make to reduce the number of model parameters and therefore \n", - "dimensionality of non-linear parameter space?" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge = af.Model(ag.lp.Sersic)\n", - "disk = af.Model(ag.lp.Exponential)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First, we create a model that assumes that the bulge and disk are geometrically aligned. That is, the bulge and\n", - "disk centres and elliptical components are perfectly aligned with one another. This may, or may \n", - "not, be a reasonable assumption, but it`ll remove 4 parameters from the model (the centre and elliptical \n", - "components of the bulge profile), so it is worth trying!\n", - "\n", - "To apply our assumption that the bulge and disk are geometrically aligned, we `pair` the `centre` and `ell_comps` \n", - "parameters by setting them equal to one another. This removes the parameter on the left-hand side of the pairing from \n", - "the galaxy model such that when a model is created it has the same value as the parameter on the right-hand side." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge.centre = disk.centre\n", - "bulge.ell_comps = disk.ell_comps" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now compose the model, which will have a non-linear parameter space with 4 less dimensions than the fit performed\n", - "previously. " - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n", - "\n", - "model = af.Collection(galaxies=af.Collection(galaxy=galaxy))" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `info` attribute shows the model, including the parameter linking specified above." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(model.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now create this search and run it." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search = af.Nautilus(\n", - " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", - " name=\"tutorial_4_reducing_complexity\",\n", - " unique_tag=dataset_name,\n", - " n_live=100,\n", - " n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2.\n", - ")\n", - "\n", - "print(\n", - " \"The non-linear search has begun running - checkout the HowToGalaxy/output/howtogalaxy/chapter_2/tutorial_4_reducing_complexity\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell will progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", - "result_bulge_disk_align = search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"Search has finished run - you may now continue the notebook.\")\n", - "\n", - "print(result_bulge_disk_align.info)\n", - "\n", - "aplt.subplot_fit_imaging(fit=result_bulge_disk_align.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Result__\n", - "\n", - "The results look pretty good. Our galaxy fits the data pretty well and we've clearly inferred a model that looks \n", - "similar to the one above. However, inspection of the residuals shows that the fit was not quite as good as the \n", - "first search.\n", - "\n", - "It turns out that for this simulation, the bulge and disk had different elliptical components. The quality of the fit \n", - "suffered and the highest value of log likelihood for the search inferred was lower as a result.\n", - "\n", - "Herein lies the pitfalls of making assumptions, they may make your model less realistic and your fits worse! \n", - "\n", - "__Discussion__\n", - "\n", - "Again, lets consider the advantages and disadvantages of this approach:\n", - "\n", - "Advantages:\n", - "\n", - " - By reducing parameter space`s complexity we again had a higher chance of inferring the global maximum log\n", - " likelihood and the time required by the search to do this is reduced.\n", - " - Unlike tuned priors, the search was not specific to one galaxy and we could run it on many galaxy images.\n", - " \n", - "Disadvantages:\n", - "\n", - " - Our model was less realistic and our fit suffered as a result.\n", - "\n", - "__Approach 3: Look Harder__\n", - "\n", - "In approaches 1 and 2 we extended our non-linear search an olive branch and helped it find the highest log likelihood \n", - "regions of parameter space. In approach 3, we're going to tell it to just `look harder`.\n", - "\n", - "Every non-linear search has settings which govern how thoroughly it searches parameter space, with the number of live\n", - "points that was passed to `Nautilus` an example of such a setting. The more thoroughly the search looks, the more likely \n", - "it is that it`ll find the global maximum model. However, the search will also take longer!\n", - "\n", - "We create a more thorough `nautilus` search, that uses `n_live=200`. What these settings\n", - "are actually changing is discussed in the optional tutorial `HowToGalaxy/chapter_optional/tutorial_searches.ipynb`.\n", - "\n", - "Due to the long run times of this search, we comment out the fit below so it does not run. Feel free to undo these\n", - "comments if you wish to perform the search yourself." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp.Sersic, disk=ag.lp.Exponential)\n", - "\n", - "model = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n", - "\n", - "search = af.Nautilus(\n", - " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", - " name=\"tutorial_4_look_harder\",\n", - " unique_tag=dataset_name,\n", - " n_live=200,\n", - " n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2.\n", - ")\n", - "\n", - "print(\n", - " \"The non-linear search has begun running - checkout the HowToGalaxy/output/howtogalaxy/chapter_2/tutorial_4_look_harder\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell will progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", - "# result_look_harder = search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"Search has finished run - you may now continue the notebook.\")\n", - "\n", - "# print(result_look_harder.info)\n", - "\n", - "# aplt.subplot_fit_imaging(fit=result_look_harder.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "lets list the advantages and disadvantages of simply adjusting the non-linear search:\n", - "\n", - "Advantages:\n", - "\n", - " - Its easy to setup, we simply change settings of the non-linear search.\n", - " \n", - " - It generalizes to any galaxy.\n", - " \n", - " - We can make our model as complex as we want.\n", - "\n", - "Disadvantage:\n", - " \n", - " - Its potentially expensive. Very expensive. For very complex models, the run times can be hours, days, weeks or, dare\n", - " I say it, months!\n", - "\n", - "So, we can now fit galaxies. And when it fails, we know how to get it to work. \n", - "\n", - "At the end of this chapter, we will introduce a technique called 'non-linear search chaining', which performs a\n", - "model fit by chaining together multiple searches back-to-back . This allows us to combine the 3 different approaches \n", - "discussed and exploit the advantages of each, whilst not being hindered by their disadvantages.\n", - "\n", - "With search chaining, we can:\n", - "\n", - " - Fit simpler models with lower dimensionality parameter spaces in the earlier searches and gradually increase the\n", - " model complexity search-by-search, guiding the model-fit to a sufficiently realistic model. \n", - " \n", - " - In these earlier searches (with easier to sample parameter spaces), use fast non-linear search settings to compute \n", - " the results quickly and switch to slower settings in later searches when we fit more complex models.\n", - "\n", - " - Use 'prior passing' to setup the priors of each parameter in the later searches, based on the models inferred \n", - " by the earlier searches. We can therefore guide each search on how to sample a complex model's parameter space \n", - " in a way that can be fully generalized to any galaxy.\n", - " \n", - "__Wrap Up__\n", - "\n", - "To wrap up chapter 2, we have a few more tutorials, where we will discuss masking in more detail, the `Result` object\n", - "and how to make **PyAutoGalaxy** run faster." - ] - } - ], - "metadata": { - "anaconda-cloud": {}, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - }, - "colab": { - "aiContexts": { - "24c2f562-da24-50bb-8eb9-5a887505fe54": { - "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", - "name": "PyAutoGalaxy assistant", - "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_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\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_2_modeling/tutorial_4_dealing_with_failure.ipynb in HowToGalaxy).\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 PyAutoGalaxy 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 PyAutoGalaxy docs (https://pyautogalaxy.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) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. 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 galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_debug_fit_failure\n\n---\nname: ag_debug_fit_failure\ndescription: Triage a galaxy fit that crashed, stalled, or finished with residuals and parameters you do not believe. Works through a failure taxonomy — bad environment, bad data, bad model, bad priors, bad search settings, or a stale result that was never re-run — and gives the probes that separate them: hand-evaluating the likelihood at prior medians, checking the mask extent and over-sampling scheme, reading the normalised-residual and chi-squared maps, walking the likelihood step by step, forcing the NumPy path to get a readable stack trace, and the `PYAUTO_TEST_MODE` short-circuit loop for fast iteration. Also covers the two silent failures: a resumed fit whose identifier ignored the data, and a cached result mistaken for a new one. Use when a fit raises, hangs, returns nonsense, or converges somewhere unphysical. Not for the first composition of a model (`ag_build_imaging_model`), not for routine result inspection (`ag_load_results`), and not for an environment that will not import at all (`ag_setup_environment`).\n---\n\n# When the fit goes wrong\n\nA galaxy fit fails in a small number of characteristic ways, and the debugging cost is\ndominated by mis-attribution: hours spent widening priors when the mask was truncating the\nouter isophotes, or rebuilding a model when the script was quietly resuming a cached result\nfrom last week. So the first move is never a fix — it is to establish *which kind* of failure\nthis is.\n\nThe discipline that makes that possible is cheap probes before expensive ones. A single\nlikelihood evaluation costs a fraction of a second and tells you whether the model and data\ncan talk to each other at all. A `PYAUTO_TEST_MODE=2` run costs seconds and proves the whole\nscript executes. Only after those pass is it worth spending an hour of sampling to find out\nwhether the *inference* is the problem.\n\n## Ask\n\nGet the symptom precisely, because the taxonomy branches on it:\n\n- *\"Did it raise, hang, or complete?\"* A raise has a traceback to read. A hang is usually\n parallelisation, a JIT compile you mistook for a stall, or an update cadence writing output\n constantly. A completed fit that looks wrong is the hardest case and needs the residuals.\n- *\"What makes you say it is wrong?\"* Coherent residuals, an unphysical parameter, an error\n bar that is implausibly tight or implausibly wide, or the number simply disagreeing with the\n literature — each points somewhere different.\n- *\"Simulated data or real observations?\"* On simulated data you know the truth, which makes\n everything below faster. If the user has real data and no simulated control, running one is\n often the fastest path to an answer ([`ag_simulate_dataset`](./ag_simulate_dataset.md)).\n- *\"Has this exact script run before?\"* This decides whether the stale-result trap is in play.\n\n## The taxonomy\n\nSix categories, ordered by how cheap they are to rule out:\n\n| Category | Tell | First probe |\n|---|---|---|\n| **Stale output** | The fit \"finished\" implausibly fast, or the result is identical after you changed something | Delete the `` folder and re-run |\n| **Environment** | An import error, a numba or matplotlib cache error, a parallelisation error the moment the search starts | `--check-install`, the cache variables, the main guard |\n| **Bad data** | Residuals dominated by one blob, or a suspiciously large chi-squared everywhere | Plot the dataset; check the noise-map and the mask |\n| **Bad model** | Coherent, structured residuals with a physical shape | Read the residual pattern; add or change a component |\n| **Bad priors** | The best fit sits on a prior boundary, or the search never moves off its start | `model.info`; hand-evaluate the likelihood |\n| **Bad search settings** | Wide posteriors, a low log evidence, different runs disagreeing, no errors at all | `search.summary`; raise `n_live`, or change search |\n\nThe rest of this skill is one branch per category.\n\n## Branch — stale output, the silent one\n\nRule this out first, every time, because it is invisible and it invalidates everything else you\nwould conclude.\n\nA fit's output folder is `output/////`, and\n`` is derived from the model, the search settings and the dataset identifier. An\nidentical configuration therefore **resumes** rather than restarting\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Unique Identifier__`). That is a\nfeature for an interrupted overnight run and a trap the rest of the time, because **the\nidentifier does not hash the pixel values of your data**. Swap `data.fits` for a different\ngalaxy while keeping the model, search and `unique_tag` the same, and the next run finds a\ncompleted fit at the same path and hands it back — in seconds, with the previous galaxy's\nparameters, and no warning that anything is wrong.\n\nThe symptoms: a fit that completes far faster than it should; a result that does not change\nafter you deliberately changed the data; `model.results` timestamps older than the run you\njust launched.\n\n```bash\n# Prove it rather than reasoning about it.\nrm -rf output////\n```\n\nThen re-run. If the answer changes, that was the bug. Going forward, change the `unique_tag`\nwhenever the data changes — that is what it is for.\n\nThe related trap: test-mode output. Any active `PYAUTO_TEST_MODE` level inserts a `test_mode`\nsegment straight after the output root, precisely so a smoke run cannot short-circuit a later\nreal fit ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)). If you\nfind yourself inspecting a result whose path contains `test_mode`, stop: every parameter in it\nis a wiring check. Also delete any simulated `dataset/` when you toggle\n`PYAUTO_SMALL_DATASETS`, or a full-resolution dataset on disk gets reused against capped grids\nand produces shape errors that look like library bugs.\n\n## Branch — environment and the errors that fire at launch\n\nIf the stack itself is the problem, nothing downstream is diagnostic. Confirm the install\nfirst:\n\n```bash\npython autoassistant/audit_skill_apis.py --check-install\n```\n\nExit `0` is ready; `2` means the packages are absent from *this* interpreter; `3` means they\nwere found but an import raised. Repairing it is\n[`ag_setup_environment`](./ag_setup_environment.md), with the routes in\n[`wiki/core/operations/installation.md`](../wiki/core/operations/installation.md).\n\nThree failures that are environment, not science:\n\n- **A numba or matplotlib cache error** buried in a long trace — the libraries cannot write\n their caches. Fix with `NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib`\n ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n- **An error the instant the search starts**, from Python's process spawning rather than from\n your model. Wrap the fit in a function under a main guard, exactly as\n `autogalaxy_workspace:scripts/guides/modeling/bug_fix.py` does — it is the same\n `modeling.py` fit with this one structural change:\n\n ```python\n def fit():\n from autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\n import autofit as af\n import autogalaxy as ag\n\n # ... dataset, mask, over-sampling, model, search, analysis ...\n result = search.fit(model=model, analysis=analysis)\n\n\n if __name__ == \"__main__\":\n fit()\n ```\n\n It applies to every dataset type, so adopt it for any modeling script that hits the error.\n That script also names the project's support channel if the fix is not enough.\n- **A stale API symbol** — an `AttributeError` on a PyAuto\\* name recalled from an older\n release. Do not guess a replacement; check it:\n\n ```bash\n python autoassistant/audit_skill_apis.py --file scripts/run_fit.py\n ```\n\n [`ag_audit_skill_apis`](./ag_audit_skill_apis.md) owns that check and its bypass.\n\n### Is it a JAX problem?\n\nThe single most useful lever, because it splits the space in two:\n\n```python\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=False)\n```\n\nor, without editing code, `PYAUTO_DISABLE_JAX=1` to force the NumPy path on every analysis\n(`autogalaxy_workspace:scripts/guides/using_jax.py` `__Disabling JAX__`). NumPy stack traces\nare far easier to read than compiled ones, and you can drop a debugger or a `print` into code\nJAX would otherwise compile away. If the failure disappears on NumPy, it is a JAX problem; if\nit survives, JAX was never involved and you have halved the search space.\n\nTwo JAX-specific failure shapes worth recognising:\n\n- **An out-of-memory error at compile time or on the first likelihood call** on a GPU. Check\n the footprint before a long run:\n `analysis.print_vram_use(model=model, batch_size=search.batch_size)`\n (`autogalaxy_workspace:scripts/imaging/modeling.py` `__VRAM Use__`), and lower the batch\n size if it is close to the card's limit.\n- **A long pause at the start that looks like a hang.** The first evaluation compiles the\n likelihood and its gradient; every step after that re-uses the compiled result. The log\n line announcing the compile is the tell\n (`autogalaxy_workspace:scripts/imaging/start_here.py` `__JAX__`). A persistent compilation\n cache means this is paid once per machine, not once per process\n ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## Branch — bad data\n\nPlot the dataset before you plot anything else. On real observations this is not optional —\nthe inspection gate in [`../AGENTS.md`](../AGENTS.md) requires it before a fit is even\ncomposed, and a fit that skipped it is a prime suspect.\n\n```python\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=PLOT_DIR,\n output_filename=\"dataset\",\n output_format=\"png\",\n)\n```\n\nFour things to check, in order:\n\n1. **Contaminants.** A neighbouring galaxy, a foreground star or a reduction artefact inside\n the mask contributes to the likelihood and biases every parameter. The fix is to scale its\n noise rather than cut the pixels out — `dataset.apply_noise_scaling(mask=mask_extra_galaxies)`\n keeps the pixels in the fit but makes them contribute negligibly, which avoids the\n discontinuities that removing pixels creates\n (`autogalaxy_workspace:scripts/imaging/modeling.py` `__Extra Galaxies Noise Scaling__`).\n Alternatively shrink the circular mask so the contaminant falls outside it. Concept:\n [`wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md);\n the tooling is [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md).\n2. **The mask extent.** Too small and it truncates the outer isophotes, which biases the\n effective radius and the Sersic index directly — the classic cause of a \"wrong\" Sersic\n index. Too large and it drags sky and neighbours in, slowing the fit for no information.\n [`wiki/core/concepts/grids_and_masks.md`](../wiki/core/concepts/grids_and_masks.md)\n \"Choosing the radius is a science decision\".\n3. **The noise-map.** If it is underestimated, chi-squared is uniformly too large and the\n posterior is spuriously tight; if overestimated, the reverse. A residual map that is\n featureless but scaled wrong across the whole image points here rather than at the model.\n4. **`pixel_scales`.** Wrong by a factor and every angular quantity is wrong by that factor,\n while the fit looks perfectly healthy. Check it against the instrument.\n\n## Branch — bad model\n\nThis is what coherent residuals mean. Rebuild the fit and read the maps:\n\n```python\nfit = result.max_log_likelihood_fit # or ag.FitImaging(dataset=dataset, galaxies=galaxies)\n\nprint(f\"chi_squared = {fit.chi_squared}\")\nprint(f\"log_likelihood = {fit.log_likelihood}\")\nprint(f\"figure_of_merit = {fit.figure_of_merit}\")\n\naplt.plot_array(\n array=fit.normalized_residual_map,\n title=\"Normalized Residual Map\",\n symmetric=True,\n output_path=PLOT_DIR,\n output_filename=\"normalized_residual_map\",\n output_format=\"png\",\n)\naplt.plot_array(\n array=fit.chi_squared_map,\n title=\"Chi-Squared Map\",\n output_path=PLOT_DIR,\n output_filename=\"chi_squared_map\",\n output_format=\"png\",\n)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Fit Figures__`. Read the\n**normalised** residuals first: they are the only map calibrated against the noise, so they\nanswer *significance* rather than *magnitude*. Scatter within roughly ±3 is consistent with\nnoise; coherent structure outside that is a model failure however faint it looks.\n\nTwo quick numerical summaries worth printing alongside the figures — chi-squared per unmasked\npixel (order unity for a good fit), and the fraction of pixels beyond 3σ (a few per cent for a\ngood fit, tens of per cent for a badly wrong model).\n\nThe residual patterns and what each implies are tabulated in\n[`ag_plot_fit`](./ag_plot_fit.md) \"The inspection discipline\". The model responses:\n\n- **Ring at one radius** → the radial profile is too rigid. One Sersic where a bulge plus a\n disk is needed, or a Sersic index that was fixed. Free it, or add the second component.\n- **Four-lobed alternating pattern** → the ellipticity or position angle is wrong, or the\n isophotes twist with radius. [`wiki/core/concepts/ellipse_fitting_and_multipoles.md`](../wiki/core/concepts/ellipse_fitting_and_multipoles.md).\n- **Central excess** → coarse over-sampling, or a nuclear component the model lacks. Check the\n over-sampling scheme before adding physics (below).\n- **Clumpy, asymmetric structure no smooth profile can absorb** → this is where a\n many-component basis or a pixelised reconstruction earns its keep:\n [`wiki/core/concepts/linear_light_profiles_and_mge.md`](../wiki/core/concepts/linear_light_profiles_and_mge.md),\n [`wiki/core/concepts/shapelets.md`](../wiki/core/concepts/shapelets.md),\n [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n- **A uniform offset across the whole image** → an unmodelled sky background:\n [`wiki/core/concepts/sky_background_and_operated_profiles.md`](../wiki/core/concepts/sky_background_and_operated_profiles.md).\n\n**Check the over-sampling before blaming the physics.** A steep central profile evaluated once\nper pixel is systematically wrong at the centre, and the symptom is exactly the residual a\nmissing nuclear component would leave:\n\n```python\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py` `__Over Sampling__`. Re-plot\nthe dataset subplot afterwards — its lower panels show the scheme that was actually applied,\nso you can confirm it rather than assume it. The full treatment, including why the outer bins\nnever drop to a single sub-pixel, is\n[`wiki/core/concepts/grids_and_masks.md`](../wiki/core/concepts/grids_and_masks.md)\n\"Over-sampling\", with the runnable guide at\n`autogalaxy_workspace:scripts/guides/advanced/over_sampling.py`.\n\nAdding complexity is [`ag_build_imaging_model`](./ag_build_imaging_model.md). Do it one\ncomponent at a time and re-fit: a model that gained three components at once tells you nothing\nabout which one mattered.\n\n## Branch — bad priors, and hand-evaluating the likelihood\n\nThe most direct probe in the whole stack. A model and an analysis are enough — no search, no\nwaiting:\n\n```python\ninstance = model.instance_from_prior_medians()\nlog_likelihood = analysis.log_likelihood_function(instance=instance)\n\nprint(f\"log likelihood at prior medians = {log_likelihood}\")\n```\n\nFrom [`wiki/core/api/analysis_objects.md`](../wiki/core/api/analysis_objects.md) \"Evaluating\nthe likelihood by hand\". `log_likelihood_function(instance)` is the single contract between a\nmodel and data, so what it returns is diagnostic on its own:\n\n- **It raises.** The failure is in the forward model or the data shapes, not in the inference.\n Force `use_jax=False` first for a readable trace, then walk the likelihood step by step\n (next branch).\n- **It returns `nan` or `-inf`.** Something in the model is degenerate at those parameter\n values — a zero or negative size, a profile whose centre sits outside the mask, a noise-map\n with zeros.\n- **It returns a finite but wildly bad value, and the fit's best likelihood is barely better.**\n The search never found anything, which usually means the priors do not contain the answer.\n- **It returns something close to the fit's best value.** The priors are fine and the search\n is doing its job; look elsewhere.\n\nThen compare against a known-good instance. On simulated data you have the truth, so evaluate\nthe likelihood there: if the true model scores much better than anything the search found, the\npriors or the search settings are at fault, not the model. This is the cleanest experiment\navailable, and it is the reason to keep a simulated control alongside real data\n([`ag_simulate_dataset`](./ag_simulate_dataset.md)).\n\nRead the priors themselves rather than recalling them:\n\n```python\nprint(model.info)\n```\n\nThree specific things to look for. **A best-fit parameter sitting on a prior boundary** means\nthe prior is truncating the posterior — the answer may be outside it entirely. **A prior far\nwider than physically sensible** wastes the search's effort and invites multi-modality. And\n**a prior narrowed to make a search behave** is a scientific choice, not a convenience: it\nchanges the posterior and therefore the answer. If you want to steer where a search *starts*\nwithout changing the posterior, that is a start point, and only the MCMC and optimisation\nsearches accept one — nested samplers draw from the prior by construction\n([`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n\"Priors and start points\"). Defaults come from configuration\n([`wiki/core/api/configuration.md`](../wiki/core/api/configuration.md)), and overriding them\nper parameter is [`ag_build_imaging_model`](./ag_build_imaging_model.md).\n\nAlso confirm the galaxy is near the coordinate origin. The default priors assume a centre near\n(0.0\", 0.0\"); a galaxy several arcseconds off-centre needs either re-centred data or\nexplicitly overridden centre priors (`autogalaxy_workspace:scripts/imaging/modeling.py`\n`__Coordinates__`).\n\n## Branch — walking the likelihood step by step\n\nWhen the hand evaluation raises or returns something inexplicable, the step-by-step\nwalkthrough is the ground truth. `autogalaxy_workspace:scripts/imaging/likelihood_function.py`\ncomputes a galaxy model's log likelihood one NumPy operation at a time — the elliptical\ncoordinate transform, each light profile's image, the sum into a galaxy image, the blurring\ngrid and PSF convolution, then:\n\n```\nmodel_data = convolved_image_2d\nresidual_map = data - model_data\nnormalized_residual_map = residual_map / noise_map\nchi_squared_map = normalized_residual_map ** 2\nchi_squared = sum(chi_squared_map)\nnoise_normalization = sum(log(2 * pi * noise_map ** 2))\nfigure_of_merit = -0.5 * (chi_squared + noise_normalization)\n```\n\nand finishes by showing that `ag.FitImaging(dataset=dataset, galaxies=galaxies).figure_of_merit`\nreproduces the same number. Running it against your own dataset localises the failure to one\nstep, which is far faster than reading a compiled trace.\n\nThere are matching walkthroughs for the features whose likelihood is genuinely different, and\nthe difference is where their failures live:\n`autogalaxy_workspace:scripts/imaging/features/linear_light_profiles/likelihood_function.py`\n(the mapping matrix, data vector, curvature matrix and the positive-only reconstruction),\n`.../multi_gaussian_expansion/likelihood_function.py` (the same for a Gaussian basis), and\n`.../pixelization/likelihood_function.py` (the regularisation matrix and the Bayesian\ncomplexity terms). If a fit with linear profiles or a pixelisation fails where a standard\nprofile fit succeeds, the extra linear-algebra steps in those scripts are the place to look.\n\nA real fit does not run that NumPy code — it runs the same calculation compiled. To probe the\ncompiled path exactly as a search drives it, `autogalaxy_workspace:scripts/guides/using_jax.py`\n`__Custom Likelihood Functions__` shows the `Fitness` route, and explains why batching a vector\nof parameters is a stricter test than one concrete call: a single call can quietly succeed on\ncode where NumPy is leaking through, and then break as soon as the search batches.\n\n## Branch — bad search settings\n\nThe model and data are fine; the sampler did not do its job. Read the search's own report\nfirst: `search.summary` in the output folder, plus `result.samples.log_evidence` and the\nposterior widths.\n\n- **Posteriors far wider than the data should allow, or a low log evidence** → too few live\n points for the model's dimensionality. `n_live=200` covers most galaxy models; raise it for\n a complex one ([`wiki/core/api/searches.md`](../wiki/core/api/searches.md)).\n- **No errors at all** → the fit used a gradient optimiser, which is maximum-a-posteriori and\n returns one model. Re-run with `Nautilus` if the science needs uncertainties\n (`autogalaxy_workspace:scripts/imaging/start_here.py` `__Posterior__`).\n- **Two runs of the same configuration disagreeing** → a multi-modal parameter space with a\n search that is finding different modes. Either raise `n_live`, or start simple and chain into\n the complex model with the simple fit's posterior as priors\n ([`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n \"Search chaining\"; the runnable version is\n `autogalaxy_workspace:scripts/guides/modeling/chaining.py`).\n- **Run time far longer than expected** → total cost is (likelihood evaluation time) ×\n (number of evaluations), and dimensionality dominates. A many-Gaussian expansion with six\n free parameters routinely beats a multi-component decomposition with thirteen, despite the\n slower per-evaluation cost. [`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n \"Run-time estimation\".\n- **The log constantly reporting that it is outputting results** → `iterations_per_quick_update`\n is too low and visualisation is eating the run. Raise it\n ([`ag_run_search`](./ag_run_search.md)).\n\nChoosing and tuning the search is [`ag_configure_search`](./ag_configure_search.md).\n\n## Branch — the fast iteration loop\n\nWhile you are changing a script's structure, do not pay for inference. `PYAUTO_TEST_MODE` has\nfour levels ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)):\n\n```bash\n# Level 2 — sampler bypassed, likelihood called exactly once. The fastest proof that the\n# model composes, the shapes agree and the likelihood evaluates.\nPYAUTO_TEST_MODE=2 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n\n# Level 1 — a real but minimal search. Slower, and the only level that writes model.results,\n# image/fit.png and a loadable samples.csv.\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\nLevel 2 does **not** write the fit products, which is worth knowing before you go looking for\n`image/fit.png` after a level-2 run. Level 3 skips the likelihood as well, so it only checks\nthe non-fitting scaffolding. `PYAUTO_SKIP_CHECKS=1` is available when a smoke run trips a\nruntime validation on data too small to be sane — never set it for a real fit, since those\nchecks are what stop a silently degenerate inversion. And **never quote a parameter measured\nin test mode**: the sampler was truncated or mocked, so the numbers are wiring evidence, not\nmeasurements.\n\nThe loop that works: level 2 until the script runs clean → level 1 until the products look\nsane → one full run on a small mask or a simulated dataset → the production fit.\n\n## Branch — when nothing above explains it\n\nTwo escalations, in order.\n\n**Reduce to a control.** Simulate a dataset from a model you choose, fit it with that same\nmodel, and confirm you recover the truth\n([`ag_simulate_dataset`](./ag_simulate_dataset.md)). If the control fails, the problem is in\nthe code or the setup. If the control succeeds, the problem is in the real data or its\npreparation — and you have narrowed it to a half of the space you could not distinguish\nbefore. This is the single highest-value move in this skill and it is under-used.\n\n**Check the library, not yourself.** If a symbol does not resolve or an idiom that reads\ncorrectly does not work, run the audit — a construction can be retired while every token in it\nstill imports:\n\n```bash\npython autoassistant/audit_skill_apis.py --scope scripts\npython autoassistant/audit_skill_apis.py --lint-idioms\n```\n\n[`ag_audit_skill_apis`](./ag_audit_skill_apis.md) owns both. Only after those come back clean\nis \"this might be a library bug\" a reasonable hypothesis — at which point\n[`contribute-upstream`](./contribute-upstream.md) is the route to filing it with a minimal\nreproduction.\n\n## Combine\n\n- [`ag_plot_fit`](./ag_plot_fit.md) — the residual-pattern table this skill's model branch\n routes through, and the figures that make a diagnosis visible.\n- [`ag_build_imaging_model`](./ag_build_imaging_model.md) — acting on a \"bad model\" or \"bad\n priors\" verdict.\n- [`ag_configure_search`](./ag_configure_search.md) — acting on a \"bad search settings\"\n verdict.\n- [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md) — acting on a \"bad data\" verdict:\n masks, noise scaling, contaminant handling.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) — the control experiment.\n- [`ag_setup_environment`](./ag_setup_environment.md) — the install will not import at all.\n- [`ag_run_search`](./ag_run_search.md) — re-launching once the cause is fixed.\n\nRecord the diagnosis, not just the fix. Offer (default-yes) a dated\n`wiki/project/YYYY-MM-DD-.md` entry naming the symptom, the probe that localised it, and\nwhat changed — per [`_style.md`](./_style.md) property #5. A debugging session that is not\nwritten down gets repeated.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Dealing with failure](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_4_dealing_with_failure.ipynb):\n why searches fail on galaxy models, what a local maximum looks like in practice, and how\n model complexity and prior choice interact.\n- **General reference** — [RTD: Likelihood function](https://pyautogalaxy.readthedocs.io/en/latest/general/likelihood_function.html):\n the likelihood the library evaluates, and pointers into the step-by-step walkthroughs.\n- **Experienced PyAutoGalaxy user** — [workspace: guides/modeling/bug_fix.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/guides/modeling/bug_fix.py):\n the main-guard fix for the parallelisation error, as a complete runnable fit.\n\n## Agent procedural checklist\n\n1. Get the symptom: raised, hung, or completed-but-wrong; and what makes it wrong.\n2. Rule out stale output first — check timestamps, then `rm -rf` the `` folder and\n re-run. Check for a `test_mode` path segment.\n3. Confirm the environment with `--check-install`; apply the cache variables and the main guard\n if either applies.\n4. Toggle `use_jax=False` (or `PYAUTO_DISABLE_JAX=1`) to split JAX from non-JAX failures and\n get a readable trace.\n5. Plot the dataset: contaminants, mask extent, noise-map, `pixel_scales`.\n6. Hand-evaluate `analysis.log_likelihood_function(instance=model.instance_from_prior_medians())`\n before running any search.\n7. Read `model.info` for boundary-hugging and over-wide priors; confirm the galaxy is near the\n origin.\n8. Rebuild the fit and read the **normalised residual** map, then the chi-squared map; check\n the over-sampling scheme before adding physics.\n9. Read `search.summary` and the log evidence for search-settings failures.\n10. Iterate with `PYAUTO_TEST_MODE=2`, then `=1`; never quote a test-mode parameter.\n11. If unresolved, build a simulated control and fit it; run the symbol and idiom audits before\n suspecting a library bug.\n12. Offer the `wiki/project/` entry recording symptom, probe and fix.\n" - } - }, - "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file diff --git a/notebooks/chapter_2_modeling/tutorial_4_linear_profiles.ipynb b/notebooks/chapter_2_modeling/tutorial_4_linear_profiles.ipynb new file mode 100644 index 0000000..0788c91 --- /dev/null +++ b/notebooks/chapter_2_modeling/tutorial_4_linear_profiles.ipynb @@ -0,0 +1,499 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Tutorial 4: Linear Profiles\n", + "===========================\n", + "\n", + "In tutorial 3, simplifying the bulge and disk geometry made the search easier but restricted the galaxies it could\n", + "represent. Linear light profiles offer a different opportunity: keep the same profile shapes and solve their\n", + "intensities directly, removing those dimensions from the non-linear search.\n", + "\n", + "We will then combine many linear Gaussians into a multi Gaussian expansion (MGE). This gives us more freedom to\n", + "represent galaxy structure without asking Nautilus to search every Gaussian's brightness and size.\n", + "\n", + "__Contents__\n", + "\n", + "- **Linear Light Profiles:** Fit shapes while solving intensities directly.\n", + "- **Results and Intensities:** Retrieve and plot the solved profiles.\n", + "- **Galaxy Structure:** Motivate a more flexible description of the light.\n", + "- **Basis:** Build and inspect a group of Gaussians.\n", + "- **Two Gaussian Groups:** Represent different central and outer shapes.\n", + "- **Benefits and Limitations:** Understand what an MGE can and cannot describe." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Google Colab Setup__\n", + "\n", + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, + "outputs": [], + "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", + "try:\n", + " import google.colab\n", + "except ImportError:\n", + " from autogalaxy import setup_colab as _setup_colab\n", + "else:\n", + " import importlib\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.check_call(\n", + " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", + " )\n", + " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", + "\n", + "_setup_colab.setup(\"howtogalaxy\")" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from autogalaxy import setup_notebook; setup_notebook()\n", + "\n", + "from pathlib import Path\n", + "import numpy as np\n", + "import autofit as af\n", + "import autogalaxy as ag\n", + "import autogalaxy.plot as aplt" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Dataset and Mask__\n", + "\n", + "Load the imaging data and retain the region inside the circular mask. The simulator creates the data if needed.\n", + "The image, noise map and PSF together describe the observation; none specifies which galaxy model we must fit." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "dataset_name = \"simple\"\n", + "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name\n", + "if ag.util.dataset.should_simulate(str(dataset_path)):\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.run([sys.executable, \"scripts/simulators/simple.py\"], check=True)\n", + "\n", + "dataset = ag.Imaging.from_fits(\n", + " data_path=dataset_path / \"data.fits\",\n", + " noise_map_path=dataset_path / \"noise_map.fits\",\n", + " psf_path=dataset_path / \"psf.fits\",\n", + " pixel_scales=0.1,\n", + ")\n", + "mask = ag.Mask2D.circular(\n", + " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5\n", + ")\n", + "dataset = dataset.apply_mask(mask=mask)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Over Sampling__\n", + "\n", + "The bright centre changes rapidly across a pixel. Adaptive over sampling evaluates it on a finer grid so that\n", + "numerical inaccuracies do not masquerade as poor models. The outskirts need fewer evaluations." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n", + " grid=dataset.grid,\n", + " sub_size_list=[8, 4, 2],\n", + " radial_list=[0.3, 0.6],\n", + " centre_list=[(0.0, 0.0)],\n", + ")\n", + "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n", + "aplt.subplot_imaging_dataset(dataset=dataset)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Linear Light Profiles__\n", + "\n", + "For a chosen centre, shape, size and Sersic index, changing intensity simply scales a profile's image. Linear\n", + "algebra can therefore calculate the intensities that best fit the data for that trial geometry. We call this\n", + "calculation an inversion. The `ag.lp_linear` profiles use it automatically within the likelihood evaluation.\n", + "\n", + "With an ordinary bulge and disk there are two intensity dimensions to search. Linear profiles remove both,\n", + "without removing either physical component. The intensities are still fitted; they are not fixed or ignored.\n", + "We also share the centres here, while retaining separate elliptical components because the image motivates them." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "bulge = af.Model(ag.lp_linear.Sersic)\n", + "disk = af.Model(ag.lp_linear.Exponential)\n", + "bulge.centre = disk.centre\n", + "model = af.Collection(\n", + " galaxies=af.Collection(\n", + " galaxy=af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n", + " )\n", + ")\n", + "print(model.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There is no intensity prior in this summary. At each trial geometry the intensities are solved conditionally;\n", + "this is not the same as sampling their full uncertainty distribution. Other parameter degeneracies remain, so\n", + "linear profiles make the search simpler without making it immune to failure.\n", + "\n", + "__Search and Analysis__\n", + "\n", + "The public modelling interface is unchanged. The Analysis object now includes the linear solve in its calculation\n", + "of the likelihood. This adds work per evaluation but can reduce the number of evaluations needed to explore the\n", + "model. Overall runtime depends on the data, hardware and search; there is no universal speed-up factor." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", + "\n", + "search = af.Nautilus(\n", + " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", + " name=\"tutorial_4_linear_light_profiles\",\n", + " unique_tag=dataset_name,\n", + " n_live=100,\n", + " n_batch=50,\n", + ")\n", + "result_linear = search.fit(model=model, analysis=analysis)\n", + "print(result_linear.info)\n", + "aplt.subplot_fit_imaging(fit=result_linear.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Intensities__\n", + "\n", + "The result summary describes the searched parameters. To inspect the solved intensities, use the galaxies in\n", + "`max_log_likelihood_galaxies`. Their linear profiles have been converted to ordinary profiles with the solved\n", + "intensities. The fit also provides an explicit conversion property for this purpose." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "galaxies = result_linear.max_log_likelihood_galaxies\n", + "print(galaxies[0].bulge.intensity)\n", + "fit = result_linear.max_log_likelihood_fit\n", + "solved_galaxies = fit.galaxies_linear_light_profiles_to_light_profiles\n", + "print(solved_galaxies[0].disk.intensity)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Visualisation__\n", + "\n", + "An unsolved linear profile has no brightness with which to draw its image. Plot the converted galaxies, or plot\n", + "the fit itself, which already contains the calculated model image. Compare the bulge and disk light with the data." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "aplt.plot_array(\n", + " array=galaxies.image_2d_from(grid=dataset.grid), title=\"Solved galaxy image\"\n", + ")\n", + "aplt.subplot_fit_imaging(fit=fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Galaxy Structure__\n", + "\n", + "A single Sersic profile describes a smooth radial decline with one axis ratio and orientation. Real galaxies can\n", + "have a round central component and a flatter outer disk; their apparent flattening or orientation can change with\n", + "radius. A fixed Sersic shape cannot freely follow these changes, even if its central brightness is a good match.\n", + "\n", + "An MGE adds Gaussians with different widths. Narrow Gaussians describe the central light and broader Gaussians\n", + "describe the outskirts. Their fitted intensities let the radial brightness change more freely than a single\n", + "Sersic law. Groups with different elliptical shapes can represent changes in flattening and isophotal twists,\n", + "where the orientation of equal-brightness contours varies across the galaxy.\n", + "\n", + "This flexibility depends on the geometry we allow. Gaussians sharing a centre remain centrally symmetric even\n", + "when their angles differ. Asymmetric light requires offset centres or other freedom. An MGE does not automatically\n", + "capture every irregular feature simply because it contains many profiles.\n", + "\n", + "__Basis__\n", + "\n", + "A `Basis` groups linear profiles into one component. First build 30 Gaussians with fixed widths spanning 0.01\n", + "arcseconds (one tenth of the pixel scale) to 2.5 arcseconds. They share two centre coordinates and two elliptical\n", + "components, so only four parameters describe their non-linear geometry.\n", + "\n", + "The width range is a modelling choice covering the scales of this example, not a statement that the profiles\n", + "end at the mask. Every Gaussian extends beyond its width and the mask boundary." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "total_gaussians = 30\n", + "sigma_list = np.logspace(\n", + " np.log10(dataset.pixel_scales[0] / 10.0), np.log10(2.5), total_gaussians\n", + ")\n", + "centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", + "centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", + "bulge_gaussians = af.Collection(\n", + " af.Model(ag.lp_linear.Gaussian) for _ in range(total_gaussians)\n", + ")\n", + "for i, gaussian in enumerate(bulge_gaussians):\n", + " gaussian.centre.centre_0 = centre_0\n", + " gaussian.centre.centre_1 = centre_1\n", + " gaussian.ell_comps = bulge_gaussians[0].ell_comps\n", + " gaussian.sigma = sigma_list[i]\n", + "bulge = af.Model(ag.lp_basis.Basis, profile_list=bulge_gaussians)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Before running a search, turn this model into a concrete trial instance using the median of each prior.\n", + "These are example parameter values, not fitted values. The linear solve will find intensities for this geometry,\n", + "but cannot change the geometry itself. This distinction is the reason we still need a non-linear search." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "trial_bulge = bulge.instance_from_prior_medians()\n", + "trial_galaxies = ag.Galaxies(galaxies=[ag.Galaxy(redshift=0.5, bulge=trial_bulge)])\n", + "trial_fit = ag.FitImaging(dataset=dataset, galaxies=trial_galaxies)\n", + "aplt.subplot_fit_imaging(fit=trial_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The default trial shape is round. Inspect where it leaves light along the elongated disk. More Gaussian widths\n", + "can improve a radial profile, but cannot turn a shared round shape into an ellipse or give the bulge and disk\n", + "different shapes. Those freedoms must be present in our model.\n", + "\n", + "__Two Gaussian Groups__\n", + "\n", + "Add ten Gaussians for a second group. They share the first group's centre but have their own elliptical components.\n", + "The two groups can now represent the rounder centre and flatter outer light with different weights at different\n", + "radii. Calling them `bulge` and `disk` is convenient, but does not prove a unique physical decomposition." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "disk_gaussians = af.Collection(af.Model(ag.lp_linear.Gaussian) for _ in range(10))\n", + "disk_sigmas = np.logspace(np.log10(dataset.pixel_scales[0] / 10.0), np.log10(2.5), 10)\n", + "for i, gaussian in enumerate(disk_gaussians):\n", + " gaussian.centre.centre_0 = centre_0\n", + " gaussian.centre.centre_1 = centre_1\n", + " gaussian.ell_comps = disk_gaussians[0].ell_comps\n", + " gaussian.sigma = disk_sigmas[i]\n", + "disk = af.Model(ag.lp_basis.Basis, profile_list=disk_gaussians)\n", + "model = af.Collection(\n", + " galaxies=af.Collection(\n", + " galaxy=af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n", + " )\n", + ")\n", + "print(model.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The 40 intensities are solved linearly and the widths are fixed. Two shared centre coordinates plus two shape\n", + "parameters for each group give six non-linear parameters. The longer model summary does not mean a larger search\n", + "space than the earlier Sersic-plus-Exponential model.\n", + "\n", + "Fit this model with Nautilus and inspect the new result. The live-point setting is illustrative; assess its\n", + "reliability from the fit and repeat searches when needed." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "search = af.Nautilus(\n", + " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", + " name=\"tutorial_4_mge\",\n", + " unique_tag=dataset_name,\n", + " n_live=100,\n", + " n_batch=50,\n", + ")\n", + "result_mge = search.fit(model=model, analysis=analysis)\n", + "print(result_mge.info)\n", + "aplt.subplot_fit_imaging(fit=result_mge.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__MGE Result__\n", + "\n", + "Use the new result to plot the fitted light and residuals. Its converted galaxies contain ordinary Gaussians with\n", + "all 40 solved intensities, so they can also be used for subsequent calculations and visualisation." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "galaxies_mge = result_mge.max_log_likelihood_galaxies\n", + "aplt.subplot_galaxies(galaxies=galaxies_mge, grid=dataset.grid)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Benefits and Limitations__\n", + "\n", + "An MGE can follow a more flexible radial light distribution and, with suitable groups, changes in apparent shape.\n", + "It does this with a compact non-linear parameter space. Fixed widths and solved intensities remove difficult\n", + "search directions, although overlapping Gaussians and geometric parameters can still be degenerate.\n", + "\n", + "The extra profiles and linear solve cost computation. An MGE is also less directly interpretable than a Sersic\n", + "index and effective radius: an individual Gaussian is a mathematical building block, not a separate stellar\n", + "population. Choose the representation for the scientific question, not only the appearance of its residuals.\n", + "\n", + "The workspace example `autogalaxy_workspace/scripts/imaging/features/multi_gaussian_expansion/modeling.py`\n", + "explores more flexible MGE models. Our common-centre example cannot represent off-centre star-forming clumps or\n", + "arbitrary asymmetric structure. Additional centres add freedom, but choosing a centre for every knot is cumbersome.\n", + "Chapter 3 introduces pixelizations to reconstruct more irregular light without prescribing such components.\n", + "\n", + "__Non-negative Intensities__\n", + "\n", + "The linear solve constrains these light-profile intensities to be non-negative, including zero. This avoids\n", + "representing positive light through large positive and negative Gaussians that cancel one another. A zero\n", + "intensity simply means that a Gaussian is not needed for that trial geometry. This constraint does not guarantee\n", + "that the geometry or scientific interpretation is correct.\n", + "\n", + "__Other Basis Functions__\n", + "\n", + "Shapelets provide another way to expand a galaxy's light. Their different functions can describe other structure,\n", + "but their flexibility and computational cost must be assessed for the particular dataset. A worked example is in\n", + "`autogalaxy_workspace/scripts/imaging/features/shapelets/modeling.py`; it is optional background after this course.\n", + "\n", + "__Wrap Up__\n", + "\n", + "We can simplify the search while retaining, or increasing, flexibility in the light model. The next tutorial\n", + "turns back to the data: which measurements should enter the fit, how should contaminants be handled, and how does\n", + "the Analysis object turn those choices into a likelihood?" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.1" + }, + "colab": { + "aiContexts": { + "24c2f562-da24-50bb-8eb9-5a887505fe54": { + "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", + "name": "PyAutoGalaxy assistant", + "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_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\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_2_modeling/tutorial_4_linear_profiles.ipynb in HowToGalaxy).\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 PyAutoGalaxy 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 PyAutoGalaxy docs (https://pyautogalaxy.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) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. 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 galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_debug_fit_failure\n\n---\nname: ag_debug_fit_failure\ndescription: Triage a galaxy fit that crashed, stalled, or finished with residuals and parameters you do not believe. Works through a failure taxonomy — bad environment, bad data, bad model, bad priors, bad search settings, or a stale result that was never re-run — and gives the probes that separate them: hand-evaluating the likelihood at prior medians, checking the mask extent and over-sampling scheme, reading the normalised-residual and chi-squared maps, walking the likelihood step by step, forcing the NumPy path to get a readable stack trace, and the `PYAUTO_TEST_MODE` short-circuit loop for fast iteration. Also covers the two silent failures: a resumed fit whose identifier ignored the data, and a cached result mistaken for a new one. Use when a fit raises, hangs, returns nonsense, or converges somewhere unphysical. Not for the first composition of a model (`ag_build_imaging_model`), not for routine result inspection (`ag_load_results`), and not for an environment that will not import at all (`ag_setup_environment`).\n---\n\n# When the fit goes wrong\n\nA galaxy fit fails in a small number of characteristic ways, and the debugging cost is\ndominated by mis-attribution: hours spent widening priors when the mask was truncating the\nouter isophotes, or rebuilding a model when the script was quietly resuming a cached result\nfrom last week. So the first move is never a fix — it is to establish *which kind* of failure\nthis is.\n\nThe discipline that makes that possible is cheap probes before expensive ones. A single\nlikelihood evaluation costs a fraction of a second and tells you whether the model and data\ncan talk to each other at all. A `PYAUTO_TEST_MODE=2` run costs seconds and proves the whole\nscript executes. Only after those pass is it worth spending an hour of sampling to find out\nwhether the *inference* is the problem.\n\n## Ask\n\nGet the symptom precisely, because the taxonomy branches on it:\n\n- *\"Did it raise, hang, or complete?\"* A raise has a traceback to read. A hang is usually\n parallelisation, a JIT compile you mistook for a stall, or an update cadence writing output\n constantly. A completed fit that looks wrong is the hardest case and needs the residuals.\n- *\"What makes you say it is wrong?\"* Coherent residuals, an unphysical parameter, an error\n bar that is implausibly tight or implausibly wide, or the number simply disagreeing with the\n literature — each points somewhere different.\n- *\"Simulated data or real observations?\"* On simulated data you know the truth, which makes\n everything below faster. If the user has real data and no simulated control, running one is\n often the fastest path to an answer ([`ag_simulate_dataset`](./ag_simulate_dataset.md)).\n- *\"Has this exact script run before?\"* This decides whether the stale-result trap is in play.\n\n## The taxonomy\n\nSix categories, ordered by how cheap they are to rule out:\n\n| Category | Tell | First probe |\n|---|---|---|\n| **Stale output** | The fit \"finished\" implausibly fast, or the result is identical after you changed something | Delete the `` folder and re-run |\n| **Environment** | An import error, a numba or matplotlib cache error, a parallelisation error the moment the search starts | `--check-install`, the cache variables, the main guard |\n| **Bad data** | Residuals dominated by one blob, or a suspiciously large chi-squared everywhere | Plot the dataset; check the noise-map and the mask |\n| **Bad model** | Coherent, structured residuals with a physical shape | Read the residual pattern; add or change a component |\n| **Bad priors** | The best fit sits on a prior boundary, or the search never moves off its start | `model.info`; hand-evaluate the likelihood |\n| **Bad search settings** | Wide posteriors, a low log evidence, different runs disagreeing, no errors at all | `search.summary`; raise `n_live`, or change search |\n\nThe rest of this skill is one branch per category.\n\n## Branch — stale output, the silent one\n\nRule this out first, every time, because it is invisible and it invalidates everything else you\nwould conclude.\n\nA fit's output folder is `output/////`, and\n`` is derived from the model, the search settings and the dataset identifier. An\nidentical configuration therefore **resumes** rather than restarting\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Unique Identifier__`). That is a\nfeature for an interrupted overnight run and a trap the rest of the time, because **the\nidentifier does not hash the pixel values of your data**. Swap `data.fits` for a different\ngalaxy while keeping the model, search and `unique_tag` the same, and the next run finds a\ncompleted fit at the same path and hands it back — in seconds, with the previous galaxy's\nparameters, and no warning that anything is wrong.\n\nThe symptoms: a fit that completes far faster than it should; a result that does not change\nafter you deliberately changed the data; `model.results` timestamps older than the run you\njust launched.\n\n```bash\n# Prove it rather than reasoning about it.\nrm -rf output////\n```\n\nThen re-run. If the answer changes, that was the bug. Going forward, change the `unique_tag`\nwhenever the data changes — that is what it is for.\n\nThe related trap: test-mode output. Any active `PYAUTO_TEST_MODE` level inserts a `test_mode`\nsegment straight after the output root, precisely so a smoke run cannot short-circuit a later\nreal fit ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)). If you\nfind yourself inspecting a result whose path contains `test_mode`, stop: every parameter in it\nis a wiring check. Also delete any simulated `dataset/` when you toggle\n`PYAUTO_SMALL_DATASETS`, or a full-resolution dataset on disk gets reused against capped grids\nand produces shape errors that look like library bugs.\n\n## Branch — environment and the errors that fire at launch\n\nIf the stack itself is the problem, nothing downstream is diagnostic. Confirm the install\nfirst:\n\n```bash\npython autoassistant/audit_skill_apis.py --check-install\n```\n\nExit `0` is ready; `2` means the packages are absent from *this* interpreter; `3` means they\nwere found but an import raised. Repairing it is\n[`ag_setup_environment`](./ag_setup_environment.md), with the routes in\n[`wiki/core/operations/installation.md`](../wiki/core/operations/installation.md).\n\nThree failures that are environment, not science:\n\n- **A numba or matplotlib cache error** buried in a long trace — the libraries cannot write\n their caches. Fix with `NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib`\n ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n- **An error the instant the search starts**, from Python's process spawning rather than from\n your model. Wrap the fit in a function under a main guard, exactly as\n `autogalaxy_workspace:scripts/guides/modeling/bug_fix.py` does — it is the same\n `modeling.py` fit with this one structural change:\n\n ```python\n def fit():\n from autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\n import autofit as af\n import autogalaxy as ag\n\n # ... dataset, mask, over-sampling, model, search, analysis ...\n result = search.fit(model=model, analysis=analysis)\n\n\n if __name__ == \"__main__\":\n fit()\n ```\n\n It applies to every dataset type, so adopt it for any modeling script that hits the error.\n That script also names the project's support channel if the fix is not enough.\n- **A stale API symbol** — an `AttributeError` on a PyAuto\\* name recalled from an older\n release. Do not guess a replacement; check it:\n\n ```bash\n python autoassistant/audit_skill_apis.py --file scripts/run_fit.py\n ```\n\n [`ag_audit_skill_apis`](./ag_audit_skill_apis.md) owns that check and its bypass.\n\n### Is it a JAX problem?\n\nThe single most useful lever, because it splits the space in two:\n\n```python\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=False)\n```\n\nor, without editing code, `PYAUTO_DISABLE_JAX=1` to force the NumPy path on every analysis\n(`autogalaxy_workspace:scripts/guides/using_jax.py` `__Disabling JAX__`). NumPy stack traces\nare far easier to read than compiled ones, and you can drop a debugger or a `print` into code\nJAX would otherwise compile away. If the failure disappears on NumPy, it is a JAX problem; if\nit survives, JAX was never involved and you have halved the search space.\n\nTwo JAX-specific failure shapes worth recognising:\n\n- **An out-of-memory error at compile time or on the first likelihood call** on a GPU. Check\n the footprint before a long run:\n `analysis.print_vram_use(model=model, batch_size=search.batch_size)`\n (`autogalaxy_workspace:scripts/imaging/modeling.py` `__VRAM Use__`), and lower the batch\n size if it is close to the card's limit.\n- **A long pause at the start that looks like a hang.** The first evaluation compiles the\n likelihood and its gradient; every step after that re-uses the compiled result. The log\n line announcing the compile is the tell\n (`autogalaxy_workspace:scripts/imaging/start_here.py` `__JAX__`). A persistent compilation\n cache means this is paid once per machine, not once per process\n ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## Branch — bad data\n\nPlot the dataset before you plot anything else. On real observations this is not optional —\nthe inspection gate in [`../AGENTS.md`](../AGENTS.md) requires it before a fit is even\ncomposed, and a fit that skipped it is a prime suspect.\n\n```python\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=PLOT_DIR,\n output_filename=\"dataset\",\n output_format=\"png\",\n)\n```\n\nFour things to check, in order:\n\n1. **Contaminants.** A neighbouring galaxy, a foreground star or a reduction artefact inside\n the mask contributes to the likelihood and biases every parameter. The fix is to scale its\n noise rather than cut the pixels out — `dataset.apply_noise_scaling(mask=mask_extra_galaxies)`\n keeps the pixels in the fit but makes them contribute negligibly, which avoids the\n discontinuities that removing pixels creates\n (`autogalaxy_workspace:scripts/imaging/modeling.py` `__Extra Galaxies Noise Scaling__`).\n Alternatively shrink the circular mask so the contaminant falls outside it. Concept:\n [`wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md);\n the tooling is [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md).\n2. **The mask extent.** Too small and it truncates the outer isophotes, which biases the\n effective radius and the Sersic index directly — the classic cause of a \"wrong\" Sersic\n index. Too large and it drags sky and neighbours in, slowing the fit for no information.\n [`wiki/core/concepts/grids_and_masks.md`](../wiki/core/concepts/grids_and_masks.md)\n \"Choosing the radius is a science decision\".\n3. **The noise-map.** If it is underestimated, chi-squared is uniformly too large and the\n posterior is spuriously tight; if overestimated, the reverse. A residual map that is\n featureless but scaled wrong across the whole image points here rather than at the model.\n4. **`pixel_scales`.** Wrong by a factor and every angular quantity is wrong by that factor,\n while the fit looks perfectly healthy. Check it against the instrument.\n\n## Branch — bad model\n\nThis is what coherent residuals mean. Rebuild the fit and read the maps:\n\n```python\nfit = result.max_log_likelihood_fit # or ag.FitImaging(dataset=dataset, galaxies=galaxies)\n\nprint(f\"chi_squared = {fit.chi_squared}\")\nprint(f\"log_likelihood = {fit.log_likelihood}\")\nprint(f\"figure_of_merit = {fit.figure_of_merit}\")\n\naplt.plot_array(\n array=fit.normalized_residual_map,\n title=\"Normalized Residual Map\",\n symmetric=True,\n output_path=PLOT_DIR,\n output_filename=\"normalized_residual_map\",\n output_format=\"png\",\n)\naplt.plot_array(\n array=fit.chi_squared_map,\n title=\"Chi-Squared Map\",\n output_path=PLOT_DIR,\n output_filename=\"chi_squared_map\",\n output_format=\"png\",\n)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/plot.py` `__Fit Figures__`. Read the\n**normalised** residuals first: they are the only map calibrated against the noise, so they\nanswer *significance* rather than *magnitude*. Scatter within roughly ±3 is consistent with\nnoise; coherent structure outside that is a model failure however faint it looks.\n\nTwo quick numerical summaries worth printing alongside the figures — chi-squared per unmasked\npixel (order unity for a good fit), and the fraction of pixels beyond 3σ (a few per cent for a\ngood fit, tens of per cent for a badly wrong model).\n\nThe residual patterns and what each implies are tabulated in\n[`ag_plot_fit`](./ag_plot_fit.md) \"The inspection discipline\". The model responses:\n\n- **Ring at one radius** → the radial profile is too rigid. One Sersic where a bulge plus a\n disk is needed, or a Sersic index that was fixed. Free it, or add the second component.\n- **Four-lobed alternating pattern** → the ellipticity or position angle is wrong, or the\n isophotes twist with radius. [`wiki/core/concepts/ellipse_fitting_and_multipoles.md`](../wiki/core/concepts/ellipse_fitting_and_multipoles.md).\n- **Central excess** → coarse over-sampling, or a nuclear component the model lacks. Check the\n over-sampling scheme before adding physics (below).\n- **Clumpy, asymmetric structure no smooth profile can absorb** → this is where a\n many-component basis or a pixelised reconstruction earns its keep:\n [`wiki/core/concepts/linear_light_profiles_and_mge.md`](../wiki/core/concepts/linear_light_profiles_and_mge.md),\n [`wiki/core/concepts/shapelets.md`](../wiki/core/concepts/shapelets.md),\n [`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n- **A uniform offset across the whole image** → an unmodelled sky background:\n [`wiki/core/concepts/sky_background_and_operated_profiles.md`](../wiki/core/concepts/sky_background_and_operated_profiles.md).\n\n**Check the over-sampling before blaming the physics.** A steep central profile evaluated once\nper pixel is systematically wrong at the centre, and the symptom is exactly the residual a\nmissing nuclear component would leave:\n\n```python\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py` `__Over Sampling__`. Re-plot\nthe dataset subplot afterwards — its lower panels show the scheme that was actually applied,\nso you can confirm it rather than assume it. The full treatment, including why the outer bins\nnever drop to a single sub-pixel, is\n[`wiki/core/concepts/grids_and_masks.md`](../wiki/core/concepts/grids_and_masks.md)\n\"Over-sampling\", with the runnable guide at\n`autogalaxy_workspace:scripts/guides/advanced/over_sampling.py`.\n\nAdding complexity is [`ag_build_imaging_model`](./ag_build_imaging_model.md). Do it one\ncomponent at a time and re-fit: a model that gained three components at once tells you nothing\nabout which one mattered.\n\n## Branch — bad priors, and hand-evaluating the likelihood\n\nThe most direct probe in the whole stack. A model and an analysis are enough — no search, no\nwaiting:\n\n```python\ninstance = model.instance_from_prior_medians()\nlog_likelihood = analysis.log_likelihood_function(instance=instance)\n\nprint(f\"log likelihood at prior medians = {log_likelihood}\")\n```\n\nFrom [`wiki/core/api/analysis_objects.md`](../wiki/core/api/analysis_objects.md) \"Evaluating\nthe likelihood by hand\". `log_likelihood_function(instance)` is the single contract between a\nmodel and data, so what it returns is diagnostic on its own:\n\n- **It raises.** The failure is in the forward model or the data shapes, not in the inference.\n Force `use_jax=False` first for a readable trace, then walk the likelihood step by step\n (next branch).\n- **It returns `nan` or `-inf`.** Something in the model is degenerate at those parameter\n values — a zero or negative size, a profile whose centre sits outside the mask, a noise-map\n with zeros.\n- **It returns a finite but wildly bad value, and the fit's best likelihood is barely better.**\n The search never found anything, which usually means the priors do not contain the answer.\n- **It returns something close to the fit's best value.** The priors are fine and the search\n is doing its job; look elsewhere.\n\nThen compare against a known-good instance. On simulated data you have the truth, so evaluate\nthe likelihood there: if the true model scores much better than anything the search found, the\npriors or the search settings are at fault, not the model. This is the cleanest experiment\navailable, and it is the reason to keep a simulated control alongside real data\n([`ag_simulate_dataset`](./ag_simulate_dataset.md)).\n\nRead the priors themselves rather than recalling them:\n\n```python\nprint(model.info)\n```\n\nThree specific things to look for. **A best-fit parameter sitting on a prior boundary** means\nthe prior is truncating the posterior — the answer may be outside it entirely. **A prior far\nwider than physically sensible** wastes the search's effort and invites multi-modality. And\n**a prior narrowed to make a search behave** is a scientific choice, not a convenience: it\nchanges the posterior and therefore the answer. If you want to steer where a search *starts*\nwithout changing the posterior, that is a start point, and only the MCMC and optimisation\nsearches accept one — nested samplers draw from the prior by construction\n([`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n\"Priors and start points\"). Defaults come from configuration\n([`wiki/core/api/configuration.md`](../wiki/core/api/configuration.md)), and overriding them\nper parameter is [`ag_build_imaging_model`](./ag_build_imaging_model.md).\n\nAlso confirm the galaxy is near the coordinate origin. The default priors assume a centre near\n(0.0\", 0.0\"); a galaxy several arcseconds off-centre needs either re-centred data or\nexplicitly overridden centre priors (`autogalaxy_workspace:scripts/imaging/modeling.py`\n`__Coordinates__`).\n\n## Branch — walking the likelihood step by step\n\nWhen the hand evaluation raises or returns something inexplicable, the step-by-step\nwalkthrough is the ground truth. `autogalaxy_workspace:scripts/imaging/likelihood_function.py`\ncomputes a galaxy model's log likelihood one NumPy operation at a time — the elliptical\ncoordinate transform, each light profile's image, the sum into a galaxy image, the blurring\ngrid and PSF convolution, then:\n\n```\nmodel_data = convolved_image_2d\nresidual_map = data - model_data\nnormalized_residual_map = residual_map / noise_map\nchi_squared_map = normalized_residual_map ** 2\nchi_squared = sum(chi_squared_map)\nnoise_normalization = sum(log(2 * pi * noise_map ** 2))\nfigure_of_merit = -0.5 * (chi_squared + noise_normalization)\n```\n\nand finishes by showing that `ag.FitImaging(dataset=dataset, galaxies=galaxies).figure_of_merit`\nreproduces the same number. Running it against your own dataset localises the failure to one\nstep, which is far faster than reading a compiled trace.\n\nThere are matching walkthroughs for the features whose likelihood is genuinely different, and\nthe difference is where their failures live:\n`autogalaxy_workspace:scripts/imaging/features/linear_light_profiles/likelihood_function.py`\n(the mapping matrix, data vector, curvature matrix and the positive-only reconstruction),\n`.../multi_gaussian_expansion/likelihood_function.py` (the same for a Gaussian basis), and\n`.../pixelization/likelihood_function.py` (the regularisation matrix and the Bayesian\ncomplexity terms). If a fit with linear profiles or a pixelisation fails where a standard\nprofile fit succeeds, the extra linear-algebra steps in those scripts are the place to look.\n\nA real fit does not run that NumPy code — it runs the same calculation compiled. To probe the\ncompiled path exactly as a search drives it, `autogalaxy_workspace:scripts/guides/using_jax.py`\n`__Custom Likelihood Functions__` shows the `Fitness` route, and explains why batching a vector\nof parameters is a stricter test than one concrete call: a single call can quietly succeed on\ncode where NumPy is leaking through, and then break as soon as the search batches.\n\n## Branch — bad search settings\n\nThe model and data are fine; the sampler did not do its job. Read the search's own report\nfirst: `search.summary` in the output folder, plus `result.samples.log_evidence` and the\nposterior widths.\n\n- **Posteriors far wider than the data should allow, or a low log evidence** → too few live\n points for the model's dimensionality. `n_live=200` covers most galaxy models; raise it for\n a complex one ([`wiki/core/api/searches.md`](../wiki/core/api/searches.md)).\n- **No errors at all** → the fit used a gradient optimiser, which is maximum-a-posteriori and\n returns one model. Re-run with `Nautilus` if the science needs uncertainties\n (`autogalaxy_workspace:scripts/imaging/start_here.py` `__Posterior__`).\n- **Two runs of the same configuration disagreeing** → a multi-modal parameter space with a\n search that is finding different modes. Either raise `n_live`, or start simple and chain into\n the complex model with the simple fit's posterior as priors\n ([`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n \"Search chaining\"; the runnable version is\n `autogalaxy_workspace:scripts/guides/modeling/chaining.py`).\n- **Run time far longer than expected** → total cost is (likelihood evaluation time) ×\n (number of evaluations), and dimensionality dominates. A many-Gaussian expansion with six\n free parameters routinely beats a multi-component decomposition with thirteen, despite the\n slower per-evaluation cost. [`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n \"Run-time estimation\".\n- **The log constantly reporting that it is outputting results** → `iterations_per_quick_update`\n is too low and visualisation is eating the run. Raise it\n ([`ag_run_search`](./ag_run_search.md)).\n\nChoosing and tuning the search is [`ag_configure_search`](./ag_configure_search.md).\n\n## Branch — the fast iteration loop\n\nWhile you are changing a script's structure, do not pay for inference. `PYAUTO_TEST_MODE` has\nfour levels ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)):\n\n```bash\n# Level 2 — sampler bypassed, likelihood called exactly once. The fastest proof that the\n# model composes, the shapes agree and the likelihood evaluates.\nPYAUTO_TEST_MODE=2 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n\n# Level 1 — a real but minimal search. Slower, and the only level that writes model.results,\n# image/fit.png and a loadable samples.csv.\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\nLevel 2 does **not** write the fit products, which is worth knowing before you go looking for\n`image/fit.png` after a level-2 run. Level 3 skips the likelihood as well, so it only checks\nthe non-fitting scaffolding. `PYAUTO_SKIP_CHECKS=1` is available when a smoke run trips a\nruntime validation on data too small to be sane — never set it for a real fit, since those\nchecks are what stop a silently degenerate inversion. And **never quote a parameter measured\nin test mode**: the sampler was truncated or mocked, so the numbers are wiring evidence, not\nmeasurements.\n\nThe loop that works: level 2 until the script runs clean → level 1 until the products look\nsane → one full run on a small mask or a simulated dataset → the production fit.\n\n## Branch — when nothing above explains it\n\nTwo escalations, in order.\n\n**Reduce to a control.** Simulate a dataset from a model you choose, fit it with that same\nmodel, and confirm you recover the truth\n([`ag_simulate_dataset`](./ag_simulate_dataset.md)). If the control fails, the problem is in\nthe code or the setup. If the control succeeds, the problem is in the real data or its\npreparation — and you have narrowed it to a half of the space you could not distinguish\nbefore. This is the single highest-value move in this skill and it is under-used.\n\n**Check the library, not yourself.** If a symbol does not resolve or an idiom that reads\ncorrectly does not work, run the audit — a construction can be retired while every token in it\nstill imports:\n\n```bash\npython autoassistant/audit_skill_apis.py --scope scripts\npython autoassistant/audit_skill_apis.py --lint-idioms\n```\n\n[`ag_audit_skill_apis`](./ag_audit_skill_apis.md) owns both. Only after those come back clean\nis \"this might be a library bug\" a reasonable hypothesis — at which point\n[`contribute-upstream`](./contribute-upstream.md) is the route to filing it with a minimal\nreproduction.\n\n## Combine\n\n- [`ag_plot_fit`](./ag_plot_fit.md) — the residual-pattern table this skill's model branch\n routes through, and the figures that make a diagnosis visible.\n- [`ag_build_imaging_model`](./ag_build_imaging_model.md) — acting on a \"bad model\" or \"bad\n priors\" verdict.\n- [`ag_configure_search`](./ag_configure_search.md) — acting on a \"bad search settings\"\n verdict.\n- [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md) — acting on a \"bad data\" verdict:\n masks, noise scaling, contaminant handling.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) — the control experiment.\n- [`ag_setup_environment`](./ag_setup_environment.md) — the install will not import at all.\n- [`ag_run_search`](./ag_run_search.md) — re-launching once the cause is fixed.\n\nRecord the diagnosis, not just the fix. Offer (default-yes) a dated\n`wiki/project/YYYY-MM-DD-.md` entry naming the symptom, the probe that localised it, and\nwhat changed — per [`_style.md`](./_style.md) property #5. A debugging session that is not\nwritten down gets repeated.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Dealing with failure](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_4_dealing_with_failure.ipynb):\n why searches fail on galaxy models, what a local maximum looks like in practice, and how\n model complexity and prior choice interact.\n- **General reference** — [RTD: Likelihood function](https://pyautogalaxy.readthedocs.io/en/latest/general/likelihood_function.html):\n the likelihood the library evaluates, and pointers into the step-by-step walkthroughs.\n- **Experienced PyAutoGalaxy user** — [workspace: guides/modeling/bug_fix.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/guides/modeling/bug_fix.py):\n the main-guard fix for the parallelisation error, as a complete runnable fit.\n\n## Agent procedural checklist\n\n1. Get the symptom: raised, hung, or completed-but-wrong; and what makes it wrong.\n2. Rule out stale output first — check timestamps, then `rm -rf` the `` folder and\n re-run. Check for a `test_mode` path segment.\n3. Confirm the environment with `--check-install`; apply the cache variables and the main guard\n if either applies.\n4. Toggle `use_jax=False` (or `PYAUTO_DISABLE_JAX=1`) to split JAX from non-JAX failures and\n get a readable trace.\n5. Plot the dataset: contaminants, mask extent, noise-map, `pixel_scales`.\n6. Hand-evaluate `analysis.log_likelihood_function(instance=model.instance_from_prior_medians())`\n before running any search.\n7. Read `model.info` for boundary-hugging and over-wide priors; confirm the galaxy is near the\n origin.\n8. Rebuild the fit and read the **normalised residual** map, then the chi-squared map; check\n the over-sampling scheme before adding physics.\n9. Read `search.summary` and the log evidence for search-settings failures.\n10. Iterate with `PYAUTO_TEST_MODE=2`, then `=1`; never quote a test-mode parameter.\n11. If unresolved, build a simulated control and fit it; run the symbol and idiom audits before\n suspecting a library bug.\n12. Offer the `wiki/project/` entry recording symptom, probe and fix.\n" + } + }, + "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file diff --git a/notebooks/chapter_2_modeling/tutorial_5_data_and_likelihoods.ipynb b/notebooks/chapter_2_modeling/tutorial_5_data_and_likelihoods.ipynb new file mode 100644 index 0000000..31c33e6 --- /dev/null +++ b/notebooks/chapter_2_modeling/tutorial_5_data_and_likelihoods.ipynb @@ -0,0 +1,372 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Tutorial 5: Data and Likelihoods\n", + "===============================\n", + "\n", + "So far we have changed the galaxy model and the search. Now consider the other side of the fit: the measurements\n", + "we include and how they are compared with a prediction. The data, model and Analysis object have distinct jobs.\n", + "This separation lets the same modelling tools work with different observations and likelihood functions.\n", + "\n", + "__Contents__\n", + "\n", + "- **Masking:** Retain useful constraints without fitting unrelated objects.\n", + "- **Extra Galaxy Noise Scaling:** Reduce the weight of contaminated pixels.\n", + "- **Analysis:** Connect the prepared data to the model.\n", + "- **Interferometer Data:** Apply the same modelling pattern to visibilities.\n", + "- **Multiple Datasets:** A pointer to advanced joint modelling." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Google Colab Setup__\n", + "\n", + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, + "outputs": [], + "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", + "try:\n", + " import google.colab\n", + "except ImportError:\n", + " from autogalaxy import setup_colab as _setup_colab\n", + "else:\n", + " import importlib\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.check_call(\n", + " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", + " )\n", + " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", + "\n", + "_setup_colab.setup(\"howtogalaxy\")" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from autogalaxy import setup_notebook; setup_notebook()\n", + "\n", + "from pathlib import Path\n", + "import numpy as np\n", + "import autofit as af\n", + "import autogalaxy as ag\n", + "import autogalaxy.plot as aplt" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Dataset and Mask__\n", + "\n", + "Load the imaging data and retain the region inside the circular mask. The simulator creates the data if needed.\n", + "The image, noise map and PSF together describe the observation; none specifies which galaxy model we must fit." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "dataset_name = \"simple__sersic\"\n", + "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name\n", + "if ag.util.dataset.should_simulate(str(dataset_path)):\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.run([sys.executable, \"scripts/simulators/sersic.py\"], check=True)\n", + "\n", + "dataset = ag.Imaging.from_fits(\n", + " data_path=dataset_path / \"data.fits\",\n", + " noise_map_path=dataset_path / \"noise_map.fits\",\n", + " psf_path=dataset_path / \"psf.fits\",\n", + " pixel_scales=0.1,\n", + ")\n", + "mask = ag.Mask2D.circular(\n", + " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=6.0\n", + ")\n", + "dataset = dataset.apply_mask(mask=mask)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Over Sampling__\n", + "\n", + "The bright centre changes rapidly across a pixel. Adaptive over sampling evaluates it on a finer grid so that\n", + "numerical inaccuracies do not masquerade as poor models. The outskirts need fewer evaluations." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n", + " grid=dataset.grid,\n", + " sub_size_list=[8, 4, 2],\n", + " radial_list=[0.3, 0.6],\n", + " centre_list=[(0.0, 0.0)],\n", + ")\n", + "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n", + "aplt.subplot_imaging_dataset(dataset=dataset)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Masking__\n", + "\n", + "Our first fit used a 3.0-arcsecond radius. Here we use 6.0 arcseconds to include more of the faint outskirts.\n", + "Look beyond the bright centre: individually faint pixels can collectively constrain how quickly the light falls\n", + "away. A mask that is too tight may discard those constraints.\n", + "\n", + "There is another reason to include the outskirts. A model may predict light outside the fitted region that the\n", + "real image does not contain. Masking that region hides the disagreement from the likelihood. A visually good fit\n", + "inside a small mask can therefore conceal a poor description of the galaxy as a whole.\n", + "\n", + "A larger mask is not automatically better. It includes more pixels to calculate and may admit neighbouring galaxies,\n", + "background structure or defects our model does not describe. Choose the fitted region from the data and the\n", + "scientific question, then check that reasonable changes to it do not undermine the result." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "model = af.Collection(\n", + " galaxies=af.Collection(\n", + " galaxy=af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp_linear.Sersic)\n", + " )\n", + ")\n", + "analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", + "\n", + "search = af.Nautilus(\n", + " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", + " name=\"tutorial_5_larger_mask\",\n", + " unique_tag=dataset_name,\n", + " n_live=100,\n", + " n_batch=50,\n", + ")\n", + "result_mask = search.fit(model=model, analysis=analysis)\n", + "print(result_mask.info)\n", + "aplt.subplot_fit_imaging(fit=result_mask.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Contaminating Light__\n", + "\n", + "A nearby galaxy is real signal, but it is not light from the target. If we fit it with the target's profile, the\n", + "search may distort the target's size or shape to account for it. We can exclude contaminated regions, reduce their\n", + "weight, or explicitly model the neighbour. The right choice depends on overlap and the information we need.\n", + "\n", + "Load a second image containing a visible neighbour. The simulator also supplies a region identifying its light.\n", + "For real data, inspect and define this region yourself, for example with the workspace's data-preparation GUI.\n", + "Check the mask against the image rather than assuming a circular region removes every trace of contamination." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "dataset_name = \"extra_galaxy\"\n", + "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name\n", + "if ag.util.dataset.should_simulate(str(dataset_path)):\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.run([sys.executable, \"scripts/simulators/extra_galaxy.py\"], check=True)\n", + "dataset = ag.Imaging.from_fits(\n", + " data_path=dataset_path / \"data.fits\",\n", + " noise_map_path=dataset_path / \"noise_map.fits\",\n", + " psf_path=dataset_path / \"psf.fits\",\n", + " pixel_scales=0.1,\n", + ")\n", + "aplt.subplot_imaging_dataset(dataset=dataset)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Extra Galaxy Noise Scaling__\n", + "\n", + "Noise scaling keeps the contaminated pixels in the grid but greatly reduces their influence on the fit. The\n", + "helper below sets their data to zero and their noise to very large values. This is a deliberate modification of\n", + "which measurements constrain the model, not a physical subtraction of the neighbouring galaxy.\n", + "\n", + "The supplied file follows the workspace's mask-storage convention; `invert=True` makes `False` select the pixels\n", + "to scale. Apply this to the freshly loaded image before applying the main mask, so the grids have matching shapes." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "mask_extra_galaxies = ag.Mask2D.from_fits(\n", + " file_path=dataset_path / \"mask_extra_galaxies.fits\",\n", + " pixel_scales=0.1,\n", + " invert=True,\n", + ")\n", + "dataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies)\n", + "mask = ag.Mask2D.circular(\n", + " shape_native=dataset.shape_native,\n", + " pixel_scales=dataset.pixel_scales,\n", + " radius=6.0,\n", + ")\n", + "dataset = dataset.apply_mask(mask=mask)\n", + "over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n", + " grid=dataset.grid,\n", + " sub_size_list=[8, 4, 2],\n", + " radial_list=[0.3, 0.6],\n", + " centre_list=[(0.0, 0.0)],\n", + ")\n", + "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n", + "aplt.subplot_imaging_dataset(dataset=dataset)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Inspect the data, noise and signal-to-noise panels together. The neighbour's selected pixels should have almost\n", + "no weight, while the target remains constrained. This also retains a continuous grid, useful for some later\n", + "reconstruction methods. Light outside the selected region, including PSF wings, can still contaminate the fit.\n", + "Where the galaxies overlap substantially, fitting both is often preferable. Tutorial 6 illustrates that approach.\n", + "\n", + "__Analysis as the Interface__\n", + "\n", + "Our galaxy model does not change merely because we scale a region's noise. The new Analysis object receives the\n", + "prepared dataset and uses its noise map when calculating the likelihood. This is where our data choices enter\n", + "the model comparison. A search sees the returned score, not the reasons we chose a mask or excluded a neighbour." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", + "\n", + "search = af.Nautilus(\n", + " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", + " name=\"tutorial_5_noise_scaling\",\n", + " unique_tag=dataset_name,\n", + " n_live=100,\n", + " n_batch=50,\n", + ")\n", + "result_scaled = search.fit(model=model, analysis=analysis)\n", + "print(result_scaled.info)\n", + "aplt.subplot_fit_imaging(fit=result_scaled.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Do not compare the absolute likelihood of this fit with the earlier dataset or a differently scaled noise map\n", + "as if only the galaxy model had changed. The measurements and their weighting also define the likelihood.\n", + "\n", + "__Interferometer Data__\n", + "\n", + "Chapter 1 introduced interferometer visibilities. The same galaxy model can predict those measurements, but the\n", + "comparison changes: `AnalysisInterferometer` Fourier transforms the model light and compares predicted visibilities\n", + "with the measured complex values and their uncertainties. Its likelihood is evaluated in visibility space.\n", + "The real-space mask defines the image grid used for predictions; it does not select image pixels as observations.\n", + "\n", + "The pattern remains data + model + Analysis + search. See `autogalaxy_workspace/scripts/interferometer/modeling.py`\n", + "for a complete example after this course. The shared interface does not mean that different datasets have the\n", + "same noise properties or likelihood calculation.\n", + "\n", + "__Multiple Datasets__\n", + "\n", + "We can also combine Analysis objects. For independent observations, their likelihoods multiply, or equivalently\n", + "their log likelihoods add. A joint model can share parameters such as galaxy geometry while allowing others, such\n", + "as brightness in different wavebands, to differ between datasets.\n", + "\n", + "The `autogalaxy_workspace/scripts/multi_dataset` examples develop this approach. It is advanced modelling:\n", + "finish HowToGalaxy first, then explore how shared parameters, calibration and any correlations between datasets\n", + "affect a joint analysis. No extra Python is needed here to understand the principle.\n", + "\n", + "__Wrap Up__\n", + "\n", + "The data describe measurements and uncertainty; the model describes possible galaxies; Analysis defines how to\n", + "compare them. The search explores that model using the resulting likelihood. Keeping these roles clear makes it\n", + "easier to decide whether a poor fit needs better data preparation, a different model or more thorough exploration." + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.1" + }, + "colab": { + "aiContexts": { + "24c2f562-da24-50bb-8eb9-5a887505fe54": { + "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", + "name": "PyAutoGalaxy assistant", + "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_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\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_2_modeling/tutorial_5_data_and_likelihoods.ipynb in HowToGalaxy).\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 PyAutoGalaxy 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 PyAutoGalaxy docs (https://pyautogalaxy.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) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. 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 galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_basis_profiles\n\n---\nname: ag_basis_profiles\ndescription: Fit a galaxy's morphology with a *basis* rather than one or two smooth profiles — linear light profiles (`ag.lp_linear`), a Multi-Gaussian Expansion, or a shapelet expansion — where every component's `intensity` is solved analytically by a linear inversion instead of sampled by the search. Covers why `ag.lp_linear` is the default for any bulge-disk decomposition, when an MGE beats a Sersic pair (isophotal twists, radially varying ellipticity, asymmetry), when shapelets beat an MGE, the positive-only versus signed linear solver and what a negative amplitude means physically, `ag.model_util.mge_model_from` and the hand-rolled `ag.lp_basis.Basis` idiom behind it, a compact MGE for an unresolved nucleus, and how to read solved intensities back out of a fit. Use when a Sersic or bulge-plus-disk model leaves structure in the residuals but the galaxy still has a well-defined centre. Not for pixelized reconstruction of genuinely irregular clumps (`ag_pixelization`), not for non-parametric isophote measurement (`ag_ellipse_fitting`), and not for the basics of composing an `af.Model` tree (`ag_build_imaging_model`).\n---\n\n# Fitting morphology with a basis\n\nA Sersic profile makes a strong claim: that the galaxy's isophotes are concentric, similar\nellipses with a single fixed axis ratio and position angle, and that its surface brightness\nfalls off as one power of radius. Real galaxies routinely violate all of that. Isophotes twist\nwith radius, the ellipticity varies from the bulge outwards, a bar or a spiral pattern breaks\nthe symmetry — and when a Sersic cannot represent those features it does not fail loudly. It\nabsorbs them, and returns an `effective_radius` and `sersic_index` biased by exactly the\nstructure it could not fit.\n\nA **basis** is the answer: instead of one profile with a shape, use tens of simple profiles\nwhose superposition can take almost any shape. The reason this is affordable — and the reason\nit is often *cheaper* than a Sersic pair — is statistical. Every basis component's `intensity`\nis a **linear** parameter: given the shapes and positions of the components, the amplitudes\nthat maximise the likelihood follow from solving a linear system, exactly, in one step. So they\nnever enter the non-linear search's parameter space at all. A 60-Gaussian MGE can have four\nfree parameters where a two-component linear Sersic decomposition has nine.\n\nThree tiers, same machinery, increasing flexibility:\n\n| Tier | What it is | Free parameters | Reach for it when |\n|---|---|---|---|\n| `ag.lp_linear.*` | ordinary profiles with `intensity` solved | 6 per Sersic, 3 per aligned Exponential | you want interpretable bulge/disk parameters — **the default** |\n| MGE (`ag.lp_basis.Basis` of `Gaussian`s) | 15–100 Gaussians on a fixed log-spaced `sigma` ladder | 4 (one basis) to 6 (two) | isophotal twists, radial ellipticity variation, mild asymmetry |\n| shapelets | an orthonormal polar or Cartesian basis | 3 (spherical) to 5 (elliptical) | disky, star-forming morphology the MGE still smooths over |\n\nThe science this serves is the decomposition itself. A bulge-plus-disk fit measures the\nbulge-to-total light ratio, the two components' sizes and the bulge's concentration — the\nquantities that place a galaxy on the mass–size relation and separate a classical spheroid from\na pseudo-bulge. A basis fit measures something the parametric fit cannot: how the shape of the\nlight changes with radius. Both concepts are in\n[`../wiki/core/concepts/linear_light_profiles_and_mge.md`](../wiki/core/concepts/linear_light_profiles_and_mge.md)\nand [`../wiki/core/concepts/shapelets.md`](../wiki/core/concepts/shapelets.md); the catalogue of\nwhich variant lives in which module is\n[`../wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md).\n\nThis skill assumes you already have a masked, over-sampled dataset and know how to build an\n`af.Model` tree — that is [`ag_build_imaging_model`](./ag_build_imaging_model.md), whose MGE\nbranch is the one-paragraph version of what follows.\n\n## Ask\n\n- *\"Do you need the Sersic parameters, or the best fit?\"* This is the real fork. If your science\n is a bulge-to-total ratio, an effective radius, a Sersic index — a number you will put in a\n table next to other people's — stay with `ag.lp_linear` Sersic-family profiles, because an\n MGE does not hand you those numbers. If your science is the light distribution itself, or you\n need the residuals flat before you can trust anything else, go to a basis.\n- *\"What does the residual map look like after a single Sersic?\"* Structured residuals that\n follow the isophotes (a four-lobed or twisted pattern) say the *shape* is wrong — an MGE\n fixes that. Residuals in discrete off-centre lumps say the shape is fine but there is\n substructure — that is a pixelization ([`ag_pixelization`](./ag_pixelization.md)), not a basis.\n If you have not looked yet, look first; it is one plot and it decides the branch.\n- *\"Does the galaxy have a single well-defined centre?\"* Every basis in this skill shares one\n centre across all its components. A merger, or a galaxy with a bright companion overlapping\n it, breaks that assumption — handle the companion first with\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- *\"Is there a compact nuclear source?\"* An AGN or a nuclear starburst is a separate component,\n and there is a purpose-built compact MGE for it (branch four below).\n\n## Branch — linear light profiles, the default for any decomposition\n\nStart here even when you expect to end up with a basis. This is the same bulge-plus-disk model\n`ag_build_imaging_model` composes, and the point of this branch is what happens to `intensity`.\n\n```python\n\"\"\"\nGalaxy Structure: Linear Bulge-Disk Decomposition\n=================================================\n\nDecompose a galaxy's light into a Sersic bulge and an Exponential disk using *linear* light\nprofiles, whose `intensity` parameters are solved analytically by a linear inversion inside\nevery likelihood evaluation rather than sampled by the non-linear search. The ratio of the two\nsolved intensities, integrated, is the bulge-to-total light ratio.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the masked, over-sampled imaging dataset.\n- **Model:** Compose the linear bulge and disk, with their centres paired.\n- **Check:** Confirm the parameter count and evaluate one likelihood.\n- **Intensities:** Read the solved intensities back out of a completed fit.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPIXEL_SCALES = 0.1\nMASK_RADIUS = 3.0\n\n\"\"\"\n__Dataset__\n\nLoaded from FITS, masked to a radius chosen by inspecting the data, and over-sampled adaptively\nwhere the profile's intensity gradient is steep. All three decisions change the answer, so they\nare reproduced here rather than hidden\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\"\"\"\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=PIXEL_SCALES,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n\n\"\"\"\n__Model__\n\nThe decomposition is identifiable because the two components are *asymmetric* in what they are\nallowed to be: the bulge's `sersic_index` is free, so the fit can find a concentrated spheroid\n(n ~ 4), while the `Exponential` disk has n fixed at 1 by construction. Two free Sersics on one\ngalaxy are largely degenerate and the fit will trade light between them.\n\n`ag.lp_linear` rather than `ag.lp` is the only change from a standard composition, and it is\nnot a small one: each profile's `intensity` leaves the search's parameter space and is instead\nsolved by a linear inversion that always returns the amplitudes maximising the likelihood given\nthe other parameters. Two dimensions vanish, and with them the strong degeneracies between\n`intensity` and `effective_radius` / `sersic_index` that a sampler finds hardest to map\n(`PyAutoGalaxy:autogalaxy/profiles/light/linear/sersic.py`).\n\n`bulge.centre = disk.centre` asserts the components are concentric — physically reasonable for\nmost galaxies, and worth two parameters.\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\ndisk = af.Model(ag.lp_linear.Exponential)\nbulge.centre = disk.centre\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\nThe likelihood at the prior medians costs one evaluation and proves the model, dataset and\nanalysis are mutually compatible. Pass `use_jax=False` while debugging — NumPy tracebacks are\nfar easier to read (`PyAutoGalaxy:autogalaxy/imaging/model/analysis.py`).\n\"\"\"\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\nlog_likelihood = analysis.log_likelihood_function(\n instance=model.instance_from_prior_medians()\n)\nprint(f\"log likelihood at prior medians: {float(log_likelihood):.2f}\")\n```\n\nN = 9: the bulge's centre (2), two `ell_comps` pairs (4), two `effective_radius` values and the\nbulge's `sersic_index` — with both intensities solved. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/linear_light_profiles/modeling.py`, which\nreduces `n_live` to 75 for exactly this reason: a simpler parameter space needs fewer live\npoints to map.\n\nThe cost is real but small. A linear likelihood evaluation is roughly three to five times\nslower than a standard one, because the inversion has to be solved every time. The workspace\nexample measures ~0.05 s against ~0.01 s on a low-resolution dataset. That is repaid by fewer\niterations and a more reliable posterior, and the trade tips further towards linear the more\nprofiles you add — which is what makes the next two branches possible at all.\n\n### The consequence: `intensity` is not in the model, so it is not in the results\n\nThis trips up everyone once. A linear profile has no `intensity` attribute to report, so\n`model.results` does not list one, and **a linear profile cannot be plotted directly** — there\nis no amplitude to evaluate. The intensities exist only after a fit, as the inversion's\nsolution. Three ways to get at them, all from\n`autogalaxy_workspace:scripts/imaging/features/linear_light_profiles/modeling.py`:\n\n```python\n\"\"\"\n__Intensities__\n\n`max_log_likelihood_galaxies` has already performed the inversion, so its profiles carry their\nsolved `intensity` values and can be evaluated and plotted like ordinary profiles. The\n`Fit` additionally exposes a dictionary keyed by the profile objects themselves, which is the\nunambiguous route when several components share a class\n(`PyAutoGalaxy:autogalaxy/imaging/fit_imaging.py`).\n\"\"\"\ngalaxies = result.max_log_likelihood_galaxies\n\nprint(f\"bulge intensity = {galaxies[0].bulge.intensity}\")\n\nfit = result.max_log_likelihood_fit\n\nprint(fit.linear_light_profile_intensity_dict[fit.galaxies[0].bulge])\nprint(fit.linear_light_profile_intensity_dict[fit.galaxies[0].disk])\n\ngalaxies_ordinary = fit.model_obj_linear_light_profiles_to_light_profiles\n\naplt.subplot_galaxies(\n galaxies=galaxies_ordinary,\n grid=dataset.grid,\n output_path=\"scripts/scratch/my_galaxy/\",\n auto_filename=\"decomposition\",\n output_format=\"png\",\n)\n```\n\n`model_obj_linear_light_profiles_to_light_profiles` returns the same galaxies with every linear\nprofile replaced by its ordinary equivalent at the solved amplitude — that is the object to\nhand to any plotting or derived-quantity call. `fit.inversion.linear_obj_list` holds one\n`LightProfileLinearObjFuncList` per linear component (or per `Basis`), which is where the\nbookkeeping lives when you need to be certain which amplitude belongs to which profile.\n\nIntegrating those amplitudes over the two profiles is what gives you the bulge-to-total ratio;\nthe machinery for luminosities and magnitudes is\n[`../wiki/core/concepts/cosmology_and_units.md`](../wiki/core/concepts/cosmology_and_units.md).\nAsk if you want the derived-quantity route spelled out.\n\n## Branch — a Multi-Gaussian Expansion, when the *shape* is wrong\n\nA Gaussian is a poor galaxy profile on its own and an excellent basis function in company:\nsum enough of them at fixed, logarithmically spaced widths and you can build any monotonic\nradial profile, and — if you let separate groups of them carry separate ellipticities — an\nisophote shape that changes with radius. That last property is the one a Sersic cannot have at\nany parameter count, and it is why an MGE is the workspace's recommended default model.\n\nThe composition is long, so the library ships a helper:\n\n```python\n\"\"\"\n__Model__\n\nAn MGE bulge: 20 linear Gaussians sharing one centre and one ellipticity, with every `sigma`\nfixed on a logarithmic ladder running from below the pixel scale out to `mask_radius`, and\nevery intensity solved by the inversion. `mask_radius` sets the outer end of that ladder, so\npass the radius you actually masked at — a ladder that stops short of the data leaves the\nouter isophotes unrepresented (`PyAutoGalaxy:autogalaxy/analysis/model_util.py`).\n\"\"\"\nbulge = ag.model_util.mge_model_from(\n mask_radius=MASK_RADIUS,\n total_gaussians=20,\n centre_prior_is_uniform=True,\n)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n```\n\n**N = 4** — a shared centre and a shared `ell_comps`. Twenty Gaussians, four dimensions, more\nmorphological freedom than a Sersic's six. Adapted from\n`autogalaxy_workspace:scripts/imaging/start_here.py`, where the MGE is the recommended default.\n\nThe full signature is\n`mge_model_from(mask_radius, total_gaussians=30, gaussian_per_basis=1,\ncentre_prior_is_uniform=True, centre=(0.0, 0.0), centre_fixed=None, centre_per_basis=False,\ncentre_sigma=0.3, ell_comps_prior_is_uniform=False, ell_comps_uniform_width=0.2,\nell_comps_sigma=0.3, use_spherical=False)`. The arguments worth knowing:\n\n- **`gaussian_per_basis=2`** splits the ladder into two bases with *independent* ellipticities.\n N goes 4 → 6 and you buy the ability to fit an isophotal twist: an inner group and an outer\n group free to be differently elongated and differently oriented. This is the single most\n useful knob here, and the reason to prefer an MGE over a Sersic pair for an early-type galaxy.\n- **`centre_fixed=(y, x)`** pins the centre entirely, dropping two more parameters. Used for\n contaminating neighbours ([`ag_light_model_extras`](./ag_light_model_extras.md)).\n- **`use_spherical=True`** drops the ellipticity — for a genuinely round system, or as a\n deliberately rigid comparison model.\n- **`total_gaussians`** buys radial resolution, not shape freedom. 15 is enough for a smooth\n profile; 60 for a well-resolved one; beyond that you are mostly paying for likelihood\n evaluations. Cost scales with the count, because every Gaussian's image must be computed and\n PSF-convolved: the workspace measures ~0.5 s per evaluation for 60 Gaussians, against ~0.01 s\n for a standard Sersic. VRAM rises too — 10–50 MB per batched likelihood at 60 Gaussians, so\n check `analysis.print_vram_use(model=model, batch_size=search.batch_size)` before a GPU run\n with hundreds of components.\n\nThat run time is why the overall comparison is not obvious, and the workspace is honest about\nit: the MGE's likelihood is much slower, but its parameter space is so much simpler — and\ncrucially contains *no parameter that scales the galaxy's size* — that the search converges far\nfaster. Net, it usually wins, and it fits better.\n\n### The hand-rolled `Basis`, and why you might want it\n\nThe helper is a convenience over one explicit idiom. Compose it yourself when you need\nsomething the arguments do not offer — a bespoke `sigma` range, a third basis, per-basis\npriors. From `autogalaxy_workspace:scripts/imaging/features/multi_gaussian_expansion/modeling.py`:\n\n```python\n\"\"\"\n__Model__\n\nTwo groups of 30 Gaussians. Within a group every Gaussian shares the centre and ellipticity of\nthe first, and every `sigma` is *fixed* to a value on a log10 ladder spanning a tenth of the\npixel scale to the mask radius. `ag.lp_basis.Basis` then groups the whole list into one model\ncomponent the galaxy can hold (`PyAutoGalaxy:autogalaxy/profiles/basis.py`).\n\nThe lower end matters: anchoring it to the pixel scale stops the basis spending Gaussians on\nscales the data cannot resolve. `mge_model_from` exposes this as `sigma_min` (default `1e-4`,\nwhich reproduces the historical ladder exactly).\n\"\"\"\nimport numpy as np\n\ntotal_gaussians = 30\ngaussian_per_basis = 2\n\nlog10_sigma_list = np.linspace(\n np.log10(dataset.pixel_scales[0] / 10.0), np.log10(MASK_RADIUS), total_gaussians\n)\n\ncentre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\ncentre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n\nbulge_gaussian_list = []\n\nfor _ in range(gaussian_per_basis):\n\n gaussian_list = af.Collection(\n af.Model(ag.lp_linear.Gaussian) for _ in range(total_gaussians)\n )\n\n for i, gaussian in enumerate(gaussian_list):\n gaussian.centre.centre_0 = centre_0 # one shared y centre\n gaussian.centre.centre_1 = centre_1 # one shared x centre\n gaussian.ell_comps = gaussian_list[0].ell_comps # shared within this basis\n gaussian.sigma = 10 ** log10_sigma_list[i] # fixed, not sampled\n\n bulge_gaussian_list += gaussian_list\n\nbulge = af.Model(ag.lp_basis.Basis, profile_list=bulge_gaussian_list)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n```\n\nN = 6. `print(model.info)` prints all sixty Gaussians and looks alarming; almost every\nparameter shown is fixed. Trust `model.total_free_parameters`, not the length of the printout.\n\nTwo details that are load-bearing. Assigning `gaussian.sigma = ` **fixes** it — the\nwhole scheme depends on the widths not being sampled, because a free `sigma` reintroduces the\nsize-scaling degeneracy the MGE exists to remove. And sharing `ell_comps` *within* a basis but\nnot *between* bases is precisely what makes the twist fittable.\n\nThe `Basis` constructor also accepts a `regularization` argument that penalises non-smooth\namplitude solutions. Treat it as research-only: the positive-only solver below already fixes\nthe pathology it was introduced for, and no production analysis uses it — the workspace moved\nthat branch out of the user-facing script deliberately.\n\n## Branch — a compact MGE for an unresolved nucleus\n\nAn AGN or nuclear starburst is not the extended stellar light, and forcing one basis to cover\nboth makes the fit choose between them. Model it as a second, deliberately compact basis: the\nsame construction with the `sigma` ladder capped at about twice the pixel scale, so the\ncomponent cannot be broader than a PSF-convolved point source.\n\n```python\n\"\"\"\n__Model__\n\nThe galaxy's light becomes the sum of a diffuse stellar `bulge` MGE and a compact `point` MGE.\nThe point basis is 10 linear Gaussians sharing one centre and ellipticity with `sigma` values\nlog-spaced from `sigma_min` (default 0.01\") to twice the pixel scale — compact relative to the\nresolution of the data, which is what makes it read as a point source rather than a small galaxy\n(`PyAutoGalaxy:autogalaxy/analysis/model_util.py`).\n\"\"\"\npoint = ag.model_util.mge_point_model_from(\n pixel_scales=PIXEL_SCALES,\n total_gaussians=10,\n centre=(0.0, 0.0),\n)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, point=point)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/features/multi_gaussian_expansion/modeling.py`,\nwhose `__Point Source__` section builds the same basis line by line first if you want to see\ninside the helper. Four extra parameters on top of the bulge MGE.\n\nThere is a genuinely different approach to the same problem — an **operated** light profile,\nwhich is assumed to be already PSF-convolved and so bypasses the convolution entirely. Which\nto pick, and why a compact model source is so sensitive to sub-pixel placement, is\n[`ag_light_model_extras`](./ag_light_model_extras.md) and\n[`../wiki/core/concepts/sky_background_and_operated_profiles.md`](../wiki/core/concepts/sky_background_and_operated_profiles.md).\n\n## Branch — shapelets, and the price of a signed solver\n\nShapelets are an orthonormal basis of Gauss–Hermite (Cartesian) or Gauss–Laguerre (polar)\nfunctions on a single scale `beta`, introduced for exactly this problem\n(Refregier 2003, arXiv:astro-ph/0105178). Because the basis is complete, it can represent\nmorphology an MGE smooths over — the disky, star-forming structure the workspace cites them\nfor. But completeness has a price, and it is a physical one.\n\n**Shapelets require negative amplitudes.** The higher-order basis functions oscillate in sign,\nand reproducing an arbitrary shape means combining them with signed coefficients. Every other\nbranch in this skill uses a positive-only linear solver, because a negative surface brightness\nis not a thing a galaxy has. Shapelets cannot: you must pass\n`ag.Settings(use_positive_only_solver=False)`, and the reconstructed light *will* contain\nnegative flux — verified, not assumed. That is not a numerical wrinkle to ignore; it is the\nmodel telling you it is a mathematical fit rather than a physical decomposition, and it is why\nthe workspace recommends trying an MGE alongside.\n\n```python\n\"\"\"\n__Model__\n\nA polar shapelet basis to order n = 5: 11 `ShapeletPolar` components whose `n` and `m` indices\nare fixed by construction, sharing one centre, one ellipticity and one scale `beta`. `beta` is\nthe only shape parameter — it sets the physical size the whole basis is expressed on, so its\nprior matters more here than any single amplitude\n(`PyAutoGalaxy:autogalaxy/profiles/light/linear/shapelets/polar.py`).\n\"\"\"\ntotal_n = 5\ntotal_m = sum(range(2, total_n + 1)) + 1\n\nshapelets_bulge_list = af.Collection(\n af.Model(ag.lp_linear.ShapeletPolar) for _ in range(total_n + total_m)\n)\n\nn_count = 1\nm_count = -1\n\nfor shapelet in shapelets_bulge_list:\n shapelet.n = n_count\n shapelet.m = m_count\n\n m_count += 2\n\n if m_count > n_count:\n n_count += 1\n m_count = -n_count\n\n shapelet.centre = shapelets_bulge_list[0].centre\n shapelet.ell_comps = shapelets_bulge_list[0].ell_comps\n shapelet.beta = shapelets_bulge_list[0].beta\n\nbulge = af.Model(ag.lp_basis.Basis, profile_list=shapelets_bulge_list)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\n\"\"\"\n__Analysis__\n\nThe signed solver is requested through `ag.Settings`, which is passed to the analysis rather\nthan to the model — it is a property of how the inversion is solved, not of what is being\nfitted (`PyAutoArray:autoarray/settings.py`).\n\"\"\"\nanalysis = ag.AnalysisImaging(\n dataset=dataset,\n settings=ag.Settings(use_positive_only_solver=False),\n use_jax=True,\n)\n```\n\n**N = 5**: centre (2), `ell_comps` (2), `beta` (1). Adapted from\n`autogalaxy_workspace:scripts/imaging/features/shapelets/modeling.py` — note that the workspace\nloop as written does *not* link `ell_comps` across the basis, which leaves each shapelet's\nellipticity free and inflates the model to N = 43 rather than the N = 3 its prose claims. The\nline `shapelet.ell_comps = shapelets_bulge_list[0].ell_comps` above is the fix; N = 3 is what\nyou get from the spherical variant `ag.lp_linear.ShapeletPolarSph`, which has no `ell_comps` at\nall. Check `model.total_free_parameters` rather than trusting a comment — including this one.\n\nPolar shapelets suit radially organised light, which is most galaxies.\n`ag.lp_linear.ShapeletCartesian` (indexed by `n_y`, `n_x` instead of `n`, `m`) and\n`ag.lp_linear.ShapeletExponential` are the other two families; the Cartesian basis is not\ngenerally recommended for galaxies. You can see what a basis actually looks like before fitting\nanything:\n\n```python\nshapelets = [\n ag.lp_linear.ShapeletCartesian(\n n_y=y, n_x=x, centre=(0.0, 0.0), ell_comps=(0.0, 0.0), beta=1.0\n )\n for x in range(5)\n for y in range(5)\n]\n\nbasis = ag.lp_basis.Basis(profile_list=shapelets)\n\naplt.subplot_basis_image(\n basis=basis,\n grid=ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.05),\n output_path=\"scripts/scratch/shapelet_basis/\",\n output_format=\"png\",\n)\n```\n\n`subplot_basis_image` renders every component of the basis on a grid, which is the fastest way\nto build intuition for what `beta` and the order limit are buying you. It takes `output_path` /\n`output_format` but **not** `output_filename` — give each variant its own directory\n([`../wiki/core/api/plotting.md`](../wiki/core/api/plotting.md) tabulates that split). Print the\nabsolute path and offer to open it.\n\nShapelets also cost about 0.37 s per likelihood evaluation for ~60 components in the workspace's\nmeasurement — slower than linear profiles, comparable to an MGE, and with more free parameters\nthan an MGE of similar flexibility. The workspace's own recommendation is to run both and\ncompare; the concept page\n[`../wiki/core/concepts/shapelets.md`](../wiki/core/concepts/shapelets.md) has the full\nwhen-to-use discussion.\n\n## Choosing between the three\n\nFit them in order and let the residuals decide, because each step is cheap given the last:\n\n1. **Single linear Sersic** — the reference every other fit is judged against, and the source of\n the size and concentration you will actually quote. Six parameters.\n2. **Linear bulge plus disk** — if the science is a bulge-to-total ratio, this *is* the answer;\n a basis will fit better and tell you less. Nine parameters.\n3. **MGE, `gaussian_per_basis=2`** — if the residuals show a twist or a radially varying\n ellipticity. Six parameters, better fit, less interpretable.\n4. **Shapelets** — if the MGE still leaves disky or asymmetric structure and you accept a signed\n solution. Five parameters.\n5. **Neither is enough** — the residuals sit in discrete off-centre lumps, and no basis with a\n single shared centre will absorb them. That is\n [`ag_pixelization`](./ag_pixelization.md).\n\nAn MGE and a shapelet basis can be compared by Bayesian evidence only with care, because they\nsolve different linear problems (positive-only versus signed). Compare them on the residual map\nand the chi-squared first, and ask if you want the evidence caveats spelled out.\n\n## Combine — where this hands off\n\n- **Pick a search** → [`ag_configure_search`](./ag_configure_search.md). Basis models want\n *fewer* live points than a parametric fit, not more — the workspace drops `n_live` to 75 for\n both linear profiles and the MGE — because the parameter space is simpler.\n- **Run it and read the output folder** → [`ag_run_search`](./ag_run_search.md).\n- **Plot the fit** → [`ag_plot_fit`](./ag_plot_fit.md), remembering that a linear profile has to\n go through `model_obj_linear_light_profiles_to_light_profiles` before it can be plotted.\n- **The basis fits worse than you expected, or the search stalls** →\n [`ag_debug_fit_failure`](./ag_debug_fit_failure.md). The two failure modes specific to this\n skill are a `sigma` ladder that stops short of the mask radius, and a free `sigma` or `beta`\n reintroducing a size degeneracy.\n- **Structured residuals a basis cannot reach** → [`ag_pixelization`](./ag_pixelization.md).\n- **A neighbour overlapping the galaxy, a residual sky, or a nuclear point source** →\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- **A non-parametric shape measurement instead of a model** →\n [`ag_ellipse_fitting`](./ag_ellipse_fitting.md), which measures the isophotal twist directly\n rather than inferring it from a two-basis MGE.\n- **The same galaxy in several bands** → the multi-dataset skill (`ag_multi_dataset`). A basis\n across bands is where the factor graph earns its keep, since the shape can be shared while\n the amplitudes are solved per band.\n- **Chaining a parametric fit into a basis fit** → the search-chaining skill\n (`ag_chain_searches`); a Sersic fit's centre and ellipticity make excellent starting priors\n for an MGE.\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording which tier you\nused, `total_gaussians` / `gaussian_per_basis` or the shapelet order, the solver you chose, and\nwhat the residuals looked like at each step — the last is the evidence for the model choice and\nthe first thing a referee will ask for.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Linear profiles](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_5_linear_profiles.ipynb):\n builds up from a standard profile to a linear one to a basis, showing what the inversion\n actually solves at each step.\n- **General reference** — [RTD: Light profiles API](https://pyautogalaxy.readthedocs.io/en/latest/api/light.html):\n every standard, linear, operated and basis variant with its module and parameters.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/features/multi_gaussian_expansion/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/multi_gaussian_expansion/modeling.py):\n the MGE end to end, including the compact nuclear basis and the run-time and VRAM discussion.\n\n## Agent procedural checklist\n\n1. Ask whether the user needs interpretable Sersic parameters or the best achievable fit — that\n choice, not the API, picks the branch.\n2. Look at the residual map of a single linear Sersic first; structured-but-smooth residuals mean\n a basis, discrete lumps mean `ag_pixelization`.\n3. Default to `ag.lp_linear` for every parametric component; never use `ag.lp` in a model\n without a reason.\n4. For an MGE, pass the real `mask_radius`, and reach for `gaussian_per_basis=2` when the\n isophotes twist.\n5. For shapelets, pass `ag.Settings(use_positive_only_solver=False)` on the *analysis*, link\n `ell_comps` across the basis, and tell the user the reconstruction may contain negative flux.\n6. Always check `model.total_free_parameters` against what you intended — a basis's `model.info`\n is long and mostly fixed, and one unlinked parameter multiplies by the component count.\n7. Evaluate one likelihood before committing to a search; run `print_vram_use` before a GPU run\n with a large basis.\n8. Read intensities out via `max_log_likelihood_galaxies`,\n `fit.linear_light_profile_intensity_dict`, or\n `model_obj_linear_light_profiles_to_light_profiles` — never expect them in `model.results`.\n9. Save the script to `scripts/`, quote every plot's absolute path and offer to open it, then\n offer the `wiki/project/` entry.\n" + } + }, + "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file diff --git a/notebooks/chapter_2_modeling/tutorial_5_linear_profiles.ipynb b/notebooks/chapter_2_modeling/tutorial_5_linear_profiles.ipynb deleted file mode 100644 index 63f4853..0000000 --- a/notebooks/chapter_2_modeling/tutorial_5_linear_profiles.ipynb +++ /dev/null @@ -1,886 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 5: Linear Profiles\n", - "===========================\n", - "\n", - "In the previous tutorial we learned how to balance model complexity with our non-linear search in order to infer\n", - "accurate model solutions and avoid failure. We saw how in order to fit a model accurately one may have to\n", - "parameterize and fit a simpler model with fewer non-linear parameters, at the expense of fitting the data less\n", - "accurately.\n", - "\n", - "It would be desirable if we could make our model have more flexibility enabling it to fit more complex galaxy\n", - "structures, but in a way that does not increase (or perhaps even decreases) the number of non-linear parameters.\n", - "This would keep the `nautilus` model-fit efficient and accurate.\n", - "\n", - "This is possible using linear light profiles, which solve for their `intensity` parameter via efficient linear\n", - "algebra, using a process called an inversion. The inversion always computes `intensity` values that give the best\n", - "fit to the data (e.g. they minimize the chi-squared and therefore maximize the likelihood).\n", - "\n", - "This tutorial will first fit a model using two linear light profiles. Because their `intensity` values are solved for\n", - "implicitly, this means they are not a dimension of the non-linear parameter space fitted by `nautilus`, therefore\n", - "reducing the complexity of parameter space and making the fit faster and more accurate.\n", - "\n", - "This tutorial will then show how many linear light profiles can be combined into a `Basis`, which comes from the term\n", - "'basis function'. By combining many linear light profiles models can be composed which are able to fit complex galaxy\n", - "structures (e.g. asymmetries, twists) with just N=6-8 non-linear parameters.\n", - "\n", - "__Contents__\n", - "\n", - "- **Initial Setup:** Load the dataset and apply a mask.\n", - "- **Linear Light Profiles:** Fit a model using linear light profiles that solve for intensity via linear algebra.\n", - "- **Run Time:** Estimate the run time of the model-fit before starting.\n", - "- **Result:** Inspect the result and the solved intensity values.\n", - "- **Intensities:** Access the intensity values of linear light profiles after the fit.\n", - "- **Visualization:** Visualize the fit using linear light profiles.\n", - "- **Basis:** Combine many linear light profiles into a basis for fitting complex structures.\n", - "- **Model Fit:** Fit the basis model to the data.\n", - "- **Disk MGE:** Use a Multi-Gaussian Expansion for the disk component.\n", - "- **Multi Gaussian Expansion Benefits:** Discussion of the advantages of MGE models.\n", - "- **Positive Only Solver:** Ensure linear algebra solutions have positive intensity values.\n", - "- **Other Basis Functions:** Overview of other basis functions like shapelets.\n", - "- **Wrap Up:** Summary of linear light profiles and basis functions." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Google Colab Setup__\n", - "\n", - "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "jupyter": { - "source_hidden": true - } - }, - "outputs": [], - "source": [ - "# @title Set up Google Colab { display-mode: \"form\" }\n", - "try:\n", - " import google.colab\n", - "except ImportError:\n", - " from autogalaxy import setup_colab as _setup_colab\n", - "else:\n", - " import importlib\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.check_call(\n", - " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", - " )\n", - " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", - "\n", - "_setup_colab.setup(\"howtogalaxy\")" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autogalaxy import setup_notebook; setup_notebook()\n", - "\n", - "import numpy as np\n", - "from pathlib import Path\n", - "import autogalaxy as ag\n", - "import autogalaxy.plot as aplt\n", - "import autofit as af" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Initial Setup__\n", - "\n", - "we'll use the same galaxy data as the previous tutorial, where:\n", - "\n", - " - The galaxy's bulge is a `Sersic`.\n", - " - The galaxy's disk is an `Exponential`." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "dataset_name = \"simple\"\n", - "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Dataset Auto-Simulation__\n", - "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "if ag.util.dataset.should_simulate(str(dataset_path)):\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulators/simple.py\"],\n", - " check=True,\n", - " )\n", - "\n", - "\n", - "dataset = ag.Imaging.from_fits(\n", - " data_path=dataset_path / \"data.fits\",\n", - " noise_map_path=dataset_path / \"noise_map.fits\",\n", - " psf_path=dataset_path / \"psf.fits\",\n", - " pixel_scales=0.1,\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Mask__\n", - "\n", - "we'll create and use a smaller 2.5\" `Mask2D` again." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mask = ag.Mask2D.circular(\n", - " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5\n", - ")\n", - "\n", - "dataset = dataset.apply_mask(mask=mask)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Over Sampling__\n", - "\n", - "Apply adaptive over sampling to ensure the calculation is accurate, you can read up on over-sampling in more detail via \n", - "the `autogalaxy_workspace/*/guides/advanced/over_sampling.ipynb` notebook." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n", - " grid=dataset.grid,\n", - " sub_size_list=[8, 4, 2],\n", - " radial_list=[0.3, 0.6],\n", - " centre_list=[(0.0, 0.0)],\n", - ")\n", - "\n", - "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "When plotted, the galaxy's bulge and disk are clearly visible in the centre of the image." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_imaging_dataset(dataset=dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Linear Light Profiles__\n", - "\n", - "First, we use a variant of a light profile discussed called a \"linear light profile\", which is accessed via the\n", - "command `ag.lp_linear`. \n", - " \n", - "The `intensity` values of linear light profiles are solved for via linear algebra. We use the `Sersic` \n", - "and `Exponential` linear light profiles, which are identical to the ordinary `Sersic` and `Exponential` \n", - "profiles fitted in previous tutorials, except for their `intensity` parameter now being solved for implicitly.\n", - "\n", - "Because the `intensity` parameter of each light profile is not a free parameter in the model-fit, the dimensionality of \n", - "non-linear parameter space is reduced by 1 for each light profile (in this example, 2). This also removes the \n", - "degeneracies between the `intensity` and other light profile parameters (e.g. `effective_radius`, `sersic_index`), \n", - "making the model-fit more robust.\n", - "\n", - "This is a rare example where we are able to reduce the complexity of parameter space without making the model itself \n", - "any simpler. There is really no downside to using linear light profiles, so I would recommend you adopt them as \n", - "standard for your own model-fits from here on!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge = af.Model(ag.lp_linear.Sersic)\n", - "disk = af.Model(ag.lp_linear.Exponential)\n", - "\n", - "bulge.centre = disk.centre\n", - "\n", - "galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n", - "\n", - "model = af.Collection(galaxies=af.Collection(galaxy=galaxy))" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `info` attribute shows the model, including the linear light profiles.\n", - "\n", - "Note how the `intensity` is no longer listed and does not have a prior associated with it." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(model.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now create this search and run it." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search = af.Nautilus(\n", - " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", - " name=\"tutorial_5_linear_light_profile\",\n", - " unique_tag=dataset_name,\n", - " n_live=100,\n", - " n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2.\n", - ")\n", - "\n", - "analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Run Time__\n", - "\n", - "For standard light profiles, the log likelihood evaluation time is of order ~0.01 seconds for this dataset.\n", - "\n", - "For linear light profiles, the log likelihood evaluation increases to around ~0.05 seconds per likelihood evaluation.\n", - "This is still fast, but it does mean that the fit may take around five times longer to run.\n", - "\n", - "However, because two free parameters have been removed from the model (the `intensity` of the bulge and\n", - "disk), the total number of likelihood evaluations will reduce. Furthermore, the simpler parameter space\n", - "likely means that the fit will take less than 10000 likelihood evaluations per free parameter to converge. This is\n", - "aided further by the reduction in `n_live` to 100.\n", - "\n", - "Fits using standard light profiles and linear light profiles therefore take roughly the same time to run. However,\n", - "the simpler parameter space of linear light profiles means that the model-fit is more reliable, less susceptible to\n", - "converging to an incorrect solution and scales better if even more light profiles are included in the model.\n", - "\n", - "Run the non-linear search." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(\n", - " \"The non-linear search has begun running - checkout the HowToGalaxy/output/howtogalaxy/chapter_2/tutorial_5_linear_light_profile\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell will progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", - "result_linear_light_profile = search.fit(model=model, analysis=analysis)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Result__\n", - "\n", - "The `info` attribute shows the resulting model, which does not display the `intensity` values for each light profile." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result_linear_light_profile.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Intensities__\n", - "\n", - "The intensities of linear light profiles are not a part of the model parameterization and therefore are not displayed\n", - "in the `model.results` file.\n", - "\n", - "To extract the `intensity` values of a specific component in the model, we use the `max_log_likelihood_galaxies`,\n", - "which has already performed the inversion and therefore the galaxy light profiles have their solved for\n", - "`intensity`'s associated with them." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "galaxies = result_linear_light_profile.max_log_likelihood_galaxies\n", - "\n", - "print(galaxies[0].bulge.intensity)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `Galaxies` contained in the `max_log_likelihood_fit` also has the solved for `intensity` values:" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "fit = result_linear_light_profile.max_log_likelihood_fit\n", - "\n", - "galaxies = fit.galaxies\n", - "\n", - "print(galaxies[0].bulge.intensity)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Visualization__\n", - "\n", - "Linear light profiles and objects containing them (e.g. galaxies) cannot be plotted because they do not \n", - "have an `intensity` value.\n", - "\n", - "Therefore, the objects created above which replaces all linear light profiles with ordinary light profiles must be\n", - "used for visualization:" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "galaxies = result_linear_light_profile.max_log_likelihood_galaxies\n", - "\n", - "aplt.plot_array(array=galaxies.image_2d_from(grid=dataset.grid), title=\"Image\")\n", - "\n", - "aplt.plot_array(array=galaxies[0].image_2d_from(grid=dataset.grid), title=\"Image\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Basis__\n", - "\n", - "We can use many linear light profiles to build a `Basis`. \n", - "\n", - "For example, below, we make a `Basis` out of 30 elliptical Gaussian linear light profiles which: \n", - "\n", - " - All share the same centre and elliptical components.\n", - " - The `sigma` size of the Gaussians increases in log10 increments.\n", - "\n", - "The `sigma` values are spaced in log10 increments from a tenth of the pixel scale (0.01\") to the mask\n", - "radius (3.0\"), ensuring the Gaussians span all scales the data constrains." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "total_gaussians = 30\n", - "\n", - "# The sigma values of the Gaussians will be fixed to values spanning a tenth of the pixel scale to the mask radius, 3.0\".\n", - "mask_radius = 3.0\n", - "log10_sigma_list = np.linspace(\n", - " np.log10(dataset.pixel_scales[0] / 10.0), np.log10(mask_radius), total_gaussians\n", - ")\n", - "\n", - "# By defining the centre here, it creates two free parameters that are assigned below to all Gaussians.\n", - "\n", - "centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", - "centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", - "\n", - "bulge_gaussian_list = []\n", - "\n", - "# A list of Gaussian model components whose parameters are customized belows.\n", - "\n", - "gaussian_list = af.Collection(\n", - " af.Model(ag.lp_linear.Gaussian) for _ in range(total_gaussians)\n", - ")\n", - "\n", - "# Iterate over every Gaussian and customize its parameters.\n", - "\n", - "for i, gaussian in enumerate(gaussian_list):\n", - " gaussian.centre.centre_0 = centre_0 # All Gaussians have same y centre.\n", - " gaussian.centre.centre_1 = centre_1 # All Gaussians have same x centre.\n", - " gaussian.ell_comps = gaussian_list[\n", - " 0\n", - " ].ell_comps # All Gaussians have same elliptical components.\n", - " gaussian.sigma = (\n", - " 10 ** log10_sigma_list[i]\n", - " ) # All Gaussian sigmas are fixed to values above.\n", - "\n", - "bulge_gaussian_list += gaussian_list\n", - "\n", - "# The Basis object groups many light profiles together into a single model component.\n", - "\n", - "bulge = af.Model(\n", - " ag.lp_basis.Basis,\n", - " profile_list=bulge_gaussian_list,\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "One we have a `Basis`, we can treat it like any other light profile in order to create a `Galaxy` and `Galaxies` and \n", - "use it to fit data." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "galaxy = ag.Galaxy(redshift=0.5, bulge=bulge)\n", - "\n", - "galaxies = ag.Galaxies(galaxies=[galaxy])\n", - "\n", - "fit = ag.FitImaging(dataset=dataset, galaxies=galaxies)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "By plotting the fit, we see that the `Basis` does a reasonable job at capturing the appearance of the galaxy.\n", - "\n", - "There are imperfections, but this is because we did not fit the model via a non-linear search in order to determine\n", - "the optimal values of the Gaussians in the basis. In particular, the Gaussians above were all spherical, when the\n", - "galaxy is elliptical.\n", - "\n", - "We rectify this below, where we use a non-linear search to determine the optimal values of the Gaussians!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_fit_imaging(fit=fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Model Fit__\n", - "\n", - "To fit a model using `Basis` functions, the API is very similar to that shown throughout this chapter, using both\n", - "the `af.Model()` and `af.Collection()` objects.\n", - "\n", - "In this example we fit a `Basis` model for the bulge where:\n", - "\n", - " - The bulge is a superposition of 30 parametric linear `Gaussian` profiles [4 parameters]. \n", - " - The centres and elliptical components of each family of Gaussians are all linked together.\n", - " - The `sigma` size of the Gaussians increases in log10 increments.\n", - "\n", - "The number of free parameters and therefore the dimensionality of the MGE is just N=4." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "total_gaussians = 30\n", - "\n", - "# The sigma values of the Gaussians will be fixed to values spanning a tenth of the pixel scale to the mask radius, 3.0\".\n", - "mask_radius = 3.0\n", - "log10_sigma_list = np.linspace(\n", - " np.log10(dataset.pixel_scales[0] / 10.0), np.log10(mask_radius), total_gaussians\n", - ")\n", - "\n", - "# By defining the centre here, it creates two free parameters that are assigned below to all Gaussians.\n", - "\n", - "centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", - "centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", - "\n", - "bulge_gaussian_list = []\n", - "\n", - "# A list of Gaussian model components whose parameters are customized belows.\n", - "\n", - "gaussian_list = af.Collection(\n", - " af.Model(ag.lp_linear.Gaussian) for _ in range(total_gaussians)\n", - ")\n", - "\n", - "# Iterate over every Gaussian and customize its parameters.\n", - "\n", - "for i, gaussian in enumerate(gaussian_list):\n", - " gaussian.centre.centre_0 = centre_0 # All Gaussians have same y centre.\n", - " gaussian.centre.centre_1 = centre_1 # All Gaussians have same x centre.\n", - " gaussian.ell_comps = gaussian_list[\n", - " 0\n", - " ].ell_comps # All Gaussians have same elliptical components.\n", - " gaussian.sigma = (\n", - " 10 ** log10_sigma_list[i]\n", - " ) # All Gaussian sigmas are fixed to values above.\n", - "\n", - "bulge_gaussian_list += gaussian_list\n", - "\n", - "# The Basis object groups many light profiles together into a single model component.\n", - "\n", - "bulge = af.Model(\n", - " ag.lp_basis.Basis,\n", - " profile_list=bulge_gaussian_list,\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Disk MGE__\n", - "\n", - "The residuals of the fit above showed us that the galaxy in the data is composed of multiple structures (e.g. a bulge\n", - "and disk) which have distinct elliptical coordinates.\n", - "\n", - "We therefore compose a second `Basis` of 10 Gaussians to represent the `disk`. This is parameterized the same as\n", - "the `bulge` (e.g. all Gaussians share the same `centre` and `ell_comps`) but is treated as a completely\n", - "independent set of parameters." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "total_gaussians = 10\n", - "\n", - "# The sigma values of the Gaussians will be fixed to values spanning a tenth of the pixel scale to the mask radius, 3.0\".\n", - "mask_radius = 3.0\n", - "log10_sigma_list = np.linspace(\n", - " np.log10(dataset.pixel_scales[0] / 10.0), np.log10(mask_radius), total_gaussians\n", - ")\n", - "\n", - "disk_gaussian_list = []\n", - "\n", - "# A list of Gaussian model components whose parameters are customized belows.\n", - "\n", - "gaussian_list = af.Collection(\n", - " af.Model(ag.lp_linear.Gaussian) for _ in range(total_gaussians)\n", - ")\n", - "\n", - "# Iterate over every Gaussian and customize its parameters.\n", - "\n", - "for i, gaussian in enumerate(gaussian_list):\n", - " gaussian.centre.centre_0 = bulge_gaussian_list[\n", - " 0\n", - " ].centre_0 # All Gaussians have same y centre as bulge.\n", - " gaussian.centre.centre_1 = bulge_gaussian_list[\n", - " 0\n", - " ].centre_1 # All Gaussians have same x centre as bulge.\n", - " gaussian.ell_comps = gaussian_list[\n", - " 0\n", - " ].ell_comps # All Gaussians have same elliptical components.\n", - " gaussian.sigma = (\n", - " 10 ** log10_sigma_list[i]\n", - " ) # All Gaussian sigmas are fixed to values above.\n", - "\n", - "disk_gaussian_list += gaussian_list\n", - "\n", - "# The Basis object groups many light profiles together into a single model component.\n", - "\n", - "disk = af.Model(\n", - " ag.lp_basis.Basis,\n", - " profile_list=disk_gaussian_list,\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now compose the overall model which uses both sets of Gaussians to represent separately the bulge and disk.\n", - "\n", - "The overall dimensionality of non-linear parameter space is just N=6, which is fairly remarkable if you\n", - "think about just how complex the structures are that these two `Basis` of Gaussians can capture!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n", - "\n", - "model = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `info` attribute shows the model, which is a lot longer than we have seen previously, given that is \n", - "composed of many Gaussians!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(model.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now fit the model, with just `n_live=50` given the simplicity of parameter space." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search = af.Nautilus(\n", - " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", - " name=\"tutorial_5_basis\",\n", - " unique_tag=dataset_name,\n", - " n_live=50,\n", - " n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2.\n", - ")\n", - "\n", - "print(\n", - " \"The non-linear search has begun running - checkout the HowToGalaxy/output/howtogalaxy/chapter_2/tutorial_5_basis\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell will progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", - "result_basis = search.fit(model=model, analysis=analysis)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Result__\n", - "\n", - "The result `info` attribute shows the result, which is again longer than usual given the large number of Gaussians\n", - "used in the fit." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result_basis.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Visualizing the fit shows that we successfully fit the data to the noise level.\n", - "\n", - "Note that the result objects `max_log_likelihood_galaxies` and `max_log_likelihood_fit` automatically convert\n", - "all linear light profiles to ordinary light profiles, including every single one of the 40 Gaussians fitted\n", - "above.\n", - "\n", - "This means we can use them directly to perform the visualization below." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result_basis.max_log_likelihood_instance)\n", - "\n", - "aplt.subplot_galaxies(\n", - " galaxies=result_basis.max_log_likelihood_galaxies, grid=result_basis.grids.lp\n", - ")\n", - "\n", - "aplt.subplot_fit_imaging(fit=result_basis.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Multi Gaussian Expansion Benefits__\n", - "\n", - "Symmetric light profiles (e.g. elliptical Sersics) may leave significant residuals, because they fail to capture\n", - "irregular and asymmetric morphological features of galaxies (e.g. isophotal twists, an ellipticity which varies radially).\n", - "An MGE fully captures these features and can therefore much better represent the emission of complex galaxies.\n", - "\n", - "The MGE model can be composed in a way that has fewer non-linear parameters than an elliptical Sersic. In this example,\n", - "a group of Gaussians is used to represent the `bulge` of the galaxy, which in total correspond to just N=4 non-linear\n", - "parameters (a `bulge` and `disk` comprising two linear Sersics has N=10 parameters).\n", - "\n", - "The MGE model parameterization is also composed such that neither the `intensity` parameters or any of the\n", - "parameters controlling the size of the Gaussians (their `sigma` values) are non-linear parameters sampled by Nautilus.\n", - "This removes the most significant degeneracies in parameter space, making the model much more reliable and efficient\n", - "to fit.\n", - "\n", - "Therefore, not only does an MGE fit more complex galaxy morphologies, it does so using fewer non-linear parameters\n", - "in a much simpler non-linear parameter space which has far less significant parameter degeneracies!\n", - "\n", - "__Positive Only Solver__\n", - "\n", - "Many codes which use linear algebra typically rely on a linear algebra solver which allows for positive and negative\n", - "values of the solution (e.g. `np.linalg.solve`), because they are computationally fast. \n", - "\n", - "This is problematic, as it means that negative surface brightnesses values can be computed to represent a galaxy's \n", - "light, which is clearly unphysical. For an MGE, this produces a positive-negative \"ringing\", where the\n", - "Gaussians alternate between large positive and negative values. This is clearly undesirable and unphysical.\n", - "\n", - "**PyAutoGalaxy** (and therefore all examples above) uses a positive only linear algebra solver which has been \n", - "extensively optimized to ensure it is as fast as positive-negative solvers. This ensures that all light profile \n", - "intensities are positive and therefore physical. \n", - "\n", - "__Other Basis Functions__\n", - "\n", - "In addition to the Gaussians used in this example, there is another basis function implemented in PyAutoGalaxy \n", - "that is commonly used to represent the light of galaxies, called a `Shapelet`. \n", - "\n", - "Shapelets are basis functions with analytic properties that are appropriate for capturing the exponential / disk-like\n", - "features of a galaxy. They do so over a wide range of scales, and can often represent features in galaxies\n", - "that a single Sersic function or MGE cannot.\n", - "\n", - "An example using shapelets is given at `autogalaxy_workspace/scripts/imaging/features/shapelets/modeling.py`.\n", - "\n", - "Feel free to experiment with using shapelets to model the galaxy yourself. However they incur higher computational\n", - "overheads than the MGE and include a free parameter which governs the size of the basis functions and therefore galaxy,\n", - "slowing down convergence of the non-linear search. We have found that MGEs perform better than shapelets in most\n", - "galaxy modeling problems.\n", - "\n", - "If you have a desire to fit galaxies with even more complex morphologies we recommend you look at how to reconstruct\n", - "galaxies using pixelizations in the `modeling/features` section or chapter 3 of **HowToGalaxy**.\n", - "\n", - "__Wrap Up__\n", - "\n", - "In this tutorial we described how linearizing light profiles allows us to fit more complex light profiles to\n", - "galaxies using fewer non-linear parameters, keeping the fit performed by the non-linear search fast, accurate\n", - "and robust.\n", - "\n", - "Perhaps the biggest downside to basis functions is that they are only as good as the features they can capture\n", - "in the data. For example, a basis of Gaussians still assumes that they have a well defined centre, but there are\n", - "galaxies which may have multiple components with multiple centres (e.g. many star forming knots) which such a\n", - "basis cannot capture.\n", - "\n", - "In chapter 3 of **HowToGalaxy** we introduce non-parametric pixelizations, which reconstruct the data in way\n", - "that does not make assumptions like a centre and can thus reconstruct even more complex, asymmetric and irregular\n", - "galaxy morphologies." - ] - } - ], - "metadata": { - "anaconda-cloud": {}, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - }, - "colab": { - "aiContexts": { - "24c2f562-da24-50bb-8eb9-5a887505fe54": { - "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", - "name": "PyAutoGalaxy assistant", - "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_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\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_2_modeling/tutorial_5_linear_profiles.ipynb in HowToGalaxy).\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 PyAutoGalaxy 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 PyAutoGalaxy docs (https://pyautogalaxy.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) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. 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 galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_basis_profiles\n\n---\nname: ag_basis_profiles\ndescription: Fit a galaxy's morphology with a *basis* rather than one or two smooth profiles — linear light profiles (`ag.lp_linear`), a Multi-Gaussian Expansion, or a shapelet expansion — where every component's `intensity` is solved analytically by a linear inversion instead of sampled by the search. Covers why `ag.lp_linear` is the default for any bulge-disk decomposition, when an MGE beats a Sersic pair (isophotal twists, radially varying ellipticity, asymmetry), when shapelets beat an MGE, the positive-only versus signed linear solver and what a negative amplitude means physically, `ag.model_util.mge_model_from` and the hand-rolled `ag.lp_basis.Basis` idiom behind it, a compact MGE for an unresolved nucleus, and how to read solved intensities back out of a fit. Use when a Sersic or bulge-plus-disk model leaves structure in the residuals but the galaxy still has a well-defined centre. Not for pixelized reconstruction of genuinely irregular clumps (`ag_pixelization`), not for non-parametric isophote measurement (`ag_ellipse_fitting`), and not for the basics of composing an `af.Model` tree (`ag_build_imaging_model`).\n---\n\n# Fitting morphology with a basis\n\nA Sersic profile makes a strong claim: that the galaxy's isophotes are concentric, similar\nellipses with a single fixed axis ratio and position angle, and that its surface brightness\nfalls off as one power of radius. Real galaxies routinely violate all of that. Isophotes twist\nwith radius, the ellipticity varies from the bulge outwards, a bar or a spiral pattern breaks\nthe symmetry — and when a Sersic cannot represent those features it does not fail loudly. It\nabsorbs them, and returns an `effective_radius` and `sersic_index` biased by exactly the\nstructure it could not fit.\n\nA **basis** is the answer: instead of one profile with a shape, use tens of simple profiles\nwhose superposition can take almost any shape. The reason this is affordable — and the reason\nit is often *cheaper* than a Sersic pair — is statistical. Every basis component's `intensity`\nis a **linear** parameter: given the shapes and positions of the components, the amplitudes\nthat maximise the likelihood follow from solving a linear system, exactly, in one step. So they\nnever enter the non-linear search's parameter space at all. A 60-Gaussian MGE can have four\nfree parameters where a two-component linear Sersic decomposition has nine.\n\nThree tiers, same machinery, increasing flexibility:\n\n| Tier | What it is | Free parameters | Reach for it when |\n|---|---|---|---|\n| `ag.lp_linear.*` | ordinary profiles with `intensity` solved | 6 per Sersic, 3 per aligned Exponential | you want interpretable bulge/disk parameters — **the default** |\n| MGE (`ag.lp_basis.Basis` of `Gaussian`s) | 15–100 Gaussians on a fixed log-spaced `sigma` ladder | 4 (one basis) to 6 (two) | isophotal twists, radial ellipticity variation, mild asymmetry |\n| shapelets | an orthonormal polar or Cartesian basis | 3 (spherical) to 5 (elliptical) | disky, star-forming morphology the MGE still smooths over |\n\nThe science this serves is the decomposition itself. A bulge-plus-disk fit measures the\nbulge-to-total light ratio, the two components' sizes and the bulge's concentration — the\nquantities that place a galaxy on the mass–size relation and separate a classical spheroid from\na pseudo-bulge. A basis fit measures something the parametric fit cannot: how the shape of the\nlight changes with radius. Both concepts are in\n[`../wiki/core/concepts/linear_light_profiles_and_mge.md`](../wiki/core/concepts/linear_light_profiles_and_mge.md)\nand [`../wiki/core/concepts/shapelets.md`](../wiki/core/concepts/shapelets.md); the catalogue of\nwhich variant lives in which module is\n[`../wiki/core/api/light_profile_catalog.md`](../wiki/core/api/light_profile_catalog.md).\n\nThis skill assumes you already have a masked, over-sampled dataset and know how to build an\n`af.Model` tree — that is [`ag_build_imaging_model`](./ag_build_imaging_model.md), whose MGE\nbranch is the one-paragraph version of what follows.\n\n## Ask\n\n- *\"Do you need the Sersic parameters, or the best fit?\"* This is the real fork. If your science\n is a bulge-to-total ratio, an effective radius, a Sersic index — a number you will put in a\n table next to other people's — stay with `ag.lp_linear` Sersic-family profiles, because an\n MGE does not hand you those numbers. If your science is the light distribution itself, or you\n need the residuals flat before you can trust anything else, go to a basis.\n- *\"What does the residual map look like after a single Sersic?\"* Structured residuals that\n follow the isophotes (a four-lobed or twisted pattern) say the *shape* is wrong — an MGE\n fixes that. Residuals in discrete off-centre lumps say the shape is fine but there is\n substructure — that is a pixelization ([`ag_pixelization`](./ag_pixelization.md)), not a basis.\n If you have not looked yet, look first; it is one plot and it decides the branch.\n- *\"Does the galaxy have a single well-defined centre?\"* Every basis in this skill shares one\n centre across all its components. A merger, or a galaxy with a bright companion overlapping\n it, breaks that assumption — handle the companion first with\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- *\"Is there a compact nuclear source?\"* An AGN or a nuclear starburst is a separate component,\n and there is a purpose-built compact MGE for it (branch four below).\n\n## Branch — linear light profiles, the default for any decomposition\n\nStart here even when you expect to end up with a basis. This is the same bulge-plus-disk model\n`ag_build_imaging_model` composes, and the point of this branch is what happens to `intensity`.\n\n```python\n\"\"\"\nGalaxy Structure: Linear Bulge-Disk Decomposition\n=================================================\n\nDecompose a galaxy's light into a Sersic bulge and an Exponential disk using *linear* light\nprofiles, whose `intensity` parameters are solved analytically by a linear inversion inside\nevery likelihood evaluation rather than sampled by the non-linear search. The ratio of the two\nsolved intensities, integrated, is the bulge-to-total light ratio.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the masked, over-sampled imaging dataset.\n- **Model:** Compose the linear bulge and disk, with their centres paired.\n- **Check:** Confirm the parameter count and evaluate one likelihood.\n- **Intensities:** Read the solved intensities back out of a completed fit.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPIXEL_SCALES = 0.1\nMASK_RADIUS = 3.0\n\n\"\"\"\n__Dataset__\n\nLoaded from FITS, masked to a radius chosen by inspecting the data, and over-sampled adaptively\nwhere the profile's intensity gradient is steep. All three decisions change the answer, so they\nare reproduced here rather than hidden\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\"\"\"\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=PIXEL_SCALES,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n\n\"\"\"\n__Model__\n\nThe decomposition is identifiable because the two components are *asymmetric* in what they are\nallowed to be: the bulge's `sersic_index` is free, so the fit can find a concentrated spheroid\n(n ~ 4), while the `Exponential` disk has n fixed at 1 by construction. Two free Sersics on one\ngalaxy are largely degenerate and the fit will trade light between them.\n\n`ag.lp_linear` rather than `ag.lp` is the only change from a standard composition, and it is\nnot a small one: each profile's `intensity` leaves the search's parameter space and is instead\nsolved by a linear inversion that always returns the amplitudes maximising the likelihood given\nthe other parameters. Two dimensions vanish, and with them the strong degeneracies between\n`intensity` and `effective_radius` / `sersic_index` that a sampler finds hardest to map\n(`PyAutoGalaxy:autogalaxy/profiles/light/linear/sersic.py`).\n\n`bulge.centre = disk.centre` asserts the components are concentric — physically reasonable for\nmost galaxies, and worth two parameters.\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\ndisk = af.Model(ag.lp_linear.Exponential)\nbulge.centre = disk.centre\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\n\"\"\"\n__Check__\n\nThe likelihood at the prior medians costs one evaluation and proves the model, dataset and\nanalysis are mutually compatible. Pass `use_jax=False` while debugging — NumPy tracebacks are\nfar easier to read (`PyAutoGalaxy:autogalaxy/imaging/model/analysis.py`).\n\"\"\"\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\nlog_likelihood = analysis.log_likelihood_function(\n instance=model.instance_from_prior_medians()\n)\nprint(f\"log likelihood at prior medians: {float(log_likelihood):.2f}\")\n```\n\nN = 9: the bulge's centre (2), two `ell_comps` pairs (4), two `effective_radius` values and the\nbulge's `sersic_index` — with both intensities solved. Adapted from\n`autogalaxy_workspace:scripts/imaging/features/linear_light_profiles/modeling.py`, which\nreduces `n_live` to 75 for exactly this reason: a simpler parameter space needs fewer live\npoints to map.\n\nThe cost is real but small. A linear likelihood evaluation is roughly three to five times\nslower than a standard one, because the inversion has to be solved every time. The workspace\nexample measures ~0.05 s against ~0.01 s on a low-resolution dataset. That is repaid by fewer\niterations and a more reliable posterior, and the trade tips further towards linear the more\nprofiles you add — which is what makes the next two branches possible at all.\n\n### The consequence: `intensity` is not in the model, so it is not in the results\n\nThis trips up everyone once. A linear profile has no `intensity` attribute to report, so\n`model.results` does not list one, and **a linear profile cannot be plotted directly** — there\nis no amplitude to evaluate. The intensities exist only after a fit, as the inversion's\nsolution. Three ways to get at them, all from\n`autogalaxy_workspace:scripts/imaging/features/linear_light_profiles/modeling.py`:\n\n```python\n\"\"\"\n__Intensities__\n\n`max_log_likelihood_galaxies` has already performed the inversion, so its profiles carry their\nsolved `intensity` values and can be evaluated and plotted like ordinary profiles. The\n`Fit` additionally exposes a dictionary keyed by the profile objects themselves, which is the\nunambiguous route when several components share a class\n(`PyAutoGalaxy:autogalaxy/imaging/fit_imaging.py`).\n\"\"\"\ngalaxies = result.max_log_likelihood_galaxies\n\nprint(f\"bulge intensity = {galaxies[0].bulge.intensity}\")\n\nfit = result.max_log_likelihood_fit\n\nprint(fit.linear_light_profile_intensity_dict[fit.galaxies[0].bulge])\nprint(fit.linear_light_profile_intensity_dict[fit.galaxies[0].disk])\n\ngalaxies_ordinary = fit.model_obj_linear_light_profiles_to_light_profiles\n\naplt.subplot_galaxies(\n galaxies=galaxies_ordinary,\n grid=dataset.grid,\n output_path=\"scripts/scratch/my_galaxy/\",\n auto_filename=\"decomposition\",\n output_format=\"png\",\n)\n```\n\n`model_obj_linear_light_profiles_to_light_profiles` returns the same galaxies with every linear\nprofile replaced by its ordinary equivalent at the solved amplitude — that is the object to\nhand to any plotting or derived-quantity call. `fit.inversion.linear_obj_list` holds one\n`LightProfileLinearObjFuncList` per linear component (or per `Basis`), which is where the\nbookkeeping lives when you need to be certain which amplitude belongs to which profile.\n\nIntegrating those amplitudes over the two profiles is what gives you the bulge-to-total ratio;\nthe machinery for luminosities and magnitudes is\n[`../wiki/core/concepts/cosmology_and_units.md`](../wiki/core/concepts/cosmology_and_units.md).\nAsk if you want the derived-quantity route spelled out.\n\n## Branch — a Multi-Gaussian Expansion, when the *shape* is wrong\n\nA Gaussian is a poor galaxy profile on its own and an excellent basis function in company:\nsum enough of them at fixed, logarithmically spaced widths and you can build any monotonic\nradial profile, and — if you let separate groups of them carry separate ellipticities — an\nisophote shape that changes with radius. That last property is the one a Sersic cannot have at\nany parameter count, and it is why an MGE is the workspace's recommended default model.\n\nThe composition is long, so the library ships a helper:\n\n```python\n\"\"\"\n__Model__\n\nAn MGE bulge: 20 linear Gaussians sharing one centre and one ellipticity, with every `sigma`\nfixed on a logarithmic ladder running from below the pixel scale out to `mask_radius`, and\nevery intensity solved by the inversion. `mask_radius` sets the outer end of that ladder, so\npass the radius you actually masked at — a ladder that stops short of the data leaves the\nouter isophotes unrepresented (`PyAutoGalaxy:autogalaxy/analysis/model_util.py`).\n\"\"\"\nbulge = ag.model_util.mge_model_from(\n mask_radius=MASK_RADIUS,\n total_gaussians=20,\n centre_prior_is_uniform=True,\n)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n```\n\n**N = 4** — a shared centre and a shared `ell_comps`. Twenty Gaussians, four dimensions, more\nmorphological freedom than a Sersic's six. Adapted from\n`autogalaxy_workspace:scripts/imaging/start_here.py`, where the MGE is the recommended default.\n\nThe full signature is\n`mge_model_from(mask_radius, total_gaussians=30, gaussian_per_basis=1,\ncentre_prior_is_uniform=True, centre=(0.0, 0.0), centre_fixed=None, centre_per_basis=False,\ncentre_sigma=0.3, ell_comps_prior_is_uniform=False, ell_comps_uniform_width=0.2,\nell_comps_sigma=0.3, use_spherical=False)`. The arguments worth knowing:\n\n- **`gaussian_per_basis=2`** splits the ladder into two bases with *independent* ellipticities.\n N goes 4 → 6 and you buy the ability to fit an isophotal twist: an inner group and an outer\n group free to be differently elongated and differently oriented. This is the single most\n useful knob here, and the reason to prefer an MGE over a Sersic pair for an early-type galaxy.\n- **`centre_fixed=(y, x)`** pins the centre entirely, dropping two more parameters. Used for\n contaminating neighbours ([`ag_light_model_extras`](./ag_light_model_extras.md)).\n- **`use_spherical=True`** drops the ellipticity — for a genuinely round system, or as a\n deliberately rigid comparison model.\n- **`total_gaussians`** buys radial resolution, not shape freedom. 15 is enough for a smooth\n profile; 60 for a well-resolved one; beyond that you are mostly paying for likelihood\n evaluations. Cost scales with the count, because every Gaussian's image must be computed and\n PSF-convolved: the workspace measures ~0.5 s per evaluation for 60 Gaussians, against ~0.01 s\n for a standard Sersic. VRAM rises too — 10–50 MB per batched likelihood at 60 Gaussians, so\n check `analysis.print_vram_use(model=model, batch_size=search.batch_size)` before a GPU run\n with hundreds of components.\n\nThat run time is why the overall comparison is not obvious, and the workspace is honest about\nit: the MGE's likelihood is much slower, but its parameter space is so much simpler — and\ncrucially contains *no parameter that scales the galaxy's size* — that the search converges far\nfaster. Net, it usually wins, and it fits better.\n\n### The hand-rolled `Basis`, and why you might want it\n\nThe helper is a convenience over one explicit idiom. Compose it yourself when you need\nsomething the arguments do not offer — a bespoke `sigma` range, a third basis, per-basis\npriors. From `autogalaxy_workspace:scripts/imaging/features/multi_gaussian_expansion/modeling.py`:\n\n```python\n\"\"\"\n__Model__\n\nTwo groups of 30 Gaussians. Within a group every Gaussian shares the centre and ellipticity of\nthe first, and every `sigma` is *fixed* to a value on a log10 ladder spanning a tenth of the\npixel scale to the mask radius. `ag.lp_basis.Basis` then groups the whole list into one model\ncomponent the galaxy can hold (`PyAutoGalaxy:autogalaxy/profiles/basis.py`).\n\nThe lower end matters: anchoring it to the pixel scale stops the basis spending Gaussians on\nscales the data cannot resolve. `mge_model_from` exposes this as `sigma_min` (default `1e-4`,\nwhich reproduces the historical ladder exactly).\n\"\"\"\nimport numpy as np\n\ntotal_gaussians = 30\ngaussian_per_basis = 2\n\nlog10_sigma_list = np.linspace(\n np.log10(dataset.pixel_scales[0] / 10.0), np.log10(MASK_RADIUS), total_gaussians\n)\n\ncentre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\ncentre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n\nbulge_gaussian_list = []\n\nfor _ in range(gaussian_per_basis):\n\n gaussian_list = af.Collection(\n af.Model(ag.lp_linear.Gaussian) for _ in range(total_gaussians)\n )\n\n for i, gaussian in enumerate(gaussian_list):\n gaussian.centre.centre_0 = centre_0 # one shared y centre\n gaussian.centre.centre_1 = centre_1 # one shared x centre\n gaussian.ell_comps = gaussian_list[0].ell_comps # shared within this basis\n gaussian.sigma = 10 ** log10_sigma_list[i] # fixed, not sampled\n\n bulge_gaussian_list += gaussian_list\n\nbulge = af.Model(ag.lp_basis.Basis, profile_list=bulge_gaussian_list)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n```\n\nN = 6. `print(model.info)` prints all sixty Gaussians and looks alarming; almost every\nparameter shown is fixed. Trust `model.total_free_parameters`, not the length of the printout.\n\nTwo details that are load-bearing. Assigning `gaussian.sigma = ` **fixes** it — the\nwhole scheme depends on the widths not being sampled, because a free `sigma` reintroduces the\nsize-scaling degeneracy the MGE exists to remove. And sharing `ell_comps` *within* a basis but\nnot *between* bases is precisely what makes the twist fittable.\n\nThe `Basis` constructor also accepts a `regularization` argument that penalises non-smooth\namplitude solutions. Treat it as research-only: the positive-only solver below already fixes\nthe pathology it was introduced for, and no production analysis uses it — the workspace moved\nthat branch out of the user-facing script deliberately.\n\n## Branch — a compact MGE for an unresolved nucleus\n\nAn AGN or nuclear starburst is not the extended stellar light, and forcing one basis to cover\nboth makes the fit choose between them. Model it as a second, deliberately compact basis: the\nsame construction with the `sigma` ladder capped at about twice the pixel scale, so the\ncomponent cannot be broader than a PSF-convolved point source.\n\n```python\n\"\"\"\n__Model__\n\nThe galaxy's light becomes the sum of a diffuse stellar `bulge` MGE and a compact `point` MGE.\nThe point basis is 10 linear Gaussians sharing one centre and ellipticity with `sigma` values\nlog-spaced from `sigma_min` (default 0.01\") to twice the pixel scale — compact relative to the\nresolution of the data, which is what makes it read as a point source rather than a small galaxy\n(`PyAutoGalaxy:autogalaxy/analysis/model_util.py`).\n\"\"\"\npoint = ag.model_util.mge_point_model_from(\n pixel_scales=PIXEL_SCALES,\n total_gaussians=10,\n centre=(0.0, 0.0),\n)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, point=point)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/features/multi_gaussian_expansion/modeling.py`,\nwhose `__Point Source__` section builds the same basis line by line first if you want to see\ninside the helper. Four extra parameters on top of the bulge MGE.\n\nThere is a genuinely different approach to the same problem — an **operated** light profile,\nwhich is assumed to be already PSF-convolved and so bypasses the convolution entirely. Which\nto pick, and why a compact model source is so sensitive to sub-pixel placement, is\n[`ag_light_model_extras`](./ag_light_model_extras.md) and\n[`../wiki/core/concepts/sky_background_and_operated_profiles.md`](../wiki/core/concepts/sky_background_and_operated_profiles.md).\n\n## Branch — shapelets, and the price of a signed solver\n\nShapelets are an orthonormal basis of Gauss–Hermite (Cartesian) or Gauss–Laguerre (polar)\nfunctions on a single scale `beta`, introduced for exactly this problem\n(Refregier 2003, arXiv:astro-ph/0105178). Because the basis is complete, it can represent\nmorphology an MGE smooths over — the disky, star-forming structure the workspace cites them\nfor. But completeness has a price, and it is a physical one.\n\n**Shapelets require negative amplitudes.** The higher-order basis functions oscillate in sign,\nand reproducing an arbitrary shape means combining them with signed coefficients. Every other\nbranch in this skill uses a positive-only linear solver, because a negative surface brightness\nis not a thing a galaxy has. Shapelets cannot: you must pass\n`ag.Settings(use_positive_only_solver=False)`, and the reconstructed light *will* contain\nnegative flux — verified, not assumed. That is not a numerical wrinkle to ignore; it is the\nmodel telling you it is a mathematical fit rather than a physical decomposition, and it is why\nthe workspace recommends trying an MGE alongside.\n\n```python\n\"\"\"\n__Model__\n\nA polar shapelet basis to order n = 5: 11 `ShapeletPolar` components whose `n` and `m` indices\nare fixed by construction, sharing one centre, one ellipticity and one scale `beta`. `beta` is\nthe only shape parameter — it sets the physical size the whole basis is expressed on, so its\nprior matters more here than any single amplitude\n(`PyAutoGalaxy:autogalaxy/profiles/light/linear/shapelets/polar.py`).\n\"\"\"\ntotal_n = 5\ntotal_m = sum(range(2, total_n + 1)) + 1\n\nshapelets_bulge_list = af.Collection(\n af.Model(ag.lp_linear.ShapeletPolar) for _ in range(total_n + total_m)\n)\n\nn_count = 1\nm_count = -1\n\nfor shapelet in shapelets_bulge_list:\n shapelet.n = n_count\n shapelet.m = m_count\n\n m_count += 2\n\n if m_count > n_count:\n n_count += 1\n m_count = -n_count\n\n shapelet.centre = shapelets_bulge_list[0].centre\n shapelet.ell_comps = shapelets_bulge_list[0].ell_comps\n shapelet.beta = shapelets_bulge_list[0].beta\n\nbulge = af.Model(ag.lp_basis.Basis, profile_list=shapelets_bulge_list)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(f\"Total free parameters = {model.total_free_parameters}\")\n\n\"\"\"\n__Analysis__\n\nThe signed solver is requested through `ag.Settings`, which is passed to the analysis rather\nthan to the model — it is a property of how the inversion is solved, not of what is being\nfitted (`PyAutoArray:autoarray/settings.py`).\n\"\"\"\nanalysis = ag.AnalysisImaging(\n dataset=dataset,\n settings=ag.Settings(use_positive_only_solver=False),\n use_jax=True,\n)\n```\n\n**N = 5**: centre (2), `ell_comps` (2), `beta` (1). Adapted from\n`autogalaxy_workspace:scripts/imaging/features/shapelets/modeling.py` — note that the workspace\nloop as written does *not* link `ell_comps` across the basis, which leaves each shapelet's\nellipticity free and inflates the model to N = 43 rather than the N = 3 its prose claims. The\nline `shapelet.ell_comps = shapelets_bulge_list[0].ell_comps` above is the fix; N = 3 is what\nyou get from the spherical variant `ag.lp_linear.ShapeletPolarSph`, which has no `ell_comps` at\nall. Check `model.total_free_parameters` rather than trusting a comment — including this one.\n\nPolar shapelets suit radially organised light, which is most galaxies.\n`ag.lp_linear.ShapeletCartesian` (indexed by `n_y`, `n_x` instead of `n`, `m`) and\n`ag.lp_linear.ShapeletExponential` are the other two families; the Cartesian basis is not\ngenerally recommended for galaxies. You can see what a basis actually looks like before fitting\nanything:\n\n```python\nshapelets = [\n ag.lp_linear.ShapeletCartesian(\n n_y=y, n_x=x, centre=(0.0, 0.0), ell_comps=(0.0, 0.0), beta=1.0\n )\n for x in range(5)\n for y in range(5)\n]\n\nbasis = ag.lp_basis.Basis(profile_list=shapelets)\n\naplt.subplot_basis_image(\n basis=basis,\n grid=ag.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.05),\n output_path=\"scripts/scratch/shapelet_basis/\",\n output_format=\"png\",\n)\n```\n\n`subplot_basis_image` renders every component of the basis on a grid, which is the fastest way\nto build intuition for what `beta` and the order limit are buying you. It takes `output_path` /\n`output_format` but **not** `output_filename` — give each variant its own directory\n([`../wiki/core/api/plotting.md`](../wiki/core/api/plotting.md) tabulates that split). Print the\nabsolute path and offer to open it.\n\nShapelets also cost about 0.37 s per likelihood evaluation for ~60 components in the workspace's\nmeasurement — slower than linear profiles, comparable to an MGE, and with more free parameters\nthan an MGE of similar flexibility. The workspace's own recommendation is to run both and\ncompare; the concept page\n[`../wiki/core/concepts/shapelets.md`](../wiki/core/concepts/shapelets.md) has the full\nwhen-to-use discussion.\n\n## Choosing between the three\n\nFit them in order and let the residuals decide, because each step is cheap given the last:\n\n1. **Single linear Sersic** — the reference every other fit is judged against, and the source of\n the size and concentration you will actually quote. Six parameters.\n2. **Linear bulge plus disk** — if the science is a bulge-to-total ratio, this *is* the answer;\n a basis will fit better and tell you less. Nine parameters.\n3. **MGE, `gaussian_per_basis=2`** — if the residuals show a twist or a radially varying\n ellipticity. Six parameters, better fit, less interpretable.\n4. **Shapelets** — if the MGE still leaves disky or asymmetric structure and you accept a signed\n solution. Five parameters.\n5. **Neither is enough** — the residuals sit in discrete off-centre lumps, and no basis with a\n single shared centre will absorb them. That is\n [`ag_pixelization`](./ag_pixelization.md).\n\nAn MGE and a shapelet basis can be compared by Bayesian evidence only with care, because they\nsolve different linear problems (positive-only versus signed). Compare them on the residual map\nand the chi-squared first, and ask if you want the evidence caveats spelled out.\n\n## Combine — where this hands off\n\n- **Pick a search** → [`ag_configure_search`](./ag_configure_search.md). Basis models want\n *fewer* live points than a parametric fit, not more — the workspace drops `n_live` to 75 for\n both linear profiles and the MGE — because the parameter space is simpler.\n- **Run it and read the output folder** → [`ag_run_search`](./ag_run_search.md).\n- **Plot the fit** → [`ag_plot_fit`](./ag_plot_fit.md), remembering that a linear profile has to\n go through `model_obj_linear_light_profiles_to_light_profiles` before it can be plotted.\n- **The basis fits worse than you expected, or the search stalls** →\n [`ag_debug_fit_failure`](./ag_debug_fit_failure.md). The two failure modes specific to this\n skill are a `sigma` ladder that stops short of the mask radius, and a free `sigma` or `beta`\n reintroducing a size degeneracy.\n- **Structured residuals a basis cannot reach** → [`ag_pixelization`](./ag_pixelization.md).\n- **A neighbour overlapping the galaxy, a residual sky, or a nuclear point source** →\n [`ag_light_model_extras`](./ag_light_model_extras.md).\n- **A non-parametric shape measurement instead of a model** →\n [`ag_ellipse_fitting`](./ag_ellipse_fitting.md), which measures the isophotal twist directly\n rather than inferring it from a two-basis MGE.\n- **The same galaxy in several bands** → the multi-dataset skill (`ag_multi_dataset`). A basis\n across bands is where the factor graph earns its keep, since the shape can be shared while\n the amplitudes are solved per band.\n- **Chaining a parametric fit into a basis fit** → the search-chaining skill\n (`ag_chain_searches`); a Sersic fit's centre and ellipticity make excellent starting priors\n for an MGE.\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording which tier you\nused, `total_gaussians` / `gaussian_per_basis` or the shapelet order, the solver you chose, and\nwhat the residuals looked like at each step — the last is the evidence for the model choice and\nthe first thing a referee will ask for.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Linear profiles](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_5_linear_profiles.ipynb):\n builds up from a standard profile to a linear one to a basis, showing what the inversion\n actually solves at each step.\n- **General reference** — [RTD: Light profiles API](https://pyautogalaxy.readthedocs.io/en/latest/api/light.html):\n every standard, linear, operated and basis variant with its module and parameters.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/features/multi_gaussian_expansion/modeling.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/features/multi_gaussian_expansion/modeling.py):\n the MGE end to end, including the compact nuclear basis and the run-time and VRAM discussion.\n\n## Agent procedural checklist\n\n1. Ask whether the user needs interpretable Sersic parameters or the best achievable fit — that\n choice, not the API, picks the branch.\n2. Look at the residual map of a single linear Sersic first; structured-but-smooth residuals mean\n a basis, discrete lumps mean `ag_pixelization`.\n3. Default to `ag.lp_linear` for every parametric component; never use `ag.lp` in a model\n without a reason.\n4. For an MGE, pass the real `mask_radius`, and reach for `gaussian_per_basis=2` when the\n isophotes twist.\n5. For shapelets, pass `ag.Settings(use_positive_only_solver=False)` on the *analysis*, link\n `ell_comps` across the basis, and tell the user the reconstruction may contain negative flux.\n6. Always check `model.total_free_parameters` against what you intended — a basis's `model.info`\n is long and mostly fixed, and one unlinked parameter multiplies by the component count.\n7. Evaluate one likelihood before committing to a search; run `print_vram_use` before a GPU run\n with a large basis.\n8. Read intensities out via `max_log_likelihood_galaxies`,\n `fit.linear_light_profile_intensity_dict`, or\n `model_obj_linear_light_profiles_to_light_profiles` — never expect them in `model.results`.\n9. Save the script to `scripts/`, quote every plot's absolute path and offer to open it, then\n offer the `wiki/project/` entry.\n" - } - }, - "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file diff --git a/notebooks/chapter_2_modeling/tutorial_6_masking.ipynb b/notebooks/chapter_2_modeling/tutorial_6_masking.ipynb deleted file mode 100644 index 0264640..0000000 --- a/notebooks/chapter_2_modeling/tutorial_6_masking.ipynb +++ /dev/null @@ -1,298 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 6: Masking\n", - "===================\n", - "\n", - "We have learnt everything we need to know about non-linear searches to model a galaxy and infer a good\n", - "model solution. Now, lets consider masking in more detail, something we have not given much consideration previously.\n", - "We'll also learn a neat trick to improve the speed and accuracy of a non-linear search.\n", - "\n", - "__Contents__\n", - "\n", - "- **Initial Setup:** Load the dataset and apply a mask.\n", - "- **Mask:** Apply a custom mask to focus the fit on specific regions.\n", - "- **Model + Search + Analysis:** Fit the model using the custom mask.\n", - "- **Discussion:** How the mask affects the fit quality and run time.\n", - "- **Wrap Up:** Summary of masking strategies for galaxy modeling." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Google Colab Setup__\n", - "\n", - "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "jupyter": { - "source_hidden": true - } - }, - "outputs": [], - "source": [ - "# @title Set up Google Colab { display-mode: \"form\" }\n", - "try:\n", - " import google.colab\n", - "except ImportError:\n", - " from autogalaxy import setup_colab as _setup_colab\n", - "else:\n", - " import importlib\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.check_call(\n", - " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", - " )\n", - " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", - "\n", - "_setup_colab.setup(\"howtogalaxy\")" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autogalaxy import setup_notebook; setup_notebook()\n", - "\n", - "from pathlib import Path\n", - "import autogalaxy as ag\n", - "import autogalaxy.plot as aplt\n", - "import autofit as af" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Initial Setup__\n", - "\n", - "we'll use the same galaxy data as tutorials 1 & 2, where:\n", - "\n", - " - The galaxy's `LightProfile` is a `Sersic`." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "dataset_name = \"simple__sersic\"\n", - "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Dataset Auto-Simulation__\n", - "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "if ag.util.dataset.should_simulate(str(dataset_path)):\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulators/sersic.py\"],\n", - " check=True,\n", - " )\n", - "\n", - "\n", - "dataset = ag.Imaging.from_fits(\n", - " data_path=dataset_path / \"data.fits\",\n", - " noise_map_path=dataset_path / \"noise_map.fits\",\n", - " psf_path=dataset_path / \"psf.fits\",\n", - " pixel_scales=0.1,\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Mask__\n", - "\n", - "In tutorials 1 and 2 we used a 3.0\" circular mask. \n", - "\n", - "However, there is very faint flux emitted at the outskirts of the galaxy, which the model will benefit from fitting\n", - "by using a larger mask." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "mask = ag.Mask2D.circular(\n", - " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=6.0\n", - ")\n", - "\n", - "dataset = dataset.apply_mask(mask=mask)\n", - "\n", - "aplt.subplot_imaging_dataset(dataset=dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Over Sampling__\n", - "\n", - "Apply adaptive over sampling to ensure the calculation is accurate, you can read up on over-sampling in more detail via \n", - "the `autogalaxy_workspace/*/guides/advanced/over_sampling.ipynb` notebook." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n", - " grid=dataset.grid,\n", - " sub_size_list=[8, 4, 2],\n", - " radial_list=[0.3, 0.6],\n", - " centre_list=[(0.0, 0.0)],\n", - ")\n", - "\n", - "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Model + Search + Analysis__\n", - "\n", - "Lets fit the data using this mask, by creating the search as per usual. Note that the `imaging` data with this mask\n", - "applied is passed into the `AnalysisImaging` object, ensuring that this is the mask the model-fit uses. " - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp.Sersic)\n", - "model = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n", - "\n", - "search = af.Nautilus(\n", - " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", - " name=\"tutorial_6_with_custom_mask\",\n", - " unique_tag=dataset_name,\n", - " n_live=80,\n", - " n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2.\n", - ")\n", - "\n", - "analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", - "\n", - "search.fit(model=model, analysis=analysis)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Discussion__\n", - "\n", - "So, we can choose the mask we use in a model-fit. We know that we want the mask to remove as little of the galaxy's light,\n", - "but is this the 'right' mask? What is the 'right' mask? Maybe we want a bigger mask? a smaller mask?\n", - "\n", - "When it comes to choosing a mask, we are essentially balancing two things: computational run-time and accuracy. When we\n", - "use a bigger mask the model-fit will take longer to perform. Why? Because a bigger mask includes more image-pixels \n", - "in the analysis, and for every additional image-pixel we have to compute its light, blur it with the PSF, compare\n", - "it to the data, etc.\n", - " \n", - "If run-time was not a consideration we would always choose a bigger mask, for two reasons:\n", - "\n", - " 1) The galaxy may have very faint emission that when you choose the mask you simply do not notice. Overly aggressive \n", - " masking runs the risk of us inadvertently masking out some of the galaxy's light, which would otherwise better\n", - " constrain the model!\n", - " \n", - " 2) When the data is fitted with a model image, the fit is performed only within the masked region. For certain galaxies\n", - " it is possible that it may produce extraneous emission outside of the masked region that is not actually observed in \n", - " the data itself. If this region had not been masked-out, the model would create residuals in these locations and \n", - " reduce the value of likelihood appropriately, whereas if it is masked out this reduction in likelihood is \n", - " not fed through to the analysis. \n", - "\n", - "As you use **PyAutoGalaxy** more you will get a feel for how fast a model-fit will run given the quality of data,\n", - "model complexity, non-linear search settings, etc. As you develop this intuition, I recommend that you always aim to \n", - "use as large of a mask as possible (whilst still achieving reasonable run-times). Aggressive masking will make \n", - "**PyAutoGalaxy** run very fast, but could lead you to infer an incorrect model! \n", - "\n", - "At the end of this chapter, where we introduce 'non-linear search chaining', we will see how chaining makes it\n", - "possible to use tighter masks in earlier searches to achieve faster run times.\n", - "\n", - "If your data includes the light of additional galaxies nearby you may have no choice but to use a smaller\n", - "circular mask, because it is important these objects do not interfere with the fit.\n", - "\n", - "In fact, you can draw custom masks that remove their light entirely. You may now wish to checkout\n", - "the `autogalaxy_workspace/*/imaging/data_preparation` package. This includes tools for creating custom masks and\n", - "marking the positions on a galaxy (via a GUI) so you can use them in a model-fit.\n", - "\n", - "__Wrap Up__\n", - "\n", - "There is one thing you should bear in mind in terms of masking:\n", - "\n", - " 1) Customizing the mask for the analysis of one galaxy gets the analysis running fast and can provide accurate \n", - " non-linear sampling. However, for a large sample of galaxies, this high level of customization may take a lot of time. " - ] - } - ], - "metadata": { - "anaconda-cloud": {}, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - }, - "colab": { - "aiContexts": { - "24c2f562-da24-50bb-8eb9-5a887505fe54": { - "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", - "name": "PyAutoGalaxy assistant", - "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_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\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_2_modeling/tutorial_6_masking.ipynb in HowToGalaxy).\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 PyAutoGalaxy 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 PyAutoGalaxy docs (https://pyautogalaxy.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) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. 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 galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_prepare_imaging_data\n\n---\nname: ag_prepare_imaging_data\ndescription: Load a user's own CCD imaging of a galaxy from FITS into an `ag.Imaging` dataset and get it ready to fit — pixel scale, flux units, the RMS noise-map, the PSF, the mask extent, contaminating extra galaxies and foreground stars, over-sampling, and the optional `info.json` / centre sidecars. **This skill owns the real-data inspection gate**: the plot-and-settle procedure that must run before any model is composed or fitted on real observational data. Use whenever the user brings their own data (HST, JWST, Euclid, ground-based), whenever a dataset needs checking against PyAutoGalaxy's standards, or whenever a mask or contaminant decision is open. Not for simulating data (`ag_simulate_dataset`), not for composing the model itself (`ag_build_imaging_model`), and not for visibility-plane data.\n---\n\n# Preparing your own imaging data\n\nEverything downstream inherits the decisions made here. A noise-map that is a variance\nrather than an RMS makes every likelihood wrong by a constant power; a mask that truncates\nthe outer isophotes biases the effective radius and Sersic index directly; an unmodelled\nneighbour inside the mask pulls the fit toward a galaxy that isn't there. None of those\nthree announce themselves — the search converges, the residuals look plausible, and the\nnumber you publish is wrong. That is why this step is a gate rather than a formality.\n\nScientifically, the job is to hand the likelihood three things it can trust: an **image**\nin electrons per second, a **per-pixel RMS noise-map** in the same units, and a **PSF** to\nforward-convolve the model with. Statistically, the job is to define the *support* of the\nlikelihood — which pixels are in the sum — and to make sure every pixel inside it is\ndescribed by the model you are about to fit. The standards themselves come from\n`autogalaxy_workspace:scripts/imaging/data_preparation/start_here.py`; the API catalogue\nis [`../wiki/core/api/datasets.md`](../wiki/core/api/datasets.md).\n\n## The real-data gate — non-negotiable\n\n**Before composing or running any model-fit on real observational data**, plot it, show the\nuser the `dataset.png` path, and settle two things from that same look:\n\n**(a) Extra galaxies, foreground stars and artefacts.** These are the single largest source\nof fit bias. Decide, explicitly, which of the three strategies below applies to each one.\n\n**(b) The mask extent** — the radius and shape that captures the galaxy's emission out to\nwhere it meets the sky, without dragging in noise or contaminants. **Never leave the mask\nradius as a silent default on real data.** A mask that cuts inside the outer isophotes\nbiases `effective_radius` and `sersic_index`, so this is a science-critical choice, not a\ntidy-up.\n\n**If you cannot execute code in the current session** — a planning-only or read-only session,\na harness whose tools are restricted — **the gate is not waived**: ask the user to plot and inspect the data, and to confirm both\n(a) contaminants and (b) the mask extent, before you compose the fit. These are the\nquestions every real-data run must ask, on every harness.\n\n**Simulated data is exempt** — you know the truth, including where every component is, so\nthere is nothing to discover by looking. Everything else in this skill still applies to\nsimulated data as documentation of what a real run would need.\n\nThe gate is satisfied by looking, not by asserting. The first branch below is how you look.\n\n## Ask\n\n- *\"What instrument and filter, and what is the pixel scale?\"* — you cannot proceed without\n it, and it is the one number nothing in the data can tell you.\n- *\"Is the noise-map an RMS standard deviation per pixel, or a variance / weight map / HST\n WHT map?\"* — if they are not certain, treat it as unknown and convert; the likelihood\n assumes RMS.\n- *\"Are there neighbouring galaxies, foreground stars or reduction artefacts near the\n target?\"* — the (a) half of the gate.\n- *\"How far out do you care about the light — just the bright body, or the faint outer\n envelope?\"* — this is the (b) half of the gate phrased as a science question, which is\n how it should be decided.\n\n## Branch — look at it first\n\nLoad the three ingredients and plot them. Nothing else happens until this figure has been\nseen.\n\n```python\n\"\"\"\nData Inspection: ()\n=============================================\n\nLoad a galaxy's CCD imaging from FITS and inspect it before any model is composed. This\nscript exists to satisfy the real-data inspection gate: the image, noise-map, PSF and\nsignal-to-noise map are plotted so that two science-critical decisions can be made from\nevidence rather than defaults — which contaminating objects are present, and how far out\nthe mask should extend.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the image, noise-map and PSF from FITS with the correct pixel scale.\n- **Standards Check:** Verify the PSF is odd-sized and normalised, and report the S/N.\n- **Plot:** Write the dataset subplot to disk for inspection.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPLOT_DIR = Path(\"scripts\") / \"scratch\" / \"my_galaxy\"\n\n\"\"\"\n__Dataset__\n\nThree ingredients are needed for galaxy modeling: the image in electrons per second, a\nper-pixel RMS noise-map in the same units, and the PSF describing the blurring imposed by\nthe telescope optics. The PSF is *forward-convolved* onto the model rather than divided out\nof the data, which is what lets a fit distinguish a genuinely compact bulge from a\nseeing-broadened one.\n\n`pixel_scales` converts pixels to arcseconds and must be correct for your instrument —\nHST/ACS ~0.05\", JWST/NIRCam ~0.03-0.06\", Euclid VIS 0.1\" and NISP 0.2\", ground-based\n0.2-0.3\". Nothing in the FITS data can correct a wrong value for you; every inferred size\nscales with it. Loading is handled by `ag.Imaging.from_fits`\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\"\"\"\nPIXEL_SCALES = 0.1\n\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=PIXEL_SCALES,\n)\n\n\"\"\"\n__Standards Check__\n\nTwo properties of the PSF are cheap to check and expensive to get wrong. An **even-sized**\nkernel shifts the convolved model by half a pixel, which propagates straight into the\ninferred centre; and a kernel that does not **sum to unity** does not conserve flux, which\ncorrupts any magnitude or luminosity derived from the fit. The signal-to-noise peak is a\nsanity check on the noise-map: a galaxy usually peaks somewhere around 10-300, and a value\norders of magnitude away from that is a sign the noise-map is in the wrong units or is a\nvariance rather than an RMS.\n\"\"\"\npsf_shape = dataset.psf.kernel.shape_native\n\nprint(f\"PSF shape: {psf_shape}, odd: {all(s % 2 == 1 for s in psf_shape)}\")\nprint(f\"PSF sum: {float(dataset.psf.kernel.sum()):.6f} (should be 1.0)\")\nprint(f\"peak signal-to-noise: {float(dataset.signal_to_noise_map.max()):.1f}\")\n\n\"\"\"\n__Plot__\n\nThe subplot shows the image, noise-map, PSF and signal-to-noise map together, which is\nexactly the set needed to answer the two gate questions: what contaminating objects are\npresent, and how far out the galaxy's emission extends before it meets the sky.\n\"\"\"\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=PLOT_DIR,\n output_filename=\"dataset\",\n output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThen **quote the absolute path of `dataset.png` back to the user and offer to open it**\n(`xdg-open` on Linux, `open` on macOS, `explorer.exe` or `wslview` from WSL) — one offer,\nnot repeated nagging. Ask the two gate questions against that specific figure, naming what\nyou can see in it. \"There's a compact object about 2\" north-east of the centre — is that a\nneighbour or part of the galaxy?\" is a useful question; \"are there any contaminants?\" in the\nabstract is not.\n\n## Branch — the three standards, and how to fix a violation\n\n`autogalaxy_workspace:scripts/imaging/data_preparation/start_here.py` is the checklist; the\nper-ingredient tools are in `examples/data.py`, `examples/noise_map.py` and\n`examples/psf.py` beside it.\n\n**The image.** Flux in **electrons per second**, galaxy near the centre, cut down to a\npostage stamp. The units matter because default priors on light-profile `intensity` assume\nthem, and because magnitudes are computed from them. Conversions both ways are in the\npreprocess module (`PyAutoArray:autoarray/dataset/preprocess.py`):\n\n```python\nexposure_time_map = ag.Array2D.full(\n fill_value=1000.0,\n shape_native=data.shape_native,\n pixel_scales=data.pixel_scales,\n)\n\ndata_counts = ag.preprocess.array_eps_to_counts(\n array_eps=data, exposure_time_map=exposure_time_map\n)\ndata_eps = ag.preprocess.array_counts_to_eps(\n array_counts=data_counts, exposure_time_map=exposure_time_map\n)\n```\n\nADUs need the gain as well — `ag.preprocess.array_eps_to_adus(array_eps=data, gain=4.0,\nexposure_time_map=exposure_time_map)` and `array_adus_to_eps` back. If your reduction\nproduced a real per-pixel exposure-time map, load it with `ag.Array2D.from_fits` instead of\nthe flat `full` above; a flat map is a good approximation for many HST observations and not\nfor all. Trim an oversized stamp with\n`ag.preprocess.array_with_new_shape(array=data, new_shape=(80, 80))`, which crops centred.\nBackground subtraction is better done by your reduction pipeline, but\n`background_sky_level_via_edges_from` and `background_noise_map_via_edges_from` exist for\nwhen it wasn't — and modelling the residual sky as a free parameter is often the better\nanswer anyway (see the sky-background note in\n[`ag_build_imaging_model`](./ag_build_imaging_model.md)).\n\n**The noise-map.** RMS standard deviation per pixel, in electrons per second, **including**\nthe Poisson contribution from the galaxy's own counts as well as background sky. This is the\none to be most careful about: reduction pipelines frequently drop the Poisson term, and a\nnoise-map that is a variance, an inverse variance, or an HST WHT map will produce a fit that\nconverges confidently to the wrong answer. The preprocess module has a converter for each\ncommon input form — `noise_map_via_weight_map_from`,\n`noise_map_via_inverse_noise_map_from`,\n`noise_map_via_data_eps_and_exposure_time_map_from`,\n`noise_map_via_data_eps_exposure_time_map_and_background_noise_map_from`,\n`noise_map_via_data_eps_exposure_time_map_and_background_variances_from` and\n`poisson_noise_via_data_eps_from`. If you cannot determine which form you have, the\ninstrument handbook is the authority; guessing here is not recoverable later.\n\n**The PSF.** Odd dimensions, normalised to unity, centred, and roughly 11×11 to 21×21\npixels. Larger kernels (51×51) work but slow every likelihood evaluation, since convolution\nruns on every model image. Load with normalisation applied:\n\n```python\npsf = ag.Convolver.from_fits(\n file_path=DATASET_PATH / \"psf.fits\",\n hdu=0,\n pixel_scales=PIXEL_SCALES,\n normalize=True,\n)\n```\n\n`ag.Imaging.from_fits` normalises the PSF internally anyway, so this is belt-and-braces. An\neven-sized kernel is a genuine problem rather than a warning:\n`ag.preprocess.kernel_with_odd_dimensions_from` will interpolate one for you, but it *is*\nan interpolation and the right fix is to re-derive the PSF at odd size in your reduction.\nResize with `ag.preprocess.array_with_new_shape(array=psf.kernel, new_shape=(21, 21))`.\n\n## Branch — (a) contaminants: three strategies, one decision per object\n\nFor each neighbouring galaxy, foreground star or artefact you identified in the figure,\nchoose one:\n\n**1. Scale its noise (the default).** Keep the pixels in the fit but blow their noise-map\nvalues up so they contribute negligibly to the likelihood. Preferred over deleting pixels\nbecause it leaves the pixel grid intact — which matters a great deal later if you move to a\npixelised reconstruction, where removed pixels create discontinuities.\n\n```python\nmask_extra_galaxies = ag.Mask2D.from_fits(\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n pixel_scales=dataset.pixel_scales,\n invert=True, # `True` marks the pixels whose noise is scaled.\n)\n\ndataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies)\n\naplt.subplot_imaging_dataset(\n dataset=dataset, output_path=PLOT_DIR, output_filename=\"dataset_scaled\",\n output_format=\"png\",\n)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py`. Note `invert=True`: the\nFITS convention here marks the *scaled* region as `True`. Build the mask as a union of\ncircles when you know the positions, following\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/mask_extra_galaxies.py`:\n\n```python\nimport numpy as np\n\nextra_galaxies_mask = np.zeros(data.shape_native, dtype=bool)\n\nfor centre, radius in [((1.0, 3.5), 1.5), ((-2.0, -3.5), 2.4)]:\n circle = ag.Mask2D.circular(\n shape_native=data.shape_native,\n pixel_scales=data.pixel_scales,\n centre=centre,\n radius=radius,\n invert=True,\n )\n extra_galaxies_mask = np.logical_or(extra_galaxies_mask, circle.native)\n\nmask = ag.Mask2D(mask=extra_galaxies_mask, pixel_scales=data.pixel_scales)\n\naplt.fits_array(\n array=mask, file_path=DATASET_PATH / \"mask_extra_galaxies.fits\", overwrite=True\n)\n```\n\nFor irregular shapes there is a spray-paint GUI at\n`autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask_extra_galaxies.py`, and the\nsame `ag.Scribbler`-based tool appears inline at the foot of\n`autogalaxy_workspace:scripts/imaging/start_here.py`. Point the user at it rather than\nhand-deriving centres when the contaminant is a messy blend.\n\n**2. Shrink the mask so it falls outside.** The simplest option, and the right one when the\ncontaminant sits comfortably beyond the galaxy's emission. It costs you nothing except the\nsky annulus you gave up — but check it does not also cut into the outer isophotes, because\nthen you have traded a known bias for a worse one.\n\n**3. Model it as an extra galaxy.** Give it its own light profile with a fixed centre. This\nis the choice when its light genuinely overlaps the target's, so neither masking nor scaling\ncan separate them without also removing signal you need. That is a *model* decision, so it\nbelongs to [`ag_build_imaging_model`](./ag_build_imaging_model.md); what you produce here is\nthe list of centres it will consume:\n\n```python\nextra_galaxies_centres = ag.Grid2DIrregular(values=[(1.0, 3.5), (-2.0, -3.5)])\n\naplt.plot_array(\n array=data,\n title=\"Data\",\n positions=[np.array(extra_galaxies_centres)],\n output_path=PLOT_DIR,\n output_filename=\"data_with_extra_galaxies\",\n output_format=\"png\",\n)\n\nag.output_to_json(\n obj=extra_galaxies_centres,\n file_path=DATASET_PATH / \"extra_galaxies_centres.json\",\n)\n```\n\nAdapted from\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/extra_galaxies_centres.py`.\nAlways plot the centres over the image before saving them — an off-by-a-sign (y,x) ordering\nis obvious in a figure and invisible in a JSON file. There is a click-to-select GUI at\n`autogalaxy_workspace:scripts/imaging/data_preparation/gui/extra_galaxies_centres.py` which\nsnaps to the brightest pixel in a 5×5 box.\n\nThe physics of choosing between the three, and what noise scaling does to the likelihood,\nis\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch — (b) the mask extent\n\nThe mask defines which pixels enter the likelihood. Choose its radius from the figure, and\nsay out loud what you chose and why:\n\n```python\nMASK_RADIUS = 2.5\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\n\ndataset = dataset.apply_mask(mask=mask)\n\naplt.subplot_imaging_dataset(\n dataset=dataset, output_path=PLOT_DIR, output_filename=\"dataset_masked\",\n output_format=\"png\",\n)\n```\n\nTwo failure directions, and they are not symmetric. **Too small** truncates the outer\nisophotes and biases `effective_radius` and `sersic_index` — a real, systematic error in\nyour science result. **Too large** drags in sky-dominated pixels: it slows the fit and adds\nlittle information, but it does not bias the answer, and it keeps honest sky pixels that\nconstrain a background level. When in doubt, err large and re-plot; the cost is run time,\nnot correctness.\n\nCircular is the default and usually right for a single galaxy. Non-circular shapes exist\nwhen the geometry calls for it — `ag.Mask2D.circular_annular(inner_radius=..., outer_radius=...)`\nto exclude a saturated core, `ag.Mask2D.elliptical(major_axis_radius=..., axis_ratio=...,\nangle=...)` and `ag.Mask2D.elliptical_annular(...)` for a strongly inclined disk. All four\nare shown in\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/mask.py`, and\n`autogalaxy_workspace:scripts/guides/modeling/customize.py` covers applying a custom mask to\na fit. A mask drawn by hand in the GUI\n(`autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask.py`) is written to\n`mask.fits` and loaded back with `ag.Mask2D.from_fits`; for a genuinely irregular footprint,\n`autogalaxy_workspace:scripts/imaging/data_preparation/manual/mask_irregular.py` is the\nmanual route.\n\nWhy the radius is a science decision rather than a default, and what the slim/native\ndistinction means once a mask is applied, is\n[`../wiki/core/concepts/grids_and_masks.md`](../wiki/core/concepts/grids_and_masks.md).\n\n## Branch — over-sampling\n\nA Sersic profile's intensity varies steeply across a single central pixel, so evaluating it\nonce at the pixel centre under-counts the flux. Over-sampling evaluates the profile on a\nfiner sub-grid and averages, and it changes the inferred parameters — this is accuracy, not\ncosmetics. Do it adaptively: high in the centre where the gradient is steep, low in the\noutskirts where it is flat and the cost would be wasted.\n\n```python\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py`. That reads as 8×8\nsub-sampling inside 0.3\", 4×4 between 0.3\" and 0.6\", and 2×2 beyond — note the list ends at\n2, never 1, so even the outskirts keep a floor. `centre_list` takes **every** bright\ncentre, so if you are modelling an extra galaxy rather than masking it, add its centre here\ntoo; a companion evaluated at 2×2 while the target gets 8×8 is a quiet accuracy loss. A\nplain integer (`over_sample_size_lp=4`) applies uniform over-sampling when you want\nsimplicity over tuning. The `_lp` suffix names the grid used for **l**ight-**p**rofile\nevaluation, which is a different grid from a pixelisation's.\n\n## Branch — the optional sidecars\n\nNone of these are required to fit; all of them make the result easier to interpret later.\n\n**`info.json`** — auxiliary numbers that travel with the dataset: redshift, velocity\ndispersion, a stellar mass from the literature, a previous paper's measurement. Passed to\n`search.fit(model=model, analysis=analysis, info=info)`, it is stored with the fit and can\nbe read back by the aggregator, which is what makes a population-scale comparison against\nexternal measurements possible.\n\n```python\nimport json\n\ninfo = {\"redshift\": 0.5, \"velocity_dispersion\": 250.0, \"stellar_mass\": 1e11}\n\nwith open(DATASET_PATH / \"info.json\", \"w+\") as f:\n json.dump(info, f, indent=4)\n```\n\nAdapted from\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/info.py`.\n\n**`light_centre.json`** — the galaxy's light centre as an `ag.Grid2DIrregular`, saved with\n`ag.output_to_json`, for use as a fixed value in the model. Fixing the centre removes two\nfree parameters and rules out solutions where the model centre wanders somewhere\nunphysical; it is the standard rescue when a search will not converge. Grounded in\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/light_centre.py`,\nwith a click-to-select GUI at\n`autogalaxy_workspace:scripts/imaging/data_preparation/gui/light_centre.py`.\n\nThe on-disk layout these files belong to is documented in\n[`../wiki/core/operations/dataset.md`](../wiki/core/operations/dataset.md), grounded on the\nbundled dataset and `autogalaxy_workspace:scripts/imaging/data_preparation/start_here.py`\n(the workspace simulates its imaging datasets on first run rather than committing them).\n\n## Combine — where this hands off\n\n- **The gate is satisfied and the dataset is loaded, masked and over-sampled** →\n [`ag_build_imaging_model`](./ag_build_imaging_model.md). Tell it what you decided about\n contaminants and the mask; it will ask otherwise.\n- **You want to rehearse the whole loop before touching real data** →\n [`ag_simulate_dataset`](./ag_simulate_dataset.md), which builds a dataset in exactly this\n format with known truth.\n- **A contaminant needs modelling rather than masking** → the model skill's extra-galaxies\n branch, fed by the `extra_galaxies_centres.json` you wrote above.\n- **The data looks wrong in a way you can't place** → the environment skill\n ([`ag_setup_environment`](./ag_setup_environment.md)) if it is the *plot* misbehaving, or\n the fit-debugging skill (`ag_debug_fit_failure`) once a fit has actually run.\n\nOffer (default-yes) to record the session as a dated\n`wiki/project/YYYY-MM-DD-.md` entry — the mask radius you chose and *why*, and what\nyou did about each contaminant, are exactly the decisions you will want justified when you\nwrite the paper.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Data](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_2_data.ipynb):\n what a CCD image, a noise-map and a PSF actually are, and why the PSF is convolved onto\n the model rather than divided out of the data. Its companion,\n [chapter 2 tutorial 6](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_6_masking.ipynb),\n is the masking lecture.\n- **General reference** — [RTD: New user guide](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n routes by system scale and dataset type, and is the page to hand someone deciding how\n their data should be organised before they load it.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/data_preparation/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/data_preparation/start_here.py):\n the standards checklist with the per-ingredient example scripts and GUIs beneath it.\n\n## Agent procedural checklist\n\n1. Establish the pixel scale and the noise-map's definition before writing code.\n2. Load the three ingredients, plot the dataset subplot, **print and quote its absolute\n path**, and offer to open it once.\n3. Run the gate against that figure: settle (a) every contaminant and (b) the mask extent\n *with the user*. On a harness that cannot plot, ask the user to do both — never waive it.\n4. Check the three standards: eps units, RMS-with-Poisson noise-map, odd normalised PSF.\n Convert rather than assume.\n5. Apply, in order: noise scaling for contaminants → the mask → adaptive over-sampling\n (with every bright centre in `centre_list`).\n6. Write the sidecars the model will need (`extra_galaxies_centres.json`,\n `light_centre.json`, `info.json`) and plot any centres over the image before saving.\n7. Save the script to `scripts/`, hand off to `ag_build_imaging_model`, and offer the\n `wiki/project/` entry recording the mask and contaminant decisions.\n" - } - }, - "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file diff --git a/notebooks/chapter_2_modeling/tutorial_6_search_chaining.ipynb b/notebooks/chapter_2_modeling/tutorial_6_search_chaining.ipynb new file mode 100644 index 0000000..ebdbd72 --- /dev/null +++ b/notebooks/chapter_2_modeling/tutorial_6_search_chaining.ipynb @@ -0,0 +1,417 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Tutorial 6: Search Chaining\n", + "===========================\n", + "\n", + "A neighbouring galaxy can complicate the fit to our target. We need to describe its light, but repeatedly\n", + "searching all its parameters while refining the target can waste effort and introduce difficult degeneracies.\n", + "Search chaining lets us fit different parts of the scene in stages.\n", + "\n", + "First we fit a simple target profile and an MGE for the neighbour using a fast Prodigy optimisation. After checking\n", + "that fit, we fix the neighbour's fitted geometry and use Nautilus to fit a more flexible MGE for the target.\n", + "The second search can concentrate on the target without exploring the neighbour's geometry again.\n", + "\n", + "This is the main benefit of chaining here: separating well-constrained components can make a realistic model\n", + "more robust and manageable. It does not depend on automatically narrowing the priors of the second search.\n", + "\n", + "__Contents__\n", + "\n", + "- **Dataset:** Keep both galaxies in the fit.\n", + "- **Search 1:** Obtain a useful description of the neighbour.\n", + "- **Inspect Before Chaining:** Check that the first result is suitable to fix.\n", + "- **Search 2:** Fix the neighbour's geometry and refine the target.\n", + "- **Limits and Pipelines:** Understand the assumptions and extend the workflow." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Google Colab Setup__\n", + "\n", + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, + "outputs": [], + "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", + "try:\n", + " import google.colab\n", + "except ImportError:\n", + " from autogalaxy import setup_colab as _setup_colab\n", + "else:\n", + " import importlib\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.check_call(\n", + " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", + " )\n", + " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", + "\n", + "_setup_colab.setup(\"howtogalaxy\")" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from autogalaxy import setup_notebook; setup_notebook()\n", + "\n", + "from pathlib import Path\n", + "import numpy as np\n", + "import autofit as af\n", + "import autogalaxy as ag\n", + "import autogalaxy.plot as aplt" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Dataset and Mask__\n", + "\n", + "Load the imaging data and retain the region inside the circular mask. The simulator creates the data if needed.\n", + "The image, noise map and PSF together describe the observation; none specifies which galaxy model we must fit." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "dataset_name = \"extra_galaxy\"\n", + "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name\n", + "if ag.util.dataset.should_simulate(str(dataset_path)):\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.run([sys.executable, \"scripts/simulators/extra_galaxy.py\"], check=True)\n", + "\n", + "dataset = ag.Imaging.from_fits(\n", + " data_path=dataset_path / \"data.fits\",\n", + " noise_map_path=dataset_path / \"noise_map.fits\",\n", + " psf_path=dataset_path / \"psf.fits\",\n", + " pixel_scales=0.1,\n", + ")\n", + "mask = ag.Mask2D.circular(\n", + " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=6.0\n", + ")\n", + "dataset = dataset.apply_mask(mask=mask)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Over Sampling__\n", + "\n", + "The bright centre changes rapidly across a pixel. Adaptive over sampling evaluates it on a finer grid so that\n", + "numerical inaccuracies do not masquerade as poor models. The outskirts need fewer evaluations." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n", + " grid=dataset.grid,\n", + " sub_size_list=[8, 4, 2],\n", + " radial_list=[0.3, 0.6],\n", + " centre_list=[(0.0, 0.0)],\n", + ")\n", + "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n", + "aplt.subplot_imaging_dataset(dataset=dataset)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Keep Both Galaxies__\n", + "\n", + "Unlike tutorial 5's noise-scaling example, this fit uses the original data and includes both galaxies in the model.\n", + "The target is near (0.0, 0.0), and the visible neighbour near (1.0, 3.5) arcseconds. On your own data, identify\n", + "these approximate centres from the image or with the workspace's data-preparation tools.\n", + "\n", + "Include fine over sampling around both bright centres, since both contribute to the predicted image." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n", + " grid=dataset.grid,\n", + " sub_size_list=[8, 4, 2],\n", + " radial_list=[0.3, 0.6],\n", + " centre_list=[(0.0, 0.0), (1.0, 3.5)],\n", + ")\n", + "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Search 1 Model__\n", + "\n", + "The target starts as a linear Sersic. The neighbour uses 20 Gaussians with fixed widths and shared centre and\n", + "shape, following tutorial 4. The centre priors cover its visually identified location. All Gaussian intensities\n", + "are solved together with the target intensity each time the trial geometry is fitted." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "neighbor_gaussians = af.Collection(af.Model(ag.lp_linear.Gaussian) for _ in range(20))\n", + "sigmas = np.logspace(-2.0, np.log10(2.5), 20)\n", + "neighbor_centre_0 = af.UniformPrior(lower_limit=0.8, upper_limit=1.2)\n", + "neighbor_centre_1 = af.UniformPrior(lower_limit=3.3, upper_limit=3.7)\n", + "for i, gaussian in enumerate(neighbor_gaussians):\n", + " gaussian.centre.centre_0 = neighbor_centre_0\n", + " gaussian.centre.centre_1 = neighbor_centre_1\n", + " gaussian.ell_comps = neighbor_gaussians[0].ell_comps\n", + " gaussian.sigma = sigmas[i]\n", + "neighbor = af.Model(\n", + " ag.Galaxy,\n", + " redshift=0.5,\n", + " light=af.Model(ag.lp_basis.Basis, profile_list=neighbor_gaussians),\n", + ")\n", + "target = af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp_linear.Sersic)\n", + "model_1 = af.Collection(galaxies=af.Collection(target=target, neighbor=neighbor))\n", + "print(model_1.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Fast First Search__\n", + "\n", + "Prodigy improves trial models by following directions that increase their fit score, which includes the prior\n", + "weight as well as the likelihood. `MultiStartProdigy` tries several starting points so it is less dependent on\n", + "one initial guess. It uses JAX, the accelerated numerical engine already enabled in our Analysis objects.\n", + "\n", + "Here we want a useful fitted neighbour, rather than a detailed range of uncertainty estimates. We use 24 starts\n", + "and a ceiling of 300 steps per start as a first pass. These settings are not a guarantee of a good result.\n", + "`batch_size=4` limits how many starts are evaluated together to keep memory use manageable." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "analysis_1 = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", + "search_1 = af.MultiStartProdigy(\n", + " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", + " name=\"tutorial_6_search_1\",\n", + " unique_tag=dataset_name,\n", + " n_starts=24,\n", + " batch_size=4,\n", + " n_steps=300,\n", + " iterations_per_quick_update=50,\n", + ")\n", + "result_1 = search_1.fit(model=model_1, analysis=analysis_1)\n", + "print(result_1.info)\n", + "aplt.subplot_fit_imaging(fit=result_1.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Inspect Before Chaining__\n", + "\n", + "Look especially at the neighbour's centre and outskirts, and at the region where its light overlaps the target.\n", + "If systematic residuals remain, improve the first fit before fixing anything. More starts, a better neighbour\n", + "model or a more thorough search may be necessary. Chaining a poor result carries its mistakes into the next fit.\n", + "\n", + "__Fix the Neighbour__\n", + "\n", + "`result_1.instance` provides concrete fitted parameter values. Passing its neighbour into the next model fixes\n", + "that component's centre and shape, removing its four geometric parameters from the non-linear search.\n", + "\n", + "This instance still contains linear Gaussian profiles: their intensities are solved again alongside the target\n", + "at each likelihood evaluation. We fix the neighbour's geometry, not a completely frozen image. Using converted\n", + "ordinary profiles would instead fix the brightnesses too, which is a different modelling choice." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "neighbor_fixed = result_1.instance.galaxies.neighbor" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Search 2 Model__\n", + "\n", + "Replace the target Sersic with a group of 30 Gaussians. This flexible radial light model has four non-linear\n", + "parameters: two centre coordinates and two elliptical components. A simultaneous fit with the neighbour's MGE\n", + "geometry free would have eight. Fixing the already-fitted neighbour therefore halves this geometric search space.\n", + "\n", + "This example target is smooth. For a galaxy whose central and outer shapes differ, use the two-group construction\n", + "from tutorial 4; the same separation of the neighbour still helps. No result-based prior narrowing is needed." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "target_gaussians = af.Collection(af.Model(ag.lp_linear.Gaussian) for _ in range(30))\n", + "target_sigmas = np.logspace(-2.0, np.log10(6.0), 30)\n", + "target_centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", + "target_centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", + "for i, gaussian in enumerate(target_gaussians):\n", + " gaussian.centre.centre_0 = target_centre_0\n", + " gaussian.centre.centre_1 = target_centre_1\n", + " gaussian.ell_comps = target_gaussians[0].ell_comps\n", + " gaussian.sigma = target_sigmas[i]\n", + "target = af.Model(\n", + " ag.Galaxy,\n", + " redshift=0.5,\n", + " light=af.Model(ag.lp_basis.Basis, profile_list=target_gaussians),\n", + ")\n", + "model_2 = af.Collection(galaxies=af.Collection(target=target, neighbor=neighbor_fixed))\n", + "print(model_2.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__More Thorough Second Search__\n", + "\n", + "Use Nautilus to explore the target's geometric parameters and estimate their uncertainties. The dataset and\n", + "likelihood definition are unchanged; the model and search have different roles in this second stage." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "analysis_2 = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", + "search_2 = af.Nautilus(\n", + " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", + " name=\"tutorial_6_search_2\",\n", + " unique_tag=dataset_name,\n", + " n_live=200,\n", + " n_batch=50,\n", + ")\n", + "result_2 = search_2.fit(model=model_2, analysis=analysis_2)\n", + "print(result_2.info)\n", + "aplt.subplot_fit_imaging(fit=result_2.max_log_likelihood_fit)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Inspect both galaxies again. A refined target model can expose weaknesses in the neighbour that were less obvious\n", + "before. The first result is useful information, not a guarantee that this separation is valid.\n", + "\n", + "__Benefits and Limits__\n", + "\n", + "When a component can be fitted robustly, fixing its geometry removes unnecessary search directions and lets later\n", + "fits concentrate effort on the components of scientific interest. This can bring large improvements in reliability\n", + "and runtime, particularly in scenes with several galaxies. A fast first fit and a more thorough second fit also\n", + "avoid spending equal effort on every stage.\n", + "\n", + "The second result is conditional on the fixed neighbour geometry. Its uncertainty does not automatically include\n", + "uncertainty in those fixed values. If blending makes the components strongly dependent, repeat the second fit with\n", + "plausible neighbour geometries or perform a final joint fit with the relevant parameters free. Inspecting each\n", + "stage is essential; more stages do not automatically make a fit more trustworthy.\n", + "\n", + "__From Searches to Pipelines__\n", + "\n", + "A pipeline packages repeated preparation, fits and checks into a reusable sequence. Chapter 4 applies these ideas\n", + "to systems with more galaxies. The workspace's `scripts/guides/modeling/chaining.py` provides further API examples.\n", + "\n", + "The SLaM pipelines in PyAutoLens apply related component-by-component modelling to lensing. They are a useful\n", + "example of how far chaining can be developed, but are not required for learning galaxy morphology here.\n", + "\n", + "__Wrap Up__\n", + "\n", + "The chapter's tools work together: inspect the data, choose an adequate model, define its comparison through an\n", + "Analysis object, and organise searches so the difficult parts are explored reliably. Search chaining helps strike\n", + "the balance between flexibility and tractability without requiring every component to be fitted afresh at every stage." + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.1" + }, + "colab": { + "aiContexts": { + "24c2f562-da24-50bb-8eb9-5a887505fe54": { + "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", + "name": "PyAutoGalaxy assistant", + "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_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\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_2_modeling/tutorial_6_search_chaining.ipynb in HowToGalaxy).\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 PyAutoGalaxy 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 PyAutoGalaxy docs (https://pyautogalaxy.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) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. 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 galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_prepare_imaging_data\n\n---\nname: ag_prepare_imaging_data\ndescription: Load a user's own CCD imaging of a galaxy from FITS into an `ag.Imaging` dataset and get it ready to fit — pixel scale, flux units, the RMS noise-map, the PSF, the mask extent, contaminating extra galaxies and foreground stars, over-sampling, and the optional `info.json` / centre sidecars. **This skill owns the real-data inspection gate**: the plot-and-settle procedure that must run before any model is composed or fitted on real observational data. Use whenever the user brings their own data (HST, JWST, Euclid, ground-based), whenever a dataset needs checking against PyAutoGalaxy's standards, or whenever a mask or contaminant decision is open. Not for simulating data (`ag_simulate_dataset`), not for composing the model itself (`ag_build_imaging_model`), and not for visibility-plane data.\n---\n\n# Preparing your own imaging data\n\nEverything downstream inherits the decisions made here. A noise-map that is a variance\nrather than an RMS makes every likelihood wrong by a constant power; a mask that truncates\nthe outer isophotes biases the effective radius and Sersic index directly; an unmodelled\nneighbour inside the mask pulls the fit toward a galaxy that isn't there. None of those\nthree announce themselves — the search converges, the residuals look plausible, and the\nnumber you publish is wrong. That is why this step is a gate rather than a formality.\n\nScientifically, the job is to hand the likelihood three things it can trust: an **image**\nin electrons per second, a **per-pixel RMS noise-map** in the same units, and a **PSF** to\nforward-convolve the model with. Statistically, the job is to define the *support* of the\nlikelihood — which pixels are in the sum — and to make sure every pixel inside it is\ndescribed by the model you are about to fit. The standards themselves come from\n`autogalaxy_workspace:scripts/imaging/data_preparation/start_here.py`; the API catalogue\nis [`../wiki/core/api/datasets.md`](../wiki/core/api/datasets.md).\n\n## The real-data gate — non-negotiable\n\n**Before composing or running any model-fit on real observational data**, plot it, show the\nuser the `dataset.png` path, and settle two things from that same look:\n\n**(a) Extra galaxies, foreground stars and artefacts.** These are the single largest source\nof fit bias. Decide, explicitly, which of the three strategies below applies to each one.\n\n**(b) The mask extent** — the radius and shape that captures the galaxy's emission out to\nwhere it meets the sky, without dragging in noise or contaminants. **Never leave the mask\nradius as a silent default on real data.** A mask that cuts inside the outer isophotes\nbiases `effective_radius` and `sersic_index`, so this is a science-critical choice, not a\ntidy-up.\n\n**If you cannot execute code in the current session** — a planning-only or read-only session,\na harness whose tools are restricted — **the gate is not waived**: ask the user to plot and inspect the data, and to confirm both\n(a) contaminants and (b) the mask extent, before you compose the fit. These are the\nquestions every real-data run must ask, on every harness.\n\n**Simulated data is exempt** — you know the truth, including where every component is, so\nthere is nothing to discover by looking. Everything else in this skill still applies to\nsimulated data as documentation of what a real run would need.\n\nThe gate is satisfied by looking, not by asserting. The first branch below is how you look.\n\n## Ask\n\n- *\"What instrument and filter, and what is the pixel scale?\"* — you cannot proceed without\n it, and it is the one number nothing in the data can tell you.\n- *\"Is the noise-map an RMS standard deviation per pixel, or a variance / weight map / HST\n WHT map?\"* — if they are not certain, treat it as unknown and convert; the likelihood\n assumes RMS.\n- *\"Are there neighbouring galaxies, foreground stars or reduction artefacts near the\n target?\"* — the (a) half of the gate.\n- *\"How far out do you care about the light — just the bright body, or the faint outer\n envelope?\"* — this is the (b) half of the gate phrased as a science question, which is\n how it should be decided.\n\n## Branch — look at it first\n\nLoad the three ingredients and plot them. Nothing else happens until this figure has been\nseen.\n\n```python\n\"\"\"\nData Inspection: ()\n=============================================\n\nLoad a galaxy's CCD imaging from FITS and inspect it before any model is composed. This\nscript exists to satisfy the real-data inspection gate: the image, noise-map, PSF and\nsignal-to-noise map are plotted so that two science-critical decisions can be made from\nevidence rather than defaults — which contaminating objects are present, and how far out\nthe mask should extend.\n\n__Contents__\n\n- **Imports:** Import the required libraries.\n- **Dataset:** Load the image, noise-map and PSF from FITS with the correct pixel scale.\n- **Standards Check:** Verify the PSF is odd-sized and normalised, and report the S/N.\n- **Plot:** Write the dataset subplot to disk for inspection.\n\"\"\"\n\n\"\"\"\n__Imports__\n\"\"\"\nfrom pathlib import Path\n\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"my_galaxy\"\nPLOT_DIR = Path(\"scripts\") / \"scratch\" / \"my_galaxy\"\n\n\"\"\"\n__Dataset__\n\nThree ingredients are needed for galaxy modeling: the image in electrons per second, a\nper-pixel RMS noise-map in the same units, and the PSF describing the blurring imposed by\nthe telescope optics. The PSF is *forward-convolved* onto the model rather than divided out\nof the data, which is what lets a fit distinguish a genuinely compact bulge from a\nseeing-broadened one.\n\n`pixel_scales` converts pixels to arcseconds and must be correct for your instrument —\nHST/ACS ~0.05\", JWST/NIRCam ~0.03-0.06\", Euclid VIS 0.1\" and NISP 0.2\", ground-based\n0.2-0.3\". Nothing in the FITS data can correct a wrong value for you; every inferred size\nscales with it. Loading is handled by `ag.Imaging.from_fits`\n(`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\"\"\"\nPIXEL_SCALES = 0.1\n\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=PIXEL_SCALES,\n)\n\n\"\"\"\n__Standards Check__\n\nTwo properties of the PSF are cheap to check and expensive to get wrong. An **even-sized**\nkernel shifts the convolved model by half a pixel, which propagates straight into the\ninferred centre; and a kernel that does not **sum to unity** does not conserve flux, which\ncorrupts any magnitude or luminosity derived from the fit. The signal-to-noise peak is a\nsanity check on the noise-map: a galaxy usually peaks somewhere around 10-300, and a value\norders of magnitude away from that is a sign the noise-map is in the wrong units or is a\nvariance rather than an RMS.\n\"\"\"\npsf_shape = dataset.psf.kernel.shape_native\n\nprint(f\"PSF shape: {psf_shape}, odd: {all(s % 2 == 1 for s in psf_shape)}\")\nprint(f\"PSF sum: {float(dataset.psf.kernel.sum()):.6f} (should be 1.0)\")\nprint(f\"peak signal-to-noise: {float(dataset.signal_to_noise_map.max()):.1f}\")\n\n\"\"\"\n__Plot__\n\nThe subplot shows the image, noise-map, PSF and signal-to-noise map together, which is\nexactly the set needed to answer the two gate questions: what contaminating objects are\npresent, and how far out the galaxy's emission extends before it meets the sky.\n\"\"\"\naplt.subplot_imaging_dataset(\n dataset=dataset,\n output_path=PLOT_DIR,\n output_filename=\"dataset\",\n output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nThen **quote the absolute path of `dataset.png` back to the user and offer to open it**\n(`xdg-open` on Linux, `open` on macOS, `explorer.exe` or `wslview` from WSL) — one offer,\nnot repeated nagging. Ask the two gate questions against that specific figure, naming what\nyou can see in it. \"There's a compact object about 2\" north-east of the centre — is that a\nneighbour or part of the galaxy?\" is a useful question; \"are there any contaminants?\" in the\nabstract is not.\n\n## Branch — the three standards, and how to fix a violation\n\n`autogalaxy_workspace:scripts/imaging/data_preparation/start_here.py` is the checklist; the\nper-ingredient tools are in `examples/data.py`, `examples/noise_map.py` and\n`examples/psf.py` beside it.\n\n**The image.** Flux in **electrons per second**, galaxy near the centre, cut down to a\npostage stamp. The units matter because default priors on light-profile `intensity` assume\nthem, and because magnitudes are computed from them. Conversions both ways are in the\npreprocess module (`PyAutoArray:autoarray/dataset/preprocess.py`):\n\n```python\nexposure_time_map = ag.Array2D.full(\n fill_value=1000.0,\n shape_native=data.shape_native,\n pixel_scales=data.pixel_scales,\n)\n\ndata_counts = ag.preprocess.array_eps_to_counts(\n array_eps=data, exposure_time_map=exposure_time_map\n)\ndata_eps = ag.preprocess.array_counts_to_eps(\n array_counts=data_counts, exposure_time_map=exposure_time_map\n)\n```\n\nADUs need the gain as well — `ag.preprocess.array_eps_to_adus(array_eps=data, gain=4.0,\nexposure_time_map=exposure_time_map)` and `array_adus_to_eps` back. If your reduction\nproduced a real per-pixel exposure-time map, load it with `ag.Array2D.from_fits` instead of\nthe flat `full` above; a flat map is a good approximation for many HST observations and not\nfor all. Trim an oversized stamp with\n`ag.preprocess.array_with_new_shape(array=data, new_shape=(80, 80))`, which crops centred.\nBackground subtraction is better done by your reduction pipeline, but\n`background_sky_level_via_edges_from` and `background_noise_map_via_edges_from` exist for\nwhen it wasn't — and modelling the residual sky as a free parameter is often the better\nanswer anyway (see the sky-background note in\n[`ag_build_imaging_model`](./ag_build_imaging_model.md)).\n\n**The noise-map.** RMS standard deviation per pixel, in electrons per second, **including**\nthe Poisson contribution from the galaxy's own counts as well as background sky. This is the\none to be most careful about: reduction pipelines frequently drop the Poisson term, and a\nnoise-map that is a variance, an inverse variance, or an HST WHT map will produce a fit that\nconverges confidently to the wrong answer. The preprocess module has a converter for each\ncommon input form — `noise_map_via_weight_map_from`,\n`noise_map_via_inverse_noise_map_from`,\n`noise_map_via_data_eps_and_exposure_time_map_from`,\n`noise_map_via_data_eps_exposure_time_map_and_background_noise_map_from`,\n`noise_map_via_data_eps_exposure_time_map_and_background_variances_from` and\n`poisson_noise_via_data_eps_from`. If you cannot determine which form you have, the\ninstrument handbook is the authority; guessing here is not recoverable later.\n\n**The PSF.** Odd dimensions, normalised to unity, centred, and roughly 11×11 to 21×21\npixels. Larger kernels (51×51) work but slow every likelihood evaluation, since convolution\nruns on every model image. Load with normalisation applied:\n\n```python\npsf = ag.Convolver.from_fits(\n file_path=DATASET_PATH / \"psf.fits\",\n hdu=0,\n pixel_scales=PIXEL_SCALES,\n normalize=True,\n)\n```\n\n`ag.Imaging.from_fits` normalises the PSF internally anyway, so this is belt-and-braces. An\neven-sized kernel is a genuine problem rather than a warning:\n`ag.preprocess.kernel_with_odd_dimensions_from` will interpolate one for you, but it *is*\nan interpolation and the right fix is to re-derive the PSF at odd size in your reduction.\nResize with `ag.preprocess.array_with_new_shape(array=psf.kernel, new_shape=(21, 21))`.\n\n## Branch — (a) contaminants: three strategies, one decision per object\n\nFor each neighbouring galaxy, foreground star or artefact you identified in the figure,\nchoose one:\n\n**1. Scale its noise (the default).** Keep the pixels in the fit but blow their noise-map\nvalues up so they contribute negligibly to the likelihood. Preferred over deleting pixels\nbecause it leaves the pixel grid intact — which matters a great deal later if you move to a\npixelised reconstruction, where removed pixels create discontinuities.\n\n```python\nmask_extra_galaxies = ag.Mask2D.from_fits(\n file_path=DATASET_PATH / \"mask_extra_galaxies.fits\",\n pixel_scales=dataset.pixel_scales,\n invert=True, # `True` marks the pixels whose noise is scaled.\n)\n\ndataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies)\n\naplt.subplot_imaging_dataset(\n dataset=dataset, output_path=PLOT_DIR, output_filename=\"dataset_scaled\",\n output_format=\"png\",\n)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py`. Note `invert=True`: the\nFITS convention here marks the *scaled* region as `True`. Build the mask as a union of\ncircles when you know the positions, following\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/mask_extra_galaxies.py`:\n\n```python\nimport numpy as np\n\nextra_galaxies_mask = np.zeros(data.shape_native, dtype=bool)\n\nfor centre, radius in [((1.0, 3.5), 1.5), ((-2.0, -3.5), 2.4)]:\n circle = ag.Mask2D.circular(\n shape_native=data.shape_native,\n pixel_scales=data.pixel_scales,\n centre=centre,\n radius=radius,\n invert=True,\n )\n extra_galaxies_mask = np.logical_or(extra_galaxies_mask, circle.native)\n\nmask = ag.Mask2D(mask=extra_galaxies_mask, pixel_scales=data.pixel_scales)\n\naplt.fits_array(\n array=mask, file_path=DATASET_PATH / \"mask_extra_galaxies.fits\", overwrite=True\n)\n```\n\nFor irregular shapes there is a spray-paint GUI at\n`autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask_extra_galaxies.py`, and the\nsame `ag.Scribbler`-based tool appears inline at the foot of\n`autogalaxy_workspace:scripts/imaging/start_here.py`. Point the user at it rather than\nhand-deriving centres when the contaminant is a messy blend.\n\n**2. Shrink the mask so it falls outside.** The simplest option, and the right one when the\ncontaminant sits comfortably beyond the galaxy's emission. It costs you nothing except the\nsky annulus you gave up — but check it does not also cut into the outer isophotes, because\nthen you have traded a known bias for a worse one.\n\n**3. Model it as an extra galaxy.** Give it its own light profile with a fixed centre. This\nis the choice when its light genuinely overlaps the target's, so neither masking nor scaling\ncan separate them without also removing signal you need. That is a *model* decision, so it\nbelongs to [`ag_build_imaging_model`](./ag_build_imaging_model.md); what you produce here is\nthe list of centres it will consume:\n\n```python\nextra_galaxies_centres = ag.Grid2DIrregular(values=[(1.0, 3.5), (-2.0, -3.5)])\n\naplt.plot_array(\n array=data,\n title=\"Data\",\n positions=[np.array(extra_galaxies_centres)],\n output_path=PLOT_DIR,\n output_filename=\"data_with_extra_galaxies\",\n output_format=\"png\",\n)\n\nag.output_to_json(\n obj=extra_galaxies_centres,\n file_path=DATASET_PATH / \"extra_galaxies_centres.json\",\n)\n```\n\nAdapted from\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/extra_galaxies_centres.py`.\nAlways plot the centres over the image before saving them — an off-by-a-sign (y,x) ordering\nis obvious in a figure and invisible in a JSON file. There is a click-to-select GUI at\n`autogalaxy_workspace:scripts/imaging/data_preparation/gui/extra_galaxies_centres.py` which\nsnaps to the brightest pixel in a 5×5 box.\n\nThe physics of choosing between the three, and what noise scaling does to the likelihood,\nis\n[`../wiki/core/concepts/extra_galaxies_and_noise_scaling.md`](../wiki/core/concepts/extra_galaxies_and_noise_scaling.md).\n\n## Branch — (b) the mask extent\n\nThe mask defines which pixels enter the likelihood. Choose its radius from the figure, and\nsay out loud what you chose and why:\n\n```python\nMASK_RADIUS = 2.5\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\n\ndataset = dataset.apply_mask(mask=mask)\n\naplt.subplot_imaging_dataset(\n dataset=dataset, output_path=PLOT_DIR, output_filename=\"dataset_masked\",\n output_format=\"png\",\n)\n```\n\nTwo failure directions, and they are not symmetric. **Too small** truncates the outer\nisophotes and biases `effective_radius` and `sersic_index` — a real, systematic error in\nyour science result. **Too large** drags in sky-dominated pixels: it slows the fit and adds\nlittle information, but it does not bias the answer, and it keeps honest sky pixels that\nconstrain a background level. When in doubt, err large and re-plot; the cost is run time,\nnot correctness.\n\nCircular is the default and usually right for a single galaxy. Non-circular shapes exist\nwhen the geometry calls for it — `ag.Mask2D.circular_annular(inner_radius=..., outer_radius=...)`\nto exclude a saturated core, `ag.Mask2D.elliptical(major_axis_radius=..., axis_ratio=...,\nangle=...)` and `ag.Mask2D.elliptical_annular(...)` for a strongly inclined disk. All four\nare shown in\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/mask.py`, and\n`autogalaxy_workspace:scripts/guides/modeling/customize.py` covers applying a custom mask to\na fit. A mask drawn by hand in the GUI\n(`autogalaxy_workspace:scripts/imaging/data_preparation/gui/mask.py`) is written to\n`mask.fits` and loaded back with `ag.Mask2D.from_fits`; for a genuinely irregular footprint,\n`autogalaxy_workspace:scripts/imaging/data_preparation/manual/mask_irregular.py` is the\nmanual route.\n\nWhy the radius is a science decision rather than a default, and what the slim/native\ndistinction means once a mask is applied, is\n[`../wiki/core/concepts/grids_and_masks.md`](../wiki/core/concepts/grids_and_masks.md).\n\n## Branch — over-sampling\n\nA Sersic profile's intensity varies steeply across a single central pixel, so evaluating it\nonce at the pixel centre under-counts the flux. Over-sampling evaluates the profile on a\nfiner sub-grid and averages, and it changes the inferred parameters — this is accuracy, not\ncosmetics. Do it adaptively: high in the centre where the gradient is steep, low in the\noutskirts where it is flat and the cost would be wasted.\n\n```python\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py`. That reads as 8×8\nsub-sampling inside 0.3\", 4×4 between 0.3\" and 0.6\", and 2×2 beyond — note the list ends at\n2, never 1, so even the outskirts keep a floor. `centre_list` takes **every** bright\ncentre, so if you are modelling an extra galaxy rather than masking it, add its centre here\ntoo; a companion evaluated at 2×2 while the target gets 8×8 is a quiet accuracy loss. A\nplain integer (`over_sample_size_lp=4`) applies uniform over-sampling when you want\nsimplicity over tuning. The `_lp` suffix names the grid used for **l**ight-**p**rofile\nevaluation, which is a different grid from a pixelisation's.\n\n## Branch — the optional sidecars\n\nNone of these are required to fit; all of them make the result easier to interpret later.\n\n**`info.json`** — auxiliary numbers that travel with the dataset: redshift, velocity\ndispersion, a stellar mass from the literature, a previous paper's measurement. Passed to\n`search.fit(model=model, analysis=analysis, info=info)`, it is stored with the fit and can\nbe read back by the aggregator, which is what makes a population-scale comparison against\nexternal measurements possible.\n\n```python\nimport json\n\ninfo = {\"redshift\": 0.5, \"velocity_dispersion\": 250.0, \"stellar_mass\": 1e11}\n\nwith open(DATASET_PATH / \"info.json\", \"w+\") as f:\n json.dump(info, f, indent=4)\n```\n\nAdapted from\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/info.py`.\n\n**`light_centre.json`** — the galaxy's light centre as an `ag.Grid2DIrregular`, saved with\n`ag.output_to_json`, for use as a fixed value in the model. Fixing the centre removes two\nfree parameters and rules out solutions where the model centre wanders somewhere\nunphysical; it is the standard rescue when a search will not converge. Grounded in\n`autogalaxy_workspace:scripts/imaging/data_preparation/examples/optional/light_centre.py`,\nwith a click-to-select GUI at\n`autogalaxy_workspace:scripts/imaging/data_preparation/gui/light_centre.py`.\n\nThe on-disk layout these files belong to is documented in\n[`../wiki/core/operations/dataset.md`](../wiki/core/operations/dataset.md), grounded on the\nbundled dataset and `autogalaxy_workspace:scripts/imaging/data_preparation/start_here.py`\n(the workspace simulates its imaging datasets on first run rather than committing them).\n\n## Combine — where this hands off\n\n- **The gate is satisfied and the dataset is loaded, masked and over-sampled** →\n [`ag_build_imaging_model`](./ag_build_imaging_model.md). Tell it what you decided about\n contaminants and the mask; it will ask otherwise.\n- **You want to rehearse the whole loop before touching real data** →\n [`ag_simulate_dataset`](./ag_simulate_dataset.md), which builds a dataset in exactly this\n format with known truth.\n- **A contaminant needs modelling rather than masking** → the model skill's extra-galaxies\n branch, fed by the `extra_galaxies_centres.json` you wrote above.\n- **The data looks wrong in a way you can't place** → the environment skill\n ([`ag_setup_environment`](./ag_setup_environment.md)) if it is the *plot* misbehaving, or\n the fit-debugging skill (`ag_debug_fit_failure`) once a fit has actually run.\n\nOffer (default-yes) to record the session as a dated\n`wiki/project/YYYY-MM-DD-.md` entry — the mask radius you chose and *why*, and what\nyou did about each contaminant, are exactly the decisions you will want justified when you\nwrite the paper.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Data](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_2_data.ipynb):\n what a CCD image, a noise-map and a PSF actually are, and why the PSF is convolved onto\n the model rather than divided out of the data. Its companion,\n [chapter 2 tutorial 6](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_6_masking.ipynb),\n is the masking lecture.\n- **General reference** — [RTD: New user guide](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n routes by system scale and dataset type, and is the page to hand someone deciding how\n their data should be organised before they load it.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/data_preparation/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/data_preparation/start_here.py):\n the standards checklist with the per-ingredient example scripts and GUIs beneath it.\n\n## Agent procedural checklist\n\n1. Establish the pixel scale and the noise-map's definition before writing code.\n2. Load the three ingredients, plot the dataset subplot, **print and quote its absolute\n path**, and offer to open it once.\n3. Run the gate against that figure: settle (a) every contaminant and (b) the mask extent\n *with the user*. On a harness that cannot plot, ask the user to do both — never waive it.\n4. Check the three standards: eps units, RMS-with-Poisson noise-map, odd normalised PSF.\n Convert rather than assume.\n5. Apply, in order: noise scaling for contaminants → the mask → adaptive over-sampling\n (with every bright centre in `centre_list`).\n6. Write the sidecars the model will need (`extra_galaxies_centres.json`,\n `light_centre.json`, `info.json`) and plot any centres over the image before saving.\n7. Save the script to `scripts/`, hand off to `ag_build_imaging_model`, and offer the\n `wiki/project/` entry recording the mask and contaminant decisions.\n" + } + }, + "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file diff --git a/notebooks/chapter_2_modeling/tutorial_7_results.ipynb b/notebooks/chapter_2_modeling/tutorial_7_results.ipynb deleted file mode 100644 index 06ffb83..0000000 --- a/notebooks/chapter_2_modeling/tutorial_7_results.ipynb +++ /dev/null @@ -1,296 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 7: Results\n", - "===================\n", - "\n", - "In the previous tutorials, each search returned a `Result` object, which we used to plot the maximum log likelihood\n", - "fit of each model-fit. In this tutorial, we'll take a look at the result object in a little more detail.\n", - "\n", - "__Contents__\n", - "\n", - "- **Initial Setup:** Perform a model-fit to obtain a Result object.\n", - "- **Galaxies & Fit:** Access the maximum likelihood galaxies and fit from the result.\n", - "- **Samples:** Inspect the non-linear search samples, including parameter estimates and errors.\n", - "- **Workspace:** Pointers to more detailed results examples in the workspace.\n", - "- **Database:** Overview of the database functionality for managing large numbers of results.\n", - "- **Wrap Up:** Summary of the Result object and its key attributes." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Google Colab Setup__\n", - "\n", - "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "jupyter": { - "source_hidden": true - } - }, - "outputs": [], - "source": [ - "# @title Set up Google Colab { display-mode: \"form\" }\n", - "try:\n", - " import google.colab\n", - "except ImportError:\n", - " from autogalaxy import setup_colab as _setup_colab\n", - "else:\n", - " import importlib\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.check_call(\n", - " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", - " )\n", - " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", - "\n", - "_setup_colab.setup(\"howtogalaxy\")" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autogalaxy import setup_notebook; setup_notebook()\n", - "\n", - "from pathlib import Path\n", - "import autogalaxy as ag\n", - "import autogalaxy.plot as aplt\n", - "import autofit as af" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Initial Setup__\n", - "\n", - "Lets repeat the simple Sersic model-fit performed earlier in this chapter to get a `Result` object." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "dataset_name = \"simple__sersic\"\n", - "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Dataset Auto-Simulation__\n", - "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "if ag.util.dataset.should_simulate(str(dataset_path)):\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulators/sersic.py\"],\n", - " check=True,\n", - " )\n", - "\n", - "\n", - "dataset = ag.Imaging.from_fits(\n", - " data_path=dataset_path / \"data.fits\",\n", - " noise_map_path=dataset_path / \"noise_map.fits\",\n", - " psf_path=dataset_path / \"psf.fits\",\n", - " pixel_scales=0.1,\n", - ")\n", - "\n", - "mask = ag.Mask2D.circular(\n", - " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=3.0\n", - ")\n", - "\n", - "dataset = dataset.apply_mask(mask=mask)\n", - "\n", - "over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n", - " grid=dataset.grid,\n", - " sub_size_list=[8, 4, 2],\n", - " radial_list=[0.3, 0.6],\n", - " centre_list=[(0.0, 0.0)],\n", - ")\n", - "\n", - "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n", - "\n", - "model = af.Collection(\n", - " galaxies=af.Collection(galaxy=af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp.Sersic))\n", - ")\n", - "\n", - "search = af.Nautilus(\n", - " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", - " name=\"tutorial_7_results\",\n", - " unique_tag=dataset_name,\n", - " n_live=80,\n", - " n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2.\n", - ")\n", - "\n", - "analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", - "\n", - "result = search.fit(model=model, analysis=analysis)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Galaxies & Fit__\n", - "\n", - "In the previous tutorials, we saw that this result contains the maximum log likelihood fit, which provide\n", - "a fast way to visualize the result.\n", - "\n", - "It also contains the maximum log likelihood galaxies." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_galaxies(\n", - " galaxies=result.max_log_likelihood_galaxies, grid=mask.derive_grid.all_false\n", - ")\n", - "\n", - "aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Samples__\n", - "\n", - "The result contains a lot more information about the model-fit. \n", - "\n", - "For example, the `Samples` object contains all of the non-linear search samples, including the parameters \n", - "of every successful model evaluation and their log likelihood values. These are used for computing information \n", - "about the model-fit, such as the most probable parameter estimates and the error inferred for every parameter." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result.samples)\n", - "print(\"Parameters of 1st Sample:\")\n", - "print(result.samples.parameter_lists[0][:])\n", - "print(\"Log Likelihood of 1st Sample:\")\n", - "print(result.samples.log_likelihood_list[0])" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Workspace__\n", - "\n", - "We are not going into any more detail on the result variable in this tutorial, or in the **HowToGalaxy** lectures.\n", - "\n", - "A comprehensive description of the results can be found at the following packages:\n", - "\n", - " `autogalaxy_workspace/*/results`\n", - " \n", - "The results API for CCD imaging data is the same as for other data types (e.g. interferometer). This\n", - "package can therefore be used to learn the API and then translate to other data types.\n", - "\n", - "__Database__\n", - "\n", - "Once a search has completed running, we have a set of results on our hard disk which we can manually inspect and \n", - "analyse. Alternatively, we can return the results from the search.fit() method and manipulate them in a Python script\n", - "or notebook. \n", - "\n", - "However, imagine you have a large dataset consisting of many images of galaxies. You analyse each image \n", - "individually using a search, producing a large library of results on your hard disk. There will be lots of paths and \n", - "directories to navigate, and at some point there will simply be too many results for it to be an efficient use of your \n", - "time to analyse the results by sifting through the outputs on your hard disk one-by-one.\n", - "\n", - "**PyAutoGalaxy**'s database tools solve this problem, by making it possible for us to write the results to a .sqlite \n", - "database file and load the results from hard-disk to a Python script or Jupyter notebook. This database supports\n", - "advanced queries, so specific results can be loaded and inspected.\n", - "\n", - "We won't go into any more detail on the database in this tutorial. If you think the database will be useful, checkout \n", - "the full set of database tutorials which can be found in the folder `autogalaxy_workspace/*/guides/results/database`. \n", - "\n", - "Here, you'll learn how to:\n", - "\n", - " - Use the database to query for results which fit a certain model or give a certain result. \n", - " \n", - " - Use the `Samples` to produce many different results from the fit, including error estimates on parameters and \n", - " plots of the probability density function of parameters in 1D and 2D.\n", - " \n", - " - Visualize results, for example the fit to a galaxy dataset.\n", - "\n", - "\n", - "__Wrap Up__\n", - "\n", - "Even if you are only modeling a small sample of galaxies, if you anticipate using **PyAutoGalaxy** for the long-term I \n", - "strongly recommend you begin using the database to inspect and analyse your result. \n", - "\n", - "This is because it makes it simple to perform all analysis in a Jupyter notebook, which is the most flexible and\n", - "versatile way to check results and make figures." - ] - } - ], - "metadata": { - "anaconda-cloud": {}, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - }, - "colab": { - "aiContexts": { - "24c2f562-da24-50bb-8eb9-5a887505fe54": { - "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", - "name": "PyAutoGalaxy assistant", - "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_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\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_2_modeling/tutorial_7_results.ipynb in HowToGalaxy).\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 PyAutoGalaxy 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 PyAutoGalaxy docs (https://pyautogalaxy.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) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. 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 galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_load_results\n\n---\nname: ag_load_results\ndescription: Get a completed fit's results back into Python and turn them into science — the in-session `Result` object (max-log-likelihood instance, galaxies and fit), direct loading of one fit's output folder via `from_json` and `SamplesNest.from_table`, the `Samples` API for medians and errors, and the aggregator for a whole sample of fits with its `ag.agg` generators, queries and CSV/FITS/PNG workflow exports. Also covers the traps: linear light-profile intensities are solved rather than sampled and are absent from the samples, derived-quantity errors need posterior draws, and test-mode results are not physically meaningful. Use when a search has finished (or is mid-run) and the user wants numbers, errors, derived quantities, a results table, or a comparison across fits. Not for running the fit (`ag_run_search`), not for rendering figures of a single fit (`ag_plot_fit`), and not for diagnosing a fit that converged somewhere wrong (`ag_debug_fit_failure`).\n---\n\n# Reading a finished fit\n\nThe search is over; the question is what it measured. This skill is the bridge from an\n`output/` folder to a sentence you could put in a paper: *\"the bulge has an effective radius\nof 1.62 ± 0.08 arcseconds and a Sersic index of 3.9 ± 0.3\"*.\n\nLoading is never the goal on its own — the user already wants something specific: a\nparameter with errors, a derived quantity the fit did not parameterise directly, the\nresiduals, a table across fifty galaxies. The job here is to establish which, load only that,\nand be honest about what the fit can and cannot support.\n\nTwo things about the statistics are worth stating before any API. First, the default view of a\nresult is the **maximum log likelihood** model — the single best-fitting parameter vector.\nThat is not the same as the posterior, and quoting it without errors is quoting half a\nmeasurement. Second, a nested-sampling run gives you the full posterior, so errors,\ncovariances and the Bayesian evidence are all available; a gradient optimiser such as\n`MultiStartProdigy` is a maximum-a-posteriori method and gives you **no errors at all**\n(`autogalaxy_workspace:scripts/imaging/start_here.py` `__Posterior__`). If the fit used the\noptimiser and the user wants uncertainties, the answer is to re-run with `Nautilus`, not to\nmanufacture them.\n\nThe concept page behind everything below is\n[`wiki/core/concepts/samples_and_posteriors.md`](../wiki/core/concepts/samples_and_posteriors.md);\nthe aggregator's full API surface is\n[`wiki/core/api/aggregator.md`](../wiki/core/api/aggregator.md).\n\n## Ask\n\nTwo questions, and they choose the branch outright:\n\n- **What do you want out of it?** *\"A parameter and its error\"* → the `Samples` branch.\n *\"The residuals / how good is the fit\"* → the fit branch, then\n [`ag_plot_fit`](./ag_plot_fit.md). *\"A physical quantity in kpc or solar luminosities\"* →\n the derived-quantities branch. *\"A table over all my galaxies\"* → the aggregator branch.\n- **One fit, or many?** One fit you already have a path to → simple loading. More than a\n handful, or you want to iterate and filter → the aggregator, which is generator-based and\n keeps memory bounded no matter how many fits the tree holds.\n\nIf they give you a path, list it and confirm which sub-folder: the layout is\n`output/////`, and a parent path can hold many\nfits. If the path contains a `test_mode` segment, say so immediately — every number in it is a\nwiring check, not a measurement\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## Branch — the result you already have in the session\n\nIf the fit just ran, `search.fit(...)` returned everything, no disk access needed:\n\n```python\nresult = search.fit(model=model, analysis=analysis)\n\nprint(result.info) # human-readable summary, parameters + errors\nprint(result.max_log_likelihood_instance) # best-fit model as concrete objects\n\ngalaxies = result.max_log_likelihood_galaxies # ag.Galaxies at the best-fit values\nfit = result.max_log_likelihood_fit # ag.FitImaging: model image, residuals, chi²\nsamples = result.samples # the full posterior\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py` `__Result__` and\n`autogalaxy_workspace:scripts/guides/results/start_here.py`. The full member list —\n`result.samples_summary`, `result.model`, `result.instance`, `result.dataset`, `result.grids`,\n`result.unmasked_model_image`, the per-galaxy image dictionaries — is tabulated in\n[`wiki/core/api/analysis_objects.md`](../wiki/core/api/analysis_objects.md)\n\"What the result gives you\". Sources: `PyAutoGalaxy:autogalaxy/analysis/result.py` and\n`PyAutoGalaxy:autogalaxy/imaging/model/result.py`.\n\n`result.samples_summary` is worth knowing about: it holds pre-computed maximum-likelihood\nvalues and 1σ/3σ errors, so reaching for it instead of re-deriving from `samples` is\nsubstantially faster and gives the same answer.\n\n## Branch — loading one fit from disk\n\nEverything the `Result` holds was also written to the output folder, and each file loads back\ninto a full Python object in one line — much cheaper than re-running the search:\n\n```python\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nfrom autogalaxy import from_json\n\nFIT_PATH = Path(\"output\") / \"imaging\" / \"\" / \"sersic\" / \"\"\nfiles_path = FIT_PATH / \"files\"\nimage_path = FIT_PATH / \"image\"\n\ngalaxies = from_json(file_path=files_path / \"galaxies.json\")\nmodel = from_json(file_path=files_path / \"model.json\")\n\nsamples = af.SamplesNest.from_table(filename=files_path / \"samples.csv\", model=model)\nprint(samples.max_log_likelihood())\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/results/start_here.py`\n\"Simple Loading\". If the fit ran in the same session, `search.paths.output_path` already\npoints at the right folder, so you never have to know the hash.\n\nTwo things to know about what comes back:\n\n- **`galaxies.json` deserialises to a plain Python list of `Galaxy` objects, not an\n `ag.Galaxies`.** The list is enough for `ag.FitImaging(dataset=dataset, galaxies=galaxies)`\n and for indexing (`galaxies[0].bulge`), but it has no `image_2d_from`. Wrap it when you need\n the collection's own methods: `galaxies = ag.Galaxies(galaxies=galaxies)`.\n- **`model.json` is the *prior* model, with free parameters** — not the best-fit instance. It\n is what you pass to `SamplesNest.from_table` so the sample columns can be mapped back onto\n named parameters, and it is worth printing (`model.info`) to confirm what was actually\n fitted.\n\nThe `image/` folder holds the imaging products as FITS, loadable with the standard readers —\n`ag.Imaging.from_fits` for `dataset.fits` (multi-HDU, so pass the `*_hdu` arguments) and\n`ag.Array2D.from_fits` for the per-galaxy image stacks. The annotated tree of everything the\nfit wrote is `__Output Folder Layout__` in\n[`autogalaxy_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/modeling.py),\nalso condensed in\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n\"The output folder\".\n\nThe whole `/` folder is portable: a collaborator with a compatible environment\nloads it exactly as above. `files/*.json`, `files/samples.csv`, the `image/*.fits` products\nand the human-readable `model.info` / `model.results` are what matter to them.\n\n## Branch — parameters with errors, from `Samples`\n\nThe `Samples` object holds every accepted sample and its likelihood, which is what makes error\nestimation possible at all:\n\n```python\nsamples = result.samples\n\nmedian_instance = samples.median_pdf()\nu3 = samples.values_at_upper_sigma(sigma=3.0)\nl3 = samples.values_at_lower_sigma(sigma=3.0)\n\nprint(median_instance.galaxies.galaxy.bulge)\nprint(u3.galaxies.galaxy.bulge, \"\\n\", l3.galaxies.galaxy.bulge)\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/results/start_here.py` `__Samples__`. Each\nof these returns a **model instance** — the same shape of object as the model you composed, so\n`instance.galaxies.galaxy.bulge.sersic_index` addresses a parameter by the names you chose.\n`samples.max_log_likelihood()` gives the best-fit instance, `samples.parameter_lists` the raw\nvectors, `samples.log_likelihood_list` and `samples.log_evidence` the statistics.\n`samples.errors_at_upper_sigma(...)` returns the error rather than the value.\n\nTwo disciplines when reporting:\n\n- **Quote the sigma level and the summary you used.** \"Effective radius 1.62, +0.08/−0.07 at\n 1σ from the marginalised PDF\" is a result. \"1.62\" is not.\n- **Be explicit about units.** PyAutoGalaxy works in arcseconds and instrumental flux units.\n \"Effective radius = 1.6 arcsec\" is fine; \"effective radius = 1.6\" is a bug waiting to\n happen.\n\n### Linear intensities are not in the samples\n\nThis one catches everyone. A linear light profile (`ag.lp_linear.*`, and every basis built\nfrom them — a Multi-Gaussian Expansion, a shapelet expansion) has its `intensity` solved by\nlinear inversion at every iteration rather than sampled. So in the `Samples` object those\nintensities are placeholders of 1.0, and reading them there gives you nothing\n(`autogalaxy_workspace:scripts/guides/results/start_here.py` `__Linear Light Profiles__`).\n\nThe solved values live on the fit. Either take them off the result directly:\n\n```python\nprint(result.max_log_likelihood_galaxies[0].bulge.intensity)\n```\n\nor, if you are working from a `Samples` instance you loaded yourself, rebuild the fit and let\nit solve:\n\n```python\nml_instance = samples.max_log_likelihood()\n\nfit = ag.FitImaging(dataset=dataset, galaxies=ml_instance.galaxies)\ngalaxies = fit.galaxies_linear_light_profiles_to_light_profiles\n\nprint(galaxies[0].bulge.intensity)\n```\n\nThe same conversion is what lets you plot a linear-profile model at all\n([`ag_plot_fit`](./ag_plot_fit.md)). Background:\n[`wiki/core/concepts/linear_light_profiles_and_mge.md`](../wiki/core/concepts/linear_light_profiles_and_mge.md).\nThe same principle applies to a pixelised reconstruction's pixel fluxes —\n[`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\n## Branch — derived quantities, and their errors\n\nMost interesting numbers are not model parameters. A bulge-to-total light ratio, a luminosity\ninside an aperture, an effective radius in kiloparsecs — each is a *function* of the\nparameters, so its error has to be propagated rather than read off.\n\nCompute the quantity from the best-fit galaxies:\n\n```python\ngalaxies = result.max_log_likelihood_galaxies\n\nluminosity = galaxies[0].luminosity_within_circle_from(radius=10.0)\n\ncosmology = ag.cosmo.Planck15()\nkpc_per_arcsec = cosmology.kpc_per_arcsec_from(redshift=galaxies[0].redshift)\neffective_radius_kpc = galaxies[0].bulge.effective_radius * kpc_per_arcsec\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/results/aggregator/models.py` and\n`autogalaxy_workspace:scripts/guides/results/start_here.py`\n`__Units and Cosmological Quantities__`. The angular-to-physical machinery, fluxes, magnitudes\nand luminosities are\n[`wiki/core/concepts/cosmology_and_units.md`](../wiki/core/concepts/cosmology_and_units.md);\nthe runnable guides are `autogalaxy_workspace:scripts/guides/units/cosmology.py` and\n`autogalaxy_workspace:scripts/guides/units/flux.py`.\n\nFor the **error** on a derived quantity, recompute it for galaxies drawn from the posterior\nand take the spread. The aggregator's `randomly_drawn_via_pdf_gen_from` exists for exactly\nthis, and `all_above_weight_gen_from` / `weights_above_gen_from` give you the weighted version\n(`autogalaxy_workspace:scripts/guides/results/aggregator/models.py`). Anything else — scaling\nthe parameter's own error, or quoting the best-fit value with no error — is guesswork.\n\nQuantities the library can compute but the model never sampled can also be recorded during the\nfit as **latent variables**, which puts them in the samples with errors like any other\nparameter. That machinery, including subclassing `ag.LatentGalaxy` for your own, is\n`autogalaxy_workspace:scripts/guides/results/latent_variables.py` and\n[`wiki/core/concepts/samples_and_posteriors.md`](../wiki/core/concepts/samples_and_posteriors.md)\n\"Latent variables\". Note that any active `PYAUTO_TEST_MODE` level skips the latent pass, so a\nsmoke run never has them.\n\n## Branch — many fits, with the aggregator\n\nOnce the unit of work is a *sample* — a hundred galaxies with one model, or one galaxy with\nten models — the aggregator gives you one query surface over all of them and, crucially,\nreturns **generators** rather than lists, so memory stays bounded:\n\n```python\nfrom pathlib import Path\nfrom autofit.aggregator.aggregator import Aggregator\n\nagg = Aggregator.from_directory(directory=Path(\"output\") / \"imaging\")\n\nfor samples in agg.values(\"samples\"):\n print(samples.parameter_lists[0])\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/results/start_here.py`\n\"Aggregator\". Note the explicit import: `Aggregator.from_directory` lives in\n`PyAutoFit:autofit/aggregator/aggregator.py` and is **not** `af.Aggregator`, which is the\ndatabase-backed class. Keys worth knowing for `agg.values(...)`: `\"samples\"`,\n`\"samples_summary\"` (much faster — nothing re-derived), `\"samples_info\"`, `\"model\"`,\n`\"search\"`, `\"info\"`, `\"covariance\"`, `\"cosmology\"`, and the `\"dataset/...\"` family.\n\nA generator is consumed once. Remake it rather than storing it — this is why the workspace\nexamples build each one at the point of use.\n\n**Queries** compose, because each returns a new aggregator\n(`autogalaxy_workspace:scripts/guides/results/aggregator/queries.py`):\n\n```python\nunique_tag = agg.search.unique_tag\nagg_query = agg.query(unique_tag == \"\")\n\nbulge = agg.model.galaxies.galaxy.bulge\nagg_query = agg.query((bulge == ag.lp_linear.Sersic) & (bulge.effective_radius > 3.0))\n```\n\n`agg.search` addresses fit-level fields (`name`, `unique_tag`, `path_prefix`, `is_complete`);\n`agg.model` addresses the fitted model by the names you chose, so you can select on a\ncomponent's class or on an inferred value.\n\n### `ag.agg` — galaxy objects back out of stored fits\n\nPyAutoFit's aggregator loads what the search wrote; PyAutoGalaxy's `ag.agg` rebuilds\n*galaxy-domain* objects from those files, as generators. The classes are `ImagingAgg`,\n`InterferometerAgg`, `GalaxiesAgg`, `FitImagingAgg`, `FitInterferometerAgg`, `EllipsesAgg`,\n`FitEllipseAgg` and `MultipolesAgg`:\n\n```python\nimport autogalaxy.plot as aplt\n\ngalaxies_agg = ag.agg.GalaxiesAgg(aggregator=agg)\ngalaxies_gen = galaxies_agg.max_log_likelihood_gen_from()\n\ndataset_agg = ag.agg.ImagingAgg(aggregator=agg)\ndataset_gen = dataset_agg.dataset_gen_from()\n\nfor dataset_list, galaxies_list in zip(dataset_gen, galaxies_gen):\n dataset = dataset_list[0] # one entry per analysis in the fit\n galaxies = galaxies_list[0]\n\n fit = ag.FitImaging(dataset=dataset, galaxies=galaxies)\n galaxies = fit.galaxies_linear_light_profiles_to_light_profiles\n\n print(galaxies[0].bulge.intensity)\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/results/aggregator/models.py`. The inner\n`[0]` is not noise: a fit can hold several analyses (a multi-band factor graph, for instance),\nso each generator yields a *list* per fit. The dataset classes expose `dataset_gen_from()`;\nthe model classes share `max_log_likelihood_gen_from()`,\n`randomly_drawn_via_pdf_gen_from(total_samples=...)`,\n`all_above_weight_gen_from(minimum_weight=...)` and\n`weights_above_gen_from(minimum_weight=...)`, all built on `object_via_gen_from(...)`.\n`FitImagingAgg` also takes a `settings=` argument if you need to rebuild the fit with\ndifferent settings than it ran with\n(`autogalaxy_workspace:scripts/guides/results/aggregator/data_fitting.py`).\n\n### The three enumerations, and the workflow exports\n\n`ag.agg` exposes exactly three enumerations, naming panels and HDUs the completed fits\n**already have on disk** — you are extracting stored output, not re-rendering it\n(`PyAutoGalaxy:autogalaxy/aggregator/subplot.py`):\n\n| Enumeration | Members |\n|---|---|\n| `ag.agg.fits_fit` | `model_data`, `residual_map`, `normalized_residual_map`, `chi_squared_map` |\n| `ag.agg.subplot_dataset` | `data`, `data_log_10`, `noise_map`, `psf`, `psf_log_10`, `signal_to_noise_map`, `over_sample_size_lp`, `over_sample_size_pixelization` |\n| `ag.agg.subplot_fit` | `data`, `signal_to_noise_map`, `model_data`, `normalized_residual_map`, `normalized_residual_map_one_sigma`, `chi_squared_map` |\n\nThey feed three PyAutoFit export helpers, each taking `aggregator=agg`\n(`autogalaxy_workspace:scripts/guides/results/workflow/csv_make.py`,\n`fits_make.py` and `png_make.py`):\n\n```python\nimport autofit as af\n\nworkflow_path = Path(\"output\") / \"workflow\"\n\nagg_csv = af.AggregateCSV(aggregator=agg)\nagg_csv.add_variable(\n argument=\"galaxies.galaxy.bulge.sersic_index\",\n value_types=[af.ValueType.Median, af.ValueType.ValuesAt3Sigma],\n)\nagg_csv.add_variable(argument=\"galaxies.galaxy.bulge.effective_radius\")\nagg_csv.save(path=workflow_path / \"results.csv\")\n\nagg_fits = af.AggregateFITS(aggregator=agg)\nagg_fits.output_to_folder(\n folder=workflow_path,\n name=\"unique_tag\",\n hdus=[ag.agg.fits_fit.model_data, ag.agg.fits_fit.residual_map],\n)\n\nagg_image = af.AggregateImages(aggregator=agg)\nagg_image.output_to_folder(\n folder=workflow_path,\n name=\"unique_tag\",\n subplots=[\n ag.agg.subplot_fit.data,\n ag.agg.subplot_fit.model_data,\n ag.agg.subplot_fit.normalized_residual_map,\n ],\n)\n```\n\n`af.ValueType` has four members — `Median`, `MaxLogLikelihood`, `ValuesAt1Sigma`,\n`ValuesAt3Sigma`. `AggregateCSV` also offers `add_computed_column` (a function of the loaded\nobjects, for a derived quantity) and `add_label_column` (an explicit per-fit label, e.g. the\ndataset names from `[search.unique_tag for search in agg.values(\"search\")]`). `extract_fits`\nand `extract_image` return one combined object across all fits; `output_to_folder` writes one\nfile per fit instead, which is usually easier to click through when reviewing a sample.\n\nFull API surface, including the database-backed `af.Aggregator.from_database` route for\nhundreds of fits: [`wiki/core/api/aggregator.md`](../wiki/core/api/aggregator.md). The\ndatabase walkthrough is `autogalaxy_workspace:scripts/guides/results/database/start_here.py`\n— note that `from_database` has no overwrite flag, which is why that example deletes a stale\n`.sqlite` itself. Start with the directory aggregator and move to the database only when\nreading from disk becomes the slow part.\n\nThe shape that makes this worth the setup: **query** the subset you care about, **load or\nderive** the quantity per fit, **export** it under a uniform naming scheme. Fitting is\nexpensive; changing your mind about which columns you wanted should cost seconds.\n\n## Branch — the honest caveats\n\nSay these out loud rather than letting a user discover them:\n\n- **A test-mode result is not a measurement.** Any `PYAUTO_TEST_MODE` level truncates or mocks\n the sampler, so the parameters are whatever the short-circuited run produced, the errors are\n degenerate, and latent variables were skipped. The `test_mode` path segment is the tell.\n- **A gradient-optimiser fit has no errors.** `MultiStartProdigy` returns one best-fit model.\n If the science needs uncertainties, re-run with `Nautilus`\n ([`ag_configure_search`](./ag_configure_search.md)).\n- **A resumed fit may not be the fit you think.** The unique identifier does not hash the\n pixel values, so a result can be a silent resume of an earlier run on different data — see\n [`ag_run_search`](./ag_run_search.md) \"Resuming\".\n- **An unconverged search still produces a `samples.csv`.** Check `search.summary` and the\n log-evidence before trusting a posterior width.\n\n## Combine\n\n- [`ag_plot_fit`](./ag_plot_fit.md) — turn the loaded fit into figures, and read the residuals\n properly before quoting anything.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) — the numbers loaded fine but they are\n not believable.\n- [`ag_run_search`](./ag_run_search.md) — the run that produced this output, and what it wrote\n where.\n- [`ag_configure_search`](./ag_configure_search.md) — the posterior is too coarse, or you need\n errors an optimiser cannot give.\n\nThere is a second, lighter route to a result: the read-only results-inspector MCP server,\nwhich lets a chat harness with no code execution list fits, read summaries and view result\nimages without a script — [`ag_inspect_results_mcp`](./ag_inspect_results_mcp.md). It is the\nfallback, not the upgrade: whenever code execution is available, this skill's Python is richer\nand is the way in.\n\nWhen a load turns into real analysis — a table, a derived quantity, a comparison across fits —\noffer (default-yes) the dated `wiki/project/YYYY-MM-DD-.md` entry: the science question,\nwhat was inferred and how, and the script produced (per [`_style.md`](./_style.md) property\n#5).\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Results](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_7_results.ipynb):\n the `Result` object from first principles — best-fit model, galaxies, posterior samples, and\n pulling parameter values with uncertainties out of them.\n- **General reference** — [RTD: Fitting API reference](https://pyautogalaxy.readthedocs.io/en/latest/api/fitting.html):\n the generated reference for the fit objects a loaded result rebuilds.\n- **Experienced PyAutoGalaxy user** — [workspace: guides/results/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/guides/results/start_here.py):\n both routes in one runnable script — direct JSON/CSV loading of one fit, then the aggregator\n over many.\n\n## Agent procedural checklist\n\n1. Establish what the user wants out of the result before loading anything.\n2. Establish one fit or many; pick simple loading or the aggregator accordingly.\n3. Check the path for a `test_mode` segment and say so if it is there.\n4. Check which search ran — no errors are available from a gradient optimiser.\n5. For any linear light profile or pixelisation, get intensities from the fit, never from the\n samples.\n6. Quote a sigma level, a summary statistic and a unit with every number.\n7. For a derived quantity's error, draw from the posterior; never scale a parameter error.\n8. Write the loading recipe to a script in `scripts/` rather than leaving it inline.\n9. Route figures to the fit-plotting skill and unbelievable numbers to the debug skill.\n10. Offer the `wiki/project/` entry when the load became analysis.\n" - } - }, - "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file diff --git a/notebooks/chapter_2_modeling/tutorial_7_summary.ipynb b/notebooks/chapter_2_modeling/tutorial_7_summary.ipynb new file mode 100644 index 0000000..7fe4f90 --- /dev/null +++ b/notebooks/chapter_2_modeling/tutorial_7_summary.ipynb @@ -0,0 +1,62 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Tutorial 7: Summary\n", + "===================\n", + "\n", + "__Summary__\n", + "\n", + "You have completed chapter 2. You can now define galaxy models and priors, connect them to data through Analysis\n", + "objects, and use searches to obtain and inspect fits.\n", + "\n", + "The central challenge is balancing realism, reliable exploration and runtime. Visual inspection helps motivate\n", + "priors and reveal inadequate models. Linear profiles and MGEs can describe flexible light distributions with\n", + "fewer non-linear parameters. Data preparation determines which measurements constrain the model. Search chaining\n", + "lets different components be fitted in stages, while requiring care about the uncertainty of fixed components.\n", + "\n", + "Try adapting the modelling examples in `autogalaxy_workspace/scripts/imaging` to your own data, or use the\n", + "simulators to make a controlled experiment. Once your fits are reliable, the workspace's results guides explain\n", + "how to load and analyse them in depth. Multiple-dataset modelling is another advanced topic for after this course.\n", + "\n", + "Chapter 3 introduces pixelizations for reconstructing more irregular light, including features that a common-centre\n", + "MGE cannot describe. Chapter 4 develops modelling of scenes containing multiple galaxies. The optional searches\n", + "and speed tutorials are available when you need them; historical prior passing is not required reading." + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.1" + }, + "colab": { + "aiContexts": { + "24c2f562-da24-50bb-8eb9-5a887505fe54": { + "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", + "name": "PyAutoGalaxy assistant", + "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_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\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_2_modeling/tutorial_7_summary.ipynb in HowToGalaxy).\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 PyAutoGalaxy 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 PyAutoGalaxy docs (https://pyautogalaxy.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) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. 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 galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_load_results\n\n---\nname: ag_load_results\ndescription: Get a completed fit's results back into Python and turn them into science — the in-session `Result` object (max-log-likelihood instance, galaxies and fit), direct loading of one fit's output folder via `from_json` and `SamplesNest.from_table`, the `Samples` API for medians and errors, and the aggregator for a whole sample of fits with its `ag.agg` generators, queries and CSV/FITS/PNG workflow exports. Also covers the traps: linear light-profile intensities are solved rather than sampled and are absent from the samples, derived-quantity errors need posterior draws, and test-mode results are not physically meaningful. Use when a search has finished (or is mid-run) and the user wants numbers, errors, derived quantities, a results table, or a comparison across fits. Not for running the fit (`ag_run_search`), not for rendering figures of a single fit (`ag_plot_fit`), and not for diagnosing a fit that converged somewhere wrong (`ag_debug_fit_failure`).\n---\n\n# Reading a finished fit\n\nThe search is over; the question is what it measured. This skill is the bridge from an\n`output/` folder to a sentence you could put in a paper: *\"the bulge has an effective radius\nof 1.62 ± 0.08 arcseconds and a Sersic index of 3.9 ± 0.3\"*.\n\nLoading is never the goal on its own — the user already wants something specific: a\nparameter with errors, a derived quantity the fit did not parameterise directly, the\nresiduals, a table across fifty galaxies. The job here is to establish which, load only that,\nand be honest about what the fit can and cannot support.\n\nTwo things about the statistics are worth stating before any API. First, the default view of a\nresult is the **maximum log likelihood** model — the single best-fitting parameter vector.\nThat is not the same as the posterior, and quoting it without errors is quoting half a\nmeasurement. Second, a nested-sampling run gives you the full posterior, so errors,\ncovariances and the Bayesian evidence are all available; a gradient optimiser such as\n`MultiStartProdigy` is a maximum-a-posteriori method and gives you **no errors at all**\n(`autogalaxy_workspace:scripts/imaging/start_here.py` `__Posterior__`). If the fit used the\noptimiser and the user wants uncertainties, the answer is to re-run with `Nautilus`, not to\nmanufacture them.\n\nThe concept page behind everything below is\n[`wiki/core/concepts/samples_and_posteriors.md`](../wiki/core/concepts/samples_and_posteriors.md);\nthe aggregator's full API surface is\n[`wiki/core/api/aggregator.md`](../wiki/core/api/aggregator.md).\n\n## Ask\n\nTwo questions, and they choose the branch outright:\n\n- **What do you want out of it?** *\"A parameter and its error\"* → the `Samples` branch.\n *\"The residuals / how good is the fit\"* → the fit branch, then\n [`ag_plot_fit`](./ag_plot_fit.md). *\"A physical quantity in kpc or solar luminosities\"* →\n the derived-quantities branch. *\"A table over all my galaxies\"* → the aggregator branch.\n- **One fit, or many?** One fit you already have a path to → simple loading. More than a\n handful, or you want to iterate and filter → the aggregator, which is generator-based and\n keeps memory bounded no matter how many fits the tree holds.\n\nIf they give you a path, list it and confirm which sub-folder: the layout is\n`output/////`, and a parent path can hold many\nfits. If the path contains a `test_mode` segment, say so immediately — every number in it is a\nwiring check, not a measurement\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## Branch — the result you already have in the session\n\nIf the fit just ran, `search.fit(...)` returned everything, no disk access needed:\n\n```python\nresult = search.fit(model=model, analysis=analysis)\n\nprint(result.info) # human-readable summary, parameters + errors\nprint(result.max_log_likelihood_instance) # best-fit model as concrete objects\n\ngalaxies = result.max_log_likelihood_galaxies # ag.Galaxies at the best-fit values\nfit = result.max_log_likelihood_fit # ag.FitImaging: model image, residuals, chi²\nsamples = result.samples # the full posterior\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py` `__Result__` and\n`autogalaxy_workspace:scripts/guides/results/start_here.py`. The full member list —\n`result.samples_summary`, `result.model`, `result.instance`, `result.dataset`, `result.grids`,\n`result.unmasked_model_image`, the per-galaxy image dictionaries — is tabulated in\n[`wiki/core/api/analysis_objects.md`](../wiki/core/api/analysis_objects.md)\n\"What the result gives you\". Sources: `PyAutoGalaxy:autogalaxy/analysis/result.py` and\n`PyAutoGalaxy:autogalaxy/imaging/model/result.py`.\n\n`result.samples_summary` is worth knowing about: it holds pre-computed maximum-likelihood\nvalues and 1σ/3σ errors, so reaching for it instead of re-deriving from `samples` is\nsubstantially faster and gives the same answer.\n\n## Branch — loading one fit from disk\n\nEverything the `Result` holds was also written to the output folder, and each file loads back\ninto a full Python object in one line — much cheaper than re-running the search:\n\n```python\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nfrom autogalaxy import from_json\n\nFIT_PATH = Path(\"output\") / \"imaging\" / \"\" / \"sersic\" / \"\"\nfiles_path = FIT_PATH / \"files\"\nimage_path = FIT_PATH / \"image\"\n\ngalaxies = from_json(file_path=files_path / \"galaxies.json\")\nmodel = from_json(file_path=files_path / \"model.json\")\n\nsamples = af.SamplesNest.from_table(filename=files_path / \"samples.csv\", model=model)\nprint(samples.max_log_likelihood())\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/results/start_here.py`\n\"Simple Loading\". If the fit ran in the same session, `search.paths.output_path` already\npoints at the right folder, so you never have to know the hash.\n\nTwo things to know about what comes back:\n\n- **`galaxies.json` deserialises to a plain Python list of `Galaxy` objects, not an\n `ag.Galaxies`.** The list is enough for `ag.FitImaging(dataset=dataset, galaxies=galaxies)`\n and for indexing (`galaxies[0].bulge`), but it has no `image_2d_from`. Wrap it when you need\n the collection's own methods: `galaxies = ag.Galaxies(galaxies=galaxies)`.\n- **`model.json` is the *prior* model, with free parameters** — not the best-fit instance. It\n is what you pass to `SamplesNest.from_table` so the sample columns can be mapped back onto\n named parameters, and it is worth printing (`model.info`) to confirm what was actually\n fitted.\n\nThe `image/` folder holds the imaging products as FITS, loadable with the standard readers —\n`ag.Imaging.from_fits` for `dataset.fits` (multi-HDU, so pass the `*_hdu` arguments) and\n`ag.Array2D.from_fits` for the per-galaxy image stacks. The annotated tree of everything the\nfit wrote is `__Output Folder Layout__` in\n[`autogalaxy_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/modeling.py),\nalso condensed in\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n\"The output folder\".\n\nThe whole `/` folder is portable: a collaborator with a compatible environment\nloads it exactly as above. `files/*.json`, `files/samples.csv`, the `image/*.fits` products\nand the human-readable `model.info` / `model.results` are what matter to them.\n\n## Branch — parameters with errors, from `Samples`\n\nThe `Samples` object holds every accepted sample and its likelihood, which is what makes error\nestimation possible at all:\n\n```python\nsamples = result.samples\n\nmedian_instance = samples.median_pdf()\nu3 = samples.values_at_upper_sigma(sigma=3.0)\nl3 = samples.values_at_lower_sigma(sigma=3.0)\n\nprint(median_instance.galaxies.galaxy.bulge)\nprint(u3.galaxies.galaxy.bulge, \"\\n\", l3.galaxies.galaxy.bulge)\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/results/start_here.py` `__Samples__`. Each\nof these returns a **model instance** — the same shape of object as the model you composed, so\n`instance.galaxies.galaxy.bulge.sersic_index` addresses a parameter by the names you chose.\n`samples.max_log_likelihood()` gives the best-fit instance, `samples.parameter_lists` the raw\nvectors, `samples.log_likelihood_list` and `samples.log_evidence` the statistics.\n`samples.errors_at_upper_sigma(...)` returns the error rather than the value.\n\nTwo disciplines when reporting:\n\n- **Quote the sigma level and the summary you used.** \"Effective radius 1.62, +0.08/−0.07 at\n 1σ from the marginalised PDF\" is a result. \"1.62\" is not.\n- **Be explicit about units.** PyAutoGalaxy works in arcseconds and instrumental flux units.\n \"Effective radius = 1.6 arcsec\" is fine; \"effective radius = 1.6\" is a bug waiting to\n happen.\n\n### Linear intensities are not in the samples\n\nThis one catches everyone. A linear light profile (`ag.lp_linear.*`, and every basis built\nfrom them — a Multi-Gaussian Expansion, a shapelet expansion) has its `intensity` solved by\nlinear inversion at every iteration rather than sampled. So in the `Samples` object those\nintensities are placeholders of 1.0, and reading them there gives you nothing\n(`autogalaxy_workspace:scripts/guides/results/start_here.py` `__Linear Light Profiles__`).\n\nThe solved values live on the fit. Either take them off the result directly:\n\n```python\nprint(result.max_log_likelihood_galaxies[0].bulge.intensity)\n```\n\nor, if you are working from a `Samples` instance you loaded yourself, rebuild the fit and let\nit solve:\n\n```python\nml_instance = samples.max_log_likelihood()\n\nfit = ag.FitImaging(dataset=dataset, galaxies=ml_instance.galaxies)\ngalaxies = fit.galaxies_linear_light_profiles_to_light_profiles\n\nprint(galaxies[0].bulge.intensity)\n```\n\nThe same conversion is what lets you plot a linear-profile model at all\n([`ag_plot_fit`](./ag_plot_fit.md)). Background:\n[`wiki/core/concepts/linear_light_profiles_and_mge.md`](../wiki/core/concepts/linear_light_profiles_and_mge.md).\nThe same principle applies to a pixelised reconstruction's pixel fluxes —\n[`wiki/core/concepts/inversions_and_pixelizations.md`](../wiki/core/concepts/inversions_and_pixelizations.md).\n\n## Branch — derived quantities, and their errors\n\nMost interesting numbers are not model parameters. A bulge-to-total light ratio, a luminosity\ninside an aperture, an effective radius in kiloparsecs — each is a *function* of the\nparameters, so its error has to be propagated rather than read off.\n\nCompute the quantity from the best-fit galaxies:\n\n```python\ngalaxies = result.max_log_likelihood_galaxies\n\nluminosity = galaxies[0].luminosity_within_circle_from(radius=10.0)\n\ncosmology = ag.cosmo.Planck15()\nkpc_per_arcsec = cosmology.kpc_per_arcsec_from(redshift=galaxies[0].redshift)\neffective_radius_kpc = galaxies[0].bulge.effective_radius * kpc_per_arcsec\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/results/aggregator/models.py` and\n`autogalaxy_workspace:scripts/guides/results/start_here.py`\n`__Units and Cosmological Quantities__`. The angular-to-physical machinery, fluxes, magnitudes\nand luminosities are\n[`wiki/core/concepts/cosmology_and_units.md`](../wiki/core/concepts/cosmology_and_units.md);\nthe runnable guides are `autogalaxy_workspace:scripts/guides/units/cosmology.py` and\n`autogalaxy_workspace:scripts/guides/units/flux.py`.\n\nFor the **error** on a derived quantity, recompute it for galaxies drawn from the posterior\nand take the spread. The aggregator's `randomly_drawn_via_pdf_gen_from` exists for exactly\nthis, and `all_above_weight_gen_from` / `weights_above_gen_from` give you the weighted version\n(`autogalaxy_workspace:scripts/guides/results/aggregator/models.py`). Anything else — scaling\nthe parameter's own error, or quoting the best-fit value with no error — is guesswork.\n\nQuantities the library can compute but the model never sampled can also be recorded during the\nfit as **latent variables**, which puts them in the samples with errors like any other\nparameter. That machinery, including subclassing `ag.LatentGalaxy` for your own, is\n`autogalaxy_workspace:scripts/guides/results/latent_variables.py` and\n[`wiki/core/concepts/samples_and_posteriors.md`](../wiki/core/concepts/samples_and_posteriors.md)\n\"Latent variables\". Note that any active `PYAUTO_TEST_MODE` level skips the latent pass, so a\nsmoke run never has them.\n\n## Branch — many fits, with the aggregator\n\nOnce the unit of work is a *sample* — a hundred galaxies with one model, or one galaxy with\nten models — the aggregator gives you one query surface over all of them and, crucially,\nreturns **generators** rather than lists, so memory stays bounded:\n\n```python\nfrom pathlib import Path\nfrom autofit.aggregator.aggregator import Aggregator\n\nagg = Aggregator.from_directory(directory=Path(\"output\") / \"imaging\")\n\nfor samples in agg.values(\"samples\"):\n print(samples.parameter_lists[0])\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/results/start_here.py`\n\"Aggregator\". Note the explicit import: `Aggregator.from_directory` lives in\n`PyAutoFit:autofit/aggregator/aggregator.py` and is **not** `af.Aggregator`, which is the\ndatabase-backed class. Keys worth knowing for `agg.values(...)`: `\"samples\"`,\n`\"samples_summary\"` (much faster — nothing re-derived), `\"samples_info\"`, `\"model\"`,\n`\"search\"`, `\"info\"`, `\"covariance\"`, `\"cosmology\"`, and the `\"dataset/...\"` family.\n\nA generator is consumed once. Remake it rather than storing it — this is why the workspace\nexamples build each one at the point of use.\n\n**Queries** compose, because each returns a new aggregator\n(`autogalaxy_workspace:scripts/guides/results/aggregator/queries.py`):\n\n```python\nunique_tag = agg.search.unique_tag\nagg_query = agg.query(unique_tag == \"\")\n\nbulge = agg.model.galaxies.galaxy.bulge\nagg_query = agg.query((bulge == ag.lp_linear.Sersic) & (bulge.effective_radius > 3.0))\n```\n\n`agg.search` addresses fit-level fields (`name`, `unique_tag`, `path_prefix`, `is_complete`);\n`agg.model` addresses the fitted model by the names you chose, so you can select on a\ncomponent's class or on an inferred value.\n\n### `ag.agg` — galaxy objects back out of stored fits\n\nPyAutoFit's aggregator loads what the search wrote; PyAutoGalaxy's `ag.agg` rebuilds\n*galaxy-domain* objects from those files, as generators. The classes are `ImagingAgg`,\n`InterferometerAgg`, `GalaxiesAgg`, `FitImagingAgg`, `FitInterferometerAgg`, `EllipsesAgg`,\n`FitEllipseAgg` and `MultipolesAgg`:\n\n```python\nimport autogalaxy.plot as aplt\n\ngalaxies_agg = ag.agg.GalaxiesAgg(aggregator=agg)\ngalaxies_gen = galaxies_agg.max_log_likelihood_gen_from()\n\ndataset_agg = ag.agg.ImagingAgg(aggregator=agg)\ndataset_gen = dataset_agg.dataset_gen_from()\n\nfor dataset_list, galaxies_list in zip(dataset_gen, galaxies_gen):\n dataset = dataset_list[0] # one entry per analysis in the fit\n galaxies = galaxies_list[0]\n\n fit = ag.FitImaging(dataset=dataset, galaxies=galaxies)\n galaxies = fit.galaxies_linear_light_profiles_to_light_profiles\n\n print(galaxies[0].bulge.intensity)\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/results/aggregator/models.py`. The inner\n`[0]` is not noise: a fit can hold several analyses (a multi-band factor graph, for instance),\nso each generator yields a *list* per fit. The dataset classes expose `dataset_gen_from()`;\nthe model classes share `max_log_likelihood_gen_from()`,\n`randomly_drawn_via_pdf_gen_from(total_samples=...)`,\n`all_above_weight_gen_from(minimum_weight=...)` and\n`weights_above_gen_from(minimum_weight=...)`, all built on `object_via_gen_from(...)`.\n`FitImagingAgg` also takes a `settings=` argument if you need to rebuild the fit with\ndifferent settings than it ran with\n(`autogalaxy_workspace:scripts/guides/results/aggregator/data_fitting.py`).\n\n### The three enumerations, and the workflow exports\n\n`ag.agg` exposes exactly three enumerations, naming panels and HDUs the completed fits\n**already have on disk** — you are extracting stored output, not re-rendering it\n(`PyAutoGalaxy:autogalaxy/aggregator/subplot.py`):\n\n| Enumeration | Members |\n|---|---|\n| `ag.agg.fits_fit` | `model_data`, `residual_map`, `normalized_residual_map`, `chi_squared_map` |\n| `ag.agg.subplot_dataset` | `data`, `data_log_10`, `noise_map`, `psf`, `psf_log_10`, `signal_to_noise_map`, `over_sample_size_lp`, `over_sample_size_pixelization` |\n| `ag.agg.subplot_fit` | `data`, `signal_to_noise_map`, `model_data`, `normalized_residual_map`, `normalized_residual_map_one_sigma`, `chi_squared_map` |\n\nThey feed three PyAutoFit export helpers, each taking `aggregator=agg`\n(`autogalaxy_workspace:scripts/guides/results/workflow/csv_make.py`,\n`fits_make.py` and `png_make.py`):\n\n```python\nimport autofit as af\n\nworkflow_path = Path(\"output\") / \"workflow\"\n\nagg_csv = af.AggregateCSV(aggregator=agg)\nagg_csv.add_variable(\n argument=\"galaxies.galaxy.bulge.sersic_index\",\n value_types=[af.ValueType.Median, af.ValueType.ValuesAt3Sigma],\n)\nagg_csv.add_variable(argument=\"galaxies.galaxy.bulge.effective_radius\")\nagg_csv.save(path=workflow_path / \"results.csv\")\n\nagg_fits = af.AggregateFITS(aggregator=agg)\nagg_fits.output_to_folder(\n folder=workflow_path,\n name=\"unique_tag\",\n hdus=[ag.agg.fits_fit.model_data, ag.agg.fits_fit.residual_map],\n)\n\nagg_image = af.AggregateImages(aggregator=agg)\nagg_image.output_to_folder(\n folder=workflow_path,\n name=\"unique_tag\",\n subplots=[\n ag.agg.subplot_fit.data,\n ag.agg.subplot_fit.model_data,\n ag.agg.subplot_fit.normalized_residual_map,\n ],\n)\n```\n\n`af.ValueType` has four members — `Median`, `MaxLogLikelihood`, `ValuesAt1Sigma`,\n`ValuesAt3Sigma`. `AggregateCSV` also offers `add_computed_column` (a function of the loaded\nobjects, for a derived quantity) and `add_label_column` (an explicit per-fit label, e.g. the\ndataset names from `[search.unique_tag for search in agg.values(\"search\")]`). `extract_fits`\nand `extract_image` return one combined object across all fits; `output_to_folder` writes one\nfile per fit instead, which is usually easier to click through when reviewing a sample.\n\nFull API surface, including the database-backed `af.Aggregator.from_database` route for\nhundreds of fits: [`wiki/core/api/aggregator.md`](../wiki/core/api/aggregator.md). The\ndatabase walkthrough is `autogalaxy_workspace:scripts/guides/results/database/start_here.py`\n— note that `from_database` has no overwrite flag, which is why that example deletes a stale\n`.sqlite` itself. Start with the directory aggregator and move to the database only when\nreading from disk becomes the slow part.\n\nThe shape that makes this worth the setup: **query** the subset you care about, **load or\nderive** the quantity per fit, **export** it under a uniform naming scheme. Fitting is\nexpensive; changing your mind about which columns you wanted should cost seconds.\n\n## Branch — the honest caveats\n\nSay these out loud rather than letting a user discover them:\n\n- **A test-mode result is not a measurement.** Any `PYAUTO_TEST_MODE` level truncates or mocks\n the sampler, so the parameters are whatever the short-circuited run produced, the errors are\n degenerate, and latent variables were skipped. The `test_mode` path segment is the tell.\n- **A gradient-optimiser fit has no errors.** `MultiStartProdigy` returns one best-fit model.\n If the science needs uncertainties, re-run with `Nautilus`\n ([`ag_configure_search`](./ag_configure_search.md)).\n- **A resumed fit may not be the fit you think.** The unique identifier does not hash the\n pixel values, so a result can be a silent resume of an earlier run on different data — see\n [`ag_run_search`](./ag_run_search.md) \"Resuming\".\n- **An unconverged search still produces a `samples.csv`.** Check `search.summary` and the\n log-evidence before trusting a posterior width.\n\n## Combine\n\n- [`ag_plot_fit`](./ag_plot_fit.md) — turn the loaded fit into figures, and read the residuals\n properly before quoting anything.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) — the numbers loaded fine but they are\n not believable.\n- [`ag_run_search`](./ag_run_search.md) — the run that produced this output, and what it wrote\n where.\n- [`ag_configure_search`](./ag_configure_search.md) — the posterior is too coarse, or you need\n errors an optimiser cannot give.\n\nThere is a second, lighter route to a result: the read-only results-inspector MCP server,\nwhich lets a chat harness with no code execution list fits, read summaries and view result\nimages without a script — [`ag_inspect_results_mcp`](./ag_inspect_results_mcp.md). It is the\nfallback, not the upgrade: whenever code execution is available, this skill's Python is richer\nand is the way in.\n\nWhen a load turns into real analysis — a table, a derived quantity, a comparison across fits —\noffer (default-yes) the dated `wiki/project/YYYY-MM-DD-.md` entry: the science question,\nwhat was inferred and how, and the script produced (per [`_style.md`](./_style.md) property\n#5).\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Results](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_7_results.ipynb):\n the `Result` object from first principles — best-fit model, galaxies, posterior samples, and\n pulling parameter values with uncertainties out of them.\n- **General reference** — [RTD: Fitting API reference](https://pyautogalaxy.readthedocs.io/en/latest/api/fitting.html):\n the generated reference for the fit objects a loaded result rebuilds.\n- **Experienced PyAutoGalaxy user** — [workspace: guides/results/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/guides/results/start_here.py):\n both routes in one runnable script — direct JSON/CSV loading of one fit, then the aggregator\n over many.\n\n## Agent procedural checklist\n\n1. Establish what the user wants out of the result before loading anything.\n2. Establish one fit or many; pick simple loading or the aggregator accordingly.\n3. Check the path for a `test_mode` segment and say so if it is there.\n4. Check which search ran — no errors are available from a gradient optimiser.\n5. For any linear light profile or pixelisation, get intensities from the fit, never from the\n samples.\n6. Quote a sigma level, a summary statistic and a unit with every number.\n7. For a derived quantity's error, draw from the posterior; never scale a parameter error.\n8. Write the loading recipe to a script in `scripts/` rather than leaving it inline.\n9. Route figures to the fit-plotting skill and unbelievable numbers to the debug skill.\n10. Offer the `wiki/project/` entry when the load became analysis.\n" + } + }, + "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file diff --git a/notebooks/chapter_2_modeling/tutorial_8_need_for_speed.ipynb b/notebooks/chapter_2_modeling/tutorial_8_need_for_speed.ipynb deleted file mode 100644 index ca078d3..0000000 --- a/notebooks/chapter_2_modeling/tutorial_8_need_for_speed.ipynb +++ /dev/null @@ -1,251 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 8: Need For Speed\n", - "==========================\n", - "\n", - "In this chapter, we have learnt how to model galaxies and how to balance complexity and realism to ensure that we\n", - "infer a good model.\n", - "\n", - "For fitting more complex models, the final challenge that we face is keeping the run-time low. One can easily end\n", - "up in a situation where a model-fit takes days, or longer, to fit just one image. For fitting complex models and high\n", - "resolution datasets this is somewhat unavoidable. However, it is worth us discussing what drives the long run-times of\n", - "the modeling process and how we might speed it up.\n", - "\n", - "We have kept an eye on the log likelihood evaluation times and therefore expected overall run-time of the fits\n", - "performed in this chapter. Lets quickly remind ourselves of the main factors that drive the run-time, and how we\n", - "might reduce it.\n", - "\n", - "The overall run-time of a model-fit is, to a good approximation, a simple product of two numbers:\n", - "\n", - " - The number of log likelihood evaluations the non-linear search performs before it converges.\n", - "\n", - " - The time each individual log likelihood evaluation takes.\n", - "\n", - "Everything we discuss below reduces one (or both) of these numbers.\n", - "\n", - "__Contents__\n", - "\n", - "- **Searching Non-linear Parameter Space:** What drives the number of likelihood evaluations a search performs.\n", - "- **Cost Per Evaluation:** What drives the time a single log likelihood evaluation takes.\n", - "- **JAX:** How **PyAutoGalaxy** compiles the likelihood function with JAX and runs it on CPUs and GPUs.\n", - "- **Run Time Estimation:** How to estimate the overall run-time of a fit before committing to it.\n", - "- **Data Quantity:** How the amount of data fitted, and the mask applied to it, drives run-times.\n", - "- **Wrap Up:** Summary of the script and next steps.\n", - "\n", - "__Searching Non-linear Parameter Space__\n", - "\n", - "The time it takes for the non-linear search to sample parameter space and find the high likelihood models is driven by:\n", - "\n", - " - Dimensionality: A more complex parameter space (e.g. more parameters) takes longer to search.\n", - " - Priors: The broader the priors on each parameter the longer the search.\n", - " - Settings: Non-linear search settings which sample parameter space more thoroughly (e.g. a higher `n_live`) lead to\n", - " longer run-times.\n", - "\n", - "When we use only one search to fit a model, we are somewhat restricted in how we can try to achieve faster run\n", - "times by changing these 3 aspects of the search. We have already seen one powerful exception: the linear light\n", - "profiles of tutorial 5 remove every `intensity` parameter from the non-linear parameter space, reducing its\n", - "dimensionality and removing some of its most difficult degeneracies at the same time.\n", - "\n", - "The final two tutorials of this chapter (tutorials 9 and 10) introduce 'non-linear search chaining', which fits\n", - "a model using multiple searches that are performed back-to-back, passing the results of earlier searches to\n", - "later ones. A key motivation for this is that it gives us a lot more flexibility in juggling the dimensionality,\n", - "priors and settings so as to perform faster and more efficient modeling.\n", - "\n", - "In the optional **HowToGalaxy** tutorial `chapter_optional/tutorial_searches.py` we discuss other non-linear searches\n", - "supported by **PyAutoGalaxy** which use a different approach to sample parameter space than `Nautilus`. For those\n", - "familiar with statistical inference, this includes maximum likelihood estimators and MCMC algorithms.\n", - "\n", - "For galaxy modeling, there are maximum likelihood estimator methods (e.g. the Levenberg-Marquardt) that for simple\n", - "models (e.g. a single `Sersic`) can often reliably infer the maximum likelihood model, using ten times or fewer\n", - "likelihood evaluations than `Nautilus` and therefore running over ten times faster. However, these methods do\n", - "not infer reliable errors and are prone to becoming trapped in local maxima. Nevertheless, users modeling large\n", - "galaxy samples may wish to investigate these methods.\n", - "\n", - "__Cost Per Evaluation__\n", - "\n", - "The second number is the time a single log likelihood evaluation takes, which is set by every operation\n", - "**PyAutoGalaxy** performs to fit the galaxy data with a model, for example:\n", - "\n", - " - Computing the intensity values of every light profile on the image's grid of (y,x) coordinates.\n", - " - Over-sampling: sub-dividing image pixels into finer sub-pixels where the light profile changes rapidly (e.g. the\n", - " centre of the galaxy), which multiplies the number of intensity evaluations performed.\n", - " - Convolving the model image of the galaxies with the telescope's PSF to compare it to the data. The larger the\n", - " PSF, the more expensive this convolution becomes.\n", - " - For linear light profiles, basis functions like the MGE of tutorial 5 and the pixelizations of chapter 3, solving\n", - " the linear algebra of the inversion, which computes the `intensity` values that best fit the data.\n", - "\n", - "More complex fitting techniques therefore cost more per evaluation: a couple of standard light profiles are cheap,\n", - "an MGE costs more (its inversion solves for many Gaussians), and pixelized reconstructions cost the most.\n", - "As we saw in tutorial 5, this trade often still favours the more advanced technique, because the simpler parameter\n", - "space it produces reduces the number of evaluations the search needs.\n", - "\n", - "__JAX__\n", - "\n", - "How are these operations made fast? **PyAutoGalaxy** uses JAX (https://github.com/jax-ml/jax), Google's numerical\n", - "computing library, which just-in-time (JIT) compiles the entire log likelihood function into optimized machine code.\n", - "\n", - "JIT compilation means the first time the likelihood function is called, JAX traces through every operation it\n", - "performs (light profile evaluation, over-sampling, PSF convolution, the linear algebra of an inversion) and compiles\n", - "them into a single optimized program. This compilation is a one-off overhead, typically taking seconds to a couple\n", - "of minutes depending on model complexity. Every one of the tens of thousands of likelihood evaluations that follow\n", - "then reuses the compiled program and runs dramatically faster than ordinary Python. When a search begins you will\n", - "see a log message like `JAX jit compiling vectorized (vmap) likelihood function, could take seconds or minutes...`\n", - "-- that is the compilation happening.\n", - "\n", - "JAX's second superpower is that the same compiled code runs on either a CPU or a GPU. On a GPU, likelihood\n", - "evaluations are not only faster individually but can be batched, with many evaluated simultaneously (the\n", - "`n_batch` search input we have set throughout this chapter controls the size of these batches). GPU speed-ups\n", - "over CPU of an order of magnitude or more are common, and they grow with the size of the dataset and model. If you\n", - "have access to a GPU (even a modest laptop GPU), it is the single biggest speed-up available to you.\n", - "\n", - "You do not need to do anything to switch this on. JAX installs with `autogalaxy` by default, and every\n", - "`AnalysisImaging` object we have created in this chapter defaults to `use_jax=True` and the search compiles and\n", - "batches the likelihood function automatically. You can force the plain NumPy path with\n", - "`ag.AnalysisImaging(dataset=dataset, use_jax=False)` (or by setting the environment variable\n", - "`PYAUTO_DISABLE_JAX=1`), which is mainly useful for debugging, as NumPy errors and stack traces are much easier\n", - "to read than JAX ones.\n", - "\n", - "The one trade-off to keep in mind is the compilation overhead itself. For a full model-fit performing tens of\n", - "thousands of likelihood evaluations it is negligible. For a quick one-off calculation (e.g. fitting galaxies to\n", - "data once via a `FitImaging`, as we did in chapter 1) compilation can take longer than the calculation it speeds\n", - "up, which is why short interactive computations sometimes feel slower than you might expect the first time they run.\n", - "\n", - "Long-time users may remember that **PyAutoGalaxy** previously used `numba`, which recompiles individual Python\n", - "functions into fast machine code. JAX supersedes it: rather than accelerating functions one at a time, it compiles\n", - "and optimizes the likelihood function end-to-end, and adds GPU support and batching on top.\n", - "\n", - "Therefore, **PyAutoGalaxy** is pretty well optimized and there are no 'low hanging fruit' speed ups available by\n", - "writing the code in a different language.\n", - "\n", - "__Run Time Estimation__\n", - "\n", - "Because run-time is the product of the two numbers above, we can estimate it before committing to a fit:\n", - "\n", - " - Time the log likelihood evaluation: perform a fit of the model to the data once (e.g. via a `FitImaging`) and\n", - " time it, remembering to discard the first call, which includes JIT compilation.\n", - "\n", - " - Estimate the number of evaluations: for `Nautilus` a reasonable rule of thumb is of order 10000 evaluations per\n", - " free parameter, with simpler parameter spaces (e.g. linear light profiles, chained searches with tight priors)\n", - " converging in fewer.\n", - "\n", - "Multiplying the two gives a ballpark overall run-time. In tutorial 2 we used exactly this arithmetic: a log\n", - "likelihood evaluation time of ~0.05 seconds and 50000-100000 evaluations gave expected run-times of roughly 30\n", - "minutes on CPU and 10 minutes on GPU. If your own estimate comes out at days or weeks, that is the moment to\n", - "simplify the model, tighten the search settings, reach for search chaining or find a GPU -- before starting the\n", - "fit, not after.\n", - "\n", - "On a GPU, there is one other pre-flight check: `analysis.print_vram_use(model=model, batch_size=search.batch_size)`\n", - "estimates whether the fit will fit within the GPU's memory for your chosen batch size.\n", - "\n", - "__Data Quantity__\n", - "\n", - "The final factor driving run-speed is the quantity of data that is fitted. For every image-pixel that we fit,\n", - "we have to compute the light profile intensities and convolve them with the telescope's PSF. The larger that PSF is,\n", - "the more convolution operations we have to perform too.\n", - "\n", - "In the previous exercises, we used images with a pixel scale of 0.1\". This value is relatively low resolution: most\n", - "Hubble Space Telescope images have a pixel scale of 0.05\", which is four times the number of pixels! Some telescopes\n", - "observe at scales of 0.03\" or, dare I say it, 0.01\". At these resolutions things can *really* slow down, if we\n", - "do not think carefully about run speed beforehand.\n", - "\n", - "There are ways that we can reduce the number of image-pixels we fit, via masking. If we mask out more of the image,\n", - "we will fit fewer pixels and **PyAutoGalaxy** will run faster. If you want the best, most perfect model possible,\n", - "aggressive masking and cutting the data in this way is a bad idea, as discussed in tutorial 6.\n", - "\n", - "__Wrap Up__\n", - "\n", - "This tutorial simply wanted to get you thinking about *why* a model takes as long to fit as it does: the number\n", - "of likelihood evaluations the search performs, times the cost of each evaluation, with JAX's compiled likelihood\n", - "function (and a GPU, if you have one) driving the latter down as far as it will go.\n", - "\n", - "The remaining tutorials of this chapter attack the other half of the product: search chaining (tutorial 9) and prior\n", - "passing (tutorial 10) reduce the number of evaluations needed to fit complex models, laying the groundwork for the\n", - "pixelized reconstructions of chapter 3." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Google Colab Setup__\n", - "\n", - "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "jupyter": { - "source_hidden": true - } - }, - "outputs": [], - "source": [ - "# @title Set up Google Colab { display-mode: \"form\" }\n", - "try:\n", - " import google.colab\n", - "except ImportError:\n", - " from autogalaxy import setup_colab as _setup_colab\n", - "else:\n", - " import importlib\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.check_call(\n", - " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", - " )\n", - " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", - "\n", - "_setup_colab.setup(\"howtogalaxy\")" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autogalaxy import setup_notebook; setup_notebook()\n" - ], - "outputs": [], - "execution_count": null - } - ], - "metadata": { - "anaconda-cloud": {}, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - }, - "colab": { - "aiContexts": { - "24c2f562-da24-50bb-8eb9-5a887505fe54": { - "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", - "name": "PyAutoGalaxy assistant", - "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_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\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_2_modeling/tutorial_8_need_for_speed.ipynb in HowToGalaxy).\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 PyAutoGalaxy 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 PyAutoGalaxy docs (https://pyautogalaxy.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) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. 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 galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_run_search\n\n---\nname: ag_run_search\ndescription: Run the fit — take a composed model, an analysis and a configured search and drive `search.fit(model=model, analysis=analysis)` to completion, then read what it wrote. Covers the output-folder anatomy and the on-the-fly announcement, the unique-identifier resume behaviour and when it silently reuses a stale fit, `iterations_per_quick_update` and `live_visual_update`, JAX/GPU acceleration and when it actually pays, VRAM checks before a long GPU run, the `PYAUTO_TEST_MODE` smoke levels, and the `if __name__ == \"__main__\"` parallelisation fix. Use once `ag_build_imaging_model` and `ag_configure_search` have produced `model`, `analysis` and `search` objects, or when a fit is running and the user wants to know what to watch. Not for composing the model or choosing the search (those two skills), not for interpreting the finished posterior (`ag_load_results`), and not for diagnosing a fit that ran but converged somewhere unphysical (`ag_debug_fit_failure`).\n---\n\n# Running the fit\n\nThis is the moment the inference actually happens. Everything before it was preparation:\na `model` says which morphological parameters are free and what priors they carry, an\n`analysis` binds that model to one dataset and knows how to turn a parameter vector into a\nlog likelihood, and a `search` knows how to explore the parameter space. One call joins\nthem:\n\n```python\nresult = search.fit(model=model, analysis=analysis)\n```\n\nStatistically, that call is sampling (or optimising) the posterior\n$P(\\theta | d) \\propto \\mathcal{L}(d | \\theta) P(\\theta)$, where the likelihood is the\nGaussian-noise chi-squared of the PSF-convolved model image against the data — walked\nline by line in `autogalaxy_workspace:scripts/imaging/likelihood_function.py`. Scientifically,\nit is where a Sersic index, an effective radius or a bulge-to-total ratio stops being a guess\nand becomes a measurement with errors. What this skill adds is everything *around* the call:\nhow to watch it, how long to expect, how to make it fast, and how to prove the script works\nbefore committing hours to it.\n\nTwo wiki pages carry the background this skill assumes. Read\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md) for\nwhat each sampler does and how run time scales with the model, and\n[`wiki/core/api/analysis_objects.md`](../wiki/core/api/analysis_objects.md) for what the\nreturned `Result` contains.\n\n## Ask\n\nThree questions, and the answers change the branch:\n\n- *\"Do you already have `model`, `analysis` and `search`?\"* If not, route to\n [`ag_build_imaging_model`](./ag_build_imaging_model.md) and\n [`ag_configure_search`](./ag_configure_search.md) first. A fit assembled from a\n half-remembered model is the most expensive mistake available here.\n- *\"Smoke test first, or straight to the production run?\"* Almost always smoke test first —\n it takes seconds and answers \"does this script execute end to end?\", which is a different\n question from \"is this galaxy's Sersic index 3.2?\". The smoke branch is below.\n- *\"How long can this run, and on what?\"* A `MultiStartProdigy` fit is minutes; a `Nautilus`\n fit of a smooth model is tens of minutes on a GPU and can be hours on a CPU; a pixelised\n fit can be far longer. That answer decides foreground vs background, laptop vs cluster,\n and whether `live_visual_update` is worth switching on.\n\nIf the data is real observational imaging, the inspection gate in\n[`../AGENTS.md`](../AGENTS.md) applies before you get here at all — contaminants and mask\nextent are settled in [`ag_prepare_imaging_data`](./ag_prepare_imaging_data.md), not\nretrospectively.\n\n## Branch — the production run\n\nThe deliverable is one script in `scripts/` the user can re-run and edit. Adapted from\n`autogalaxy_workspace:scripts/imaging/start_here.py` (the fit and result sections) and\n`autogalaxy_workspace:scripts/imaging/modeling.py` (the Nautilus configuration and the VRAM\ncheck):\n\n```python\n\"\"\"\nGalaxy Structure: Run the Fit\n=============================\n\nFit a galaxy's surface-brightness profile to CCD imaging: load and mask the data, compose a\nlinear Sersic bulge, and sample the posterior with Nautilus so the inferred effective radius\nand Sersic index come with errors.\n\n__Contents__\n\n- **Imports:** JAX environment first, then the standard trio.\n- **Dataset:** Load imaging, mask it, and apply adaptive over-sampling.\n- **Model:** Compose the galaxy's light profile.\n- **Search:** Configure Nautilus and its update cadence.\n- **Analysis:** Bind the model to the data and choose the JAX backend.\n- **Model-Fit:** Run the search and announce the output folder.\n- **Result:** Read the best-fit model back.\n\"\"\"\nfrom autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\n\"\"\"\n__Dataset__\n\nGalaxy modeling needs three ingredients: the image in CCD counts, a per-pixel RMS noise-map,\nand the PSF. The PSF is forward-modelled rather than divided out, which is what separates a\ngenuinely compact bulge from a seeing-broadened one. `pixel_scales` converts pixels to\narcseconds and must match the instrument (`ag.Imaging.from_fits`,\n`PyAutoArray:autoarray/dataset/imaging/dataset.py`).\n\nThe mask sets which pixels enter the likelihood, and its radius is a science choice, not a\ndefault: truncate the outer isophotes and the effective radius and Sersic index are biased\ndirectly. Over-sampling evaluates the light profile several times per pixel where the\ngradient is steep, which matters most in the central few tenths of an arcsecond\n(`ag.util.over_sample.over_sample_size_via_radial_bins_from`).\n\"\"\"\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"\"\nMASK_RADIUS = 2.5\n\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n pixel_scales=0.1,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=MASK_RADIUS,\n)\n\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n\n\"\"\"\n__Model__\n\nA linear `Sersic` bulge: the `intensity` is solved by linear inversion each iteration rather\nthan sampled, so the search explores one fewer dimension per component for free\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Linear Light Profiles__`).\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model.info)\n\n\"\"\"\n__Search__\n\n`Nautilus` is nested sampling: it returns the full posterior — every parameter's density,\nits errors, and the correlations between them. `n_live` trades accuracy against run time and\n200 covers the vast majority of galaxy models. `unique_tag` is conventionally the dataset\nname, which is what keeps the same model fitted to different data in different folders\n(`PyAutoFit:autofit/non_linear/search/nest/nautilus/search.py`).\n\"\"\"\nsearch = af.Nautilus(\n path_prefix=Path(\"imaging\"),\n name=\"sersic\",\n unique_tag=\"\",\n n_live=200,\n iterations_per_quick_update=10000,\n live_visual_update=False,\n)\n\n\"\"\"\n__Analysis__\n\n`ag.AnalysisImaging` defines the `log_likelihood_function` the search calls, and defaults to\n`use_jax=True` when JAX is installed (`PyAutoGalaxy:autogalaxy/imaging/model/analysis.py`).\n\"\"\"\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\n\"\"\"\n__Model-Fit__\n\nResults are written to the output folder on the fly, from the best model found so far, so the\nfolder is worth opening the moment the search starts.\n\"\"\"\nprint(f\"Output folder: {search.paths.output_path.resolve()}\")\n\nresult = search.fit(model=model, analysis=analysis)\n\n\"\"\"\n__Result__\n\"\"\"\nprint(result.info)\nprint(result.max_log_likelihood_instance)\n```\n\nRun it with writable caches if the default locations are not writable — a sandbox, CI, or an\ninstall imported from a Windows mount under WSL\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)):\n\n```bash\nNUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/run_fit.py\n```\n\n`search.fit` itself is `PyAutoFit:autofit/non_linear/search/abstract_search.py`.\n\n## Branch — what the output folder contains, and when to look\n\n**Announce the folder at launch, not at the end.** Quote\n`search.paths.output_path.resolve()` once the fit is running and say plainly that\n`model.results` and `image/fit.png` refresh as the search goes — there is nothing to wait\nfor. Users new to the stack sit watching a silent terminal because nobody told them.\n\nThe annotated tree of `files/`, `image/`, `model.info`, `model.results`, `search.summary`\nand the `` folder is `__Output Folder Layout__` in\n[`autogalaxy_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/modeling.py);\nthe same section appears in the `interferometer`, `multi_dataset`, `multi_galaxy` and\n`cluster` `modeling.py` scripts. Link it rather than copying the tree into the conversation,\nwhere it would rot. The condensed version is also in\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md)\n\"The output folder\".\n\nName what to open first, in this order:\n\n1. `model.results` — the human-readable fit summary, parameters with errors.\n2. `image/fit.png` — data, model image, residuals and chi-squared map in one figure.\n3. `search.log` — tail it if you want to watch progress from a terminal.\n\nDepth follows [`_style.md`](./_style.md) \"Adaptive depth\": for a newcomer, or in teacher\nmode, walk all three. For a returning user, quoting the path is enough.\n\n## Branch — resuming, and the trap inside it\n\n`` is derived from the model, the search settings and the dataset identifier, so\nre-running an identical configuration **resumes** the existing fit rather than restarting it\n(`autogalaxy_workspace:scripts/imaging/modeling.py` `__Unique Identifier__`). That is a\nfeature — an interrupted overnight run picks up where it stopped.\n\nIt is also the sharpest edge in the workflow. **The identifier does not hash the pixel\nvalues of your data.** Swap `data.fits` for a different galaxy, keep the model, the search\nand the `unique_tag` identical, and the next run finds a completed fit at the same path and\nreturns it — silently, in seconds, with the previous galaxy's parameters. If the data\nchanges, change the `unique_tag`. If you are unsure whether a result is stale, delete the\n`` folder and re-run rather than reasoning about it.\n\nTest mode namespaces its output separately: any active `PYAUTO_TEST_MODE` level inserts a\n`test_mode` segment straight after the output root, so a smoke run lands in\n`output/test_mode//...` and cannot short-circuit a later real fit\n([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)).\n\n## Branch — the update cadence and the live view\n\nTwo settings control what you see while the fit runs, both on the search\n(`PyAutoFit:autofit/non_linear/search/abstract_search.py`):\n\n- **`iterations_per_quick_update`** — how often the current best model is visualised and\n written to disk. The unit depends on the search: likelihood evaluations for `Nautilus`\n (hence the large `10000` in `modeling.py`), gradient steps for `MultiStartProdigy` (hence\n the much smaller `50` in `start_here.py`). Each update costs roughly ten seconds, so too\n low a value and output dominates the run time; too high and you cannot see progress. If\n the log is constantly reporting that it is outputting results, raise it.\n- **`live_visual_update`** — additionally push the quick-update image to a live surface: a\n matplotlib window that refreshes in a plain script, or a self-updating cell in Jupyter and\n Colab. The `fit.png` disk write happens either way. Leave it `False` on anything headless\n — an HPC node, a background process, CI.\n\nIf the search configuration already records the choice, don't re-ask; that decision belongs\nto [`ag_configure_search`](./ag_configure_search.md).\n\n## Branch — JAX, GPUs, and when the acceleration pays\n\nImaging fits run through JAX by default. Installing the extra (`pip install autogalaxy[jax]`)\nis all that is required: `ag.AnalysisImaging` then defaults to `use_jax=True`, and the search\ndriver wraps the likelihood in `jax.vmap(jax.jit(...))` so a whole batch of parameter vectors\nevaluates in one call. You will see a one-time log line as the JIT compile starts; every\nevaluation after that re-uses the compiled trace. This is described in\n`autogalaxy_workspace:scripts/guides/using_jax.py` `__Auto-Enabled Modeling__`, and if JAX is\nabsent the analysis warns once and falls back to NumPy.\n\n**When it pays.** The gain scales with how much array work each likelihood evaluation does,\nso it is largest for big masks, fine over-sampling, many-component bases and pixelised\nreconstructions, and smallest for a tiny mask with one smooth profile. GPU gains dwarf CPU\ngains: `autogalaxy_workspace:scripts/imaging/modeling.py` `__JAX__` quotes roughly ten\nminutes on a GPU against an hour on a CPU for its example, with a CPU still gaining from\nmultithreading. Gradient-based searches like `MultiStartProdigy` are not merely faster under\nJAX — they are only possible with it, because JAX is what supplies the likelihood's\nderivatives and evaluates all the parallel starts in one batched call\n(`autogalaxy_workspace:scripts/imaging/start_here.py` `__Multi Start Gradient Optimization__`).\n\n**Check VRAM before a long GPU run.** A JAX fit must fit inside the GPU's memory, and it\nfails at JIT-compile time or on the first likelihood call if it does not:\n\n```python\nanalysis.print_vram_use(model=model, batch_size=search.batch_size)\n```\n\nAdapted from `autogalaxy_workspace:scripts/imaging/modeling.py` `__VRAM Use__`. It takes\ntwenty or thirty seconds, so comment it out once you know your model's footprint. Batch size\nis the lever: larger batches cut wall-clock time and raise VRAM, smaller batches the reverse.\nA smooth-profile fit on a modest dataset is tens of megabytes; a pixelised reconstruction on\nhigh-resolution data can exceed ten gigabytes.\n\n**Turn JAX off to debug.** `ag.AnalysisImaging(dataset=dataset, use_jax=False)`, or\n`PYAUTO_DISABLE_JAX=1` to force it globally without editing code. NumPy stack traces are far\neasier to read, and you can drop a debugger or a `print` into code JAX would otherwise\ncompile. That is the first lever to pull when deciding whether a failure is a JAX problem at\nall — see [`ag_debug_fit_failure`](./ag_debug_fit_failure.md).\n\nFor running on a cluster — SLURM array jobs, one galaxy per task, the CPU and GPU batch\nscripts, and `number_of_cores` read from `SLURM_CPUS_PER_TASK` — read\n[`../wiki/core/operations/hpc.md`](../wiki/core/operations/hpc.md) for the concepts and\n[`../wiki/core/operations/hpc_infrastructure.md`](../wiki/core/operations/hpc_infrastructure.md)\nfor the `hpc/` templates and `sync` CLI this repo ships; the upstream ground truth behind both\nis `autogalaxy_workspace:scripts/guides/hpc/example_cpu_and_gpu.py`. The Python modeling code\nis identical for a GPU run; only the batch script changes.\n\n## Branch — the smoke test, before you spend hours\n\nEvery script gets one fast structural run before a real one. `PYAUTO_TEST_MODE` has four\nlevels ([`wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md)), and the\nchoice between them matters more than it looks:\n\n```bash\n# Level 1 — sampler runs with minimal iterations. A real (tiny) search: writes\n# model.results, image/fit.png and a samples.csv you can load back.\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n\n# Level 2 — sampler bypassed, likelihood called exactly once. The fastest proof that\n# the model composes and the likelihood evaluates.\nPYAUTO_TEST_MODE=2 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/run_fit.py\n```\n\n**Level 2 does not write the fit products.** A level-2 run returns a `Result`, proving the\nwiring, but leaves no `model.results` and no `image/fit.png` behind — so if the next thing\nyou want to do is plot or load the fit, use level 1. Level 3 skips the likelihood call as\nwell, which is only useful for checking that a script's non-fitting scaffolding runs.\n\n**The parameter values from any test-mode run are meaningless.** The sampler was truncated or\nmocked. Never quote a structural parameter measured in test mode; say explicitly that the\nnumber is a wiring check.\n\nFor the fastest possible loop, combine test mode with the dataset and output short-circuits:\n\n```bash\nPYAUTO_TEST_MODE=2 PYAUTO_SKIP_FIT_OUTPUT=1 PYAUTO_SKIP_VISUALIZATION=1 \\\n PYAUTO_SMALL_DATASETS=1 PYAUTO_FAST_PLOTS=1 python scripts/run_fit.py\n```\n\n`PYAUTO_SMALL_DATASETS=1` caps every array, mask and grid to 16 × 16 pixels — so delete any\npreviously simulated `dataset/` when you toggle it, or a full-resolution dataset on disk will\nbe reused and mismatch the capped grids.\n\n## Branch — the error that appears the moment the search starts\n\nOn some combinations of operating system and Python version, a script raises as soon as the\nsearch begins, from Python's process spawning rather than from anything about your model. The\nfix is to wrap the whole fit in a function and call it under a main guard:\n\n```python\ndef fit():\n from autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\n import autofit as af\n import autogalaxy as ag\n\n # ... dataset, model, search, analysis as above ...\n result = search.fit(model=model, analysis=analysis)\n\n\nif __name__ == \"__main__\":\n fit()\n```\n\nAdapted from `autogalaxy_workspace:scripts/guides/modeling/bug_fix.py`, which is the same\n`modeling.py` fit with this one structural change. It works for every dataset type, so adopt\nit for any modeling script that hits the error. If parallelisation still will not work after\nthe fix, that script points at the project's support channel.\n\n## Combine\n\n- [`ag_plot_fit`](./ag_plot_fit.md) — render the fit yourself, at whatever scaling and\n cropping the science needs, rather than reading the auto-generated `image/fit.png`.\n- [`ag_load_results`](./ag_load_results.md) — pull the posterior, the best-fit galaxies and\n the derived quantities back into Python, in-session or from disk later.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) — the fit finished but the residuals or\n the parameters are wrong.\n- [`ag_configure_search`](./ag_configure_search.md) — the fit is too slow, or the sampler is\n the wrong one for the model.\n- [`ag_simulate_dataset`](./ag_simulate_dataset.md) — build a controlled dataset with known\n truth and fit that first, which is the cleanest way to separate a model problem from a\n data problem.\n\nWhen the script and its fit are worth keeping, offer (default-yes) to record the run in a\ndated `wiki/project/YYYY-MM-DD-.md` entry: the science question, what was inferred and\nwith what search, and the output path — per [`_style.md`](./_style.md) property #5.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Practicalities](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb):\n the practical side of running a fit — output structure, reviewing results as they appear,\n and managing run times.\n- **General reference** — [RTD: New user guide](https://pyautogalaxy.readthedocs.io/en/latest/overview/overview_2_new_user_guide.html):\n the decision tree for which fit to run first, by system scale and dataset type.\n- **Experienced PyAutoGalaxy user** — [workspace: imaging/start_here.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/imaging/start_here.py):\n the minimal end-to-end imaging fit, with the JAX and quick-update sections this skill\n mirrors.\n\n## Agent procedural checklist\n\n1. Confirm `model`, `analysis` and `search` exist; if not, route to the model-building and\n search-configuration skills.\n2. On real observational data, confirm the inspection gate has been satisfied.\n3. Write the script to `scripts/` in the generated-script style; never leave it inline only.\n4. Validate it with `PYAUTO_TEST_MODE=1` (level 2 if you only need the likelihood proved),\n with the cache variables set if the environment needs them.\n5. Launch the production run; **quote the absolute output path immediately** and say results\n refresh on the fly.\n6. Name `model.results` and `image/fit.png` as the first two things to open.\n7. If the data changed but the model did not, confirm the `unique_tag` changed too.\n8. On a GPU, run the VRAM check before a long fit.\n9. On completion, hand off to the results-loading or fit-plotting skill rather than\n interpreting the numbers inline.\n10. Offer the `wiki/project/` entry.\n" - } - }, - "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file diff --git a/notebooks/chapter_2_modeling/tutorial_9_search_chaining.ipynb b/notebooks/chapter_2_modeling/tutorial_9_search_chaining.ipynb deleted file mode 100644 index 0af3807..0000000 --- a/notebooks/chapter_2_modeling/tutorial_9_search_chaining.ipynb +++ /dev/null @@ -1,624 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Tutorial 9: Search Chaining\n", - "===========================\n", - "\n", - "Throughout this chapter, we have fitted the data using just one non-linear search. The previous tutorial discussed\n", - "the run-time cost of doing this: with a single search, the dimensionality of the model, the priors on its parameters\n", - "and the search settings must all be juggled at once, leaving us little flexibility to trade them off against one\n", - "another.\n", - "\n", - "In this closing part of the chapter, we introduce a technique called 'non-linear search chaining', which fits a\n", - "model using a sequence of non-linear searches. The initial searches fit simpler models whose parameter spaces can\n", - "be more accurately and efficiently sampled. The results of this search are then passed to later searches which fit\n", - "models of gradually increasing complexity.\n", - "\n", - "Lets think back to tutorial 4 of this chapter. We learnt there were three approaches one could take fitting a model\n", - "accurately if we found that a model fit failed. These were:\n", - "\n", - " 1) Tuning our priors to the galaxy we're fitting.\n", - " 2) Making our model less complex.\n", - " 3) Searching non-linear parameter space for longer.\n", - "\n", - "However, each of the above approaches has disadvantages. The more we tune our priors, the less we can generalize our\n", - "analysis to a different galaxy. The less complex we make our model, the less realistic it is. And if we rely too\n", - "much on searching parameter space for longer, we could end up with search`s that take days, weeks or months to run.\n", - "\n", - "In this tutorial, we are going to show how search chaining combines these 3 approaches such that we can fit\n", - "complex and realistic models in a way that can be generalized to many different galaxies. To do this,\n", - "we'll run 2 searches, and chain the model inferred in the first search to the priors of the second search`s\n", - "model.\n", - "\n", - "Our first search will make the same bulge-disk alignment assumption we made in tutorial 4 of this chapter. We saw\n", - "that this gives a reasonable model. However, we'll make a couple of extra simplifying assumptions, to really try and\n", - "bring our model complexity down and get the non-linear search running fast.\n", - "\n", - "The model we infer above will therefore be a lot less realistic. But it does not matter, because in the second search\n", - "we are going to relax these assumptions and fit the more realistic model. The beauty is that, by running the first\n", - "search, we can use its results to tune the priors of our second search. For example:\n", - "\n", - " 1) The first search should give us a pretty good idea of the galaxy's bulge and disk profiles, for example its\n", - " centre, ellipticity and effective radius.\n", - "\n", - "__Contents__\n", - "\n", - "- **Initial Setup:** Load the dataset and apply a mask.\n", - "- **Dataset Auto-Simulation:** Simulate the dataset via its simulator script if it is not on your hard-disk.\n", - "- **Model:** Compose a simplified model for the first search with aligned bulge-disk assumptions.\n", - "- **Search + Analysis:** Run the first search with the simplified model.\n", - "- **Result:** Inspect the result of the first search.\n", - "- **Prior Passing:** Manually pass results from search 1 as priors for search 2.\n", - "- **Result:** Inspect the final result of the chained search.\n", - "- **Wrap Up:** Summary of how search chaining improves model-fitting reliability." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Google Colab Setup__\n", - "\n", - "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "jupyter": { - "source_hidden": true - } - }, - "outputs": [], - "source": [ - "# @title Set up Google Colab { display-mode: \"form\" }\n", - "try:\n", - " import google.colab\n", - "except ImportError:\n", - " from autogalaxy import setup_colab as _setup_colab\n", - "else:\n", - " import importlib\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.check_call(\n", - " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", - " )\n", - " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", - "\n", - "_setup_colab.setup(\"howtogalaxy\")" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "\n", - "from autogalaxy import setup_notebook; setup_notebook()\n", - "\n", - "import numpy as np\n", - "from pathlib import Path\n", - "import autogalaxy as ag\n", - "import autogalaxy.plot as aplt\n", - "import autofit as af" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Initial Setup__\n", - "\n", - "we'll use the same galaxy data as tutorial 4 of this chapter, where:\n", - "\n", - " - The galaxy's bulge is a `Sersic`.\n", - " - The galaxy's disk is an `Exponential`." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "dataset_name = \"simple\"\n", - "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Dataset Auto-Simulation__\n", - "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "if ag.util.dataset.should_simulate(str(dataset_path)):\n", - " import subprocess\n", - " import sys\n", - "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulators/simple.py\"],\n", - " check=True,\n", - " )\n", - "\n", - "\n", - "dataset = ag.Imaging.from_fits(\n", - " data_path=dataset_path / \"data.fits\",\n", - " noise_map_path=dataset_path / \"noise_map.fits\",\n", - " psf_path=dataset_path / \"psf.fits\",\n", - " pixel_scales=0.1,\n", - ")\n", - "\n", - "mask = ag.Mask2D.circular(\n", - " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5\n", - ")\n", - "\n", - "dataset = dataset.apply_mask(mask=mask)\n", - "\n", - "over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n", - " grid=dataset.grid,\n", - " sub_size_list=[8, 4, 2],\n", - " radial_list=[0.3, 0.6],\n", - " centre_list=[(0.0, 0.0)],\n", - ")\n", - "\n", - "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n", - "\n", - "aplt.subplot_imaging_dataset(dataset=dataset)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Model__\n", - "\n", - "As we've eluded to before, one can look at an image and immediately identify the centre of the galaxy. It's \n", - "that bright blob of light in the middle! Given that we know we're going to make the model more complex in the \n", - "next search, lets take a more liberal approach than before and fix the centre of the bulge and \n", - "disk to $(y,x)$ = (0.0\", 0.0\")..\n", - "\n", - "Now, you might be thinking, doesn`t this prevent our search from generalizing to other galaxies? What if the \n", - "centre of their galaxy isn't at (0.0\", 0.0\")?\n", - "\n", - "Well, this is true if our dataset reduction centres the galaxy somewhere else. But we get to choose where we \n", - "centre it when we make the image. Therefore, I`d recommend you always centre the galaxy at the same location, \n", - "and (0.0\", 0.0\") seems the best choice!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge = af.Model(ag.lp_linear.Sersic)\n", - "disk = af.Model(ag.lp_linear.Exponential)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You haven't actually seen a line like this one before. By setting a parameter to a number (and not a prior) it is be \n", - "removed from non-linear parameter space and always fixed to that value. Pretty neat, huh?" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge.centre_0 = 0.0\n", - "bulge.centre_1 = 0.0\n", - "disk.centre_0 = 0.0\n", - "disk.centre_1 = 0.0" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Lets also use the same approach as tutorial 4 of this chapter and align the ellipticity of the bulge and disk,\n", - "removing another two parameters from the model." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "disk.ell_comps = bulge.ell_comps" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We also know that the bulges of many galaxies are well described by a Sersic index of around 4 (a de Vaucouleurs\n", - "profile). Lets fix it to 4 this time." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge.sersic_index = 4.0\n", - "\n", - "galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n", - "\n", - "model_1 = af.Collection(galaxies=af.Collection(galaxy=galaxy))" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `info` attribute shows the model in a readable format." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(model_1.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Search + Analysis__\n", - "\n", - "Now lets create the search and analysis." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search_1 = af.Nautilus(\n", - " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", - " name=\"tutorial_9_search_chaining_1\",\n", - " unique_tag=dataset_name,\n", - " n_live=100,\n", - " n_batch=50, # GPU batching and VRAM use explained in tutorial 2 of this chapter.\n", - ")\n", - "\n", - "analysis_1 = ag.AnalysisImaging(dataset=dataset, use_jax=True)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Lets run the search, noting that our liberal approach to reducing the model complexity has reduced it to just\n", - "4 parameters." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(\n", - " \"The non-linear search has begun running - checkout the output/howtogalaxy/chapter_2\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell will progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", - "result_1 = search_1.fit(model=model_1, analysis=analysis_1)\n", - "\n", - "print(\"Search has finished run - you may now continue the notebook.\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Result__\n", - "\n", - "The results are summarised in the `info` attribute." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result_1.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And indeed, we get a reasonably good model and fit to the data, in a much shorter space of time!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_fit_imaging(fit=result_1.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Prior Passing__\n", - "\n", - "Now all we need to do is look at the results of search 1 and pass the results as priors for search 2. Lets setup \n", - "a custom search that does exactly that.\n", - "\n", - "`TruncatedGaussianPrior`'s are a nice way to pass priors. They tell the non-linear search where to look, but leave open the \n", - "possibility that there might be a better solution nearby. In contrast, `UniformPrior`'s put hard limits on what values a \n", - "parameter can or can`t take. It makes it more likely we will accidentally cut-out the global maxima solution.\n", - "\n", - "Note that below the `disk` has become a `Sersic`." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge = af.Model(ag.lp_linear.Sersic)\n", - "disk = af.Model(ag.lp_linear.Sersic)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "What I've done below is looked at the results of search 1 and manually specified a prior for every parameter. If a \n", - "parameter was fixed in the previous search, its prior is based around the previous value. Don't worry about the sigma \n", - "values for now, I've chosen values that I know will ensure reasonable sampling, but we'll cover this later.\n", - "\n", - "__BULGE PRIORS:__" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "bulge.centre.centre_0 = af.TruncatedGaussianPrior(\n", - " mean=0.0, sigma=0.1, lower_limit=-np.inf, upper_limit=np.inf\n", - ")\n", - "bulge.centre.centre_1 = af.TruncatedGaussianPrior(\n", - " mean=0.0, sigma=0.1, lower_limit=-np.inf, upper_limit=np.inf\n", - ")\n", - "bulge.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior(\n", - " mean=0.11, sigma=0.2, lower_limit=-1.0, upper_limit=1.0\n", - ")\n", - "bulge.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior(\n", - " mean=0.05, sigma=0.2, lower_limit=-1.0, upper_limit=1.0\n", - ")\n", - "bulge.effective_radius = af.TruncatedGaussianPrior(\n", - " mean=0.75, sigma=0.4, lower_limit=0.0, upper_limit=np.inf\n", - ")\n", - "bulge.sersic_index = af.TruncatedGaussianPrior(\n", - " mean=4.0, sigma=2.0, lower_limit=0.0, upper_limit=np.inf\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__DISK PRIORS:__" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "disk.centre.centre_0 = af.TruncatedGaussianPrior(\n", - " mean=0.0, sigma=0.1, lower_limit=-np.inf, upper_limit=np.inf\n", - ")\n", - "disk.centre.centre_1 = af.TruncatedGaussianPrior(\n", - " mean=0.0, sigma=0.1, lower_limit=-np.inf, upper_limit=np.inf\n", - ")\n", - "disk.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior(\n", - " mean=0.11, sigma=0.2, lower_limit=-1.0, upper_limit=1.0\n", - ")\n", - "disk.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior(\n", - " mean=0.05, sigma=0.2, lower_limit=-1.0, upper_limit=1.0\n", - ")\n", - "disk.effective_radius = af.TruncatedGaussianPrior(\n", - " mean=1.52, sigma=0.4, lower_limit=0.0, upper_limit=np.inf\n", - ")\n", - "disk.sersic_index = af.TruncatedGaussianPrior(\n", - " mean=1.0, sigma=2.0, lower_limit=0.0, upper_limit=np.inf\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We now compose the model with these components that have had their priors customized. " - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n", - "\n", - "model_2 = af.Collection(galaxies=af.Collection(galaxy=galaxy))" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The `info` attribute shows the model, including the priors specified above." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(model_2.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Lets setup and run the search. As expected, it gives us the correct model. However, it does so significantly \n", - "faster than we are used to!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "search_2 = af.Nautilus(\n", - " path_prefix=Path(\"howtogalaxy\", \"chapter_2\"),\n", - " name=\"tutorial_9_search_chaining_2\",\n", - " unique_tag=dataset_name,\n", - " n_live=100,\n", - " n_batch=50, # GPU batching and VRAM use explained in tutorial 2 of this chapter.\n", - ")\n", - "\n", - "analysis_2 = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", - "\n", - "print(\n", - " \"The non-linear search has begun running - checkout the output/howtogalaxy/chapter_2\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell will progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", - "result_2 = search_2.fit(model=model_2, analysis=analysis_2)\n", - "\n", - "print(\"Search has finished run - you may now continue the notebook.\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Result__\n", - "\n", - "We can again inspect the results via the `info` attribute." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(result_2.info)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And a plot of the image shows we get a good model again!" - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_fit_imaging(fit=result_2.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Wrap Up__\n", - "\n", - "Chaining two searches together was a huge success. We managed to fit a complex and realistic model, but were able to \n", - "begin by making simplifying assumptions that eased our search of non-linear parameter space. We could apply search 1 to \n", - "pretty much any galaxy and therefore get ourselves a decent model with which to tune search 2`s priors.\n", - "\n", - "You are probably thinking though that there is one huge, giant, glaring flaw in all of this that I've not mentioned. \n", - "Search 2 can`t be generalized to another galaxy, because its priors are tuned to the image we fitted. If we had a lot\n", - "of galaxies, we`d have to write a new search for every single one. This isn't ideal, is it?\n", - "\n", - "Fortunately, we can pass priors in **PyAutoGalaxy** without specifying the specific values. The API for this technique,\n", - "called prior passing, is the topic of the next tutorial." - ] - } - ], - "metadata": { - "anaconda-cloud": {}, - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.1" - }, - "colab": { - "aiContexts": { - "24c2f562-da24-50bb-8eb9-5a887505fe54": { - "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", - "name": "PyAutoGalaxy assistant", - "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_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\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_2_modeling/tutorial_9_search_chaining.ipynb in HowToGalaxy).\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 PyAutoGalaxy 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 PyAutoGalaxy docs (https://pyautogalaxy.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) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. 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 galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_chain_searches\n\n---\nname: ag_chain_searches\ndescription: Break one hard fit into a sequence of easier non-linear searches, using each result to initialize the next. Covers when chaining beats a single search and when it does not, passing a whole profile or galaxy with `result.model` (which preserves the original priors) versus narrowing them with `result.model_centred` and its absolute, relative and bounded variants, the `TruncatedGaussianPrior` those produce and where its sigma comes from in the `priors` config `width_modifier`, fixing a component with `result.instance` to remove its dimensions, and the output-path convention that keeps a chain's searches together. Use when a model is too complex for one search, when an early search should use cheap settings and a later one accurate ones, or when several galaxies must be added one at a time. Not for choosing a single search (`ag_configure_search`), not for driving one fit (`ag_run_search`), and not for combining several datasets (`ag_multi_dataset`).\n---\n\n# Chaining searches\n\nEvery other modelling skill in this workspace composes one model and hands it to one search.\nChaining is the alternative shape: split the problem into a sequence of searches, and use what\neach one learned to tell the next where to look.\n\nThe reason is statistical, not cosmetic. A non-linear search has to map a parameter space it knows\nnothing about, and the cost of doing that grows sharply with dimensionality while the risk of\nsettling in a local maximum grows with multi-modality. A galaxy model with a bulge, a disk, a sky\nlevel and two blended neighbours has both problems at once. Fit the bulge alone and the space is\nsmall, unimodal and mapped in minutes; then the disk only has to be added to a galaxy whose size\nand centre are already known. Each search in a chain solves a problem that is easy *because* of\nthe one before it.\n\nThree distinct benefits, and they are worth separating because they justify chaining in different\nsituations:\n\n- **Lower dimensionality per search.** Earlier searches fit simpler models with a parameter space\n that can be sampled properly, which reduces the chance of an incorrect local maximum in the\n final one.\n- **Cheap settings early, accurate settings late.** An early search only needs to find the high-\n likelihood region, so it can use a fast optimizer or a small `n_live`. Only the final search\n needs settings good enough to quantify errors.\n- **Cheap approximations early.** An early search can use a smaller mask, coarser over-sampling\n or a simplified component, and revert to the accurate-but-expensive settings at the end. The\n approximation costs some fidelity in the early result, which is fine when that result is only\n being used to place a prior.\n\nThis skill has **one** grounding script: `autogalaxy_workspace:scripts/guides/modeling/chaining.py`.\nIt is deliberately an API overview rather than a library of pipelines, and this skill is scoped to\nmatch it — the mechanics of prior passing, done honestly, rather than a catalogue of recipes that\ndo not exist upstream. The end of chapter 2 of the HowToGalaxy lecture series (tutorials 9-10) is where the pedagogy lives.\nRead [`../wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md) for\nhow run time scales with the model, which is the quantity chaining exists to manage.\n\n## Ask\n\n- *\"What makes this fit hard — too many parameters, or a search that keeps landing somewhere\n wrong?\"* Both are chaining's territory, but they suggest different splits: dimensionality\n suggests adding components one at a time, multi-modality suggests fixing the thing the search\n keeps getting wrong.\n- *\"What would you fit first if you had to pick one component?\"* Usually the brightest and\n simplest. If the user cannot name one, chaining may not be the right tool — see the branch on\n when not to chain.\n- *\"Is a single search actually failing, or just slow?\"* A slow-but-correct search is often better\n served by a faster sampler or JAX than by a chain, because a chain adds a whole class of\n failure: a wrong early result confidently narrowing a later prior.\n\n## Branch — the two-search chain\n\nThe deliverable is one script containing the whole chain, so it can be re-run end to end. Adapted\nfrom `autogalaxy_workspace:scripts/guides/modeling/chaining.py`.\n\n```python\n\"\"\"\nGalaxy Structure: Chained Searches\n=================================\n\nFit a galaxy's bulge alone, then add a disk with the bulge's parameters initialized from the\nfirst fit. Splitting the fit this way lets each search sample a parameter space it can actually\nmap, and makes the two-component decomposition a refinement of a known galaxy rather than a\nfourteen-dimensional search from broad priors.\n\n__Contents__\n\n- **Imports:** JAX environment first, then the standard trio.\n- **Dataset:** Load, mask and over-sample the imaging once, for every search.\n- **Paths:** One output prefix shared by every search in the chain.\n- **Model (Search 1):** A single linear Sersic bulge.\n- **Model-Fit (Search 1):** Fit it, cheaply.\n- **Model Chaining:** Pass the bulge into search 2 and add a disk.\n- **Model-Fit (Search 2):** Fit the two-component model with accurate settings.\n- **Result:** Read the final model back.\n\"\"\"\nfrom autogalaxy import jax_wrapper # Sets the JAX environment before other imports\n\nfrom pathlib import Path\n\nimport autofit as af\nimport autogalaxy as ag\nimport autogalaxy.plot as aplt\n\n\"\"\"\n__Dataset__\n\nLoaded, masked and over-sampled once. Every search in the chain shares one `analysis`, which is\nwhat makes their likelihoods comparable — if search 2 used a different mask, its log likelihood\nwould not be on the same scale as search 1's, and the priors passed between them would refer to a\ndifferent dataset.\n\"\"\"\nDATASET_PATH = Path(\"dataset\") / \"imaging\" / \"\"\n\ndataset = ag.Imaging.from_fits(\n data_path=DATASET_PATH / \"data.fits\",\n noise_map_path=DATASET_PATH / \"noise_map.fits\",\n psf_path=DATASET_PATH / \"psf.fits\",\n pixel_scales=0.1,\n)\n\nmask = ag.Mask2D.circular(\n shape_native=dataset.shape_native,\n pixel_scales=dataset.pixel_scales,\n radius=3.0,\n)\n\ndataset = dataset.apply_mask(mask=mask)\n\nover_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n grid=dataset.grid,\n sub_size_list=[8, 4, 2],\n radial_list=[0.3, 0.6],\n centre_list=[(0.0, 0.0)],\n)\n\ndataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n\nanalysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n\n\"\"\"\n__Paths__\n\nOne `path_prefix` for the whole chain, with each search distinguished only by `name`. This keeps\nevery stage of one chain in one directory tree, which matters when you come back to a fit and\nneed to see what search 1 actually inferred before trusting search 2.\n\"\"\"\npath_prefix = Path(\"imaging\") / \"chaining\" / \"\"\n\n\"\"\"\n__Model (Search 1)__\n\nThe bulge alone. A linear `Sersic` solves its own `intensity`, so this is a compact space the\nsearch can map quickly (`PyAutoGalaxy:autogalaxy/profiles/light/linear/sersic.py`).\n\"\"\"\nbulge = af.Model(ag.lp_linear.Sersic)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n\nmodel_1 = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model_1.info)\n\n\"\"\"\n__Model-Fit (Search 1)__\n\nCheap settings on purpose: this search only has to find the high-likelihood region, not measure\nerrors. Inspect its result before relying on it — a chain built on a bad first search propagates\nthat error into every subsequent prior, with more confidence at every step.\n\"\"\"\nsearch_1 = af.Nautilus(\n path_prefix=path_prefix,\n name=\"search[1]__bulge\",\n unique_tag=\"\",\n n_live=100,\n)\n\nresult_1 = search_1.fit(model=model_1, analysis=analysis)\n\nprint(result_1.info)\n\n\"\"\"\n__Model Chaining__\n\n`result_1.model_centred` returns the search-1 model with every free parameter replaced by a\n`TruncatedGaussianPrior` centred on that parameter's median from search 1\n(`PyAutoFit:autofit/non_linear/result.py`,\n`PyAutoFit:autofit/mapper/prior/truncated_gaussian.py`). Search 2 therefore starts sampling in\nthe region search 1 found, rather than from broad priors.\n\nNote the attribute: `result_1.model` passes the component through with its **original** priors\nunchanged, which is useful when you want the structure of a previous model but not its\nconstraints. `model_centred` is the one that narrows.\n\"\"\"\nbulge = result_1.model_centred.galaxies.galaxy.bulge\ndisk = af.Model(ag.lp_linear.Exponential)\n\ngalaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk)\n\nmodel_2 = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n\nprint(model_2.info)\n\n\"\"\"\n__Model-Fit (Search 2)__\n\nThe accurate search. Read search 2's `model.info` in the output folder to confirm the priors\narrived as intended before trusting the result.\n\"\"\"\nsearch_2 = af.Nautilus(\n path_prefix=path_prefix,\n name=\"search[2]__bulge_disk\",\n unique_tag=\"\",\n n_live=150,\n)\n\nresult_2 = search_2.fit(model=model_2, analysis=analysis)\n\n\"\"\"\n__Result__\n\"\"\"\nprint(result_2.info)\n\nPLOT_DIR = Path(\"scripts\") / \"scratch\" / \"\" / \"chained\"\n\naplt.subplot_fit_imaging(\n fit=result_2.max_log_likelihood_fit,\n output_path=str(PLOT_DIR),\n output_format=\"png\",\n)\n\nprint(f\"Saved to: {PLOT_DIR.resolve()}\")\n```\n\nWhole components pass, not just single parameters: `result_1.model_centred.galaxies.galaxy.bulge`\ncarries every one of the bulge's parameters across in one expression, provided the component's\n*type* has not changed. A single parameter passes the same way —\n`galaxy.bulge.effective_radius = result_1.model_centred.galaxies.galaxy.bulge.effective_radius` —\nwhich is how you narrow some parameters and leave others broad.\n\n## Branch — `model`, `model_centred`, and `instance`\n\nThis is the part to get right, and the distinction is sharper than the workspace script's prose\nsuggests. Three attributes on a `Result`, three different things:\n\n**`result.model`** — the same model with the **same priors it had before**. On the released stack\nthis attribute preserves the priors rather than narrowing them\n(`PyAutoFit:autofit/non_linear/result.py`), so a component passed this way brings its structure\nacross but no information from the fit. That is occasionally exactly what you want — reuse the\ncomposition, refit from scratch — but it is *not* prior passing, and reading the workspace\nscript's older description of it as producing narrowed Gaussians will mislead you. Check what you\nactually got:\n\n```python\nprint(type(model_2.galaxies.galaxy.bulge.sersic_index).__name__)\n```\n\n**`result.model_centred`** — the narrowing one. Every free parameter becomes a\n`TruncatedGaussianPrior` whose `mean` is that parameter's median from the previous search and whose\n`sigma` comes from the parameter's `width_modifier` in the `priors` config. Three further variants\nlet you override that width:\n\n| Attribute | Prior produced | `sigma` |\n|---|---|---|\n| `result.model_centred` | `TruncatedGaussianPrior` | from the parameter's config `width_modifier` |\n| `result.model_centred_absolute(a=0.1)` | `TruncatedGaussianPrior` | exactly `a`, for every parameter |\n| `result.model_centred_relative(r=0.2)` | `TruncatedGaussianPrior` | `r × mean`, per parameter |\n| `result.model_centred_max_lh_bounded(b=0.3)` | `UniformPrior` | bounds at `mean ± b` |\n\n**`result.instance`** — the maximum-likelihood *values*, as fixed numbers. A component passed this\nway has no free parameters at all, so search 2's dimensionality drops by that component's\nparameter count. This is the lever for \"fit the bulge, freeze it, then fit the disk against a\nfixed bulge\", and it is much stronger medicine than a narrow prior: the later search cannot\nrevisit the frozen component even if the added component would have changed it.\n\n```python\ngalaxy = af.Model(\n ag.Galaxy,\n redshift=0.5,\n bulge=result_1.instance.galaxies.galaxy.bulge, # fixed, contributes 0 parameters\n disk=af.Model(ag.lp_linear.Exponential),\n)\n```\n\nThe common three-stage pattern uses all of it: fit the bulge; fix it and fit the disk; then free\nboth from the second result's narrowed priors for a final search where everything moves together.\nFreezing permanently is a real bias risk, because a bulge fitted without a disk absorbs some of\nthe disk's light — so the third stage is not optional if the decomposition is the result you are\nquoting.\n\n## Branch — where `sigma` comes from, and its two traps\n\n`model_centred` reads each parameter's width from the `width_modifier` field of its entry in the\n`priors` config (`autogalaxy_assistant:config/priors/`, mapped in\n[`../wiki/core/api/configuration.md`](../wiki/core/api/configuration.md)). Two forms:\n\n- **Absolute** — `sigma` is the config value directly. For a linear `Sersic`, `sersic_index`\n carries `Absolute: 1.5`, each `centre` component `Absolute: 0.05`, and each `ell_comps`\n component `Absolute: 0.2`.\n- **Relative** — `sigma` is that fraction of the inferred value. `effective_radius` carries\n `Relative: 1.0`.\n\nThe reasoning behind which is which is worth understanding, because it tells you when to override.\nA relative width on a centre makes no sense: a galaxy centred near `(0.0, 0.0)` would get a sigma\nnear zero and the next search could not move it at all. An absolute width on an `intensity` makes\nno sense either, because intensity depends on units, exposure and brightness, so no single number\ngeneralises. Hence absolute centres and relative radii.\n\nTwo traps follow directly, and both are worth stating to a user before they hit them:\n\n**Relative widths break on parameters that can be negative or zero.**\n`model_centred_relative(r=...)` applies one relative width to *every* parameter, including\n`ell_comps`, whose median is legitimately near zero and often negative. That yields a negative\n`sigma` and raises rather than silently misbehaving — which is the good outcome, but it does mean\nthe blanket relative form is unusable on a general light-profile model. Use `model_centred`\n(per-parameter config widths), or `model_centred_absolute` where a single absolute width is\ndefensible for the parameters you are passing.\n\n**The bounded variant does not inherit the parameter's physical limits.**\n`model_centred_max_lh_bounded(b=...)` builds a `UniformPrior` at `mean ± b` regardless of the\nparameter's configured limits, so a `sersic_index` inferred near its ceiling of 5.0 can come back\nwith an upper limit above 5.0. Set the bound with the parameter's range in mind, or clamp the\nprior yourself afterwards.\n\nThe width you want is a genuine trade-off with no default that is right everywhere: wide enough\nthat a better nearby solution can still be found, narrow enough that the search is not doing\nsearch-1's work over again. The shipped `width_modifier` values are a considered balance rather\nthan a physical truth, and overriding them for one parameter you understand well is normal.\n\n## Branch — when chaining is the wrong tool\n\nChaining adds a failure mode that a single search does not have: **a wrong early result narrows a\nlater prior around the wrong place, and the later search never looks anywhere else.** The final\nposterior then looks tight and well-behaved and is simply wrong. Three situations where a single\nsearch is better:\n\n- **The single search works and is merely slow.** Reach for a faster sampler, a linear light\n profile, JAX or a GPU first ([`ag_configure_search`](./ag_configure_search.md),\n [`ag_run_search`](./ag_run_search.md)). Complexity you do not need is complexity that can be\n wrong.\n- **The early model is not a subset of the late one.** Prior passing assumes the parameter means\n something similar in both searches. Passing a `Sersic`'s parameters into an `Exponential`, or a\n parametric component's into a pixelised one, is either an error or meaningless.\n- **The parameter you fixed early is the one you are measuring.** If a bulge fitted without a disk\n is the number going in the paper, do not chain to a frozen bulge — chain to a narrowed one and\n let the final search move it.\n\nAlways inspect the intermediate result rather than trusting the chain. `result_1.info`, and\n`model.info` inside search 2's output folder, are the two things to read before believing the\nfinal number.\n\n## Branch — the practical mechanics\n\n**One analysis, reused.** Build the `ag.AnalysisImaging` once, before search 1, and pass the same\nobject to every search — unless you are deliberately changing the data between stages (a smaller\nmask early, the full one late), in which case say so explicitly, because the log likelihoods are\nthen not comparable across stages.\n\n**Naming.** One `path_prefix` for the chain, and `name=\"search[1]__\"` per stage. The bracket\nconvention is the workspace's and it sorts correctly; the `__` suffix is what makes an\noutput tree readable a month later.\n\n**`unique_tag`.** Keep it identical across the chain's searches, since it identifies the *dataset*.\nEach stage still lands in its own folder because `name` differs. And the identifier trap from\n[`ag_configure_search`](./ag_configure_search.md) applies to every stage: it does not hash your\ndata's pixel values, so if you swap datasets without changing `unique_tag`, every search in the\nchain silently returns the previous galaxy's result.\n\n**Smoke test the whole chain, not one search.** A chain's characteristic bug is a mis-typed\nattribute path in the passing expression, and that only fires at the second search:\n\n```bash\nPYAUTO_TEST_MODE=1 NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib \\\n python scripts/chained_fit.py\n```\n\nLevel 1 rather than level 2 here: level 1 runs a real (tiny) search at each stage, so a `Result`\nexists with samples for the next stage to pass from. Level 2 bypasses the sampler and leaves the\nchain nothing meaningful to narrow around. The levels are\n[`../wiki/core/operations/sandbox.md`](../wiki/core/operations/sandbox.md), and the priors a\ntest-mode chain produces are wiring evidence only — never quote them.\n\n## Combine\n\n- [`ag_configure_search`](./ag_configure_search.md) — cheap settings for early searches and\n accurate ones for the last; also the `unique_tag` semantics every stage inherits.\n- [`ag_run_search`](./ag_run_search.md) — driving each stage and reading its output folder.\n- [`ag_build_imaging_model`](./ag_build_imaging_model.md) — composing the models the chain steps\n between, including prior customisation by hand when you want to override a passed width.\n- [`ag_multi_galaxy_and_cluster`](./ag_multi_galaxy_and_cluster.md) — adding galaxies one at a\n time is the most common real use of chaining.\n- [`ag_multi_dataset`](./ag_multi_dataset.md) — its one-by-one branch is a chain across datasets\n rather than across model complexity.\n- [`ag_debug_fit_failure`](./ag_debug_fit_failure.md) — when a single search lands somewhere\n unphysical, which is the diagnosis that most often leads here.\n- `ag_pixelization` — a smooth-profile fit chained into a pixelised one is a natural pairing,\n because the pixelisation wants a decent light model to start from.\n\nWhen a chain is worth keeping, offer (default-yes) to record it in a dated\n`wiki/project/YYYY-MM-DD-.md` entry: why the fit was split, what each stage fitted, what was\npassed as a narrowed prior versus fixed as an instance, and the shared output prefix — per\n[`_style.md`](./_style.md) property #5. The split and the passing decisions are the reasoning a\nreader will want, and they are invisible in the final `model.results`.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: Search chaining](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_9_search_chaining.ipynb):\n the first chaining tutorial at the end of chapter 2, which builds the idea from a fit that fails\n without it; `tutorial_10_prior_passing` then walks the prior mechanics, and\n `chapter_4_scaling_up_galaxies/tutorial_2_multi_galaxy` applies the ideas to blended galaxies.\n- **General reference** — [RTD: Configs](https://pyautogalaxy.readthedocs.io/en/latest/general/configs.html):\n how the config files are laid out and looked up — the `priors` tree is where each parameter's\n `width_modifier` lives, and hence where a passed prior's `sigma` comes from.\n- **Experienced PyAutoGalaxy user** — [workspace: guides/modeling/chaining.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/guides/modeling/chaining.py):\n the API overview this skill is grounded in, with its own long discussion of absolute versus\n relative widths.\n\n## Agent procedural checklist\n\n1. Ask whether the single search is failing or merely slow; recommend a faster search before a\n chain when it is only slow.\n2. Choose the split with the user and say what each stage buys — dimensionality, settings, or a\n cheap approximation.\n3. Build the dataset and one `ag.AnalysisImaging` before search 1 and reuse it, or state\n explicitly why a stage uses different data.\n4. Write the whole chain into one script under one `path_prefix`, with `search[N]__` names.\n5. Use `result.model_centred` (or a `model_centred_*` variant) to narrow, `result.instance` to\n fix, and `result.model` only when you deliberately want the original priors back.\n6. Verify what you built: print the passed prior's type, and read `model.info` in the later\n search's output folder.\n7. Do not use `model_centred_relative` on a model containing `ell_comps` or a centre — it raises\n on a negative median.\n8. Inspect `result_1.info` before trusting anything downstream of it.\n9. If a component is frozen mid-chain, plan the final stage that frees it again before quoting its\n parameters.\n10. Validate the whole chain with `PYAUTO_TEST_MODE=1` (not 2 — the chain needs samples to pass).\n11. Offer the `wiki/project/` entry recording the split and the passing decisions.\n" - } - }, - "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} \ No newline at end of file diff --git a/notebooks/chapter_optional/tutorial_need_for_speed.ipynb b/notebooks/chapter_optional/tutorial_need_for_speed.ipynb new file mode 100644 index 0000000..1d0b8d1 --- /dev/null +++ b/notebooks/chapter_optional/tutorial_need_for_speed.ipynb @@ -0,0 +1,122 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Optional Tutorial: Need for Speed\n", + "=================================\n", + "\n", + "Return to this tutorial when a fit is too slow for your scientific needs. Faster likelihood calculations help,\n", + "but a well-organised model and search often matter just as much. Hardware cannot make an inappropriate model fit.\n", + "\n", + "__Contents__\n", + "\n", + "- **Search Effort:** Reduce unnecessary exploration without hiding uncertainty.\n", + "- **Likelihood Cost:** Understand the calculation for each trial model.\n", + "- **JAX and Batching:** Account for compilation, hardware and memory.\n", + "- **Measuring Runtime:** Use representative runs rather than fixed rules.\n", + "- **Data Quantity:** Retain the measurements needed for your science.\n", + "\n", + "__Search Effort__\n", + "\n", + "More free parameters, broad priors and difficult degeneracies can increase the work needed to explore a model.\n", + "More live points generally make exploration more thorough at additional cost. There is no reliable universal\n", + "rule such as a fixed number of likelihood evaluations per parameter.\n", + "\n", + "Linear profiles remove intensities from the non-linear search. Search chaining can fix well-constrained component\n", + "geometry so subsequent searches concentrate on the remaining problem. Both can improve reliability as well as\n", + "runtime. Narrow priors or fewer live points may shorten a run while concealing good solutions: check the result.\n", + "\n", + "Prodigy can be useful for quickly finding a fitted component, as in chapter 2 tutorial 6. It does not replace a\n", + "sampler when you need uncertainty estimates. The optional searches tutorial explains the distinction.\n", + "\n", + "__Likelihood Cost__\n", + "\n", + "Each evaluation predicts the galaxy light, accounts for the instrument and compares it with the data. Costs\n", + "include profile evaluation, over sampling, PSF convolution and, for linear profiles or pixelizations, a linear solve.\n", + "For interferometry, transforming predicted light into visibilities introduces different costs.\n", + "\n", + "More profiles or reconstruction elements usually mean more work, but the overall fit can still be faster if the\n", + "resulting parameter space is easier to search. Measure the full workflow rather than judging only one operation.\n", + "\n", + "__JAX and Batching__\n", + "\n", + "JAX compiles supported likelihood calculations into a form that can be reused efficiently on CPUs or compatible\n", + "GPUs. The first compilation costs time. Changed shapes or model structures can require compilation again, so\n", + "this cost is not necessarily paid only once during an entire session.\n", + "\n", + "Nautilus can evaluate batches of trial models; gradient optimisers can evaluate several starts together. This\n", + "parallel work may suit a GPU well, but a GPU is not automatically faster for every small dataset or model. Device\n", + "support, numerical precision, memory and compilation all matter. Installing the appropriate accelerator runtime\n", + "is also necessary; having a GPU in the machine alone does not mean JAX is using it.\n", + "\n", + "For Nautilus, `n_batch` controls batching. For `MultiStartProdigy`, explicitly choose `batch_size`; setting it to\n", + "`None` processes all starts together and may require much more memory. The practicalities tutorial shows\n", + "`analysis.print_vram_use(model=model, batch_size=search.batch_size)`. Treat it as a likelihood memory estimate,\n", + "not the total process requirement or a guarantee that gradient calculations will fit in the same memory.\n", + "\n", + "A NumPy path remains available via `use_jax=False` for supported analyses, useful for debugging or comparison.\n", + "Gradient searches require the accelerated differentiable path. Older advice based only on ordinary Python or\n", + "Numba likelihood timings does not describe the compiled, batched workflow.\n", + "\n", + "__Measuring Runtime__\n", + "\n", + "Run a representative model on the machine you intend to use. Separate initial compilation from subsequent\n", + "execution, and include search overhead and output updates when estimating the time to completion. If timing\n", + "individual JAX operations, wait for the device to finish: dispatch time alone is not execution time.\n", + "\n", + "Timing a standalone `FitImaging` call is not a benchmark of the compiled batched search. A rough estimate based on\n", + "cost per evaluation times evaluation count is useful only when both numbers refer to the same execution path;\n", + "for batches, use batch throughput rather than multiplying by a single-call timing.\n", + "\n", + "Inspect `search.summary` and logs, then compare representative runs with different batch sizes or model choices.\n", + "Do not compare a compilation-heavy first run against a cached or resumed run as though both did the same work.\n", + "Frequent visualisation and file writes can also dominate short fits; adjust update intervals when appropriate.\n", + "\n", + "__Data Quantity__\n", + "\n", + "Halving the pixel scale at fixed field of view gives four times as many pixels. Finer over sampling, a larger PSF\n", + "or a larger fitted region can add work too. However, retaining faint outskirts can be essential to constrain a\n", + "galaxy's size. Do not mask away informative residuals merely to make a fit faster.\n", + "\n", + "__Wrap Up__\n", + "\n", + "Use the data-and-likelihood lesson to decide which measurements belong in the fit, then assess numerical accuracy\n", + "and runtime together. Speed is useful when it lets you test more credible models and check them more carefully." + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.1" + }, + "colab": { + "aiContexts": { + "24c2f562-da24-50bb-8eb9-5a887505fe54": { + "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", + "name": "PyAutoGalaxy assistant", + "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_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\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_optional/tutorial_need_for_speed.ipynb in HowToGalaxy).\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 PyAutoGalaxy 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 PyAutoGalaxy docs (https://pyautogalaxy.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) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. 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 galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_configure_search\n\n---\nname: ag_configure_search\ndescription: Choose and configure the non-linear search that fits a galaxy model to data — `af.Nautilus` for a full posterior with errors you can quote, `af.MultiStartProdigy` for a fast maximum-a-posteriori check, `af.DynestyStatic` for isophote/ellipse fitting and as a cross-check, and the MCMC / quasi-Newton / diagnostic alternatives. Covers `n_live` and `n_batch`, `n_starts` and `n_steps`, the `iterations_per_quick_update` output cadence, the start-point initialiser API, grid searches, and — critically — the `unique_tag` / unique-identifier and resume semantics, since the identifier is a hash of the model and search but **not** of the data, so re-using a tag across datasets silently resumes the wrong fit. Use once a model and analysis exist. Not for composing the model (`ag_build_imaging_model`), not for executing the fit or reading its output folder (`ag_run_search`), and not for diagnosing a fit that already failed.\n---\n\n# Choosing and configuring the search\n\nA search is the algorithm that explores your model's parameter space, calling\n`analysis.log_likelihood_function(instance)` over and over and deciding where to look next.\nEvery search in PyAutoFit takes the same two arguments, so swapping one for another is a\none-line change:\n\n```python\nresult = search.fit(model=model, analysis=analysis)\n```\n\nThe choice matters for one reason above all others: **some searches return a posterior and\nsome return a point.** A nested sampler maps the probability density of every parameter, its\nerrors, and the covariances between them — so it can tell you whether an inferred effective\nradius of 1.6\" is 1.6 ± 0.01 or 1.6 ± 0.5, and whether it trades off against the Sersic index.\nA gradient optimiser hands you a single best-fit model and *nothing else*: no errors, no\ncovariances. Both are useful, for different questions, and confusing them is the most\nconsequential mistake available here.\n\nThe runnable tour of the whole menu is\n`autogalaxy_workspace:scripts/guides/modeling/searches.py`; the catalogue with every argument\nis [`../wiki/core/api/searches.md`](../wiki/core/api/searches.md), and what each family\nactually does is\n[`../wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md).\n\n## Ask\n\n- *\"Do you need error bars, or do you just want to know whether this model fits at all?\"*\n This is the whole decision. Errors → `Nautilus`. A quick check → `MultiStartProdigy`.\n- *\"How many free parameters does the model have?\"* — `print(model.info)` if you don't know.\n It sets `n_live`, and it is the main driver of run time.\n- *\"Is this dataset one of several you will fit with the same model?\"* — if yes, the\n `unique_tag` section below is not optional reading; it is where results silently collide.\n- *\"Is JAX available, and a GPU?\"* — `MultiStartProdigy` requires a JAX-traceable analysis\n (`use_jax=True`) and is not available without it.\n\n## Branch — `af.Nautilus`, the default\n\nThe search every workspace `modeling.py` example uses, and the one to reach for when the\nanswer will be quoted in a paper. Extensive testing across galaxy modelling found it the most\naccurate and efficient search available. Adapted from\n`autogalaxy_workspace:scripts/imaging/modeling.py`.\n\n```python\nsearch = af.Nautilus(\n path_prefix=Path(\"imaging\"),\n name=\"modeling\",\n unique_tag=dataset_name,\n n_live=200,\n n_batch=50,\n iterations_per_quick_update=10000,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/nautilus/`; optional dependency\n`nautilus-sampler`. Reference: Lange (2023), arXiv:2306.16923.\n\n**`n_live` is the accuracy / run-time dial**, and essentially the only setting you need to\nthink about. More live points map the posterior more reliably but cost more likelihood\nevaluations; fewer are faster but risk converging on a local maximum. 200 is sufficient for\nthe vast majority of galaxy models, and more parameters want more — a bulge-plus-disk model\nat N = 9 is comfortable at 200, while a model past ~30 free parameters is worth running at\n400. Dropping to 100 on a simple model to save time is a legitimate move (`modeling.py` does\nexactly that) but it is a deliberate accuracy trade, so say so when you make it.\n\n**`n_batch` is where the GPU speed-up comes from**, and it is worth understanding because\nNautilus is *gradient-free* — it never differentiates the likelihood, so unlike the optimisers\nbelow it does not use JAX's derivatives at all. What it does do is propose points in batches,\nand when the analysis is JAX-traceable PyAutoFit evaluates the whole batch through one\n`jax.vmap(jax.jit(...))` call, fitting all `n_batch` models simultaneously. It is therefore\nalso the main control on VRAM: a bigger batch holds more models in memory at once. Pair it\nwith `analysis.print_vram_use(model=model, batch_size=search.batch_size)` before a GPU run\n(see [`ag_build_imaging_model`](./ag_build_imaging_model.md)).\n\nFor parallel CPU runs, `number_of_cores` scales well: roughly linearly below 8 cores and\nabout `0.5 * number_of_cores` above, continuing past 50 cores — which is why supercomputing\nfacilities make even large models tractable.\n\n## Branch — `af.MultiStartProdigy`, when you want an answer now\n\nThe search every workspace `start_here.py` example uses. Far faster than Nautilus, and\nreturns a single best-fit model with **no errors at all**. Adapted from\n`autogalaxy_workspace:scripts/imaging/start_here.py`.\n\n```python\nsearch = af.MultiStartProdigy(\n path_prefix=Path(\"imaging\"),\n name=\"start_here\",\n unique_tag=dataset_name,\n n_starts=48,\n n_steps=300,\n iterations_per_quick_update=50,\n live_visual_update=False,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/mle/multi_start_gradient/`; optional dependencies\n`jax` and `optax`.\n\nThe design is what makes gradient descent usable on this problem at all. Galaxy-model\nparameter spaces are multi-modal, so a *single*-start optimiser routinely descends confidently\ninto a local maximum — which is exactly the weakness of `LBFGS` below.\n`MultiStartProdigy` launches `n_starts` independent descents from broad starting points spread\nacross the parameter space, runs them **all in parallel** through `jax.vmap`, and returns the\nbest. That wide population is what reliably finds the global maximum-likelihood basin; it is\nthe approach introduced for galaxy modelling by GIGA-Lens (Gu, Huang et al. 2022,\narXiv:2202.07663). Prodigy adds a *learning-rate free* update rule (Mishchenko & Defazio 2024,\narXiv:2306.06101): it estimates its own step size as it runs, so there is no `learning_rate`\nfor you to tune — which is precisely why it is the recommended member of the family over\n`MultiStartAdam`, `MultiStartADABelief` and `MultiStartLion`, all of which want one chosen.\n\nThree things to hold onto:\n\n- **It requires `use_jax=True`.** It is gradient-based, so a NumPy analysis cannot supply what\n it needs. It is therefore unavailable for `ag.AnalysisEllipse`, which is not JAX-traceable.\n- **`n_steps` is a ceiling, not a target.** The search stops early once the best fit stops\n improving, so expect a handful of quick updates rather than `n_steps / 50` of them.\n- **There is no posterior.** If the fit reports `effective_radius = 1.6\"`, this search cannot\n tell you the uncertainty, and no amount of extra starts will change that.\n\nThe workflow the workspace recommends, and the one to recommend to the user: run\n`MultiStartProdigy` first to confirm cheaply that the model and data are sensible, then run\n`Nautilus` on the same model when you need numbers you can quote.\n\n## Branch — `af.DynestyStatic`, for isophotes and as a cross-check\n\nThe nested-sampling alternative, and the search the workspace's **ellipse** examples use,\nbecause testing showed it the most reliable for isophote fitting specifically.\n\n```python\nsearch = af.DynestyStatic(\n path_prefix=Path(\"ellipse\"),\n name=\"fit_start\",\n unique_tag=dataset_name,\n sample=\"rwalk\",\n nlive=50,\n iterations_per_quick_update=2500,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/dynesty/`. Reference: Speagle (2020),\narXiv:1904.02180.\n\nNote `nlive`, not `n_live` — the argument names follow each upstream sampler's own convention,\nwhich is a real source of typos when switching. Dynesty's sampler options pass straight\nthrough (`sample`, `walks`, `bound`, `bootstrap`, `enlarge`, `update_interval`, `facc`,\n`slices`, `fmove`, `max_move`), and `af.DynestyDynamic` reallocates live points as it runs —\ntoward the tails for a better evidence estimate, toward the bulk for better parameters —\ntaking `nlive_init`, `dlogz_init` and the other `_init` variants instead.\n\nTwo reasons to reach for it. **Isophote fitting**: use it whenever the analysis is\n`ag.AnalysisEllipse`, where the gradient optimisers are unavailable anyway. **Independent\ncross-check**: a posterior that reproduces under a different nested sampler is far more\nconvincing than one that does not, and this is the cheapest such check available. Ellipse\nfitting has its own page,\n[`../wiki/core/api/ellipse.md`](../wiki/core/api/ellipse.md), and its own skill,\n[`ag_ellipse_fitting`](./ag_ellipse_fitting.md).\n\n## Branch — the rest of the catalogue\n\nEvery search PyAutoFit ships, generated from the installed release's search manifest\n(`python -m autofit search-manifest --json`; regenerate with PyAutoHands\n`autohands regenerate_search_roster --root .`, never by hand):\n\n\n\n- **Markov chain Monte Carlo** (`mcmc`): `af.Emcee`, `af.Zeus`, `af.BlackJAXNUTS`, `af.SMC` (experimental) — example: `autofit_workspace:scripts/searches/mcmc.py`\n- **Nested sampling** (`nest`): `af.DynestyStatic`, `af.DynestyDynamic`, `af.Nautilus`, `af.NSS` (experimental) — example: `autofit_workspace:scripts/searches/nest.py`\n- **Maximum likelihood / maximum a posteriori** (`mle`): `af.Drawer`, `af.BFGS`, `af.LBFGS`, `af.MultiStartAdam`, `af.MultiStartADABelief` (experimental), `af.MultiStartLion` (experimental), `af.MultiStartProdigy` — example: `autofit_workspace:scripts/searches/mle.py`\n\n\nReach for these only when you know why. All are tabulated with full argument lists in\n[`../wiki/core/api/searches.md`](../wiki/core/api/searches.md) and demonstrated in\n`autogalaxy_workspace:scripts/guides/modeling/searches.py`.\n\n| Search | When |\n|---|---|\n| `af.Zeus` | Ensemble MCMC **slice** sampler; the best-performing MCMC in the workspace's tests, though still behind Nautilus. Good for characterising a posterior around a mode you already found. |\n| `af.Emcee` | The familiar affine-invariant ensemble sampler. Same role as Zeus, generally a little worse on these parameter spaces. |\n| `af.NSS` | Nested slice sampling via BlackJAX, run entirely inside `jax.jit`. Needs a JAX-traceable analysis (`use_jax=True`); returns the evidence like the other nested samplers. |\n| `af.BlackJAXNUTS` / `af.SMC` | JAX gradient MCMC: the No-U-Turn sampler, and BlackJAX adaptive tempered sequential Monte Carlo (which also returns the evidence). Both need `use_jax=True`. |\n| `af.LBFGS` / `af.BFGS` | Single-start quasi-Newton descent via SciPy. Fast in principle, but galaxy-model parameter spaces are usually too complex to use it without careful initialisation — `MultiStartProdigy` exists to fix exactly that. |\n| `af.Drawer` | Not a search: draws models from the prior and evaluates them. A diagnostic for \"are my priors sane and does my likelihood run at all?\", and the workspace's one-draw container for collecting many completed fits into a single output folder (`total_draws=1`). |\n\nMCMC and MLE searches monitor convergence differently from nested samplers — both `Emcee` and\n`Zeus` accept an `af.AutoCorrelationsSettings(check_for_convergence=True, check_size=100,\nrequired_length=50, change_threshold=0.01)` and will terminate early when the chains satisfy\nit.\n\n## Branch — the output cadence\n\nEvery search writes results to disk **as it runs**, using the highest-likelihood model found\nso far, and `iterations_per_quick_update` sets how often. This is not free, and the two\ncanonical values look contradictory until you notice the unit differs:\n\n- `Nautilus(iterations_per_quick_update=10000)` — the unit is a likelihood evaluation, and on\n a fast fit writing output every few hundred would dominate the run time.\n- `MultiStartProdigy(iterations_per_quick_update=50)` — the unit is a *gradient step*, a far\n coarser thing, so 50 gives a useful handful of updates.\n\nIf the log keeps announcing that it is outputting results, raise the number. The heavier\n`iterations_per_full_update` controls the full pass — all visuals plus `model.results` and\n`search.summary`. Defaults for both live in `autogalaxy_assistant:config/general.yaml` under\n`updates:` (set to effectively infinite there, so the per-search value governs), and the\nconfig layer is [`../wiki/core/api/configuration.md`](../wiki/core/api/configuration.md).\n\n`live_visual_update=False` is the default and the right choice on a headless or cluster run.\nSet it `True` to also push each quick update to a live surface — a matplotlib window that\nrefreshes from a script, or an in-place refresh of the Jupyter cell. The disk write happens\neither way.\n\n## The unique identifier, `unique_tag`, and resuming — read this one\n\nOutput lands at `output////`, where the identifier is a\n32-character hash. Re-running an identical configuration **resumes** the existing fit rather\nthan starting over, which is a genuinely useful feature — and the sharp edge of this whole\nskill, because of what goes into the hash and what does not.\n\n**The identifier is a hash of the model and the search. It is not a hash of the data.**\n\nThat is not a subtlety; it is a trap with a silent failure mode. Fit galaxy A, then change\nonly the FITS paths and fit galaxy B with the same model and the same search: the identifier\nis identical, PyAutoFit finds a completed fit at that path, and reports \"Fit Already\nCompleted\". You get galaxy A's result back, labelled as galaxy B, with no error raised.\n\nThe fix is one argument, and it is why every workspace example passes it:\n\n```python\nsearch = af.Nautilus(\n path_prefix=Path(\"imaging\"),\n name=\"modeling\",\n unique_tag=dataset_name, # <-- the discriminator the data itself does not supply\n n_live=200,\n)\n```\n\n**Pass your dataset name as `unique_tag`, always.** Then the two galaxies hash differently and\nland in different folders. And the corollary that catches people a second time: if the *data*\nchanges but its name does not — you re-reduced it, fixed the noise-map, changed the mask,\nre-ran the simulator with different truth — **bump the `unique_tag`** (or delete the output\nfolder). Otherwise you resume a fit to data that no longer exists.\n\nChanging the model or the search *does* change the identifier, so you never need to manage\nthat case by hand: a bulge-plus-disk fit cannot collide with a single-Sersic fit, and an\n`n_live=200` run cannot collide with an `n_live=400` one. It is only the data axis that is\ninvisible to the hash.\n\nVerify rather than trust when it matters. Comparing the identifier across two configurations\nbefore launching a long run costs nothing:\n\n```python\nsearch.paths.model = model\nsearch.paths.search = search\n\nprint(search.paths.identifier)\n```\n\nTwo runs printing the same string will share an output folder, whatever you believe about\nthem. The annotated tour of what lands in that folder — `files/`, `image/`, `model.info`,\n`model.results`, `search.summary` — is the `__Output Folder Layout__` section of\n`autogalaxy_workspace:scripts/imaging/modeling.py`, and the run-search skill\n(`ag_run_search`) owns reading it.\n\n## Branch — a start point, for MCMC and MLE only\n\nMCMC and optimiser searches have a *location* in parameter space, so you can say where they\nbegin. Nested samplers draw from the prior and cannot use this API. Adapted from\n`autogalaxy_workspace:scripts/guides/modeling/searches.py`, where an early-type galaxy is\nstarted near n = 4.\n\n```python\ninitializer = af.InitializerParamBounds(\n {\n model.galaxies.galaxy.bulge.centre_0: (-0.01, 0.01),\n model.galaxies.galaxy.bulge.centre_1: (-0.01, 0.01),\n model.galaxies.galaxy.bulge.effective_radius: (0.9, 1.1),\n model.galaxies.galaxy.bulge.sersic_index: (3.9, 4.1),\n }\n)\n\nsearch = af.Emcee(\n path_prefix=Path(\"imaging\"),\n name=\"start_point\",\n unique_tag=dataset_name,\n nwalkers=50,\n nsteps=500,\n initializer=initializer,\n)\n```\n\nParameters you do not name are drawn from their priors. `af.InitializerBall(lower_limit=0.49,\nupper_limit=0.51)` is the other common choice — a tight ball in unit-prior space around the\nprior centres, and the recommended initialisation for both MCMC samplers.\n\nThe statistical point here is worth stating explicitly, because there is a tempting shortcut\nthat is not equivalent. You *could* achieve a similar effect by tightening priors instead —\na narrow `af.TruncatedGaussianPrior` on `sersic_index`, say. But priors change the posterior,\nand therefore change the errors you quote and the model you infer. The start-point API moves\nwhere the search *looks* without moving what you *infer*. Prefer it whenever your knowledge is\nabout where the answer probably is rather than about what the answer must be.\n\n## Branch — mapping a parameter on a grid\n\nTo scan a parameter on a fixed grid rather than marginalising over it — a light centre, a\nfixed `sersic_index`, anything you want mapped — wrap a search:\n\n```python\ngrid_search = af.SearchGridSearch(\n search=search, number_of_steps=4, number_of_cores=1, result_output_interval=100\n)\n```\n\nOne child fit runs per grid cell and an `af.GridSearchResult` comes back. Source:\n`PyAutoFit:autofit/non_linear/grid/`. This is the one search whose defaults *do* live in a\nYAML — `autogalaxy_assistant:config/non_linear/GridSearch.yaml` sets `number_of_cores` and\n`step_size` in unit-prior values, and it is the only file in that folder because per-search\ndefaults ship inside PyAutoFit itself\n(`autogalaxy_assistant:config/non_linear/README.md`).\n\n## A different lever: chaining instead of a better search\n\nWhen a model is too complex for any single search, the answer is usually not a bigger\n`n_live` — it is to fit a simpler model first and pass its posterior forward as the priors of\nthe complex one. Fit a single Sersic, then chain into a bulge-plus-disk or pixelised fit,\nwhich starts from a region of parameter space that is already good.\n`autogalaxy_workspace:scripts/guides/modeling/chaining.py` is the walkthrough, the\n`width_modifier` entries in the prior YAMLs control how wide the passed priors become, and it\ngets its own skill in a later phase (`ag_chain_searches`).\n\n## Picking one at a glance\n\n| Goal | Pick |\n|---|---|\n| Quick check that model + data are sensible | `MultiStartProdigy(n_starts=48, n_steps=300)` |\n| Results you will quote, model under ~30 free parameters | `Nautilus(n_live=200)` |\n| Production run, complex or multi-modal model | `Nautilus(n_live=400)`, higher `n_batch` if VRAM allows |\n| Bayesian evidence comparison between models | `Nautilus` or `DynestyStatic` |\n| Ellipse / isophote fitting | `DynestyStatic(sample=\"rwalk\", nlive=50)` |\n| Independent cross-check of a posterior | `DynestyStatic` or `Zeus` |\n| Posterior refinement around a known mode | `Zeus` or `Emcee` with an `initializer` |\n| Map a parameter on a fixed grid | `af.SearchGridSearch` |\n| Check the priors are sane and the likelihood runs | `af.Drawer` |\n\n## Combine — where this hands off\n\n- **Run the fit** → the run-search skill (`ag_run_search`), which owns\n `search.fit(model=model, analysis=analysis)`, announcing the output folder at launch, and\n what to open first while it runs.\n- **The model isn't right yet** → [`ag_build_imaging_model`](./ag_build_imaging_model.md).\n Changing the search rarely rescues a badly-specified model, and a search that will not\n converge is more often a model problem than a sampler problem.\n- **It ran and failed, stalled, or returned something unphysical** → the fit-debugging skill\n (`ag_debug_fit_failure`), which is also where \"Fit Already Completed\" on data you thought was\n new gets diagnosed.\n- **Read the posterior that comes back** → the results-loading and fit-plotting skills\n (`ag_load_results`, `ag_plot_fit`); the `Samples` API and how errors are computed is\n [`../wiki/core/concepts/samples_and_posteriors.md`](../wiki/core/concepts/samples_and_posteriors.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording the search and\nits settings — `n_live` in particular, since it is an accuracy claim about the posterior you\nare about to publish.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: The non-linear search](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb):\n what a non-linear search actually is — parameter spaces, likelihoods, priors — and the\n statistical foundation under every setting on this page. The\n [optional chapter](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_optional/tutorial_searches.ipynb)\n tours the sampler zoo.\n- **General reference** — [RTD: Configs](https://pyautogalaxy.readthedocs.io/en/latest/general/configs.html):\n how the configuration files customise searches, visualisation and output, and where each is\n looked up.\n- **Experienced PyAutoGalaxy user** — [workspace: guides/modeling/searches.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/guides/modeling/searches.py):\n every available search instantiated with its settings spelled out, plus the start-point API.\n\n## Agent procedural checklist\n\n1. Ask the one question that decides it: errors needed, or a fast check?\n2. `Nautilus(n_live=200)` by default; `MultiStartProdigy` for speed (needs `use_jax=True`);\n `DynestyStatic` for isophotes or a cross-check.\n3. Set `n_live` from the model's free-parameter count, and say when you trade it down.\n4. **Always pass `unique_tag=dataset_name`** — and bump it when the data changes but the name\n does not.\n5. Print `search.paths.identifier` before a long run whenever a collision is plausible.\n6. Set `iterations_per_quick_update` to the search's unit — thousands for Nautilus, tens for a\n gradient optimiser. Keep `live_visual_update=False` on headless runs.\n7. Run `analysis.print_vram_use(model=model, batch_size=search.batch_size)` before a GPU run.\n8. Hand off to `ag_run_search`, and offer the `wiki/project/` entry recording the settings.\n" + } + }, + "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file diff --git a/notebooks/chapter_optional/tutorial_prior_passing.ipynb b/notebooks/chapter_optional/tutorial_prior_passing.ipynb new file mode 100644 index 0000000..62ccfff --- /dev/null +++ b/notebooks/chapter_optional/tutorial_prior_passing.ipynb @@ -0,0 +1,90 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Optional Historical Tutorial: Prior Passing\n", + "===========================================\n", + "\n", + "This is historical background, not part of the recommended HowToGalaxy learning path. Older versions of the\n", + "PyAutoGalaxy / PyAutoLens workflow automatically narrowed priors between searches. That default behaviour has\n", + "been disabled. New readers are discouraged from investing time in the old prior-passing recipes: learn the\n", + "component-separation approach in chapter 2 tutorial 6 instead.\n", + "\n", + "__Contents__\n", + "\n", + "- **Historical Behaviour:** Why older tutorials describe Gaussian priors centred on results.\n", + "- **Current Behaviour:** Distinguish fixed instances, default priors and explicit centred models.\n", + "- **Why It Is Optional:** Understand the assumptions before reusing information from a fit.\n", + "\n", + "__Historical Behaviour__\n", + "\n", + "Older workflows used a first fit to create Gaussian priors for a later one. The Gaussian mean was based on the\n", + "first result, and its width used uncertainty and configurable width modifiers. An absolute modifier supplied a\n", + "width in parameter units; a relative modifier scaled with the inferred value. This was intended to guide later\n", + "searches towards plausible regions without manually copying every parameter.\n", + "\n", + "This history explains older references to `result.model` as automatic prior passing. Those descriptions are not\n", + "instructions for the current API, and should not be used to interpret a modern chained fit.\n", + "\n", + "__Current Behaviour__\n", + "\n", + "`result.instance` supplies concrete fitted parameter values. Using a component from it fixes those values in the\n", + "next model. Linear-profile intensities remain solved inside the likelihood unless converted to ordinary profiles.\n", + "This is the behaviour used in the core chaining tutorial.\n", + "\n", + "`result.model` instead supplies a model with default priors for free parameters; it does not automatically centre\n", + "those priors on the previous fit. Fixed parameters and model structure still matter, so inspect `model.info`.\n", + "\n", + "Explicit centred-model tools such as `result.model_centred`, `model_centred_absolute` and `model_centred_relative`\n", + "remain available for advanced use. Automatic default narrowing has been disabled; the capability has not been\n", + "removed entirely. See `autogalaxy_workspace/scripts/guides/modeling/chaining.py` for the current API.\n", + "\n", + "__Why It Is Optional__\n", + "\n", + "Narrowing priors around an earlier solution can exclude better solutions or carry its mistakes forward. Reusing\n", + "the same data to construct a prior and then fitting those data again also needs careful statistical interpretation;\n", + "it is not automatically equivalent to a joint analysis with independent prior information.\n", + "\n", + "__Wrap Up__\n", + "\n", + "Search chaining remains valuable without this step. It lets well-constrained components be dealt with separately,\n", + "reduces the parameter space of later fits and allows different search effort at different stages. Those are the\n", + "ideas to retain for modelling real galaxies." + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.1" + }, + "colab": { + "aiContexts": { + "24c2f562-da24-50bb-8eb9-5a887505fe54": { + "id": "24c2f562-da24-50bb-8eb9-5a887505fe54", + "name": "PyAutoGalaxy assistant", + "context": "These instructions were prepared by the PyAutoGalaxy assistant\n(https://github.com/PyAutoLabs/autogalaxy_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\nPyAutoGalaxy knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoGalaxy notebook (notebooks/chapter_optional/tutorial_prior_passing.ipynb in HowToGalaxy).\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 PyAutoGalaxy 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 PyAutoGalaxy docs (https://pyautogalaxy.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) extra galaxies, foreground stars or artefacts that\n need masking or noise-scaling, and (b) a mask extent that captures the galaxy's\n emission out to where it meets the sky. A mask that truncates the outer isophotes\n biases the effective radius and Sersic index, so never leave the mask radius at its\n default on real data. 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 galaxy, a sample of galaxies, a paper's analysis),\n point them to the PyAutoGalaxy assistant\n https://github.com/PyAutoLabs/autogalaxy_assistant, which runs in Claude Code or\n Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: ag_configure_search\n\n---\nname: ag_configure_search\ndescription: Choose and configure the non-linear search that fits a galaxy model to data — `af.Nautilus` for a full posterior with errors you can quote, `af.MultiStartProdigy` for a fast maximum-a-posteriori check, `af.DynestyStatic` for isophote/ellipse fitting and as a cross-check, and the MCMC / quasi-Newton / diagnostic alternatives. Covers `n_live` and `n_batch`, `n_starts` and `n_steps`, the `iterations_per_quick_update` output cadence, the start-point initialiser API, grid searches, and — critically — the `unique_tag` / unique-identifier and resume semantics, since the identifier is a hash of the model and search but **not** of the data, so re-using a tag across datasets silently resumes the wrong fit. Use once a model and analysis exist. Not for composing the model (`ag_build_imaging_model`), not for executing the fit or reading its output folder (`ag_run_search`), and not for diagnosing a fit that already failed.\n---\n\n# Choosing and configuring the search\n\nA search is the algorithm that explores your model's parameter space, calling\n`analysis.log_likelihood_function(instance)` over and over and deciding where to look next.\nEvery search in PyAutoFit takes the same two arguments, so swapping one for another is a\none-line change:\n\n```python\nresult = search.fit(model=model, analysis=analysis)\n```\n\nThe choice matters for one reason above all others: **some searches return a posterior and\nsome return a point.** A nested sampler maps the probability density of every parameter, its\nerrors, and the covariances between them — so it can tell you whether an inferred effective\nradius of 1.6\" is 1.6 ± 0.01 or 1.6 ± 0.5, and whether it trades off against the Sersic index.\nA gradient optimiser hands you a single best-fit model and *nothing else*: no errors, no\ncovariances. Both are useful, for different questions, and confusing them is the most\nconsequential mistake available here.\n\nThe runnable tour of the whole menu is\n`autogalaxy_workspace:scripts/guides/modeling/searches.py`; the catalogue with every argument\nis [`../wiki/core/api/searches.md`](../wiki/core/api/searches.md), and what each family\nactually does is\n[`../wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md).\n\n## Ask\n\n- *\"Do you need error bars, or do you just want to know whether this model fits at all?\"*\n This is the whole decision. Errors → `Nautilus`. A quick check → `MultiStartProdigy`.\n- *\"How many free parameters does the model have?\"* — `print(model.info)` if you don't know.\n It sets `n_live`, and it is the main driver of run time.\n- *\"Is this dataset one of several you will fit with the same model?\"* — if yes, the\n `unique_tag` section below is not optional reading; it is where results silently collide.\n- *\"Is JAX available, and a GPU?\"* — `MultiStartProdigy` requires a JAX-traceable analysis\n (`use_jax=True`) and is not available without it.\n\n## Branch — `af.Nautilus`, the default\n\nThe search every workspace `modeling.py` example uses, and the one to reach for when the\nanswer will be quoted in a paper. Extensive testing across galaxy modelling found it the most\naccurate and efficient search available. Adapted from\n`autogalaxy_workspace:scripts/imaging/modeling.py`.\n\n```python\nsearch = af.Nautilus(\n path_prefix=Path(\"imaging\"),\n name=\"modeling\",\n unique_tag=dataset_name,\n n_live=200,\n n_batch=50,\n iterations_per_quick_update=10000,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/nautilus/`; optional dependency\n`nautilus-sampler`. Reference: Lange (2023), arXiv:2306.16923.\n\n**`n_live` is the accuracy / run-time dial**, and essentially the only setting you need to\nthink about. More live points map the posterior more reliably but cost more likelihood\nevaluations; fewer are faster but risk converging on a local maximum. 200 is sufficient for\nthe vast majority of galaxy models, and more parameters want more — a bulge-plus-disk model\nat N = 9 is comfortable at 200, while a model past ~30 free parameters is worth running at\n400. Dropping to 100 on a simple model to save time is a legitimate move (`modeling.py` does\nexactly that) but it is a deliberate accuracy trade, so say so when you make it.\n\n**`n_batch` is where the GPU speed-up comes from**, and it is worth understanding because\nNautilus is *gradient-free* — it never differentiates the likelihood, so unlike the optimisers\nbelow it does not use JAX's derivatives at all. What it does do is propose points in batches,\nand when the analysis is JAX-traceable PyAutoFit evaluates the whole batch through one\n`jax.vmap(jax.jit(...))` call, fitting all `n_batch` models simultaneously. It is therefore\nalso the main control on VRAM: a bigger batch holds more models in memory at once. Pair it\nwith `analysis.print_vram_use(model=model, batch_size=search.batch_size)` before a GPU run\n(see [`ag_build_imaging_model`](./ag_build_imaging_model.md)).\n\nFor parallel CPU runs, `number_of_cores` scales well: roughly linearly below 8 cores and\nabout `0.5 * number_of_cores` above, continuing past 50 cores — which is why supercomputing\nfacilities make even large models tractable.\n\n## Branch — `af.MultiStartProdigy`, when you want an answer now\n\nThe search every workspace `start_here.py` example uses. Far faster than Nautilus, and\nreturns a single best-fit model with **no errors at all**. Adapted from\n`autogalaxy_workspace:scripts/imaging/start_here.py`.\n\n```python\nsearch = af.MultiStartProdigy(\n path_prefix=Path(\"imaging\"),\n name=\"start_here\",\n unique_tag=dataset_name,\n n_starts=48,\n n_steps=300,\n iterations_per_quick_update=50,\n live_visual_update=False,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/mle/multi_start_gradient/`; optional dependencies\n`jax` and `optax`.\n\nThe design is what makes gradient descent usable on this problem at all. Galaxy-model\nparameter spaces are multi-modal, so a *single*-start optimiser routinely descends confidently\ninto a local maximum — which is exactly the weakness of `LBFGS` below.\n`MultiStartProdigy` launches `n_starts` independent descents from broad starting points spread\nacross the parameter space, runs them **all in parallel** through `jax.vmap`, and returns the\nbest. That wide population is what reliably finds the global maximum-likelihood basin; it is\nthe approach introduced for galaxy modelling by GIGA-Lens (Gu, Huang et al. 2022,\narXiv:2202.07663). Prodigy adds a *learning-rate free* update rule (Mishchenko & Defazio 2024,\narXiv:2306.06101): it estimates its own step size as it runs, so there is no `learning_rate`\nfor you to tune — which is precisely why it is the recommended member of the family over\n`MultiStartAdam`, `MultiStartADABelief` and `MultiStartLion`, all of which want one chosen.\n\nThree things to hold onto:\n\n- **It requires `use_jax=True`.** It is gradient-based, so a NumPy analysis cannot supply what\n it needs. It is therefore unavailable for `ag.AnalysisEllipse`, which is not JAX-traceable.\n- **`n_steps` is a ceiling, not a target.** The search stops early once the best fit stops\n improving, so expect a handful of quick updates rather than `n_steps / 50` of them.\n- **There is no posterior.** If the fit reports `effective_radius = 1.6\"`, this search cannot\n tell you the uncertainty, and no amount of extra starts will change that.\n\nThe workflow the workspace recommends, and the one to recommend to the user: run\n`MultiStartProdigy` first to confirm cheaply that the model and data are sensible, then run\n`Nautilus` on the same model when you need numbers you can quote.\n\n## Branch — `af.DynestyStatic`, for isophotes and as a cross-check\n\nThe nested-sampling alternative, and the search the workspace's **ellipse** examples use,\nbecause testing showed it the most reliable for isophote fitting specifically.\n\n```python\nsearch = af.DynestyStatic(\n path_prefix=Path(\"ellipse\"),\n name=\"fit_start\",\n unique_tag=dataset_name,\n sample=\"rwalk\",\n nlive=50,\n iterations_per_quick_update=2500,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/dynesty/`. Reference: Speagle (2020),\narXiv:1904.02180.\n\nNote `nlive`, not `n_live` — the argument names follow each upstream sampler's own convention,\nwhich is a real source of typos when switching. Dynesty's sampler options pass straight\nthrough (`sample`, `walks`, `bound`, `bootstrap`, `enlarge`, `update_interval`, `facc`,\n`slices`, `fmove`, `max_move`), and `af.DynestyDynamic` reallocates live points as it runs —\ntoward the tails for a better evidence estimate, toward the bulk for better parameters —\ntaking `nlive_init`, `dlogz_init` and the other `_init` variants instead.\n\nTwo reasons to reach for it. **Isophote fitting**: use it whenever the analysis is\n`ag.AnalysisEllipse`, where the gradient optimisers are unavailable anyway. **Independent\ncross-check**: a posterior that reproduces under a different nested sampler is far more\nconvincing than one that does not, and this is the cheapest such check available. Ellipse\nfitting has its own page,\n[`../wiki/core/api/ellipse.md`](../wiki/core/api/ellipse.md), and its own skill,\n[`ag_ellipse_fitting`](./ag_ellipse_fitting.md).\n\n## Branch — the rest of the catalogue\n\nEvery search PyAutoFit ships, generated from the installed release's search manifest\n(`python -m autofit search-manifest --json`; regenerate with PyAutoHands\n`autohands regenerate_search_roster --root .`, never by hand):\n\n\n\n- **Markov chain Monte Carlo** (`mcmc`): `af.Emcee`, `af.Zeus`, `af.BlackJAXNUTS`, `af.SMC` (experimental) — example: `autofit_workspace:scripts/searches/mcmc.py`\n- **Nested sampling** (`nest`): `af.DynestyStatic`, `af.DynestyDynamic`, `af.Nautilus`, `af.NSS` (experimental) — example: `autofit_workspace:scripts/searches/nest.py`\n- **Maximum likelihood / maximum a posteriori** (`mle`): `af.Drawer`, `af.BFGS`, `af.LBFGS`, `af.MultiStartAdam`, `af.MultiStartADABelief` (experimental), `af.MultiStartLion` (experimental), `af.MultiStartProdigy` — example: `autofit_workspace:scripts/searches/mle.py`\n\n\nReach for these only when you know why. All are tabulated with full argument lists in\n[`../wiki/core/api/searches.md`](../wiki/core/api/searches.md) and demonstrated in\n`autogalaxy_workspace:scripts/guides/modeling/searches.py`.\n\n| Search | When |\n|---|---|\n| `af.Zeus` | Ensemble MCMC **slice** sampler; the best-performing MCMC in the workspace's tests, though still behind Nautilus. Good for characterising a posterior around a mode you already found. |\n| `af.Emcee` | The familiar affine-invariant ensemble sampler. Same role as Zeus, generally a little worse on these parameter spaces. |\n| `af.NSS` | Nested slice sampling via BlackJAX, run entirely inside `jax.jit`. Needs a JAX-traceable analysis (`use_jax=True`); returns the evidence like the other nested samplers. |\n| `af.BlackJAXNUTS` / `af.SMC` | JAX gradient MCMC: the No-U-Turn sampler, and BlackJAX adaptive tempered sequential Monte Carlo (which also returns the evidence). Both need `use_jax=True`. |\n| `af.LBFGS` / `af.BFGS` | Single-start quasi-Newton descent via SciPy. Fast in principle, but galaxy-model parameter spaces are usually too complex to use it without careful initialisation — `MultiStartProdigy` exists to fix exactly that. |\n| `af.Drawer` | Not a search: draws models from the prior and evaluates them. A diagnostic for \"are my priors sane and does my likelihood run at all?\", and the workspace's one-draw container for collecting many completed fits into a single output folder (`total_draws=1`). |\n\nMCMC and MLE searches monitor convergence differently from nested samplers — both `Emcee` and\n`Zeus` accept an `af.AutoCorrelationsSettings(check_for_convergence=True, check_size=100,\nrequired_length=50, change_threshold=0.01)` and will terminate early when the chains satisfy\nit.\n\n## Branch — the output cadence\n\nEvery search writes results to disk **as it runs**, using the highest-likelihood model found\nso far, and `iterations_per_quick_update` sets how often. This is not free, and the two\ncanonical values look contradictory until you notice the unit differs:\n\n- `Nautilus(iterations_per_quick_update=10000)` — the unit is a likelihood evaluation, and on\n a fast fit writing output every few hundred would dominate the run time.\n- `MultiStartProdigy(iterations_per_quick_update=50)` — the unit is a *gradient step*, a far\n coarser thing, so 50 gives a useful handful of updates.\n\nIf the log keeps announcing that it is outputting results, raise the number. The heavier\n`iterations_per_full_update` controls the full pass — all visuals plus `model.results` and\n`search.summary`. Defaults for both live in `autogalaxy_assistant:config/general.yaml` under\n`updates:` (set to effectively infinite there, so the per-search value governs), and the\nconfig layer is [`../wiki/core/api/configuration.md`](../wiki/core/api/configuration.md).\n\n`live_visual_update=False` is the default and the right choice on a headless or cluster run.\nSet it `True` to also push each quick update to a live surface — a matplotlib window that\nrefreshes from a script, or an in-place refresh of the Jupyter cell. The disk write happens\neither way.\n\n## The unique identifier, `unique_tag`, and resuming — read this one\n\nOutput lands at `output////`, where the identifier is a\n32-character hash. Re-running an identical configuration **resumes** the existing fit rather\nthan starting over, which is a genuinely useful feature — and the sharp edge of this whole\nskill, because of what goes into the hash and what does not.\n\n**The identifier is a hash of the model and the search. It is not a hash of the data.**\n\nThat is not a subtlety; it is a trap with a silent failure mode. Fit galaxy A, then change\nonly the FITS paths and fit galaxy B with the same model and the same search: the identifier\nis identical, PyAutoFit finds a completed fit at that path, and reports \"Fit Already\nCompleted\". You get galaxy A's result back, labelled as galaxy B, with no error raised.\n\nThe fix is one argument, and it is why every workspace example passes it:\n\n```python\nsearch = af.Nautilus(\n path_prefix=Path(\"imaging\"),\n name=\"modeling\",\n unique_tag=dataset_name, # <-- the discriminator the data itself does not supply\n n_live=200,\n)\n```\n\n**Pass your dataset name as `unique_tag`, always.** Then the two galaxies hash differently and\nland in different folders. And the corollary that catches people a second time: if the *data*\nchanges but its name does not — you re-reduced it, fixed the noise-map, changed the mask,\nre-ran the simulator with different truth — **bump the `unique_tag`** (or delete the output\nfolder). Otherwise you resume a fit to data that no longer exists.\n\nChanging the model or the search *does* change the identifier, so you never need to manage\nthat case by hand: a bulge-plus-disk fit cannot collide with a single-Sersic fit, and an\n`n_live=200` run cannot collide with an `n_live=400` one. It is only the data axis that is\ninvisible to the hash.\n\nVerify rather than trust when it matters. Comparing the identifier across two configurations\nbefore launching a long run costs nothing:\n\n```python\nsearch.paths.model = model\nsearch.paths.search = search\n\nprint(search.paths.identifier)\n```\n\nTwo runs printing the same string will share an output folder, whatever you believe about\nthem. The annotated tour of what lands in that folder — `files/`, `image/`, `model.info`,\n`model.results`, `search.summary` — is the `__Output Folder Layout__` section of\n`autogalaxy_workspace:scripts/imaging/modeling.py`, and the run-search skill\n(`ag_run_search`) owns reading it.\n\n## Branch — a start point, for MCMC and MLE only\n\nMCMC and optimiser searches have a *location* in parameter space, so you can say where they\nbegin. Nested samplers draw from the prior and cannot use this API. Adapted from\n`autogalaxy_workspace:scripts/guides/modeling/searches.py`, where an early-type galaxy is\nstarted near n = 4.\n\n```python\ninitializer = af.InitializerParamBounds(\n {\n model.galaxies.galaxy.bulge.centre_0: (-0.01, 0.01),\n model.galaxies.galaxy.bulge.centre_1: (-0.01, 0.01),\n model.galaxies.galaxy.bulge.effective_radius: (0.9, 1.1),\n model.galaxies.galaxy.bulge.sersic_index: (3.9, 4.1),\n }\n)\n\nsearch = af.Emcee(\n path_prefix=Path(\"imaging\"),\n name=\"start_point\",\n unique_tag=dataset_name,\n nwalkers=50,\n nsteps=500,\n initializer=initializer,\n)\n```\n\nParameters you do not name are drawn from their priors. `af.InitializerBall(lower_limit=0.49,\nupper_limit=0.51)` is the other common choice — a tight ball in unit-prior space around the\nprior centres, and the recommended initialisation for both MCMC samplers.\n\nThe statistical point here is worth stating explicitly, because there is a tempting shortcut\nthat is not equivalent. You *could* achieve a similar effect by tightening priors instead —\na narrow `af.TruncatedGaussianPrior` on `sersic_index`, say. But priors change the posterior,\nand therefore change the errors you quote and the model you infer. The start-point API moves\nwhere the search *looks* without moving what you *infer*. Prefer it whenever your knowledge is\nabout where the answer probably is rather than about what the answer must be.\n\n## Branch — mapping a parameter on a grid\n\nTo scan a parameter on a fixed grid rather than marginalising over it — a light centre, a\nfixed `sersic_index`, anything you want mapped — wrap a search:\n\n```python\ngrid_search = af.SearchGridSearch(\n search=search, number_of_steps=4, number_of_cores=1, result_output_interval=100\n)\n```\n\nOne child fit runs per grid cell and an `af.GridSearchResult` comes back. Source:\n`PyAutoFit:autofit/non_linear/grid/`. This is the one search whose defaults *do* live in a\nYAML — `autogalaxy_assistant:config/non_linear/GridSearch.yaml` sets `number_of_cores` and\n`step_size` in unit-prior values, and it is the only file in that folder because per-search\ndefaults ship inside PyAutoFit itself\n(`autogalaxy_assistant:config/non_linear/README.md`).\n\n## A different lever: chaining instead of a better search\n\nWhen a model is too complex for any single search, the answer is usually not a bigger\n`n_live` — it is to fit a simpler model first and pass its posterior forward as the priors of\nthe complex one. Fit a single Sersic, then chain into a bulge-plus-disk or pixelised fit,\nwhich starts from a region of parameter space that is already good.\n`autogalaxy_workspace:scripts/guides/modeling/chaining.py` is the walkthrough, the\n`width_modifier` entries in the prior YAMLs control how wide the passed priors become, and it\ngets its own skill in a later phase (`ag_chain_searches`).\n\n## Picking one at a glance\n\n| Goal | Pick |\n|---|---|\n| Quick check that model + data are sensible | `MultiStartProdigy(n_starts=48, n_steps=300)` |\n| Results you will quote, model under ~30 free parameters | `Nautilus(n_live=200)` |\n| Production run, complex or multi-modal model | `Nautilus(n_live=400)`, higher `n_batch` if VRAM allows |\n| Bayesian evidence comparison between models | `Nautilus` or `DynestyStatic` |\n| Ellipse / isophote fitting | `DynestyStatic(sample=\"rwalk\", nlive=50)` |\n| Independent cross-check of a posterior | `DynestyStatic` or `Zeus` |\n| Posterior refinement around a known mode | `Zeus` or `Emcee` with an `initializer` |\n| Map a parameter on a fixed grid | `af.SearchGridSearch` |\n| Check the priors are sane and the likelihood runs | `af.Drawer` |\n\n## Combine — where this hands off\n\n- **Run the fit** → the run-search skill (`ag_run_search`), which owns\n `search.fit(model=model, analysis=analysis)`, announcing the output folder at launch, and\n what to open first while it runs.\n- **The model isn't right yet** → [`ag_build_imaging_model`](./ag_build_imaging_model.md).\n Changing the search rarely rescues a badly-specified model, and a search that will not\n converge is more often a model problem than a sampler problem.\n- **It ran and failed, stalled, or returned something unphysical** → the fit-debugging skill\n (`ag_debug_fit_failure`), which is also where \"Fit Already Completed\" on data you thought was\n new gets diagnosed.\n- **Read the posterior that comes back** → the results-loading and fit-plotting skills\n (`ag_load_results`, `ag_plot_fit`); the `Samples` API and how errors are computed is\n [`../wiki/core/concepts/samples_and_posteriors.md`](../wiki/core/concepts/samples_and_posteriors.md).\n\nOffer (default-yes) a dated `wiki/project/YYYY-MM-DD-.md` entry recording the search and\nits settings — `n_live` in particular, since it is an accuracy claim about the posterior you\nare about to publish.\n\n## Further reading\n\n- **Student / new to galaxy morphology** — [HowToGalaxy: The non-linear search](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb):\n what a non-linear search actually is — parameter spaces, likelihoods, priors — and the\n statistical foundation under every setting on this page. The\n [optional chapter](https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_optional/tutorial_searches.ipynb)\n tours the sampler zoo.\n- **General reference** — [RTD: Configs](https://pyautogalaxy.readthedocs.io/en/latest/general/configs.html):\n how the configuration files customise searches, visualisation and output, and where each is\n looked up.\n- **Experienced PyAutoGalaxy user** — [workspace: guides/modeling/searches.py](https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/scripts/guides/modeling/searches.py):\n every available search instantiated with its settings spelled out, plus the start-point API.\n\n## Agent procedural checklist\n\n1. Ask the one question that decides it: errors needed, or a fast check?\n2. `Nautilus(n_live=200)` by default; `MultiStartProdigy` for speed (needs `use_jax=True`);\n `DynestyStatic` for isophotes or a cross-check.\n3. Set `n_live` from the model's free-parameter count, and say when you trade it down.\n4. **Always pass `unique_tag=dataset_name`** — and bump it when the data changes but the name\n does not.\n5. Print `search.paths.identifier` before a long run whenever a collision is plausible.\n6. Set `iterations_per_quick_update` to the search's unit — thousands for Nautilus, tens for a\n gradient optimiser. Keep `live_visual_update=False` on headless runs.\n7. Run `analysis.print_vram_use(model=model, batch_size=search.batch_size)` before a GPU run.\n8. Hand off to `ag_run_search`, and offer the `wiki/project/` entry recording the settings.\n" + } + }, + "selectedAiContext": "24c2f562-da24-50bb-8eb9-5a887505fe54" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file diff --git a/notebooks/chapter_optional/tutorial_searches.ipynb b/notebooks/chapter_optional/tutorial_searches.ipynb index 60d114a..fd00159 100644 --- a/notebooks/chapter_optional/tutorial_searches.ipynb +++ b/notebooks/chapter_optional/tutorial_searches.ipynb @@ -4,23 +4,32 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Tutorial: Alternative Searches\n", - "==============================\n", + "Optional Tutorial: Alternative Searches\n", + "=======================================\n", "\n", - "Up to now, we've always used the non-linear search Nautilus and not considered the input parameters that control its\n", - "sampling. In this tutorial, we'll consider how we can change these setting to balance finding the global maxima\n", - "solution with fast run time.\n", - "\n", - "We will also discuss other types of non-linear searches, such as MCMC and optimizers, which we can use to perform\n", - "modeling. So far, we have not found any of these alternatives to give anywhere near as robust and efficient results as\n", - "Nautilus, and we recommend users use Nautilus unless they are particularly interested in investigating different\n", - "model-fitting techniques.\n", + "You can complete HowToGalaxy using Nautilus without studying search algorithms in detail. Return here if you want\n", + "to understand the fast Prodigy stage of search chaining, or compare alternative approaches for your own work.\n", "\n", "__Contents__\n", "\n", - "- **Nested Sampling:** Customize Nautilus settings and use Dynesty as an alternative nested sampler.\n", - "- **Optimizers:** Use maximum likelihood optimizers like LBFGS for fast but less robust fitting.\n", - "- **MCMC:** Use Markov Chain Monte Carlo methods like Emcee for parameter estimation." + "- **Optimisation:** Improve trial models towards a best fit with Prodigy.\n", + "- **Nested Sampling:** Explore parameter ranges with Nautilus.\n", + "- **MCMC:** Another way to estimate parameter distributions.\n", + "\n", + "__Optimisation__\n", + "\n", + "An optimiser repeatedly proposes changes to a trial galaxy, checks whether its score improves, and moves towards\n", + "better solutions. Imagine adjusting the size and shape so that the predicted light increasingly resembles the\n", + "image. Repeating this process aims to find the best-fitting model, rather than trying to describe every plausible\n", + "model in detail. Individual steps need not always improve the likelihood.\n", + "\n", + "Prodigy uses gradients to choose useful directions. `MultiStartProdigy` repeats this from several starting models,\n", + "reducing the risk that one poor start determines the answer. Its score includes prior weight as well as likelihood\n", + "(a maximum-a-posteriori optimisation). It uses JAX, the numerical engine that accelerates these calculations and\n", + "provides the gradients; you do not need to study JAX to run it.\n", + "\n", + "The result can give a useful galaxy size, but does not by itself tell us how precisely that size is measured.\n", + "It also cannot guarantee the best solution was found. Inspect residuals and test different starts or settings." ] }, { @@ -69,9 +78,10 @@ "from autogalaxy import setup_notebook; setup_notebook()\n", "\n", "from pathlib import Path\n", + "import numpy as np\n", + "import autofit as af\n", "import autogalaxy as ag\n", - "import autogalaxy.plot as aplt\n", - "import autofit as af" + "import autogalaxy.plot as aplt" ], "outputs": [], "execution_count": null @@ -80,73 +90,35 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "we'll use the `simple__sersic` imaging data of a galaxy, where:\n", + "__Dataset and Mask__\n", "\n", - " - The galaxy's light is a `Sersic`." + "Load the imaging data and retain the region inside the circular mask. The simulator creates the data if needed.\n", + "The image, noise map and PSF together describe the observation; none specifies which galaxy model we must fit." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "dataset_name = \"simple__sersic\"\n", - "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Dataset Auto-Simulation__\n", "\n", - "If the dataset does not already exist on your system, it will be created by running the corresponding\n", - "simulator script. This ensures that all example scripts can be run without manually simulating data first." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ + "dataset_name = \"simple__sersic\"\n", + "dataset_path = Path(\"dataset\") / \"imaging\" / dataset_name\n", "if ag.util.dataset.should_simulate(str(dataset_path)):\n", " import subprocess\n", " import sys\n", "\n", - " subprocess.run(\n", - " [sys.executable, \"scripts/simulators/sersic.py\"],\n", - " check=True,\n", - " )\n", - "\n", + " subprocess.run([sys.executable, \"scripts/simulators/sersic.py\"], check=True)\n", "\n", "dataset = ag.Imaging.from_fits(\n", " data_path=dataset_path / \"data.fits\",\n", " noise_map_path=dataset_path / \"noise_map.fits\",\n", " psf_path=dataset_path / \"psf.fits\",\n", " pixel_scales=0.1,\n", - ")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "we'll create and use a 2.6\" `Mask2D`." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ + ")\n", "mask = ag.Mask2D.circular(\n", - " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.6\n", + " shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=3.0\n", ")\n", - "\n", - "dataset = dataset.apply_mask(mask=mask)\n", - "\n", - "aplt.subplot_imaging_dataset(dataset=dataset)" + "dataset = dataset.apply_mask(mask=mask)" ], "outputs": [], "execution_count": null @@ -155,97 +127,43 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Nested Sampling__\n", - "\n", - "Lets first perform the model-fit using Nautilus, but look at different parameters that control how long it takes to run. \n", - "We'll therefore discuss in a bit more detail how Nautilus works, but still keep this description conceptually simple \n", - "and avoid technical terms and jargon. For a complete description of Nautilus you should check out the Nautilus \n", - "publication `https://arxiv.org/abs/2306.16923`.\n", - "\n", - "nlive:\n", - "\n", - "Nautilus is a `nested sampling` algorithm. As we described in chapter 2, it throws down a set of `live points` in \n", - "parameter space, where each live point corresponds to a model with a given set of parameters. These points are\n", - "initially distributed according to our priors, hence why tuning our priors allows us to sample parameter space faster.\n", - " \n", - "The number of live points is set by the parameter `n_live`. More points provide a more thorough sampling of \n", - "parameter space, increasing the probability that we locate the global maxima solution. Therefore, if you think your \n", - "model-fit has gone to a local maxima, you should try increasing `n_live`. The downside of this is Nautilus will \n", - "take longer to sample parameter space and converge on a solution. Ideally, we will use as few live points as possible \n", - "to locate the global maxima as quickly as possible.\n", - "\n", - "f_live:\n", - "\n", - "A nested sampling algorithm estimates the *Bayesian Evidence* of the model-fit, which is a quantity the non-linear \n", - "search algorithms we introduce later do not. The Bayesian evidence quantifies how well the model as a whole fits\n", - "the data, following a principle called Occam's Razor (`https://simple.wikipedia.org/wiki/Occam%27s_razor`). This \n", - "penalizes models for being more complex (e.g. more parameters) and requires that their additional complexity improve \n", - "their overall fit to the data compared to a simpler model. By comparing the Bayesian evidence of \n", - "different models one can objectively choose the model that best fits the data.\n", - "\n", - "A nested sampling algorithm stops sampling when it estimates that continuing sampling will not increase the Bayesian \n", - "evidence (called the `log_evidence`) by more than the `f_live`. As Nautilus progresses and converges on the\n", - "solution, the rate of increase of the estimated Bayesian evidence slows down. Therefore, higher `f_live`s \n", - "mean Nautilus terminate sooner.\n", - " \n", - "A high `f_live` will make the errors estimated on every parameter unreliable and its value must be kept \n", - "below 0.8 for reliable error estimates. However, when chaining searches, we typically *do not care* about the errors \n", - "in the first search, therefore setting a high evidence tolerance can be an effective means to make Nautilus converge\n", - "faster (we'll estimate reliable errors in the second search when the `f_live` is 0.8 or less). \n", - "\n", + "__Over Sampling__\n", "\n", - "Lets perform two fits, where:\n", - "\n", - " - One has many live points and a higher evidence tolerance, causing the non-linear search to\n", - " take a longer time to run.\n", - " \n", - " - One has few live points, a high sampling efficiency and evidence tolerance, causing the non-linear search to\n", - " converge and end quicker." + "The bright centre changes rapidly across a pixel. Adaptive over sampling evaluates it on a finer grid so that\n", + "numerical inaccuracies do not masquerade as poor models. The outskirts need fewer evaluations." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", + "over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from(\n", + " grid=dataset.grid,\n", + " sub_size_list=[8, 4, 2],\n", + " radial_list=[0.3, 0.6],\n", + " centre_list=[(0.0, 0.0)],\n", + ")\n", + "dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size)\n", + "aplt.subplot_imaging_dataset(dataset=dataset)\n", + "\n", "model = af.Collection(\n", " galaxies=af.Collection(\n", - " galaxy=af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp.Sersic),\n", + " galaxy=af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp_linear.Sersic)\n", " )\n", ")\n", - "\n", - "search = af.Nautilus(\n", + "analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", + "search = af.MultiStartProdigy(\n", " path_prefix=Path(\"howtogalaxy\", \"chapter_optional\"),\n", - " name=\"tutorial_searches_slow\",\n", + " name=\"tutorial_searches_prodigy\",\n", " unique_tag=dataset_name,\n", - " n_live=400,\n", - " n_batch=50, # GPU model fits are batched and run simultaneously (see chapter 2 tutorial 2).\n", + " n_starts=24,\n", + " batch_size=4,\n", + " n_steps=300,\n", ")\n", - "\n", - "analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True)\n", - "\n", - "print(\n", - " \"The non-linear search has begun running - checkout the HowToGalaxy/output\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell will progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", - "result_slow = search.fit(model=model, analysis=analysis)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Lets check that we get a good model and fit to the data." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_fit_imaging(fit=result_slow.max_log_likelihood_fit)" + "result_prodigy = search.fit(model=model, analysis=analysis)\n", + "print(result_prodigy.info)\n", + "aplt.subplot_fit_imaging(fit=result_prodigy.max_log_likelihood_fit)" ], "outputs": [], "execution_count": null @@ -254,82 +172,32 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can use the result to tell us how many iterations Nautilus took to convergence on the solution." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(\"Total Nautilus Iterations (If you skip running the search, this is ~ 500000):\")\n", - "print(result_slow.samples.total_samples)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now lets run the search with fast settings, so we can compare the total number of iterations required." + "__Nested Sampling__\n", + "\n", + "Nautilus spends effort exploring the range of plausible parameters, supporting uncertainty estimates as well as\n", + "a best fit. This extra information is useful when making scientific measurements. It also estimates Bayesian\n", + "evidence, used for model comparison, and has stopping criteria rather than a prescribed number of steps.\n", + "\n", + "Increase `n_live` when exploration is inadequate, but judge convergence from repeated fits and diagnostics as well.\n", + "No fixed live-point count guarantees reliable uncertainties for every model. The following runs the same galaxy\n", + "model with Nautilus so that you can inspect its fit and parameter ranges alongside the optimiser's result." ] }, { "cell_type": "code", "metadata": {}, "source": [ + "\n", "search = af.Nautilus(\n", " path_prefix=Path(\"howtogalaxy\", \"chapter_optional\"),\n", - " name=\"tutorial_searches_fast\",\n", + " name=\"tutorial_searches_nautilus\",\n", " unique_tag=dataset_name,\n", - " n_live=75,\n", - " n_batch=50, # GPU model fits are batched and run simultaneously (see chapter 2 tutorial 2).\n", - ")\n", - "\n", - "print(\n", - " \"The non-linear search has begun running - checkout the HowToGalaxy/output\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell will progress once search has completed - this could take some time!\"\n", + " n_live=200,\n", + " n_batch=50,\n", ")\n", - "\n", - "result_fast = search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"Search has finished run - you may now continue the notebook.\")" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Lets check that this search, despite its faster sampling settings, still gives us the global maxima solution." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "aplt.subplot_fit_imaging(fit=result_fast.max_log_likelihood_fit)" - ], - "outputs": [], - "execution_count": null - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And now lets confirm it uses significantly fewer iterations." - ] - }, - { - "cell_type": "code", - "metadata": {}, - "source": [ - "print(\"Total Nautilus Iterations:\")\n", - "print(\"Slow settings: ~500000\")\n", - "print(result_slow.samples.total_samples)\n", - "print(\"Fast settings: \", result_fast.samples.total_samples)" + "result_nautilus = search.fit(model=model, analysis=analysis)\n", + "print(result_nautilus.info)\n", + "aplt.subplot_fit_imaging(fit=result_nautilus.max_log_likelihood_fit)" ], "outputs": [], "execution_count": null @@ -338,102 +206,41 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Optimizers__\n", - "\n", - "Nested sampling algorithms like Nautilus provides the errors on all of the model parameters, by fully mapping out all \n", - "of the high likelihood regions of parameter space. This provides knowledge on the complete *range* of models that do \n", - "and do not provide high likelihood fits to the data, but takes many extra iterations to perform. If we require precise \n", - "error estimates (perhaps this is our final model fit before we publish the results in a paper), these extra\n", - "iterations are acceptable. \n", - "\n", - "However, we often don't care about the errors. For example, in the previous tutorial when chaining searches, the only\n", - "result we used from the fit performed in the first search was the maximum log likelihood model, omitting the errors\n", - "entirely! Its seems wasteful to use a nested sampling algorithm like Nautilus to map out the entirity of parameter\n", - "space when we don't use this information!\n", - "\n", - "There are a class of non-linear searches called `optimizers`, which seek to optimize just one thing, the log\n", - "likelihood. They want to find the model that maximizes the log likelihood, with no regard for the errors, thus not\n", - "wasting time mapping out in intricate detail every facet of parameter space.\n", - "\n", - "PyAutoFit supports a number of optimizers, which can be used as an alternative to nested sampling when only the\n", - "maximum likelihood model is needed. These include `LBFGS` and `BFGS` (from scipy), which descend the likelihood from a\n", - "single starting point. A single-start optimizer generally needs a good starting point to work well, and in our\n", - "experience the parameter spaces fitted by models are often too complex for it without careful setup of initialization\n", - "priors.\n", - "\n", - "PyAutoFit also supports multi-start gradient optimizers (`MultiStartProdigy`, `MultiStartAdam`, `MultiStartADABelief`\n", - "and `MultiStartLion`), which use JAX to launch many optimizations from starting points spread across parameter space\n", - "in parallel and return the best one. This makes them far more robust to complex parameter spaces, and\n", - "`MultiStartProdigy` is the optimizer used by many of the `start_here.py` examples in the `autogalaxy_workspace`. Like any optimizer, they\n", - "return only the best-fit model with no errors. The `autogalaxy_workspace` script `scripts/guides/modeling/searches.py` describes\n", - "every search, including these optimizers, in detail.\n", - "\n", "__MCMC__\n", "\n", - "For users familiar with Markov Chain Monte Carlo (MCMC) non-linear samplers, PyAutoFit supports the non-linear\n", - "searches `Emcee` and `Zeus`. Like LBFGS, these also need a good starting point, and are generally less effective at\n", - "modeling than Nautilus.\n", + "Markov chain Monte Carlo methods explore distributions of parameters by proposing successive moves and accepting\n", + "or rejecting them according to their probabilities. Emcee uses an ensemble of walkers. Walkers can move to lower\n", + "likelihoods as well as higher ones; their aim is to sample the distribution, not only climb towards its peak.\n", "\n", - "I've included an example runs of Emcee and Zeus below, where the model is set up using `UniformPriors` to give\n", - "the starting point of the MCMC walkers. " + "A sensible starting region can help. Here the bounds describe an initial spread around values suggested by the\n", + "image; they do not replace the model priors. This demonstration uses a finite number of steps, which is not a\n", + "claim of convergence. Before interpreting uncertainty estimates, examine mixing, autocorrelation and whether\n", + "longer runs agree. Multiple walkers do not guarantee escape from separated regions of good fits." ] }, { "cell_type": "code", "metadata": {}, "source": [ - "bulge = af.Model(ag.lp.Sersic)\n", - "bulge.centre.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", - "bulge.centre.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1)\n", - "bulge.ell_comps.ell_comps_0 = af.UniformPrior(lower_limit=-0.3, upper_limit=0.3)\n", - "bulge.ell_comps.ell_comps_1 = af.UniformPrior(lower_limit=-0.3, upper_limit=0.3)\n", - "bulge.intensity = af.UniformPrior(lower_limit=0.5, upper_limit=1.5)\n", - "bulge.effective_radius = af.UniformPrior(lower_limit=0.2, upper_limit=1.6)\n", - "bulge.sersic_index = af.UniformPrior(lower_limit=3.0, upper_limit=5.0)\n", - "\n", - "galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge)\n", "\n", - "model = af.Collection(galaxies=af.Collection(galaxy=galaxy))\n", - "\n", - "search = af.Zeus(\n", - " path_prefix=Path(\"howtogalaxy\", \"chapter_optional\"),\n", - " name=\"tutorial_searches_zeus\",\n", - " unique_tag=dataset_name,\n", - " nwalkers=50,\n", - " nsteps=1000,\n", + "initializer = af.InitializerParamBounds(\n", + " {\n", + " model.galaxies.galaxy.bulge.centre.centre_0: (-0.05, 0.05),\n", + " model.galaxies.galaxy.bulge.centre.centre_1: (-0.05, 0.05),\n", + " model.galaxies.galaxy.bulge.effective_radius: (0.5, 1.5),\n", + " model.galaxies.galaxy.bulge.sersic_index: (2.0, 5.0),\n", + " }\n", ")\n", - "\n", - "print(\n", - " \"Zeus has begun running - checkout the HowToGalaxy/output\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell will progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", - "result_zeus = search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"Zeus has finished run - you may now continue the notebook.\")\n", - "\n", - "aplt.subplot_fit_imaging(fit=result_zeus.max_log_likelihood_fit)\n", - "\n", - "\n", "search = af.Emcee(\n", " path_prefix=Path(\"howtogalaxy\", \"chapter_optional\"),\n", " name=\"tutorial_searches_emcee\",\n", " unique_tag=dataset_name,\n", " nwalkers=50,\n", " nsteps=1000,\n", + " initializer=initializer,\n", ")\n", - "\n", - "print(\n", - " \"The non-linear search has begun running - checkout the HowToGalaxy/output\"\n", - " \" folder for live output of the results, images and model.\"\n", - " \" This Jupyter notebook cell will progress once search has completed - this could take some time!\"\n", - ")\n", - "\n", "result_emcee = search.fit(model=model, analysis=analysis)\n", - "\n", - "print(\"The search has finished run - you may now continue the notebook.\")\n", - "\n", + "print(result_emcee.info)\n", "aplt.subplot_fit_imaging(fit=result_emcee.max_log_likelihood_fit)" ], "outputs": [], @@ -445,12 +252,10 @@ "source": [ "__Wrap Up__\n", "\n", - "This tutorial showed how the same model can be fitted using different non-linear searches (e.g. `Nautilus`, `Zeus`,\n", - "`Emcee`). Each search explores parameter space in a different way, and the best choice depends on the\n", - "dimensionality and complexity of the model you are fitting.\n", - "\n", - "For the vast majority of models in **PyAutoGalaxy**, the default nested sampling search `Nautilus` is recommended, as\n", - "it is robust, efficient and requires little manual tuning." + "A quick optimisation is useful when you need a fitted component or want to check a model setup. A sampler is useful\n", + "when you need ranges of plausible parameters and uncertainty estimates. Both require checking the result.\n", + "The workspace guide `autogalaxy_workspace/scripts/guides/modeling/searches.py` covers additional searches and settings.\n", + "For the core lessons, keep your attention on the galaxy model and the quality of its fit." ] } ], diff --git a/scripts/README.md b/scripts/README.md index 3ade191..e54ca64 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -3,7 +3,7 @@ The `HowToGalaxy` folder contains **HowToGalaxy** lectures, which teach a new us # Folders - `chapter_1_introduction`: An introduction to galaxy morphology and structure using **PyAutoGalaxy**. -- `chapter_2_modeling`: How to model galaxies, including a primer on Bayesian non-linear analysis. +- `chapter_2_modeling`: How to model galaxies, with data, models, Analysis objects and searches. - `chapter_3_pixelizations`: How to perform pixelized reconstructions of a galaxy. - `chapter_4_scaling_up_galaxies`: How to scale up modeling to multiple galaxies, from blended pairs to cluster fields. - `chapter_optional`: Optional tutorials. @@ -77,9 +77,9 @@ In chapter 1, we'll learn about galaxy structure and **PyAutoGalaxy**. At the en # OVERVIEW OF CHAPTER 2 (Beginner) -**Bayesian Inference and Non-linear Searches** +**Practical Galaxy Modeling** -In chapter 2, we'll cover Bayesian inference and model-fitting via a non-linear search. We will use these tools to +In chapter 2, we'll learn practical model-fitting via a non-linear search. We will use these tools to fit CCD imaging data of a galaxy with a model. At the end, you'll understand: 1. The concept of a non-linear search and non-linear parameter space. @@ -87,7 +87,7 @@ fit CCD imaging data of a galaxy with a model. At the end, you'll understand: 3. The trade-off between realism and complexity when choosing a model. 4. Why an incorrect model may be inferred and how to prevent this from happening. 5. The challenges that are involved in inferring a robust model in a computationally reasonable run-time. -6. How to chain non-linear searches together to build automated modeling pipelines with prior passing. +6. How to chain searches to fit components separately and simplify later fits. **Once completed, you'll be ready to model your own galaxies with PyAutoGalaxy!** diff --git a/scripts/chapter_1_introduction/tutorial_2_data.py b/scripts/chapter_1_introduction/tutorial_2_data.py index ecdf566..bc7a6eb 100644 --- a/scripts/chapter_1_introduction/tutorial_2_data.py +++ b/scripts/chapter_1_introduction/tutorial_2_data.py @@ -373,8 +373,8 @@ script if it does not exist on your hard-disk, using the same auto-simulation idiom as later tutorials) and plot its dirty images — the closest an interferometer dataset comes to the CCD images we simulated above. -HowToGalaxy will not cover interferometry any further than this. The lecture series teaches galaxy modeling using -CCD imaging, and everything you learn transfers to visibility-space fitting. If you need to model interferometer +HowToGalaxy teaches model fitting using CCD imaging, with a brief reminder of visibility-space likelihoods in +chapter 2. The modelling tools transfer to visibility-space fitting. If you need to model interferometer data, go to the `autogalaxy_workspace/scripts/interferometer` package, which is the dedicated resource for uv-plane galaxy modeling. """ diff --git a/scripts/chapter_2_modeling/README.md b/scripts/chapter_2_modeling/README.md index df3547d..dffcad1 100644 --- a/scripts/chapter_2_modeling/README.md +++ b/scripts/chapter_2_modeling/README.md @@ -1,26 +1,17 @@ -In chapter 2, we'll take you through how to model galaxies using a non-linear search, ending with how -searches are chained together into automated modeling pipelines. +Chapter 2 brings together data, models, Analysis objects and searches to teach practical galaxy modelling. -**Colab** links to every tutorial are included. +- [Tutorial 1: Non-linear Search](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb) — Fit a galaxy using Nautilus. -# Files +- [Tutorial 2: Practicalities](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb) — Run a realistic model and inspect output, memory use and results. -- [Tutorial 1: Non-linear Search](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb) — How a non-linear search is used to fit a model and the concepts of a parameter space and priors. +- [Tutorial 3: Why Modeling Is Hard](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_3_why_modeling_is_hard.ipynb) — Use visual inspection to diagnose and improve difficult fits. -- [Tutorial 2: Practicalities](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb) — Practicalities of performing model-fitting, like how to inspect the results on your hard-disk. +- [Tutorial 4: Linear Profiles](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_4_linear_profiles.ipynb) — Solve intensities and represent galaxy structure with MGEs. -- [Tutorial 3: Realism and Complexity](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_3_realism_and_complexity.ipynb) — Finding a balance between realism and complexity when composing and fitting a model. +- [Tutorial 5: Data and Likelihoods](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_5_data_and_likelihoods.ipynb) — Choose measurements and connect data to models through Analysis objects. -- [Tutorial 4: Dealing with Failure](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_4_dealing_with_failure.ipynb) — What to do when PyAutoGalaxy finds an inaccurate model. +- [Tutorial 6: Search Chaining](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_6_search_chaining.ipynb) — Fit components in stages with Prodigy and Nautilus. -- [Tutorial 5: Linear Profiles](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_5_linear_profiles.ipynb) — Light profiles which capture complex morphologies in a reduced number of non-linear parameters. +- [Tutorial 7: Summary](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_2_modeling/tutorial_7_summary.ipynb) — Review the chapter and choose the next step. -- [Tutorial 6: Masking](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_6_masking.ipynb) — How to mask your data to improve the model. - -- [Tutorial 7: Results](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_7_results.ipynb) — Overview of the results available after successfully fitting a model. - -- [Tutorial 8: Need for Speed](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_8_need_for_speed.ipynb) — How to fit complex models whilst balancing efficiency and run-time. - -- [Tutorial 9: Search Chaining](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_9_search_chaining.ipynb) — Breaking the modeling procedure into a chained sequence of model-fits. - -- [Tutorial 10: Prior Passing](https://colab.research.google.com/github/PyAutoLabs/HowToGalaxy/blob/2026.10.29.1/notebooks/chapter_2_modeling/tutorial_10_prior_passing.ipynb) — How the results of earlier searches are passed to later searches. +Alternative searches and performance guidance are in `../chapter_optional`. Prior passing is historical background, not required reading. diff --git a/scripts/chapter_2_modeling/tutorial_10_prior_passing.py b/scripts/chapter_2_modeling/tutorial_10_prior_passing.py deleted file mode 100644 index ff634b4..0000000 --- a/scripts/chapter_2_modeling/tutorial_10_prior_passing.py +++ /dev/null @@ -1,331 +0,0 @@ -""" -Tutorial 10: Prior Passing -========================== - -In the previous tutorial, we used non-linear search chaining to break the model-fitting procedure down into two -non-linear searches. This used an initial search to fit a simple model, whose results were used to tune and -initialize the priors of a more complex model that was fitted by the second search. - -However, the results were passed between searches manually. I explicitly wrote out every result as a prior -containing the values inferred in the first search. **PyAutoGalaxy** has an API for passing priors in a more generalized -way, which is the topic of this tutorial. - -__Contents__ - -- **Initial Setup:** Load the dataset and apply a mask. -- **Dataset Auto-Simulation:** Simulate the dataset via its simulator script if it is not on your hard-disk. -- **Model:** Compose the model for the first search. -- **Search:** Run the first search. -- **Result (Search 1):** Inspect the result of the first search. -- **Prior Passing:** Use the prior passing API to pass results to the second search. -- **Result:** Inspect the final result of the chained search. -- **Wrap Up:** Summary of the prior passing API. -- **Detailed Explanation Of Prior Passing:** In-depth explanation of how priors are passed between searches. -- **EXAMPLE:** A worked example of prior passing for a Sersic sersic_index parameter. -""" - -# from autogalaxy import setup_notebook; setup_notebook() - -import numpy as np -from pathlib import Path -import autogalaxy as ag -import autogalaxy.plot as aplt -import autofit as af - -""" -__Initial Setup__ - -we'll use the same galaxy data as the previous tutorial, where: - - - The galaxy's bulge is a `Sersic`. - - The galaxy's disk is an `Exponential`. - -All the usual steps for setting up a model fit (masking, analysis, etc.) are included below. -""" -dataset_name = "simple" -dataset_path = Path("dataset") / "imaging" / dataset_name - -""" -__Dataset Auto-Simulation__ - -If the dataset does not already exist on your system, it will be created by running the corresponding -simulator script. This ensures that all example scripts can be run without manually simulating data first. -""" -if ag.util.dataset.should_simulate(str(dataset_path)): - import subprocess - import sys - - subprocess.run( - [sys.executable, "scripts/simulators/simple.py"], - check=True, - ) - - -dataset = ag.Imaging.from_fits( - data_path=dataset_path / "data.fits", - noise_map_path=dataset_path / "noise_map.fits", - psf_path=dataset_path / "psf.fits", - pixel_scales=0.1, -) - -mask = ag.Mask2D.circular( - shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5 -) - -dataset = dataset.apply_mask(mask=mask) - -over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from( - grid=dataset.grid, - sub_size_list=[8, 4, 2], - radial_list=[0.3, 0.6], - centre_list=[(0.0, 0.0)], -) - -dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) - -aplt.subplot_imaging_dataset(dataset=dataset) - -""" -__Model__ - -We are going to use the same result of search 1 from the previous tutorial. Thus, we set up an identical model such -that we instantly load the result from hard-disk. -""" -bulge = af.Model(ag.lp_linear.Sersic) -disk = af.Model(ag.lp_linear.Exponential) - -bulge.centre_0 = 0.0 -bulge.centre_1 = 0.0 -disk.centre_0 = 0.0 -disk.centre_1 = 0.0 - -disk.ell_comps = bulge.ell_comps - -bulge.sersic_index = 4.0 - -galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk) - -model_1 = af.Collection(galaxies=af.Collection(galaxy=galaxy)) - -""" -The `info` attribute shows the model in a readable format. -""" -print(model_1.info) - -""" -__Search__ - -We also create the same search as the previous tutorial, using the same name to ensure we use the same results, and -run it. -""" -analysis_1 = ag.AnalysisImaging(dataset=dataset, use_jax=True) - -search_1 = af.Nautilus( - path_prefix=Path("howtogalaxy", "chapter_2"), - name="tutorial_9_search_chaining_1", - unique_tag=dataset_name, - n_live=100, - n_batch=50, # GPU batching and VRAM use explained in tutorial 2 of this chapter. -) - -result_1 = search_1.fit(model=model_1, analysis=analysis_1) - -""" -__Result (Search 1)__ - -The results which are used for prior passing are summarised in the `info` attribute. -""" -print(result_1.info) - -""" -__Prior Passing__ - -We are now going to use the prior passing API to pass these results, in a way which does not require us to manually -write out the inferred parameter values of each component. The details of how prior passing is performed will be -expanded upon at the end of the tutorial. - -We start with the bulge, which in the previous search was a `Sersic` with its centre fixed to (0.0, 0.0) -and its `sersic_index` fixed to 4.0. The API for passing priors is shown below and there are two things worth noting: - - 1) We pass the priors using the `model` attribute of the result. This informs **PyAutoGalaxy** to pass the result as a - model component that is to be fitted for in the next search, using priors that are initialized from the previous - search's result. Note, if we pass as a `model` a parameter that was fixed in search 1 (e.g. the `sersic_index`) it - will be fixed to the same value in search 2. - - 2) We do not pass the `centre` or `sersic_index` using `model`, because it would be fixed to the values that it was in - the first search. By omitting the centre, it uses the default priors on a galaxy, whereas we manually tell the - Sersic index to use a `TruncatedGaussianPrior` centred on 4.0. -""" -bulge = af.Model(ag.lp_linear.Sersic) - -bulge.ell_comps = result_1.model.galaxies.galaxy.bulge.ell_comps -bulge.effective_radius = result_1.model.galaxies.galaxy.bulge.effective_radius -bulge.sersic_index = af.TruncatedGaussianPrior( - mean=4.0, sigma=2.0, lower_limit=0.0, upper_limit=5.0 -) - -""" -For the disk, we are passing the result of an `Exponential` to a `Sersic`. - -We do not pass the `ell_comps` because this would pair them to the `bulge`, as was performed in the first -model-fit. -""" -disk = af.Model(ag.lp_linear.Sersic) - -disk.effective_radius = result_1.model.galaxies.galaxy.disk.effective_radius -disk.sersic_index = af.TruncatedGaussianPrior( - mean=1.0, sigma=2.0, lower_limit=0.0, upper_limit=5.0 -) - -""" -We now compose the model with these components that have had their priors customized. -""" -galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk) - -model_2 = af.Collection(galaxies=af.Collection(galaxy=galaxy)) - -""" -The `info` attribute shows the model, including how all priors are updated via prior passing. -""" -print(model_2.info) - -""" -__Search__ - -Lets setup and run the search. I have given it a different name to the previous tutorial so we can compare the priors -that were passed. -""" -analysis_2 = ag.AnalysisImaging(dataset=dataset, use_jax=True) - -search_2 = af.Nautilus( - path_prefix=Path("howtogalaxy", "chapter_2"), - name="tutorial_10_prior_passing_2", - unique_tag=dataset_name, - n_live=100, - n_batch=50, # GPU batching and VRAM use explained in tutorial 2 of this chapter. -) - -print( - "The non-linear search has begun running - checkout the output/howtogalaxy/chapter_2" - " folder for live output of the results, images and model." - " This Jupyter notebook cell will progress once search has completed - this could take some time!" -) - -result_2 = search_2.fit(model=model_2, analysis=analysis_2) - -print("Search has finished run - you may now continue the notebook.") - - -""" -__Result__ - -We can again inspect the results via the `info` attribute. -""" -print(result_2.info) - -""" -And a plot of the image shows we get a good model again! -""" -aplt.subplot_fit_imaging(fit=result_2.max_log_likelihood_fit) - -""" -__Wrap Up__ - -This tutorial has covered the core of the prior passing API; the chaining example in the `autogalaxy_workspace` -(`autogalaxy_workspace/scripts/guides/modeling/chaining.py`) expands on it further. The main thing to note is that -we can pass entire profiles or galaxies using prior passing, if their model does not change (which for the bulge -and disk above, was not true). The API to pass a whole profile or galaxy is as follows: - - bulge = result_1.model.galaxies.galaxy.bulge - galaxy = result_1.model.galaxies.galaxy - -We can also pass priors using an `instance` instead of a `model`. When an `instance` is used, the maximum likelihood -parameter values are passed as fixed values that are therefore not fitted for by the non-linear search (reducing its -dimensionality). Chained fits often use this to fix one galaxy's light to the best-fit model of an early search -before fitting a second galaxy alongside it — chapter 4 of **HowToGalaxy**, which scales up to modeling multiple -galaxies, and the workspace's chaining example show this in action. - -Lets now think about how priors are passed. Checkout the `model.info` file of the second search of this tutorial. The -parameters do not use the default priors we saw in search 1 (which are typically broad UniformPriors). Instead, -they use GaussianPrior`s where: - - - The mean values are the median PDF results of every parameter in search 1. - - The sigma values are specified in the `width_modifier` field of the profile's entry in the `config/priors` - config files (we will discuss why this is used in a moment). - -Like the manual `GaussianPrior`'s that were used in the previous tutorial, the prior passing API sets up the prior on each -parameter with a `GaussianPrior` centred on the high likelihood regions of parameter space! - -__Detailed Explanation Of Prior Passing__ - -To end, I provide a detailed overview of how prior passing works and illustrate tools that can be used to customize -its behaviour. It is up to you whether you want read this, or move on to the summary that concludes the chapter! - -Lets say I chain two parameters as follows: - - `bulge.effective_radius = result_1.model.galaxies.galaxy.bulge.effective_radius` - -By invoking the `model` attribute, the prior is passed following 3 rules: - - 1) The new parameter, in this case the effective radius, uses a `GaussianPrior`. This is ideal, as the 1D pdf results - we compute at the end of a search are easily summarised as a Gaussian. - - 2) The mean of the `GaussianPrior` is the median PDF value of the parameter estimated in search 1. - - This ensures that the initial sampling of the new search's non-linear starts by searching the region of non-linear - parameter space that correspond to highest log likelihood solutions in the previous search. Our priors therefore - correspond to the `correct` regions of parameter space. - - 3) The sigma of the Gaussian uses the value specified for the profile in the `config/priors/*.yaml` config file's - `width_modifier` field (check these files out now). - -The idea here is simple. We want a value of sigma that gives a `GaussianPrior` wide enough to search a broad -region of parameter space, so that the model can change if a better solution is nearby. However, we want it -to be narrow enough that we don't search too much of parameter space, as this will be slow or risk leading us -into an incorrect solution! - -The `width_modifier` values in the priors config file have been chosen based on our experience as being a good -balance of broadly sampling parameter space but not being so narrow that important solutions are missed. - -There are two ways a value is specified using the priors/width file: - - 1) Absolute: In this case, the error assumed on the parameter is the value given in the config file. - For example, if for the width on centre_0 of a light profile, the width modifier reads "Absolute" with a value - 0.05. This means if the error on the parameter centre_0 was less than 0.05 in the previous search, the sigma of - its `GaussianPrior` in this search will be 0.05. - - 2) Relative: In this case, the error assumed on the parameter is the % of the value of the estimated value given in - the config file. For example, if the intensity estimated in the previous search was 2.0, and the relative error in - the config file reads "Relative" with a value 0.5, then the sigma of the `GaussianPrior` will be 50% of this - value, i.e. sigma = 0.5 * 2.0 = 1.0. - -We use absolute and relative values for different parameters, depending on their properties. For example, using the -relative value of a parameter like the `Profile` centre makes no sense. If our galaxy is centred at (0.0, 0.0), -the relative error will always be tiny and thus poorly defined. Therefore, the default configs in **PyAutoGalaxy** use -absolute errors on the centre. - -However, there are parameters where using an absolute value does not make sense. Intensity is a good example of this. -The intensity of an image depends on its units, S/N, galaxy brightness, etc. There is no single absolute value that -one can use to generically chain the intensity of any two profiles. Thus, it makes more sense to chain them using -the relative value from a previous search. - -__EXAMPLE__ - -Lets go through an example using a real parameter. Lets say in search 1 we fit the galaxy's light with an -elliptical Sersic profile, and we estimate that its sersic index is equal to 4.0. - -To pass this as a prior to search 2 we write: - - galaxy.bulge.sersic_index = result_1.model.galaxy.bulge.sersic_index - -The prior on the galaxy's bulge sersic index in search 2 would thus be a `GaussianPrior` with mean=4.0. - -The value of the Sersic index `width_modifier` in the priors config file sets sigma. The prior config file specifies -that we use an "Absolute" value of 1.5 to chain this prior. Thus, the `GaussianPrior` in search 2 would have a -mean=4.0 and sigma=1.5. - -If the prior config file had instead specified that we use a relative value of 0.8, the GaussianPrior in search 2 would -have a mean=4.0 and sigma = 4.0 * 0.8 = 3.2. - -And with that, we're done. Chaining priors is a bit of an art form, but one that works really well. -""" diff --git a/scripts/chapter_2_modeling/tutorial_11_summary b/scripts/chapter_2_modeling/tutorial_11_summary deleted file mode 100755 index bcbaf7d..0000000 --- a/scripts/chapter_2_modeling/tutorial_11_summary +++ /dev/null @@ -1,20 +0,0 @@ -Congratulations, you've completed the second chapter of the **PyAutoGalaxy** tutorials! - -In this chapter, you learnt: - -1) What a non-linear search is. -2) How to use a non-linear search to sample the parameter space of a model. -3) How the priors we give parameters specify our search of this parameter space. -4) How one must carefully balance complexity and realism when fitting a model to a data-set. -5) The importance of factoring in run-speed when modeling a galaxy, and tricks to speed up the analysis. -6) About masking data in the analysis. -7) How to chain searches together, passing priors from one search to the next so that earlier fits of simpler - models guide later fits of more complex ones. - -At this point, you are ready to begin modeling galaxies. The 'modeling' folders in the -autogalaxy_workspace contains a number of scripts that can be easily adopted to model galaxies using a variety of -different approaches, models and non-linear searches. If you have your own galaxy data, I'd recommend you adapt these -scripts to your data. If you don't have your own data, checkout the 'simulators' folder to simulate your own dataset! - -Alternatively, you may wish to continue on to chapter 3 on pixelized galaxy reconstructions, or chapter 4 on -scaling up to systems with multiple galaxies. \ No newline at end of file diff --git a/scripts/chapter_2_modeling/tutorial_1_non_linear_search.py b/scripts/chapter_2_modeling/tutorial_1_non_linear_search.py index 54ce8bb..9757cf0 100644 --- a/scripts/chapter_2_modeling/tutorial_1_non_linear_search.py +++ b/scripts/chapter_2_modeling/tutorial_1_non_linear_search.py @@ -1,218 +1,62 @@ -r""" +""" Tutorial 1: Non-linear Search ============================= -The starting point for most scientific analysis conducted by an Astronomer is that they have observations of a galaxy -using a telescope like the Hubble Space Telescope, and seek to learn about the galaxy and the Universe from these -observations. With **PyAutoGalaxy**, we seek to learn about the galaxy's structure and morphology, asking questions like -how big is the galaxy, is it disky or bulgy, and how is its light distributed? - -To answer these questions, we must therefore fit the dataset with a model of the galaxy, where the model defines the -light profile that make up the galaxy we fit. Our goal is the find the combination of light profile parameters that -best-fit the data, such that the model represents the galaxy, and therefore the Universe, as well as possible. - -This process is called model-fitting, or "modeling" for short, and we actually did our first example of this in the -previous chapter. If you recall, in the fitting tutorial we set up a fit to a simulated dataset where the parameter -used to simulate the data were unknown, and you guessed the values of the parameters that best fit the data. You -iteratively improved the model-fit by guessing new parameters, over and over, finding solutions which produced -higher `log_likelihood` values. - -However, this approach was not optimal: it was manual and slow, we had no certainty that we had found the best -(e.g. maximum likelihood) solution and for more complex models, with more parameters and light profiles, it would -have been completely unfeasible. - -In this chapter, we perform modeling as a scientist would actually do it, and introduce the statistical inference -techniques that will ultimately allow us to fit complex models made of many light profiles to real galaxy data, -and begin learning about real galaxies in the Universe. - -This first tutorial introduces a number of key statistical concepts that are fundamental to understanding how -model-fitting works, both for **PyAutoGalaxy** and in general. - -__Overview__ +In chapter 1, you adjusted a galaxy model by hand and inspected how well its image matched the data. Now we will +ask a search to do this for us. Our aim is still to learn about the galaxy: its size, shape and concentration. -In this tutorial, we will use a non-linear search to fit a single Sersic light profile to simulated imaging of a -galaxy. We will: - -- Introduce concept like a "parameter space", "likelihood surface" and "priors", and relate them to how a non-linear - search works. - -- Introduce the `Analysis` class, which defines the `log_likelihood_function` that quantifies the goodness of fit of a - model instance to the data. - -- Fit datasets with different non-linear searches, including a maximum likelihood estimator (MLE), - Markov Chain Monte Carlo (MCMC) and nested sampling. +We will fit one Sersic profile using Nautilus, a nested sampler. You do not need to learn several kinds of search +to start modelling galaxies. Alternative searches are covered in the optional searches tutorial. __Contents__ -This tutorial is split into the following sections: - -- **Parameter Space**: Introduce the concept of a "parameter space" and how it relates to model-fitting. -- **Non-Linear Search**: Introduce the concept of a "non-linear search" and how it fits models to data. -- **Search Types**: Introduce the maximum likelihood estimator (MLE), Markov Chain Monte Carlo (MCMC) and nested sampling search algorithms used in this tutorial. -- **Deeper Background**: Provide links to resources that more thoroughly describe the statistical principles that underpin non-linear searches. -- **Data**: Load and plot the galaxy dataset we'll fit. -- **Model**: Introduce the galaxy model we'll fit to the data. -- **Priors**: Introduce priors and how they are used to define the parameter space and guide the non-linear search. -- **Analysis**: Introduce the `Analysis` class, which contains the `log_likelihood_function` used to fit the model to the data. -- **Searches**: An overview of the searches used in this tutorial. -- **Maximum Likelihood Estimation (MLE)**: Perform a model-fit using the MLE search. -- **Markov Chain Monte Carlo (MCMC)**: Perform a model-fit using the MCMC search. -- **Nested Sampling**: Perform a model-fit using the nested sampling search. -- **Result**: The result of the model-fit, including the maximum likelihood model. -- **Samples**: The samples of the non-linear search, used to compute parameter estimates and uncertainties. -- **Customizing Searches**: How to customize the settings of the non-linear search. -- **Wrap Up**: A summary of the concepts introduced in this tutorial. +- **Parameter Space:** The galaxy models we can explore. +- **Dataset and Mask:** The observation we will fit. +- **Model and Priors:** The components and possible parameter values. +- **Analysis:** The interface between a model and the data. +- **Nested Sampling:** Use Nautilus to explore possible models. +- **Result:** Inspect the fit and the uncertainty in its parameters. __Parameter Space__ -In mathematics, a function is defined by its parameters, which map inputs to outputs. For example, consider the simple function: - -\[ -f(x) = x^2 -\] - -Here, \(x\) is the input parameter, and \(f(x)\) returns the output \(x^2\). This relationship defines -the "parameter space" of the function, which in this case forms a parabola. - -Functions can also have multiple parameters, such as: - -\[ -f(x, y, z) = x + y^2 - z^3 -\] - -This defines a parameter space in three dimensions, representing the relationships between \(x\), \(y\), \(z\), -and the output \(f(x, y, z)\). - -This concept of parameter space is closely related to how we approach model-fitting. For instance, in chapter 1, -we created instances of a `Galaxy` object with -parameters like \( (\text{`centre_0`}, \text{`centre_1`}, \text{`ell_comps_0`}, \text{`ell_comps_1`}, \text{`intensity`}, \text{`effective_radius`}, \text{`sersic_index`}) \). -These parameters were used to fit data and compute a log likelihood. - -We can think of this process as analogous to the function \(f(\( (\text{`centre_0`}, \text{`centre_1`}, \text{`ell_comps_0`}, \text{`ell_comps_1`}, \text{`intensity`}, \text{`effective_radius`}, \text{`sersic_index`}) \))\), -where the output is the log likelihood. This function, which maps parameter values to a log likelihood, is known -as the "likelihood function" in statistical inference. To be explicit, we’ll refer to it as the `log_likelihood_function` -since it deals with the log of the likelihood function. - -By framing the likelihood this way, we can think of our model as having its own parameter space—a multidimensional -surface defined by all possible values of the -parameters \( (\text{`centre_0`}, \text{`centre_1`}, \text{`ell_comps_0`}, \text{`ell_comps_1`}, \text{`intensity`}, \text{`effective_radius`}, \text{`sersic_index`}) \). -This surface, known as the "likelihood surface," represents how the log likelihood changes across different parameter -values. During model-fitting, our goal is to find the peak of this surface, where the fit to the data is optimal. - -This parameter space is "non-linear," meaning the relationship between the model parameters and the log likelihood is -not a simple linear one. Because of this non-linearity, we cannot predict the log likelihood from a given set of model -parameters without actually performing a fit to the data, as we did in the fitting tutorial of chapter 1. - -__Non-Linear Search__ - -Now that we understand our problem in terms of a non-linear parameter space with a likelihood surface, we can -introduce the method used to fit the model to the data —- the "non-linear search". - -Previously, our approach involved manually guessing models until finding one with a good fit and high log likelihood. -Surprisingly, this random guessing forms the basis of how model-fitting using a non-linear search actually works! - -A non-linear search involves systematically guessing many models while tracking their log likelihoods. As the -algorithm progresses, it tends to favor models with parameter combinations that have previously yielded higher -log likelihoods. This iterative refinement helps to efficiently explore the vast parameter space. - -There are two key differences between guessing random models and using a non-linear search: - -- **Computational Efficiency**: The non-linear search can evaluate the log likelihood of a model parameter - combinations in milliseconds and therefore many thousands of models in minutes. This computational speed enables - it to thoroughly sample potential solutions, which would be impractical for a human. - -- **Effective Sampling**: The search algorithm maintains a robust memory of previously guessed models and their log - likelihoods. This allows it to sample potential solutions more thoroughly and converge on the highest - likelihood solutions more efficiently, which is again impractical for a human. - -Think of the non-linear search as systematically exploring parameter space to pinpoint regions with the highest log -likelihood values. Its primary goal is to identify and converge on the parameter values that best describe the data. +Imagine changing only the galaxy's size and concentration. Each pair of values describes a different galaxy. +All those possible pairs form a two-dimensional parameter space. Adding its centre and shape adds more dimensions. +A point in this space is one particular model, with a number assigned to every free parameter. -__Search Types__ +The likelihood function gives each point a score by comparing the model prediction with the data and its noise. +Plotting that score over parameter space would give a likelihood surface. High regions describe better fits; +the parameter space is the set of possible inputs, while the likelihood surface describes their scores. -There are different types of non-linear searches, each of which explores parameter space in a unique way. -In this example, we will use three types of searches, which broadly represent the various approaches to non-linear -searches used in statistical inference. +__Non-linear Search__ -These are: - -- **Maximum Likelihood Estimation (MLE)**: This method aims to find the model that maximizes the likelihood function. - It does so by testing nearby models and adjusting parameters in the direction that increases the likelihood. - -- **Markov Chain Monte Carlo (MCMC)**: This approach uses a group of "walkers" that explore parameter space randomly. - The likelihood at each walker's position influences the probability of the walker moving to a new position. - -- **Nested Sampling**: This technique samples points from the parameter space iteratively. Lower likelihood points - are replaced by higher likelihood ones, gradually concentrating the samples in regions of high likelihood. - -We will provide more details on each of these searches below. - -__Deeper Background__ - -**The descriptions of how searches work in this example are simplified and phenomenological and do not give a full -description of how they work at a deep statistical level. The goal is to provide you with an intuition for how to use -them and when different searches are appropriate for different problems. Later tutorials will provide a more formal -description of how these searches work.** - -If you're interested in learning more about these principles, you can explore resources such as: - -- [Markov Chain Monte Carlo (MCMC)](https://en.wikipedia.org/wiki/Markov_chain_Monte_Carlo) -- [Introduction to MCMC Sampling](https://twiecki.io/blog/2015/11/10/mcmc-sampling/) -- [Nested Sampling](https://www.imperial.ac.uk/media/imperial-college/research-centres-and-groups/astrophysics/public/icic/data-analysis-workshop/2016/NestedSampling_JRP.pdf) -- [A Zero-Math Introduction to MCMC Methods](https://towardsdatascience.com/a-zero-math-introduction-to-markov-chain-monte-carlo-methods-dcba889e0c50) +A search tries many parameter combinations, evaluates their likelihoods and uses what it learns to explore +promising regions. This automates the repeated guesses you made in chapter 1. Relationships between parameters +make the task difficult: a larger, dimmer galaxy may resemble a smaller, brighter one. A search must explore +these possibilities, rather than adjust each parameter independently. """ # from autogalaxy import setup_notebook; setup_notebook() from pathlib import Path +import numpy as np +import autofit as af import autogalaxy as ag import autogalaxy.plot as aplt """ -__PyAutoFit__ - -Modeling uses the probabilistic programming language -[PyAutoFit](https://github.com/PyAutoLabs/PyAutoFit), an open-source project that allows complex model -fitting techniques to be straightforwardly integrated into scientific modeling software. - -**PyAutoFit** is actually a spin-off project of **PyAutoGalaxy**, whereby we found that the statistical techniques and -methods we applied to model galaxies could be used in a more general setting to many different scientific -problems. Check it out if you are interested in developing your own software to perform advanced model-fitting! - -We import this library separately from **PyAutoGalaxy**. -""" -import autofit as af +__Dataset and Mask__ +Load the imaging data and retain the region inside the circular mask. The simulator creates the data if needed. +The image, noise map and PSF together describe the observation; none specifies which galaxy model we must fit. """ -__Initial Setup__ -Let's first load the `Imaging` dataset, which we will use to fit a model with a non-linear search. - -The galaxy in this image was generated using a `Sersic` light profile, which we'll also use in our model fitting -in this tutorial. This means the model we are going to fit is identical to the one used to simulate the data, -allowing us to assess the fitting process under controlled conditions. - -The dataset, as well as all subsequent datasets used in future tutorials, is stored in -the `HowToGalaxy/dataset/imaging` folder. -""" dataset_name = "simple__sersic" dataset_path = Path("dataset") / "imaging" / dataset_name - -""" -__Dataset Auto-Simulation__ - -If the dataset does not already exist on your system, it will be created by running the corresponding -simulator script. This ensures that all example scripts can be run without manually simulating data first. -""" if ag.util.dataset.should_simulate(str(dataset_path)): import subprocess import sys - subprocess.run( - [sys.executable, "scripts/simulators/sersic.py"], - check=True, - ) - + subprocess.run([sys.executable, "scripts/simulators/sersic.py"], check=True) dataset = ag.Imaging.from_fits( data_path=dataset_path / "data.fits", @@ -220,506 +64,112 @@ psf_path=dataset_path / "psf.fits", pixel_scales=0.1, ) - -aplt.subplot_imaging_dataset(dataset=dataset) - -""" -__Mask__ - -The fit requires a mask, which we define as a 3.0" circle. -""" mask = ag.Mask2D.circular( shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=3.0 ) - dataset = dataset.apply_mask(mask=mask) -aplt.subplot_imaging_dataset(dataset=dataset) - -""" -__Model__ - -To compose a model, we will set up a `Galaxy` using a `af.Model`. Instead of manually specifying every parameter -for the galaxy's light profiles (as we did before), we will now define the galaxy using only the class of each -profile. Using a `Model` object tells **PyAutoGalaxy** that the parameters of the profiles should be fitted for -during the non-linear search. - -In this case, we'll model the galaxy with an elliptical Sersic light profile, which is linear and represents -its bulge component (the same profile used to simulate the galaxy). """ -galaxy_model = af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp_linear.Sersic) +__Over Sampling__ +The bright centre changes rapidly across a pixel. Adaptive over sampling evaluates it on a finer grid so that +numerical inaccuracies do not masquerade as poor models. The outskirts need fewer evaluations. """ -We now input the model component into a `Collection` object, which groups all the model components used to fit the data. - -As with profiles, we give galaxies descriptive names like `bulge`, or `disk`. Since this model has only one -galaxy, we'll simply refer to it as `galaxy` throughout the tutorials. -It may seem odd that we define two `Collections`, with the `Collection` in the outer loop only having a `galaxies` -attribute. In future tutorials, we'll see that we can add additional model-components to a model other than just -galaxies, and the API below therefore makes it simple to extend the model to include these components. -""" -model = af.Collection(galaxies=af.Collection(galaxy=galaxy_model)) +over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from( + grid=dataset.grid, + sub_size_list=[8, 4, 2], + radial_list=[0.3, 0.6], + centre_list=[(0.0, 0.0)], +) +dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) +aplt.subplot_imaging_dataset(dataset=dataset) """ -The `info` attribute shows the model in a readable format. +__Model__ -[The `info` below may not display optimally on your computer screen, for example the whitespace between parameter -names on the left and parameter priors on the right may lead them to appear across multiple lines. This is a -common issue in Jupyter notebooks. +PyAutoFit supplies the model and search tools; PyAutoGalaxy supplies the galaxy physics and data analysis. +Passing a profile class to `af.Model` makes its parameters quantities to infer. This differs from the fixed +profile instances we created in chapter 1. -The`info_whitespace_length` parameter in the file `config/general.yaml` in the [output] section can be changed to -increase or decrease the amount of whitespace (The Jupyter notebook kernel will need to be reset for this change to -appear in a notebook).] +We use a linear Sersic profile. Its intensity is still fitted, but is calculated directly for each trial shape +instead of being another parameter for Nautilus to search. Tutorial 4 explains this in detail. """ + +galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp_linear.Sersic) +model = af.Collection(galaxies=af.Collection(galaxy=galaxy)) print(model.info) """ __Priors__ -When we examine the `.info` of our model, we notice that each parameter (like `centre`, `effective_radius`, -and `sersic_index` in our `Sersic` model) is associated with priors, such as `UniformPrior`. Priors define the -range of permissible values that each parameter can assume during the model fitting process, for example a uniform -prior means that a parameter is equally likely to be any value within the given range, but cannot be outside of it. +The model summary lists a prior for every free parameter. A prior describes which values we allow and how much +weight we give them before the fit. A uniform prior assigns equal weight within its limits. A Gaussian prior +favours values near its mean, with its width set by `sigma`. -The priors displayed above use default values defined in the `config/priors` directory. These default values have -been chosen to be broad, and contain the breadth of plausible solutions one should expect when fitting light -profiles to a real galaxy. - -For instance, consider the `centre` parameter of our `Sersic` light profile. In theory, it could take on any value from -negative to positive infinity. However, imaging datasets are typically reduced such that the galaxy centre is close -to (0.0", 0.0"). Therefore, a `GaussianPrior` with `mean=0.0` and `sigma=0.1` is a good description of where the -galaxy `centre` is. - -If the galaxy had a different centre in the dataset, we would change the mean of the prior to reflect this. -However, in general, we advise all galaxy images are reduced such that the galaxy is at (0.0", 0.0"). - -Priors serve two primary purposes: - -**Defining Valid Parameter Space:** Priors specify the range of parameter values that constitute valid solutions. -This ensures that our model explores only those solutions that are consistent with our observed data and physical -constraints. - -**Incorporating Prior Knowledge:** Priors also encapsulate our prior beliefs or expectations about the model -parameters. For instance, if we have previously fitted a similar model to another dataset and obtained certain -parameter values, we can incorporate this knowledge into our priors for a new dataset. This approach guides the -model fitting process towards parameter values that are more probable based on our prior understanding. - -Below, we manually specify the priors on all parameter in our `Sersic` model. The custom priors below are -close to the default priors drawn via configfiles, with the main purpose of the code below to show you how to -customize priors yourself. +The defaults come from `config/priors`. They cover a broad range of galaxies. Our cutout places the bright centre +near (0.0, 0.0), so a prior concentrated around that position is sensible. We can customise it as follows: """ + model.galaxies.galaxy.bulge.centre.centre_0 = af.GaussianPrior(mean=0.0, sigma=0.1) model.galaxies.galaxy.bulge.centre.centre_1 = af.GaussianPrior(mean=0.0, sigma=0.1) -model.galaxies.galaxy.bulge.ell_comps.ell_comps_0 = af.UniformPrior( - lower_limit=-1.0, upper_limit=1.0 -) -model.galaxies.galaxy.bulge.ell_comps.ell_comps_1 = af.UniformPrior( - lower_limit=-1.0, upper_limit=1.0 -) -model.galaxies.galaxy.bulge.effective_radius = af.UniformPrior( - lower_limit=0.0, upper_limit=10.0 -) -model.galaxies.galaxy.bulge.sersic_index = af.UniformPrior( - lower_limit=0.8, upper_limit=8.0 -) - -""" -By reprinting the `model.info`, we can see that the priors have been updated to the values we specified. -""" print(model.info) """ -__Analysis__ - -The `AnalysisImaging` object defines how an instance of a model, consisting of a set of parameters values for the -light profiles, is fitted to the `Imaging` dataset. - -The fit is performed using the analysis class's `log_likelihood_function`, which in model-fitting is a commonly used -term to describe a function that given a model and data, fits the model to the data to return a value of log -likelihood. - -In the fitting tutorial in chapter 1 you essentially performed this likelihood function yourself by hand, when you -entered different models to a `FitImaging` object and used its `log_likelihood` property to quantify how well it -fitted the data. - -A detailed step-by-step visual guide of the likelihood function is provided -at `autogalaxy_workspace/*/imaging/likelihood_function.ipynb`. -""" -analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True) - -""" -__Searches__ - -To perform a non-linear search, we create an instance of a `NonLinearSearch` object. **PyAutoFit** offers many options -for this. A detailed description of each search method and guidance on when to use them can be found in -the [search cookbook](https://pyautofit.readthedocs.io/en/latest/cookbooks/search.html). - -In this tutorial, we’ll focus on three searches that represent different approaches to model fitting: - -1. **Maximum Likelihood Estimation (MLE)** using the `LBFGS` non-linear search. -2. **Markov Chain Monte Carlo (MCMC)** using the `Emcee` non-linear search. -3. **Nested Sampling** using the `Nautilus` non-linear search. - -In this example, non-linear search results are stored in memory rather than written to hard disk because the fits -are fast and can therefore be easily regenerated. The next tutorial will perform fits which write results to the -hard-disk and discuss the outputs that are generated. - -__Maximum Likelihood Estimation (MLE)__ - -Maximum likelihood estimation (MLE) is the most straightforward type of non-linear search. Here is a simplified -overview of how it works: - -1. Starts at a point in parameter space with a set of initial values for the model parameters. -2. Calculates the likelihood of the model at this starting point. -3. Evaluates the likelihood at nearby points to estimate the gradient, determining the direction in which to move "up" in parameter space. -4. Moves to a new point where, based on the gradient, the likelihood is higher. - -This process repeats until the search finds a point where the likelihood can no longer be improved, indicating that -the maximum likelihood has been reached. - -The `LBFGS` search is an example of an MLE algorithm that follows this iterative procedure. Let’s see how it -performs on our Sersic model. - -In the example below, we do not specify a starting point for the MLE, so it begins at the center of the prior -range for each parameter. -""" -search = af.LBFGS() - -""" -To begin the model-fit via the non-linear search, we pass it our model and analysis and begin the fit. - -The fit will take a minute or so to run. -""" -print( - """ - The non-linear search has begun running. - This Jupyter notebook cell will progress once the search has completed - this could take a few minutes! - """ -) - -model = af.Collection(galaxies=af.Collection(galaxy=galaxy_model)) - -result = search.fit(model=model, analysis=analysis) - -print("The search has finished run - you may now continue the notebook.") - -""" -Upon completion the non-linear search returns a `Result` object, which contains information about the model-fit. - -The `info` attribute shows the result in a readable format. - -[Above, we discussed that the `info_whitespace_length` parameter in the config files could be changed to make -the `model.info` attribute display optimally on your computer. This attribute also controls the whitespace of the -`result.info` attribute.] -""" -print(result.info) - - -""" - -One thing the result contains we'll use now is the `FitImaging` object that corresponds to the set of model -parameters that gave the maximum log likelihood solution. - -We plot this object to inspect how good our fit was. -""" -aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) - -""" -The fit quality is poor, with significant residuals, meaning that the MLE failed to identify the correct model. - -This happened because the starting point of the search was a poor match to the data, placing it far from the true -solution in parameter space. As a result, after moving "up" the likelihood gradient several times, the search -settled into a "local maximum", a local peak in the likelihood surface that was better than models that surrounded -it in parameter space, but far from the global maximum solution. - -To achieve a better fit with MLE, the search needs to begin in a region of parameter space where the log likelihood -is higher. This process is known as "initialization" and it involves providing the search with an -appropriate "starting point" in parameter space. - -The code below shows how we can customize the starting point of the search to provide a better initialization, -with the values input below close to the true values used to simulate the dataset. -""" -initializer = af.InitializerParamStartPoints( - { - model.galaxies.galaxy.bulge.centre.centre_0: 0.0, - model.galaxies.galaxy.bulge.centre.centre_1: 0.0, - model.galaxies.galaxy.bulge.ell_comps.ell_comps_0: 0.1, - model.galaxies.galaxy.bulge.ell_comps.ell_comps_1: 0.05, - model.galaxies.galaxy.bulge.effective_radius: 1.0, - model.galaxies.galaxy.bulge.sersic_index: 3.7, - } -) - -search = af.LBFGS(initializer=initializer) - -print( - """ - The non-linear search has begun running. - This Jupyter notebook cell will progress once the search has completed - this could take a few minutes! - """ -) - -model = af.Collection(galaxies=af.Collection(galaxy=galaxy_model)) - -result = search.fit(model=model, analysis=analysis) - -print("The search has finished run - you may now continue the notebook.") - -""" -By printing `result.info` and looking at the maximum log likelihood model, we can confirm the search provided a -good model fit with a much higher likelihood than the incorrect model above. -""" -print(result.info) - -aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) - -""" -The MLE is a great starting point for model-fitting because it’s fast, conceptually simple, and often yields -accurate results. It is especially effective if you can provide a good initialization, allowing it to find the -best-fit solution quickly. - -However, MLE has its limitations. As seen above, it can get "stuck" in a local maximum, particularly if the -starting point is poorly chosen. In complex model-fitting problems, providing a suitable starting point can be -challenging. While MLE performed well in the example with just six parameters, it struggles with models that have -many parameters, as the complexity of the likelihood surface makes simply moving "up" the gradient less effective. - -The MLE also does not provide any information on the errors on the parameters, which is a significant limitation. -The next two types of searches "map out" the likelihood surface, such that they not only infer the maximum likelihood -solution but also quantify the errors on the parameters. +A narrow prior can help a search, but can also exclude a good explanation of the data. Priors should reflect +reasonable knowledge and assumptions, not force the answer we hope to find. Tutorial 3 explores this balance. -__Markov Chain Monte Carlo (MCMC)__ - -Markov Chain Monte Carlo (MCMC) is a more powerful method for model-fitting, though it is also more computationally -intensive and conceptually complex. Here’s a simplified overview: - -1. Place a set of "walkers" in parameter space, each with random parameter values. -2. Calculate the likelihood of each walker's position. -3. Move the walkers to new positions, guided by the likelihood of their current positions. Walkers in high-likelihood -regions encourage those in lower regions to move closer to them. - -This process repeats, with the walkers converging on the highest-likelihood regions of parameter space. - -Unlike MLE, MCMC thoroughly explores parameter space. While MLE moves a single point up the likelihood gradient, -MCMC uses many walkers to explore high-likelihood regions, making it more effective at finding the global maximum, -though slower. +__Analysis__ -There is a reduced risk of getting stuck in local maxima, because whilst some walkers may temporarily get stuck in -one, other walkers will explore other regions of parameter space and encourage the walker in local maxima to move -away from it and head towards higher likelihood regions. +The data and model have separate jobs. The data describe what we measured and its uncertainty; the model describes +possible galaxies. An `Analysis` object connects them. It takes a trial model instance, predicts its image, +convolves it with the PSF and compares it with the measured image using the noise map. Its +`log_likelihood_function` returns the score that guides the search. -In the example below, we use the `Emcee` MCMC search to fit the galaxy. The search starts with walkers -initialized in a "ball" around the center of the model’s priors, similar to the MLE search that failed earlier. +This is the same comparison you performed using `FitImaging` in chapter 1, now repeated automatically. +`use_jax=True` enables the numerical engine that accelerates these repeated calculations on a CPU or a compatible +GPU. You do not need to know how JAX works to use it. """ -search = af.Emcee( - nwalkers=20, # The number of walkers we'll use to sample parameter space. - nsteps=300, # The number of steps each walker takes, after which 20 * 300 = 6000 steps the non-linear search ends. -) -print( - """ - The non-linear search has begun running. - This Jupyter notebook cell will progress once the search has completed - this could take a few minutes! - """ -) - -model = af.Collection(galaxies=af.Collection(galaxy=galaxy_model)) - -result = search.fit(model=model, analysis=analysis) - -print("The search has finished run - you may now continue the notebook.") - -print(result.info) - -aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) +analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True) """ -The MCMC search succeeded, finding the same high-likelihood model that the MLE search with a good starting point -identified, even without a good initialization. Its use of multiple walkers exploring parameter space allowed it to -avoid the local maxima that had trapped the MLE search. - -A major advantage of MCMC is that it provides estimates of parameter uncertainties by "mapping out" the likelihood -surface, unlike MLE, which only finds the maximum likelihood solution. These error estimates are accessible in -the `result.info` string and through the `result.samples` object, which is explained fully in tutorial 7. - -While a good starting point wasn't necessary for this simple model, it becomes essential for efficiently mapping the -likelihood surface in more complex models with many parameters. The code below shows an MCMC fit using a good starting -point, with two key differences from the MLE initialization: +__Nested Sampling__ -1. Instead of single starting values, we provide bounds for each parameter. MCMC initializes each walker in a -small "ball" in parameter space, requiring a defined range for each parameter from which values are randomly drawn. +Nautilus starts by drawing trial models from the priors. These are called live points. As it explores, it focuses +on regions containing higher-likelihood models. The samples describe both good-fitting parameter values and the +range of values consistent with the data under our model assumptions. -2. We do not specify a starting point for the `ell_comps` parameters, allowing its initial values to be drawn from its -priors. This illustrates that with MCMC, it’s not necessary to know a good starting point for every parameter. +The `n_live` setting controls how thoroughly the search explores. We use 100 for this introductory example; +it is not a guarantee of a correct fit. Tutorial 2 explains practical search settings, including `n_batch`. +Nautilus has stopping criteria, so we do not have to prescribe a fixed number of trial models. """ -initializer = af.InitializerParamBounds( - { - model.galaxies.galaxy.bulge.centre.centre_0: (-0.01, 0.01), - model.galaxies.galaxy.bulge.centre.centre_1: (-0.01, 0.01), - model.galaxies.galaxy.bulge.effective_radius: (0.0, 2.0), - model.galaxies.galaxy.bulge.sersic_index: (3.0, 5.0), - } -) - -search = af.Emcee( - nwalkers=20, # The number of walkers we'll use to sample parameter space. - nsteps=300, # The number of steps each walker takes, after which 20 * 300 = 6000 steps the non-linear search ends. - initializer=initializer, -) - -print( - """ - The non-linear search has begun running. - This Jupyter notebook cell will progress once the search has completed - this could take a few minutes! - """ -) - -model = af.Collection(galaxies=af.Collection(galaxy=galaxy_model)) +search = af.Nautilus(n_live=100, n_batch=50) result = search.fit(model=model, analysis=analysis) -print("The search has finished run - you may now continue the notebook.") - -print(result.info) - """ -MCMC is a powerful tool for model-fitting, providing accurate parameter estimates and uncertainties. For simple models -without a starting point, MCMC can still find the correct solution, and if a good starting point is provided, it can -efficiently scale to more complex models with more parameters. - -The main limitation of MCMC is that one has to supply the number of steps the walkers take (`nsteps`). If this value -is too low, the walkers may not explore the likelihood surface sufficiently. It can be challenging to know the right -number of steps, especially if models of different complexity are being fitted or if datasets of varying quality are -used. One often ends up having to perform "trial and error" to verify a sufficient number of steps are used. - -MCMC can perform badly in parameter spaces with certain types of complexity, for example when there are -are many local maxima "peaks" that many of the walkers can become stuck walking around them, so many walkers that -when they communicate with one another they cannot gain enough information to move away from the local peak. - -__Nested Sampling__ - -**Nested Sampling** is an advanced method for model-fitting that excels in handling complex models with intricate -parameter spaces. Here’s a simplified overview of its process: - -1. Start with a set of "live points" in parameter space, each initialized with random parameter values drawn from their respective priors. +__Result__ -2. Compute the log likelihood for each live point. - -3. Draw a new point based on the likelihood of the current live points, favoring regions of higher likelihood. - -4. If the new point has a higher likelihood than any existing live point, it becomes a live point, and the lowest likelihood live point is discarded. - -This iterative process continues, gradually focusing the live points around higher likelihood regions of parameter -space until they converge on the highest likelihood solution. - -Like MCMC, Nested Sampling effectively maps out parameter space, providing accurate estimates of parameters and -their uncertainties. +The result summary reports inferred parameter values and uncertainties. For example, a range of plausible +half-light radii tells us how precisely the data constrain the galaxy's size, given this model and its priors. +A best-fitting value alone does not tell us this. """ -search = af.Nautilus( - n_live=100, - n_batch=50, # Explained in next tutorial -) - -""" -To begin the model-fit via the non-linear search, we pass it our model and analysis and begin the fit. - -The fit will take a minute or so to run. -""" -print( - """ - The non-linear search has begun running. - This Jupyter notebook cell will progress once the search has completed - this could take a few minutes! - """ -) - -model = af.Collection(galaxies=af.Collection(galaxy=galaxy_model)) - -result = search.fit(model=model, analysis=analysis) - -print("The search has finished run - you may now continue the notebook.") print(result.info) - aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) """ -The **Nested Sampling** search was successful, identifying the same high-likelihood model as the MLE and MCMC searches. -One of the main benefits of Nested Sampling is its ability to provide accurate parameter estimates and uncertainties, -similar to MCMC. Additionally, it features a built-in stopping criterion, which eliminates the need for users to -specify the number of steps the search should take. - -This method also excels in handling complex parameter spaces, particularly those with multiple local peaks. This is because -the live points will identify each peak and converge around them, but then begin to be discarded from a peak if higher -likelihood points are found elsewhere in parameter space. In MCMC, the walkers can get stuck indefinitely in -peaks, causing the method to stall. - -Another significant advantage is that Nested Sampling estimates an important statistical quantity -known as "evidence." This value quantifies how well the model fits the data while considering the model's complexity, -making it essential for Bayesian model comparison, which will be covered in later tutorials. - -Nested sampling cannot use a starting point, as it always samples parameter space from scratch by drawing live points -from the priors. This is both good and bad, depending on if you have access to a good starting point or not. If you do -not, your MCMC / MLE fit will likely struggle with initialization compared to Nested Sampling. Conversely, if you do -possess a robust starting point, it can significantly enhance the performance of MCMC, allowing it to begin closer to -the highest likelihood regions of parameter space. This proximity can lead to faster convergence and more reliable results. - -However, Nested Sampling does have limitations; it often scales poorly with increased model complexity. For example, -once a model has around 50 or more parameters, Nested Sampling can become very slow, whereas MCMC remains efficient -even in such complex parameter spaces. +Look at the data, model image and residuals together. Does the model reproduce the central brightness and faint +outskirts? Residuals consistent with noise are encouraging; coherent bright or dark structures need investigation. +A search finishing is not evidence by itself that it found an adequate model or explored all good solutions. -__What is The Best Search To Use?__ - -In statistical inference, the choice of the best search method depends on several factors specific to the problem, -such as model complexity, availability of a starting point, and whether error estimates are required. More subtle -aspects, like the shape of the likelihood surface and the presence of multiple peaks, also play a role, as you'll -explore in later tutorials. - -When approaching a model-fitting problem, it's usually advisable to try various search methods to find the most -effective one. - -However, after extensive testing within **PyAutoGalaxy**, a clear recommendation has emerged for fitting galaxy light -profiles and studying galaxy structure. The nested sampling method `Nautilus` consistently proves to be the most -effective. It requires fewer iterations than MCMC or MLE methods (when no starting point is used), provides robust -sampling even for complex models, includes a built-in stopping criterion, and delivers reliable error estimates. - -All examples in the `autogalaxy_workspace` use the `Nautilus` search, and future tutorials in the **HowToGalaxy** -series will also use it. We strongly recommend using `Nautilus` from now on. - -That said, MLE and MCMC searches can still be effective, and you're encouraged to experiment with them. If you have -a reliable starting point, MLE and MCMC can outperform `Nautilus` in terms of speed and efficiency. Additionally, -for very complex models (e.g., with 30+ parameters), `Nautilus` may struggle, while MCMC might handle the complexity -better—though you're unlikely to encounter that level of complexity soon. - -Lastly, MLE, MCMC, and nested sampling are just three categories of non-linear searches, each containing different -algorithms with their own strengths and weaknesses. Exploring these options could help you find the best approach -for your model-fitting needs. For more details on each method, see the [search cookbook](https://pyautofit.readthedocs.io/en/latest/cookbooks/search.html). +The samples are available through `result.samples`. For now, inspecting the fit and summary is enough. Tutorial 2 +introduces saved output and points to the workspace for detailed results analysis. __Wrap Up__ -This tutorial has laid the foundation with several fundamental concepts in model fitting and statistical inference: - -1. **Parameter Space**: This refers to the range of possible values that each parameter in a model can take. It -defines the dimensions over which the likelihood of different parameter values is evaluated. - -2. **Likelihood Function**: This function receives as input a model with specific parameter values and returns a -log likelihood value that quantifies how well the model describes the data. - -3. **Likelihood Surface**: This surface represents how the likelihood of the model varies across the parameter space. -It helps in identifying the best-fit parameters that maximize the likelihood of the model given the data. - -4. **Non-linear Search**: This is an optimization technique used to explore the parameter space and find the -combination of parameter values that best describe the data. It iteratively adjusts the parameters to maximize the -likelihood. Many different search algorithms exist, each with their own strengths and weaknesses, and this tutorial -used the MLE, MCMC, and nested sampling searches. - -5. **Priors**: Priors are probabilities assigned to different values of parameters before considering the data. -They encapsulate our prior knowledge or assumptions about the parameter values. Priors can constrain the parameter -space, making the search more efficient and realistic. - -6. **Model Fitting**: The process of adjusting model parameters to minimize the difference between model predictions -and observed data, quantified by the likelihood function. - -Understanding these concepts is crucial as they form the backbone of model fitting and parameter estimation in -scientific research and data analysis. In the next tutorials, these concepts will be further expanded upon to -deepen your understanding and provide more advanced techniques for model fitting and analysis. +We supplied data, a model and an Analysis object, then asked Nautilus to explore the model's parameter space. +The next tutorial uses these same ingredients for a more realistic galaxy and explains the practicalities of +running and inspecting a fit. """ diff --git a/scripts/chapter_2_modeling/tutorial_2_practicalities.py b/scripts/chapter_2_modeling/tutorial_2_practicalities.py index 26869c6..635102e 100644 --- a/scripts/chapter_2_modeling/tutorial_2_practicalities.py +++ b/scripts/chapter_2_modeling/tutorial_2_practicalities.py @@ -2,85 +2,43 @@ Tutorial 2: Practicalities ========================== -In the last tutorial, we introduced foundational statistical concepts essential for model-fitting, such as parameter -spaces, likelihoods, priors, and non-linear searches. Understanding these statistical concepts is crucial for -performing model fits effectively. - -However, achieving successful model-fitting also requires practical skills, including how to manage outputs, -review results, interpret model quality, and ensure run-times are efficient enough for your scientific needs. - -This tutorial will focus on these practical aspects of model-fitting, including: - -- How to save results to your hard disk. -- How to navigate the output folder and examine model-fit results to assess quality. -- How to estimate the run-time of a model-fit before initiating it, and change settings to make it faster or run the analysis in parallel. +A galaxy can contain a compact bulge and an extended disk. We now fit both, while learning how to run a search, +manage its memory use and inspect its output. These practical skills let us assess a model as the fit progresses. __Contents__ -This tutorial is split into the following sections: - - **PyAutoFit:** The parent package of PyAutoGalaxy, which handles practicalities of model-fitting. - **Initial Setup:** Load the dataset we'll fit a model to using a non-linear search. - **Mask:** Apply a mask to the dataset. - **Over Sampling:** Apply adaptive over sampling to the dataset. - **Model:** Introduce the model we will fit to the data. - **Search:** Setup the non-linear search, Nautilus, used to fit the model to the data. - **Search Settings:** Discuss the settings of the non-linear search, including the number of live points. - **Iterations Per Update:** How often the non-linear search outputs the current results to hard-disk. - **Analysis:** Create the Analysis object which contains the `log_likelihood_function` that the non-linear search calls. - **Run Times:** Estimate the run-time of the model-fit before initiating it. - **Model-Fit:** Fit the model to the data. - **Result Info:** Print the results of the model-fit to the terminal. - **Output Folder:** Inspect the output folder where results are stored. - **Unique Identifier:** Discussion of the unique identifier of the model-fit which names the folder in the output directory. - **Output Folder Contents:** What is output to the output folder (model results, visualization, etc.). - **Result:** Plot the best-fit model to the data. +- **Dataset and Mask:** Inspect a galaxy with a bulge and disk. +- **Model:** Make the model more realistic. +- **Search Settings:** Balance exploration, batching and output updates. +- **Analysis and Run Times:** Understand the cost of a fit. +- **VRAM Use:** Check memory before fitting. +- **Output Folder:** Find summaries, images and saved results. +- **Unique Identifier:** Understand separate fits and resuming. +- **Results and Configuration:** Inspect the fit and find further tools. """ # from autogalaxy import setup_notebook; setup_notebook() from pathlib import Path +import numpy as np +import autofit as af import autogalaxy as ag import autogalaxy.plot as aplt """ -__PyAutoFit__ - -Modeling uses the probabilistic programming language -[PyAutoFit](https://github.com/PyAutoLabs/PyAutoFit), an open-source project that allows complex model -fitting techniques to be straightforwardly integrated into scientific modeling software. +__Dataset and Mask__ -The majority of tools that make model-fitting practical are provided by PyAutoFit, for example it handles -all output of the non-linear search to hard-disk, the visualization of results and the estimation of run-times. +Load the imaging data and retain the region inside the circular mask. The simulator creates the data if needed. +The image, noise map and PSF together describe the observation; none specifies which galaxy model we must fit. """ -import autofit as af - -""" -__Initial Setup__ - -Lets first load the `Imaging` dataset we'll fit a model with using a non-linear search. -This is the same dataset we fitted in the previous tutorial, and we'll repeat the same fit, as we simply want -to illustrate the practicalities of model-fitting in this tutorial. -""" -dataset_name = "simple__sersic" +dataset_name = "simple" dataset_path = Path("dataset") / "imaging" / dataset_name - -""" -__Dataset Auto-Simulation__ - -If the dataset does not already exist on your system, it will be created by running the corresponding -simulator script. This ensures that all example scripts can be run without manually simulating data first. -""" if ag.util.dataset.should_simulate(str(dataset_path)): import subprocess import sys - subprocess.run( - [sys.executable, "scripts/simulators/sersic.py"], - check=True, - ) - + subprocess.run([sys.executable, "scripts/simulators/simple.py"], check=True) dataset = ag.Imaging.from_fits( data_path=dataset_path / "data.fits", @@ -88,316 +46,207 @@ psf_path=dataset_path / "psf.fits", pixel_scales=0.1, ) - -aplt.subplot_imaging_dataset(dataset=dataset) - -""" -__Mask__ - -We again apply a 3.0" mask to the dataset. -""" mask = ag.Mask2D.circular( - shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=3.0 + shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5 ) - dataset = dataset.apply_mask(mask=mask) -aplt.subplot_imaging_dataset(dataset=dataset) - """ __Over Sampling__ -Over sampling is a numerical technique where the images of light profiles and galaxies are evaluated -on a higher resolution grid than the image data to ensure the calculation is accurate. - -For a new user, the details of over-sampling are not important, therefore just be aware that below we make it so that -all calculations use an adaptive over sampling scheme which ensures high accuracy and precision. - -Once you are more experienced, you should read up on over-sampling in more detail via -the `autogalaxy_workspace/*/guides/advanced/over_sampling.ipynb` notebook. +The bright centre changes rapidly across a pixel. Adaptive over sampling evaluates it on a finer grid so that +numerical inaccuracies do not masquerade as poor models. The outskirts need fewer evaluations. """ + over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from( grid=dataset.grid, sub_size_list=[8, 4, 2], radial_list=[0.3, 0.6], centre_list=[(0.0, 0.0)], ) - dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) - +aplt.subplot_imaging_dataset(dataset=dataset) """ __Model__ -We compose the model using the same API as the previous tutorial. +Look at the bright central light and the more extended emission around it. A single Sersic profile need not +capture both structures. We represent the bulge with a Sersic and the disk with an Exponential profile, as in the +simulator. Real galaxies need not separate this neatly, but this controlled example lets us practise modelling. -This model is the same as the previous tutorial, a single `Galaxy` with a `Sersic` light profile. +Here we use ordinary light profiles, so both intensities are searched along with the shapes. There are 13 free +parameters: seven for the bulge and six for the disk. Greater realism has also given the search more to explore. +Tutorial 4 returns to linear profiles and shows how to reduce this burden. """ -galaxy_model = af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp_linear.Sersic) - -model = af.Collection(galaxies=af.Collection(galaxy=galaxy_model)) +galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp.Sersic, disk=ag.lp.Exponential) +model = af.Collection(galaxies=af.Collection(galaxy=galaxy)) print(model.info) """ -__Search__ - -To fit the model, we now create the non-linear search object, selecting the nested sampling algorithm, Nautilus, -as recommended in the previous tutorial. - -We set up the `Nautilus` object with these parameters: - -- **`path_prefix`**: specifies the output directory, here set to `HowToGalaxy/output/howtogalaxy/chapter_2`. - -- **`name`**: gives the search a descriptive name, which creates the full output path -as `HowToGalaxy/output/howtogalaxy/chapter_2/tutorial_2_practicalities`. - -- **`n_live`**: controls the number of live points Nautilus uses to sample parameter space. - __Search Settings__ -Nautilus samples parameter space by placing "live points" representing different galaxy models. Each point has an -associated `log_likelihood` that reflects how well it fits the data. By mapping where high-likelihood solutions are -located, it can focus on searching those regions. +We use 200 live points for this more complex model. More live points generally improve exploration at the cost +of more work; fewer may be faster but can miss good solutions. The appropriate value depends on the model and +data, and must be judged from the results rather than a universal rule. -The main setting to balance is the **number of live points**. More live points allow Nautilus to map parameter space -more thoroughly, increasing accuracy but also runtime. Fewer live points reduce run-time but may make the search less -reliable, possibly getting stuck in local maxima. +`n_batch=50` lets the search evaluate batches of trial models using the accelerated likelihood. This can make good +use of a GPU, but larger batches need more memory. Batching does not replace adequate exploration with live points. -The ideal number of live points depends on model complexity. More parameters generally require more live points, but -the default of 3000 is more than sufficient for most galaxy models. Lower values can still yield reliable results, particularly -for simpler models. For this example (6 parameters), we reduce the live points to 80 to speed up runtime without -compromising accuracy. - -Tuning non-linear search settings (e.g., the number of live points) to match model complexity is essential. We aim -for enough live points to ensure accurate results (i.e., finding a global maximum) but not so many that runtime -is excessive. - -In practice, the optimal number of live points is often found through trial and error, guided by summary statistics -on how well the search is performing, which we’ll cover below. For this single Sersic model with a linear light -profile, 80 live points is sufficient to achieve reliable results. +`path_prefix` groups related fits, `name` identifies this tutorial and `unique_tag` identifies the dataset. +Together they organise the output folders described below. __Iterations Per Update__ -Every N iterations, the non-linear search outputs the current results to the folder `HowToGalaxy/output`, -which includes producing visualization. - -Depending on how long it takes for the model to be fitted to the data (see discussion about run times below), -this can take up a large fraction of the run-time of the non-linear search. +`iterations_per_quick_update=2500` controls quick output updates after roughly this many likelihood evaluations. +Full updates have their own setting, `iterations_per_full_update`. The two update types do different amounts of +work, so this does not mean that every saved product is regenerated every 2500 evaluations. -For this fit, the fit is very fast, thus we set a high value of `iterations_per_quick_update=2500` to ensure these updates -do not slow down the overall speed of the model-fit. - -**If the iteration per update is too low, the model-fit may be significantly slowed down by the time it takes to -output results and visualization frequently to hard-disk. If your fit is consistent displaying a log saying that it -is outputting results, try increasing this value to ensure the model-fit runs efficiently.** +Frequent plotting and disk writes can dominate a fast fit. Increase the update interval if output takes too much +of the runtime; decrease it if you need more frequent feedback while diagnosing a fit. """ + search = af.Nautilus( path_prefix=Path("howtogalaxy", "chapter_2"), name="tutorial_2_practicalities", unique_tag=dataset_name, - n_live=80, - n_batch=50, # GPU model fits are batched and run simultaneously, see the run times section below. + n_live=200, + n_batch=50, iterations_per_quick_update=2500, ) """ __Analysis__ -We again create the `AnalysisImaging` object which contains the `log_likelihood_function` that the non-linear search -calls to fit the model to the data. +The model defines possible bulges and disks; `AnalysisImaging` compares their predicted light with this masked +dataset. The search itself does not need to know how a galaxy image is calculated. """ + analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True) """ __Run Times__ -Another key practicality in model-fitting is the run-time of the model-fit. Modeling can be a computationally -expensive process, whereby the fitting of complex models to high resolution datasets run times may be of order hours, -days or weeks. - -Run times are dictated by two factors: - - - **The log likelihood evaluation time:** the time it takes for a single `instance` of the model to be fitted to - the dataset such that a log likelihood is returned. - - - **The number of iterations (e.g. log likelihood evaluations) performed by the non-linear search:** more complex - models require more iterations to converge to a solution (and as discussed above, settings like the number of live - points also control this). - -For this analysis, the log likelihood evaluation time is ~0.05 seconds, which is extremely fast for model fitting. - -The more advanced fitting techniques discussed later in this chapter (e.g. multi Gaussian expansions, shapelets) and -the pixelizations of chapter 3 have longer log likelihood evaluation times. However, on GPU, they can be so fast that -they may not produce significantly longer overall run-times. - -To estimate the expected overall run time of the model-fit we multiply the log likelihood evaluation time by an -estimate of the number of iterations the non-linear search will perform, which is around 50000 to 100000 for this model. - -Tests thus far reveal CPU run times are around 30 minutes, and GPU run times around 10 minutes. - -__Model-Fit__ - -To begin the model-fit, we pass the model and analysis objects to the search, which performs a non-linear search to -identify models that best fit the data. - -Running model fits via non-linear search can take significant time. While the fit in this tutorial should -complete in a few minutes, more complex models may require longer run times. In Jupyter notebooks, this can be -limiting, as the notebook cell will only complete once the fit finishes, preventing you from advancing through the -tutorial or running additional code. - -To work around this, we recommend running tutorial scripts as standalone Python scripts, found -in the `scripts/` folder of the HowToGalaxy repository. These scripts mirror the notebook tutorials but run independently of -Jupyter notebooks. For example, you can start a script with: - -`python3 scripts/chapter_2_modeling/tutorial_2_practicalities.py` +Two important costs are how expensive the likelihood is to evaluate and how many evaluations the search needs. +More pixels, finer over sampling and more elaborate models can increase the first; difficult parameter spaces +and more thorough search settings can increase the second. -Using scripts allows results to be saved to the hard drive in the `output` folder, enabling you to inspect results -immediately once the script completes. When rerun, the script loads results directly from disk, so any Jupyter -notebook cells will quickly load and display the complete model-fit results if they’re already saved. +With JAX, compilation adds an initial cost, after which compiled calculations are reused. Batches can evaluate +several models together, so timing one ordinary `FitImaging` call is not a reliable prediction of search runtime. +Use a representative run on your own machine and inspect `search.summary`, allowing for compilation, search work +and output overhead. There is no fixed runtime or evaluations-per-parameter rule that applies to every fit. -This approach not only avoids the slowdowns associated with notebook cells during lengthy runs but is also essential -for using super-computers for fitting tasks, as they require separate Python scripts. +__VRAM Use__ -For tasks like loading results, inspecting data, plotting, and interpreting results, Jupyter notebooks remain ideal. +A GPU has a finite amount of memory, often called VRAM. Larger datasets, models and batches need more of it. +The following estimates memory for the likelihood calculation at the chosen batch size: """ -print( - "The non-linear search has begun running - checkout the HowToGalaxy/output/" - " folder for live output of the results, images and model." - " This Jupyter notebook cell will progress once search has completed - this could take some time!" -) - -result = search.fit(model=model, analysis=analysis) -print("Search has finished run - you may now continue the notebook.") +analysis.print_vram_use(model=model, batch_size=search.batch_size) """ -__Result Info__ +This is a likelihood estimate, not a promise about the total memory required by the process. Compilation, +other arrays and other programs also need space. On a CPU, available system memory is the relevant limit. +If memory is tight, try reducing `n_batch` from 50 to 10 before removing useful data or simplifying the science. -A concise readable summary of the results is given by printing its `info` attribute. +__Model Fit__ -[Above, we discussed that the `info_whitespace_length` parameter in the config files could be changed to make -the `model.info` attribute display optimally on your computer. This attribute also controls the whitespace of the -`result.info` attribute.] +Run the fit below. A notebook cell waits until it finishes, but output appears on disk while it runs. +You can instead run `python scripts/chapter_2_modeling/tutorial_2_practicalities.py` from the repository root. +Scripts and notebooks save to the same output location when run with the same settings and working directory. +A script does not inherently make the inference faster; it is often more convenient for long unattended fits. """ + +result = search.fit(model=model, analysis=analysis) print(result.info) """ __Output Folder__ -Now checkout the `HowToGalaxy/output` folder. - -This is where the results of the search are written to hard-disk (in the `tutorial_2_practicalities` folder). - -Once completed images, results and information about the fit appear in this folder, meaning that you don't need -to keep running Python code to see the result. +Open `output` in the repository root. The layout below shows the main products of a completed fit; the exact +images and optional files depend on configuration and which updates have run. + +```text +output/ ++-- howtogalaxy/ + +-- chapter_2/ + +-- simple/ # unique_tag + +-- tutorial_2_practicalities/ # name + +-- / + +-- model.info + +-- model.results + +-- search.summary + +-- search.log + +-- image/ + | +-- dataset.png + | +-- dataset.fits + | +-- fit.png + | +-- fit.fits + +-- files/ + +-- model.json + +-- galaxies.json + +-- search.json + +-- samples.csv + +-- samples_info.json + +-- samples_summary.json + +-- covariance.csv + +-- dataset_identity.json + +-- search_internal/ +``` + +`model.info` records the model and priors. `model.results` summarises inferred parameters and uncertainties. +`image/fit.png` lets you inspect the current best fit without writing Python. `search.summary` helps assess search +progress and runtime, while `search.log` records messages. The `files` directory stores machine-readable results; +search-specific checkpoint files support resuming an interrupted fit. __Unique Identifier__ -In the output folder, you will note that results are in a folder which is a collection of random characters. This acts -as a `unique_identifier` of the model-fit, where this identifier is generated based on the model, search and dataset -that are used in the fit. - -An identical combination of model, search and dataset generates the same identifier, meaning that rerunning the -script will use the existing results to resume the model-fit. In contrast, if you change the model, search or dataset, -a new unique identifier will be generated, ensuring that the model-fit results are output into a separate folder. - -We additionally want the unique identifier to be specific to the dataset fitted, so that if we fit different datasets -with the same model and search results are output to a different folder. We achieved this for the fit above by passing -the `dataset_name` to the search's `unique_tag`. - -__Output Folder Contents__ - -Now this is running you should checkout the `HowToGalaxy/output` folder. This is where the results of the -search are written to hard-disk (in the `tutorial_2_practicalities` folder), where all outputs are human readable -(e.g. as .json, .csv or text files). - -As the fit progresses, results are written to the `output` folder on the fly using the highest likelihood model found -by the non-linear search so far. This means you can inspect the results of the model-fit as it runs, without having to -wait for the non-linear search to terminate. - -The `output` folder includes: - - - `model.info`: Summarizes the model, its parameters and their priors discussed in the next tutorial. - - - `model.results`: Summarizes the highest likelihood model inferred so far including errors. - - - `images`: Visualization of the highest likelihood model-fit to the dataset, (e.g. a fit subplot showing the - galaxies, model data and residuals). - - - `files`: A folder containing .fits files of the dataset, the model as a human-readable .json file, - a `.csv` table of every non-linear search sample and other files containing information about the model-fit. - - - `search.summary`: A file providing summary statistics on the performance of the non-linear search. - - - `search_internal`: Internal files of the non-linear search (in this case Nautilus) used for resuming the fit and - visualizing the search. - -__Result__ - -The `search.fit` method produces a `result` object, packed with useful information about the model fit that we’ll -explore in detail in a later tutorial. - -One component of the `result` object we’ll use now is the `FitImaging` object, which corresponds to the set of model -parameters that yielded the maximum log-likelihood solution. Plotting this object lets us visually inspect how well -the model fits the data. - -In this example, the fit to the data is excellent, with residuals near zero, as expected since the same model was -used both to simulate and fit the data. -""" -aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) +The identifier is derived from identifying model and search settings, including the tag. It is not a random name. +Repeating the same setup finds the same output, allowing an interrupted search to resume when its checkpoint is +intact, or a completed result to load rather than run again. Changing identifying settings creates another folder. -""" -The Probability Density Functions (PDF's) of the results can be plotted using Nautilus's in-built visualization -library, which is wrapped via the `corner_anesthetic` function. - -The PDF shows the 1D and 2D probabilities estimated for every parameter after the model-fit. The two dimensional -figures can show the degeneracies between different parameters, for example how increasing the intensity $I$ of the -galaxy and decreasing its effective radius $R_{Eff}$ lead to similar likelihoods and probabilities. +`unique_tag=dataset_name` keeps datasets separate. The identifier does not automatically hash every data pixel, +mask choice or Analysis setting. If you change these while keeping the same model and search, use a new name or +tag so that you cannot accidentally reuse an old result. Keep enough information to reproduce each analysis. -This PDF will be discussed more in the next tutorial. +__Results__ -The plot is labeled with short hand parameter names (e.g. `sersic_index` is mapped to the short hand -parameter `n`). These mappings are specified in the `config/notation.yaml` file and can be customized by users. +The result gives us the maximum-likelihood fit and galaxies, plus samples from which parameter estimates and +uncertainties are calculated. For this course, our priority is learning to obtain reliable fits. +""" -The superscripts of labels are the path of names each component was given in the model (e.g. for the `Sersic` -bulge, `galaxy.bulge`: the galaxy's name `galaxy` and its name `bulge` defined when making the `Model` above). +aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) -Components in different named galaxy or profile paths can be distinguished by their superscripts. Profiles within -the same path, such as Gaussians in a basis, can share a superscript. When the model has more than one top-level -component, each also gets its own -corner plot in the output folder (`corner_anesthetic_.png`, switched in `config/visualize/plots_search.yaml`). +""" +Inspect the central bulge, disk and residuals. A visually good fit is encouraging, but another search may find a +better solution. The next tutorial explores that failure mode. -The parameters a model is sampled in are not always the ones it is read in: a profile's elliptical components are an -axis ratio and a position angle. Passing `latent=True` to `corner_anesthetic` plots these latent parameters instead. -The same figure is written to the output folder as `corner_anesthetic_latent.png` when `corner_anesthetic_latent` -is switched on in `config/visualize/plots_search.yaml` (off by default), once the fit is complete. With -`latent_model_parameters` enabled, full-sample latent output (`latent_draw_via_pdf: false`) writes these columns -to `files/latent/samples.csv`. Only the plot recentres periodic angles; saved values keep the conversion's range. +Once you can fit real data reliably, use `autogalaxy_workspace/scripts/guides/results/start_here.py` to learn +how to load, manipulate and combine results, including database tools for larger samples. -__Other Practicalities__ +__Parameter Plots__ -The following are examples of other practicalities which I will document fully in this example script in the future, -but so far have no found the time: +The output also includes corner plots showing ranges of plausible parameters and relationships between them. +For example, the bulge's intensity and effective radius can trade off while producing similar images. +The `corner_anesthetic` plotting function can show these distributions. With `latent=True`, it displays derived +quantities such as axis ratio and position angle instead of the sampled elliptical components. -- `config`: The files in `HowToGalaxy/config` which control many aspects of how PyAutoGalaxy runs, - including visualization, the non-linear search settings. +Labels are controlled by `config/notation.yaml`. Component names become superscripts, distinguishing the bulge +from the disk. Search plot switches, including the optional latent corner plot, are in +`config/visualize/plots_search.yaml`. These plots become useful once you have checked the fit itself. -- `config/priors`: Folder containing the default priors on all model components. +__Configuration and Storage__ -- `results`: How to load the results of a model-fit from the output folder to a Python script or Jupyter notebook. +The `config` directory controls defaults for priors, search settings, plotting and output. The +`info_whitespace_length` setting in `config/general.yaml` adjusts the spacing of model and result summaries. +Restart a notebook kernel when changing configuration that is loaded at startup. -- `output.yaml`: What files are output to control file size. +`config/output.yaml` controls which products are retained. In particular, `search_internal: false` removes +search internals after completion to save space; keep them if you need the search-specific state later. +Do not remove the checkpoints of an unfinished fit you intend to resume. __Wrap Up__ -This tutorial has illustrated how to handle a number of practicalities that are key to performing model-fitting -effectively. These include: - -- How to save results to your hard disk. - -- How to navigate the output folder and examine model-fit results to assess quality. - -- How to estimate the run-time of a model-fit before initiating it, and change settings to make it faster or run the - analysis in parallel. +We have fitted a more realistic model and learnt where to inspect its progress, results and resource use. +Now we will deliberately give the search too little exploration and learn how to diagnose and improve the fit. """ diff --git a/scripts/chapter_2_modeling/tutorial_3_realism_and_complexity.py b/scripts/chapter_2_modeling/tutorial_3_realism_and_complexity.py deleted file mode 100644 index e85b1b3..0000000 --- a/scripts/chapter_2_modeling/tutorial_3_realism_and_complexity.py +++ /dev/null @@ -1,243 +0,0 @@ -""" -Tutorial 3: Realism and Complexity -================================== - -In the previous two tutorials, we fitted a fairly basic model: the galaxy's light was a single bulge component. -In real observations we know that galaxies are observed to have multiple different morphological structures. - -In this tutorial, we'll use a more realistic model, which consists of the following light profiles: - - - A `Sersic` light profile for the galaxy's bulge [7 parameters]. - - An `Exponential` light profile for the galaxy's disk [6 parameters] - -This model has 13 free parameters, meaning that the parameter space and likelihood function it defines has a -dimensionality of N=13. This is over double the number of parameters and dimensions of the models we fitted in the -previous tutorials and in future exercises, we will fit even more complex models with some 13+ parameters. - -Therefore, take note, as we make our model more realistic, we also make its parameter space more complex, this is -an important concept to keep in mind for the remainder of this chapter! - -__Contents__ - -- **Initial Setup:** Load the dataset and apply a mask. -- **Model + Search + Analysis:** Compose a bulge+disk model and fit it using Nautilus. -- **Result:** Inspect the result and compare to the true model. -- **Global and Local Maxima:** Demonstrate how the search can infer incorrect local maxima solutions. -- **Wrap Up:** Summary of the challenges of fitting more complex and realistic models. -""" - -# from autogalaxy import setup_notebook; setup_notebook() - -from pathlib import Path -import autogalaxy as ag -import autogalaxy.plot as aplt -import autofit as af - -""" -__Initial Setup__ - -we'll use new imaging data of a galaxy, where: - - - The galaxy's bulge is a `Sersic`. - - The galaxy's disk is an `Exponential`. -""" -dataset_name = "simple" -dataset_path = Path("dataset") / "imaging" / dataset_name - -""" -__Dataset Auto-Simulation__ - -If the dataset does not already exist on your system, it will be created by running the corresponding -simulator script. This ensures that all example scripts can be run without manually simulating data first. -""" -if ag.util.dataset.should_simulate(str(dataset_path)): - import subprocess - import sys - - subprocess.run( - [sys.executable, "scripts/simulators/simple.py"], - check=True, - ) - - -dataset = ag.Imaging.from_fits( - data_path=dataset_path / "data.fits", - noise_map_path=dataset_path / "noise_map.fits", - psf_path=dataset_path / "psf.fits", - pixel_scales=0.1, -) - -""" -__Mask__ - -We'll create and use a 2.5" `Mask2D`, which is slightly smaller than the masks we used in previous tutorials. -""" -mask = ag.Mask2D.circular( - shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5 -) - -dataset = dataset.apply_mask(mask=mask) - -""" -__Over Sampling__ - -Apply adaptive over sampling to ensure the calculation is accurate, you can read up on over-sampling in more detail via -the `autogalaxy_workspace/*/guides/advanced/over_sampling.ipynb` notebook. -""" -over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from( - grid=dataset.grid, - sub_size_list=[8, 4, 2], - radial_list=[0.3, 0.6], - centre_list=[(0.0, 0.0)], -) - -dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) - -""" -When plotted, the galaxy's bulge and disk are clearly visible in the centre of the image. -""" -aplt.subplot_imaging_dataset(dataset=dataset) - -""" -__Model + Search + Analysis__ - -Now lets fit the dataset using a search. -""" -model = af.Collection( - galaxies=af.Collection( - galaxy=af.Model( - ag.Galaxy, redshift=0.5, bulge=ag.lp.Sersic, disk=ag.lp.Exponential - ) - ) -) - -search = af.Nautilus( - path_prefix=Path("howtogalaxy", "chapter_2"), - name="tutorial_3_realism_and_complexity", - unique_tag=dataset_name, - n_live=100, - n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2. -) - -analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True) - -print( - "The non-linear search has begun running - checkout the HowToGalaxy/output/howtogalaxy/chapter_2/tutorial_3_realism_and_complexity" - " folder for live output of the results, images and model." - " This Jupyter notebook cell will progress once search has completed - this could take some time!" -) - -result = search.fit(model=model, analysis=analysis) - -print("Search has finished run - you may now continue the notebook.") - -""" -__Result__ - -Inspection of the `info` summary of the result suggests the model has gone to reasonable values. -""" -print(result.info) - -""" -And lets look at how well the model fits the imaging data, which as we are used to fits the data brilliantly! -""" -aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) - -""" -__Global and Local Maxima__ - -Up to now, all of our non-linear searches have been successes. They find a model that provides a visibly good fit -to the data, minimizing the residuals and inferring a high log likelihood value. - -These solutions are called 'global maxima', they correspond to the highest likelihood regions over all of parameter -space. There are no other models in parameter space that would give higher likelihoods, this is the model we want -to always infer! - -However, non-linear searches may not always successfully locate the global maxima models. They may instead infer -a 'local maxima', a solution which has a high log likelihood value relative to the models near it in parameter -space, but where the log likelihood is significantly below the global maxima solution located somewhere else in -parameter space. - -Why does a non-linear search infer these local maxima solutions? As discussed previously, the search guesses many -models over and over, guessing more models in regions of parameter space where previous guesses gave the highest -likelihood solutions. The search gradually 'converges' around any solution that gives a higher likelihood than the -models nearby it in parameter space. If the search is not thorough enough, it may converge around a solution that -appears to give a high likelihood (compared to the models around it) but, as discussed, is only a local maxima over -all of parameter space. - -Inferring such solutions is essentially a failure of our non-linear search and it is something we do not want to -happen! Lets infer a local maxima, by reducing the number of live points, `n_live`, nautilus uses to map out -parameter space. We are going to use so few that the initial search over parameter space has an extremely low -probability of getting close the global maxima, meaning it converges on a local maxima. -""" -search = af.Nautilus( - path_prefix=Path("howtogalaxy", "chapter_2"), - name="tutorial_3_realism_and_complexity__local_maxima", - unique_tag=dataset_name, - n_live=50, - n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2. -) - -print( - "The non-linear search has begun running - checkout the HowToGalaxy/output/howtogalaxy/chapter_2/tutorial_3_realism_and_complexity__local_maxima" - " folder for live output of the results, images and model." - " This Jupyter notebook cell will progress once search has completed - this could take some time!" -) - -result_local_maxima = search.fit(model=model, analysis=analysis) - -print("Search has finished run - you may now continue the notebook.") - -""" -__Result__ - -Inspection of the `info` summary of the result suggests certain parameters have gone to different values to the fit -performed above. -""" -print(result_local_maxima.info) - -""" -Lets look at the fit to the `Imaging` data, which is clearly worse than our original fit above. -""" -aplt.subplot_fit_imaging(fit=result_local_maxima.max_log_likelihood_fit) - -""" -Finally, just to be sure we hit a local maxima, lets compare the maximum log likelihood values of the two results - -The local maxima value is significantly lower, confirming that our non-linear search simply failed to locate galaxy -models which fit the data better when it searched parameter space. -""" -print("Likelihood of Global Model:") -print(result.max_log_likelihood_fit.log_likelihood) -print("Likelihood of Local Model:") -print(result_local_maxima.max_log_likelihood_fit.log_likelihood) - -""" -__Wrap Up__ - -In this example, we intentionally made our non-linear search fail, by using so few live points it had no hope of -sampling parameter space thoroughly. For modeling real galaxies we wouldn't do this intentionally, but the risk of -inferring a local maxima is still very real, especially as we make our model more complex. - -Lets think about *complexity*. As we make our model more realistic, we also made it more complex. For this -tutorial, our non-linear parameter space went from 6 dimensions to 13. This means there was a much larger *volume* of -parameter space to search. As this volume grows, there becomes a higher chance that our non-linear search gets lost -and infers a local maxima, especially if we don't set it up with enough live points! - -At its core, modeling is all about learning how to get a non-linear search to find the global maxima region of -parameter space, even when the model is complex. This will be the main theme throughout the rest of this chapter, -culminating in the 'search chaining' technique that closes it. - -In the next exercise, we'll learn how to deal with failure and begin thinking about how we can ensure our non-linear -search finds the global-maximum log likelihood solution. First, think about the following: - - 1) When you look at an image of a galaxy, do you get a sense of roughly what values certain model - parameters are? - - 2) The non-linear search failed because parameter space was too complex. Could we make it less complex, whilst - still keeping our model fairly realistic? - - 3) The galaxy in this example had only 13 non-linear parameters. Real galaxies may have multiple components (e.g. a - disk, bulge, bar, star-forming knot) and there may even be more than 1 galaxy! Do you think there is any hope of - us navigating a parameter space if the galaxies contribute 30+ parameters? -""" diff --git a/scripts/chapter_2_modeling/tutorial_3_why_modeling_is_hard.py b/scripts/chapter_2_modeling/tutorial_3_why_modeling_is_hard.py new file mode 100644 index 0000000..5ff02a4 --- /dev/null +++ b/scripts/chapter_2_modeling/tutorial_3_why_modeling_is_hard.py @@ -0,0 +1,343 @@ +""" +Tutorial 3: Why Modeling Is Hard +================================ + +The bulge and disk in tutorial 2 made our model more realistic, but also harder to fit. Their centres, shapes, +brightnesses and sizes can trade off. A search can find a plausible galaxy without finding the best explanation +available within the model. + +Here we deliberately make exploration inadequate, then try three ways to improve it: tune priors, simplify the +model and search more thoroughly. Keep the images in view throughout. They tell us what the search is getting +right, what it is missing and which assumptions might help. + +__Contents__ + +- **A Reference Fit:** Repeat the practicalities model for comparison. +- **An Inadequate Search:** Explore the same model with only 14 live points. +- **Local Maxima:** Understand how an apparently plausible fit can be wrong. +- **Prior Tuning:** Use visual impressions to guide exploration. +- **Reducing Complexity:** Test shared bulge and disk geometry. +- **Look Harder:** Give the full model more thorough exploration. +- **Benefits and Weaknesses:** Balance realism, reliability and runtime. +""" + +# from autogalaxy import setup_notebook; setup_notebook() + +from pathlib import Path +import numpy as np +import autofit as af +import autogalaxy as ag +import autogalaxy.plot as aplt + +""" +__Dataset and Mask__ + +Load the imaging data and retain the region inside the circular mask. The simulator creates the data if needed. +The image, noise map and PSF together describe the observation; none specifies which galaxy model we must fit. +""" + +dataset_name = "simple" +dataset_path = Path("dataset") / "imaging" / dataset_name +if ag.util.dataset.should_simulate(str(dataset_path)): + import subprocess + import sys + + subprocess.run([sys.executable, "scripts/simulators/simple.py"], check=True) + +dataset = ag.Imaging.from_fits( + data_path=dataset_path / "data.fits", + noise_map_path=dataset_path / "noise_map.fits", + psf_path=dataset_path / "psf.fits", + pixel_scales=0.1, +) +mask = ag.Mask2D.circular( + shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5 +) +dataset = dataset.apply_mask(mask=mask) + +""" +__Over Sampling__ + +The bright centre changes rapidly across a pixel. Adaptive over sampling evaluates it on a finer grid so that +numerical inaccuracies do not masquerade as poor models. The outskirts need fewer evaluations. +""" + +over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from( + grid=dataset.grid, + sub_size_list=[8, 4, 2], + radial_list=[0.3, 0.6], + centre_list=[(0.0, 0.0)], +) +dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) +aplt.subplot_imaging_dataset(dataset=dataset) + +""" +__A Reference Fit__ + +The bright centre and extended disk are both visible. We repeat tutorial 2's model and search settings, so an +existing completed fit can be loaded. Treat this as a reference to compare against, not a proven global optimum. +On real data we would not know the correct parameter values in advance. +""" + +model = af.Collection( + galaxies=af.Collection( + galaxy=af.Model( + ag.Galaxy, redshift=0.5, bulge=ag.lp.Sersic, disk=ag.lp.Exponential + ) + ) +) +analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True) +search = af.Nautilus( + path_prefix=Path("howtogalaxy", "chapter_2"), + name="tutorial_2_practicalities", + unique_tag=dataset_name, + n_live=200, + n_batch=50, + iterations_per_quick_update=2500, +) +result_reference = search.fit(model=model, analysis=analysis) +aplt.subplot_fit_imaging(fit=result_reference.max_log_likelihood_fit) + +""" +__An Inadequate Search__ + +Now reduce the search to `n_live=14`, leaving the data and model unchanged. Fourteen is the minimum allowed +for this 13-parameter model: ten live points would be rejected before sampling. This deliberately poor setting makes +missing good solutions much more likely. Random searches differ between runs, so it cannot guarantee failure. +If it happens to find a good fit, that does not make 14 live points a reliable choice for this model. +""" + +search = af.Nautilus( + path_prefix=Path("howtogalaxy", "chapter_2"), + name="tutorial_3_inadequate", + unique_tag=dataset_name, + n_live=14, + n_batch=50, +) +result_inadequate = search.fit(model=model, analysis=analysis) +print(result_inadequate.info) +aplt.subplot_fit_imaging(fit=result_inadequate.max_log_likelihood_fit) + +""" +__Compare the Fits__ + +Look for a centre that is too bright or too faint, or residual light following the disk. A reasonable-looking +parameter summary can conceal these failures. Compare the log likelihoods as well as the plots; here the data, +mask and likelihood definition are the same, so higher values mean a better fit. +""" + +print("Reference:", result_reference.max_log_likelihood_fit.log_likelihood) +print("14 live points:", result_inadequate.max_log_likelihood_fit.log_likelihood) + +""" +__Global and Local Maxima__ + +A local maximum is a solution better than nearby alternatives, with a better solution elsewhere in parameter +space. The global maximum is the highest likelihood available in that model. A search can concentrate around a +local peak and miss another: improving the fit nearby does not prove there is nowhere better to look. + +If the reference has a higher likelihood, it directly demonstrates that the inadequate search missed better +models. It does not prove that the reference is the global maximum. If the two agree, inspect repeated runs and +more thorough searches before concluding the exploration is reliable. + +Adding physical components increases the combinations we must explore. This is the central challenge of modelling: +we want enough flexibility to describe a real galaxy, while still exploring the model reliably. + +__Approach 1: Prior Tuning__ + +Return to the image before changing settings. We can see roughly where the galaxy sits, its orientation and how +far its light extends. The default priors must cover many different galaxies; our visual impressions can guide a +search of this particular image. Below we create the bulge and disk separately to make those choices easy to read. +""" +bulge = af.Model(ag.lp.Sersic) +disk = af.Model(ag.lp.Exponential) + + +""" +The light peaks at the centre of the cutout. This suggests that both component centres lie close to (0.0, 0.0). +We use a narrow range around that position, leaving room for a small offset. This judgement comes from the image, +not from looking up the simulator's answer. On real data, first check the coordinate origin and any bright contaminants. +""" + +bulge.centre_0 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05) +bulge.centre_1 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05) +disk.centre_0 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05) +disk.centre_1 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05) + + +""" +The central light is fairly round, while the outer disk is more elongated. The central contours suggest an angle +around 45 degrees; the outer contours lie closer to 30 degrees. The bulge's angle is less obvious because it is +rounder. These are rough impressions, not precise measurements, so our priors allow variation around them. + +We convert approximate axis ratios of 0.9 and 0.7 and those angles into elliptical components. Allowing each +component its own shape matters: forcing them to agree would erase the visual distinction we are trying to model. +""" + +bulge_ell_comps = ag.convert.ell_comps_from(axis_ratio=0.9, angle=45.0) +disk_ell_comps = ag.convert.ell_comps_from(axis_ratio=0.7, angle=30.0) + +bulge.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior( + mean=bulge_ell_comps[0], sigma=0.1, lower_limit=-1.0, upper_limit=1.0 +) +bulge.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior( + mean=bulge_ell_comps[1], sigma=0.1, lower_limit=-1.0, upper_limit=1.0 +) + +disk.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior( + mean=disk_ell_comps[0], sigma=0.1, lower_limit=-1.0, upper_limit=1.0 +) +disk.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior( + mean=disk_ell_comps[1], sigma=0.1, lower_limit=-1.0, upper_limit=1.0 +) + + +""" +The visible galaxy occupies only a few arcseconds. A half-light radius of tens of arcseconds would be a poor +starting guess for this cutout. We favour a compact bulge and a more extended disk, while retaining broad tails. + +The half-light radius encloses half the profile's total light. It is not the radius where the image disappears +into the noise, so visual extent gives guidance rather than an exact radius. Positive limits exclude unphysical +sizes; the width of each prior leaves room for the data to refine our impression. +""" + +bulge.effective_radius = af.TruncatedGaussianPrior( + mean=0.8, sigma=0.5, lower_limit=0.0, upper_limit=np.inf +) +disk.effective_radius = af.TruncatedGaussianPrior( + mean=1.5, sigma=0.8, lower_limit=0.0, upper_limit=np.inf +) + + +""" +The bright, concentrated centre motivates a bulge with a Sersic index around 3, whereas the disk's Exponential +profile has index 1. Neither a bright centre nor a fitted index uniquely identifies a galaxy's physical history. +This is a modelling assumption to test against the residuals, not a morphological classification imposed by eye. +""" + +bulge.sersic_index = af.TruncatedGaussianPrior( + mean=3.0, sigma=1.0, lower_limit=0.0, upper_limit=np.inf +) + + +""" +Now compose the model from these customised components. The names and physical profiles are unchanged; +we have changed the ranges and relative weights assigned to possible parameter values. +""" + +galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk) + +model = af.Collection(galaxies=af.Collection(galaxy=galaxy)) + + +print(model.info) + +""" +Run with 75 live points. This is fewer than the reference's 200, but more than the deliberately inadequate 14. +We are testing a practical remedy, changing both the priors and search effort; it is not an isolated experiment +measuring the effect of priors alone. Check whether the central and outer residuals improve. +""" + +search = af.Nautilus( + path_prefix=Path("howtogalaxy", "chapter_2"), + name="tutorial_3_tuned_priors", + unique_tag=dataset_name, + n_live=75, + n_batch=50, +) +result_tuned = search.fit(model=model, analysis=analysis) +print(result_tuned.info) +aplt.subplot_fit_imaging(fit=result_tuned.max_log_likelihood_fit) + +""" +__Approach 2: Reducing Complexity__ + +The bulge and disk overlap and have similar centres, so sharing a centre is plausible. We go further and also +force them to have identical elliptical components. This removes four free parameters, leaving nine. + +The image already hints at the risk: the outer disk looks flatter than the central bulge. An easier model to +search can still be a worse description of the galaxy. We deliberately test this assumption and inspect its cost. +Use fresh profiles so the tuned priors above do not carry into this separate experiment. +""" + +bulge = af.Model(ag.lp.Sersic) +disk = af.Model(ag.lp.Exponential) +bulge.centre = disk.centre +bulge.ell_comps = disk.ell_comps +model = af.Collection( + galaxies=af.Collection( + galaxy=af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk) + ) +) +print(model.info) + +""" +Use 75 live points again. Inspect the residuals around the centre and along the disk. This simulation has +components with different shapes, so the shared-geometry model cannot reproduce both exactly, even with a +perfect search. Persistent structure can signal an inadequate model rather than inadequate exploration. +""" + +search = af.Nautilus( + path_prefix=Path("howtogalaxy", "chapter_2"), + name="tutorial_3_reduced_complexity", + unique_tag=dataset_name, + n_live=75, + n_batch=50, +) +result_reduced = search.fit(model=model, analysis=analysis) +print(result_reduced.info) +aplt.subplot_fit_imaging(fit=result_reduced.max_log_likelihood_fit) + +""" +__Approach 3: Look Harder__ + +We can retain the original model and broad priors, and give Nautilus more live points. This is straightforward +and does not require deciding by eye how each galaxy should look. It costs more computation, and still cannot +guarantee that every good region will be found. + +The optional fit below uses 300 live points. Uncomment it to run the more thorough comparison. It is left out of +the default execution because the earlier experiments already involve several fits. +""" + +model = af.Collection( + galaxies=af.Collection( + galaxy=af.Model( + ag.Galaxy, redshift=0.5, bulge=ag.lp.Sersic, disk=ag.lp.Exponential + ) + ) +) +search = af.Nautilus( + path_prefix=Path("howtogalaxy", "chapter_2"), + name="tutorial_3_look_harder", + unique_tag=dataset_name, + n_live=300, + n_batch=50, +) +# result_thorough = search.fit(model=model, analysis=analysis) +# aplt.subplot_fit_imaging(fit=result_thorough.max_log_likelihood_fit) + +""" +__Benefits and Weaknesses__ + +| Approach | Benefit | Weakness | +| --- | --- | --- | +| Tune priors (75 live points) | Use visible structure to avoid implausible regions. | Incorrect or overly narrow choices can bias the fit; individual tuning takes time for large samples. | +| Reduce complexity (75 live points) | Fewer dimensions can make exploration easier and faster. | Shared geometry can prevent the model from describing real differences between components. | +| Look harder (300 live points) | Keep the flexible model and apply the same approach to many galaxies. | More computation can become expensive and does not repair an unsuitable model. | + +The 14-live-point run is deliberately inadequate; the 200-live-point practicalities run is our reference. +Compare actual residuals and likelihoods rather than expecting these settings to produce identical outcomes on +every run. These experiments illustrate choices, not a controlled ranking of runtime. + +__Model Limitations__ + +Even a well-explored Sersic-plus-Exponential model cannot reproduce every real galaxy. A bar, spiral structure, +dust or bright star-forming knots can leave residuals no adjustment of these two smooth profiles will remove. +Look at the shape and location of those residuals before deciding that the search simply needs longer. + +__Wrap Up__ + +Search chaining is especially useful because it helps strike a balance between realistic models, reliable +exploration and manageable runtimes. It is a central tool for moving beyond isolated, hand-tuned fits. Tutorial 6 +shows it in practice; first, linear profiles give us another way to simplify exploration while retaining flexibility. +""" diff --git a/scripts/chapter_2_modeling/tutorial_4_dealing_with_failure.py b/scripts/chapter_2_modeling/tutorial_4_dealing_with_failure.py deleted file mode 100644 index d0afc60..0000000 --- a/scripts/chapter_2_modeling/tutorial_4_dealing_with_failure.py +++ /dev/null @@ -1,439 +0,0 @@ -""" -Tutorial 4: Dealing With Failure -================================ - -In the previous tutorial we intentionally made our non-linear search infer a local maxima solution and therefore return -a physically incorrect model. In this tutorial, we will pretend that we have modeled our galaxy and inferred a local -maxima. We introduce three approaches one can take that changes how we fit the model, all of which have the aim of -ensuring we infer the global maxima: - - 1) Prior Tuning: Tell the non-linear search where to search parameter space. - 2) Reduce Complexity: Fit a model with fewer parameters and therefore a simpler parameter space. - 3) Look Harder: Brute force a global maxima by telling the non-linear search to sample parameter space more thoroughly. - -Each approach has its benefits and disadvantages and we will discuss them in detail. - -In the previous tutorial, when we inferred a local maxima we knew that we had done so. For modeling a real galaxy, -we do not know the true model and it may be unclear if the solution we inferred is a global or local maxima. The -methods we learn in this tutorial are therefore equally important for verifying that a solution that looks like a -global maxima solution is in indeed the global maxima. - -__Contents__ - -- **Initial Setup:** Load the dataset and apply a mask. -- **Approach 1: Prior Tuning:** Narrow the priors to guide the search to the correct region of parameter space. -- **Approach 2: Reducing Complexity:** Simplify the model to reduce the dimensionality of parameter space. -- **Approach 3: Look Harder:** Increase the thoroughness of the non-linear search sampling. -""" - -# from autogalaxy import setup_notebook; setup_notebook() - -import numpy as np -from pathlib import Path -import autogalaxy as ag -import autogalaxy.plot as aplt -import autofit as af - -""" -__Initial Setup__ - -we'll use the same galaxy data as the previous tutorial, where: - - - The galaxy's bulge is a `Sersic`. - - The galaxy's disk is an `Exponential`. -""" -dataset_name = "simple" -dataset_path = Path("dataset") / "imaging" / dataset_name - -""" -__Dataset Auto-Simulation__ - -If the dataset does not already exist on your system, it will be created by running the corresponding -simulator script. This ensures that all example scripts can be run without manually simulating data first. -""" -if ag.util.dataset.should_simulate(str(dataset_path)): - import subprocess - import sys - - subprocess.run( - [sys.executable, "scripts/simulators/simple.py"], - check=True, - ) - - -dataset = ag.Imaging.from_fits( - data_path=dataset_path / "data.fits", - noise_map_path=dataset_path / "noise_map.fits", - psf_path=dataset_path / "psf.fits", - pixel_scales=0.1, -) - -""" -__Mask__ - -we'll create and use a smaller 2.5" `Mask2D` again. -""" -mask = ag.Mask2D.circular( - shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5 -) - -dataset = dataset.apply_mask(mask=mask) - -""" -__Over Sampling__ - -Apply adaptive over sampling to ensure the calculation is accurate, you can read up on over-sampling in more detail via -the `autogalaxy_workspace/*/guides/advanced/over_sampling.ipynb` notebook. -""" -over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from( - grid=dataset.grid, - sub_size_list=[8, 4, 2], - radial_list=[0.3, 0.6], - centre_list=[(0.0, 0.0)], -) - -dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) - -""" -When plotted, the galaxy's bulge and disk are clearly visible in the centre of the image. -""" -aplt.subplot_imaging_dataset(dataset=dataset) - -""" -__Approach 1: Prior Tuning__ - -First, we are going to try giving our non-linear search a helping hand. Our priors tell the non-linear search where -to look in parameter space. If we tell it to look in the right place (that is, 'tune' our priors), this might mean -the search finds the global solution when it previously found a local maxima. - -We saw in a previous tutorial that we can fully customize priors in **PyAutoGalaxy**, so lets give it a go. I've set up -a custom search below and specified priors that give the non-linear search a better chance of inferring the global -maxima solution, alongside discussing how I have changed each prior from the default values specified by the -`config/priors` config files. - -In a previous tutorial, we customized the priors of a model by creating a `Galaxy` as a `Model` and customizing each -prior: -""" -galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp.Sersic, disk=ag.lp.Exponential) - -galaxy.bulge.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) -galaxy.bulge.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) -galaxy.disk.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) -galaxy.disk.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) - -""" -We can alternatively create the light and bulge profiles as a `Model` and customize their parameters, and then pass them -to the model galaxy and overall model. These two approaches are equivalent, but in this example the style below -provides more concise and readable code. We will therefore switch to this code style in this tutorial, but may swap -back and forth between the two styles throughout **HowToGalaxy** depending on what is more readable. -""" -bulge = af.Model(ag.lp.Sersic) -disk = af.Model(ag.lp.Exponential) - -""" -By default, the prior on the $(y,x)$ coordinates of a `LightProfile` is a GaussianPrior with -`mean=0.0` and `sigma=0.3`. However, visual inspection of our galaxy image tells us that its centre (based on the -galaxy's luminous emission) is at x = 0.0" and y = 0.0", so lets replace this prior with a narrow `UniformPrior`, so -the non-linear search looks over a very narrow range of `centre` values in parameter space. -""" -bulge.centre_0 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05) -bulge.centre_1 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05) -disk.centre_0 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05) -disk.centre_1 = af.UniformPrior(lower_limit=-0.05, upper_limit=0.05) - -""" -By default, the elliptical components of our galaxy's elliptical `LightProfile` are `TruncatedGaussianPrior`'s -with `mean=0.0` and `sigma=0.3`. Note that the solution `ell_comps=(0.0, 0.0)` corresponds to a spherical system -and that all physical solutions (e.g. with axis-ratios running from 0.0 -> 1.0 and position angles 0.0 -> 180.0 degrees) -are encapsulated for solutions where each component runs from -1.0 -> 1.0). - -However, through visual inspection of the image we can often determine the position angle of the galaxy's light, which -for this data is clearly 45.0 degrees counter-clockwise from the x-axis. We can update the priors on our elliptical -components to reflect this. The `lower_limit` and `upper_limit` on a `TruncatedGaussianPrior` ensure the solutions cannot go -outside the physically plausible range -1.0 -> 1.0. -""" -bulge.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior( - mean=0.333333, sigma=0.1, lower_limit=-1.0, upper_limit=1.0 -) -bulge.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior( - mean=0.0, sigma=0.1, lower_limit=-1.0, upper_limit=1.0 -) - -disk.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior( - mean=0.333333, sigma=0.1, lower_limit=-1.0, upper_limit=1.0 -) -disk.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior( - mean=0.0, sigma=0.1, lower_limit=-1.0, upper_limit=1.0 -) - -""" -The `effective_radius` of light profile is its 'half-light' radius, the radius at which 50% of its total luminosity -is internal to a circle defined within that radius. **PyAutoGalaxy** assumes a `UniformPrior` on this quantity between -0.0" and 30.0". This large range of values is required to cover the size of all possible galaxies that can be -observed in the Universe. - -However, inspection of this image shows the galaxy's light does not extend anywhere near 30.0", so lets reduce its -value for both bulge and disk components. - -We retain an `upper_limit=np.inf`, which means that the maximum physical value that the effective radius -can go to is infinity, as it is in the real Universe. Equally, the `lower_limit=0.0` ensures unphysical negative -values are not sampled. - -However, the inputs `mean=1.0` and `sigma=0.8` ensure the majority of samples are drawn around much lower values -between 0.0" -> 2.0". -""" -bulge.effective_radius = af.TruncatedGaussianPrior( - mean=1.0, sigma=0.8, lower_limit=0.0, upper_limit=np.inf -) -disk.effective_radius = af.TruncatedGaussianPrior( - mean=1.0, sigma=0.8, lower_limit=0.0, upper_limit=np.inf -) - -""" -The `sersic_index` defines how concentrated the light profile is. In galaxy structure studies, values of Sersic index -around 1.0 indicate a disk galaxy (which is the value the `Exponential` uses). - -Higher values of 3 or 4 indicate an elliptical galaxy. **PyAutoGalaxy** assumes a `UniformPrior` between 0.8 and 5.0 -by default on this parameter, as a user could model galaxies -where the galaxy is of any morphology. - -We are assuming the `bulge` component is a bulge, thus we can change its prior on the `sersic_index` to a value near 3. -""" -bulge.sersic_index = af.TruncatedGaussianPrior( - mean=3.0, sigma=1.0, lower_limit=0.0, upper_limit=np.inf -) - -""" -We now compose the overall model, where the galaxy model uses the `Model` components above which had their -priors customized. -""" -galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk) - -model = af.Collection(galaxies=af.Collection(galaxy=galaxy)) - -""" -The `info` attribute shows the model, including the priors specified above. -""" -print(model.info) - -""" -We can now create this custom search and run it. Our non-linear search will now start by sampling higher likelihood -regions of parameter space, given our improved and more informed priors. -""" -search = af.Nautilus( - path_prefix=Path("howtogalaxy", "chapter_2"), - name="tutorial_4_custom_priors", - unique_tag=dataset_name, - n_live=100, - n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2. -) - -analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True) - -print( - "The non-linear search has begun running - checkout the HowToGalaxy/output/howtogalaxy/chapter_2/tutorial_4_custom_priors" - " folder for live output of the results, images and model." - " This Jupyter notebook cell will progress once search has completed - this could take some time!" -) - -result_custom_priors = search.fit(model=model, analysis=analysis) - -print("Search has finished run - you may now continue the notebook.") - -print(result_custom_priors.info) - -""" -__Result__ - -Bam! We get a good model, which corresponds to the global maxima. By giving our non-linear search a helping hand and -informing it of where to sample parameter space, we can increase the odds that we find the global maxima solution. -""" -aplt.subplot_fit_imaging(fit=result_custom_priors.max_log_likelihood_fit) - -""" -__Discussion__ - -By tuning our priors to the galaxy we fit we increase the chance of inferring the global maxima model. The search -may also fit the model a lot faster, given it spends less time searches regions of parameter space that do not -correspond to good solutions. - -Before moving onto the next approach, lets think about the advantages and disadvantages of prior tuning: - -Advantages: - - - We have a higher chance of finding the globally maximum log likelihood solutions in parameter space. - - The search took less time to run because the non-linear search explored less of parameter space. - -Disadvantages: - - - If we specified a prior incorrectly the non-linear search will infer an incorrect solution. - - The priors for the search were tailored to the specific galaxy we fitted. If we are fitting multiple galaxies, - we would have to customize the priors for every single fit, for large samples of galaxies this would take a lot of time! - -__Approach 2: Reducing Complexity__ - -The non-linear search may fail because the model is too complex, making its parameter space too difficult to -sample accurately. Can we can make the model less complex, whilst keeping it realistic enough to perform our -scientific study? What assumptions can we make to reduce the number of model parameters and therefore -dimensionality of non-linear parameter space? -""" -bulge = af.Model(ag.lp.Sersic) -disk = af.Model(ag.lp.Exponential) - -""" -First, we create a model that assumes that the bulge and disk are geometrically aligned. That is, the bulge and -disk centres and elliptical components are perfectly aligned with one another. This may, or may -not, be a reasonable assumption, but it`ll remove 4 parameters from the model (the centre and elliptical -components of the bulge profile), so it is worth trying! - -To apply our assumption that the bulge and disk are geometrically aligned, we `pair` the `centre` and `ell_comps` -parameters by setting them equal to one another. This removes the parameter on the left-hand side of the pairing from -the galaxy model such that when a model is created it has the same value as the parameter on the right-hand side. -""" -bulge.centre = disk.centre -bulge.ell_comps = disk.ell_comps - -""" -We now compose the model, which will have a non-linear parameter space with 4 less dimensions than the fit performed -previously. -""" -galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk) - -model = af.Collection(galaxies=af.Collection(galaxy=galaxy)) - -""" -The `info` attribute shows the model, including the parameter linking specified above. -""" -print(model.info) - -""" -We now create this search and run it. -""" -search = af.Nautilus( - path_prefix=Path("howtogalaxy", "chapter_2"), - name="tutorial_4_reducing_complexity", - unique_tag=dataset_name, - n_live=100, - n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2. -) - -print( - "The non-linear search has begun running - checkout the HowToGalaxy/output/howtogalaxy/chapter_2/tutorial_4_reducing_complexity" - " folder for live output of the results, images and model." - " This Jupyter notebook cell will progress once search has completed - this could take some time!" -) - -result_bulge_disk_align = search.fit(model=model, analysis=analysis) - -print("Search has finished run - you may now continue the notebook.") - -print(result_bulge_disk_align.info) - -aplt.subplot_fit_imaging(fit=result_bulge_disk_align.max_log_likelihood_fit) - -""" -__Result__ - -The results look pretty good. Our galaxy fits the data pretty well and we've clearly inferred a model that looks -similar to the one above. However, inspection of the residuals shows that the fit was not quite as good as the -first search. - -It turns out that for this simulation, the bulge and disk had different elliptical components. The quality of the fit -suffered and the highest value of log likelihood for the search inferred was lower as a result. - -Herein lies the pitfalls of making assumptions, they may make your model less realistic and your fits worse! - -__Discussion__ - -Again, lets consider the advantages and disadvantages of this approach: - -Advantages: - - - By reducing parameter space`s complexity we again had a higher chance of inferring the global maximum log - likelihood and the time required by the search to do this is reduced. - - Unlike tuned priors, the search was not specific to one galaxy and we could run it on many galaxy images. - -Disadvantages: - - - Our model was less realistic and our fit suffered as a result. - -__Approach 3: Look Harder__ - -In approaches 1 and 2 we extended our non-linear search an olive branch and helped it find the highest log likelihood -regions of parameter space. In approach 3, we're going to tell it to just `look harder`. - -Every non-linear search has settings which govern how thoroughly it searches parameter space, with the number of live -points that was passed to `Nautilus` an example of such a setting. The more thoroughly the search looks, the more likely -it is that it`ll find the global maximum model. However, the search will also take longer! - -We create a more thorough `nautilus` search, that uses `n_live=200`. What these settings -are actually changing is discussed in the optional tutorial `HowToGalaxy/chapter_optional/tutorial_searches.ipynb`. - -Due to the long run times of this search, we comment out the fit below so it does not run. Feel free to undo these -comments if you wish to perform the search yourself. -""" -galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp.Sersic, disk=ag.lp.Exponential) - -model = af.Collection(galaxies=af.Collection(galaxy=galaxy)) - -search = af.Nautilus( - path_prefix=Path("howtogalaxy", "chapter_2"), - name="tutorial_4_look_harder", - unique_tag=dataset_name, - n_live=200, - n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2. -) - -print( - "The non-linear search has begun running - checkout the HowToGalaxy/output/howtogalaxy/chapter_2/tutorial_4_look_harder" - " folder for live output of the results, images and model." - " This Jupyter notebook cell will progress once search has completed - this could take some time!" -) - -# result_look_harder = search.fit(model=model, analysis=analysis) - -print("Search has finished run - you may now continue the notebook.") - -# print(result_look_harder.info) - -# aplt.subplot_fit_imaging(fit=result_look_harder.max_log_likelihood_fit) - -""" -lets list the advantages and disadvantages of simply adjusting the non-linear search: - -Advantages: - - - Its easy to setup, we simply change settings of the non-linear search. - - - It generalizes to any galaxy. - - - We can make our model as complex as we want. - -Disadvantage: - - - Its potentially expensive. Very expensive. For very complex models, the run times can be hours, days, weeks or, dare - I say it, months! - -So, we can now fit galaxies. And when it fails, we know how to get it to work. - -At the end of this chapter, we will introduce a technique called 'non-linear search chaining', which performs a -model fit by chaining together multiple searches back-to-back . This allows us to combine the 3 different approaches -discussed and exploit the advantages of each, whilst not being hindered by their disadvantages. - -With search chaining, we can: - - - Fit simpler models with lower dimensionality parameter spaces in the earlier searches and gradually increase the - model complexity search-by-search, guiding the model-fit to a sufficiently realistic model. - - - In these earlier searches (with easier to sample parameter spaces), use fast non-linear search settings to compute - the results quickly and switch to slower settings in later searches when we fit more complex models. - - - Use 'prior passing' to setup the priors of each parameter in the later searches, based on the models inferred - by the earlier searches. We can therefore guide each search on how to sample a complex model's parameter space - in a way that can be fully generalized to any galaxy. - -__Wrap Up__ - -To wrap up chapter 2, we have a few more tutorials, where we will discuss masking in more detail, the `Result` object -and how to make **PyAutoGalaxy** run faster. -""" diff --git a/scripts/chapter_2_modeling/tutorial_4_linear_profiles.py b/scripts/chapter_2_modeling/tutorial_4_linear_profiles.py new file mode 100644 index 0000000..4522076 --- /dev/null +++ b/scripts/chapter_2_modeling/tutorial_4_linear_profiles.py @@ -0,0 +1,289 @@ +""" +Tutorial 4: Linear Profiles +=========================== + +In tutorial 3, simplifying the bulge and disk geometry made the search easier but restricted the galaxies it could +represent. Linear light profiles offer a different opportunity: keep the same profile shapes and solve their +intensities directly, removing those dimensions from the non-linear search. + +We will then combine many linear Gaussians into a multi Gaussian expansion (MGE). This gives us more freedom to +represent galaxy structure without asking Nautilus to search every Gaussian's brightness and size. + +__Contents__ + +- **Linear Light Profiles:** Fit shapes while solving intensities directly. +- **Results and Intensities:** Retrieve and plot the solved profiles. +- **Galaxy Structure:** Motivate a more flexible description of the light. +- **Basis:** Build and inspect a group of Gaussians. +- **Two Gaussian Groups:** Represent different central and outer shapes. +- **Benefits and Limitations:** Understand what an MGE can and cannot describe. +""" + +# from autogalaxy import setup_notebook; setup_notebook() + +from pathlib import Path +import numpy as np +import autofit as af +import autogalaxy as ag +import autogalaxy.plot as aplt + +""" +__Dataset and Mask__ + +Load the imaging data and retain the region inside the circular mask. The simulator creates the data if needed. +The image, noise map and PSF together describe the observation; none specifies which galaxy model we must fit. +""" + +dataset_name = "simple" +dataset_path = Path("dataset") / "imaging" / dataset_name +if ag.util.dataset.should_simulate(str(dataset_path)): + import subprocess + import sys + + subprocess.run([sys.executable, "scripts/simulators/simple.py"], check=True) + +dataset = ag.Imaging.from_fits( + data_path=dataset_path / "data.fits", + noise_map_path=dataset_path / "noise_map.fits", + psf_path=dataset_path / "psf.fits", + pixel_scales=0.1, +) +mask = ag.Mask2D.circular( + shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5 +) +dataset = dataset.apply_mask(mask=mask) + +""" +__Over Sampling__ + +The bright centre changes rapidly across a pixel. Adaptive over sampling evaluates it on a finer grid so that +numerical inaccuracies do not masquerade as poor models. The outskirts need fewer evaluations. +""" + +over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from( + grid=dataset.grid, + sub_size_list=[8, 4, 2], + radial_list=[0.3, 0.6], + centre_list=[(0.0, 0.0)], +) +dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) +aplt.subplot_imaging_dataset(dataset=dataset) + +""" +__Linear Light Profiles__ + +For a chosen centre, shape, size and Sersic index, changing intensity simply scales a profile's image. Linear +algebra can therefore calculate the intensities that best fit the data for that trial geometry. We call this +calculation an inversion. The `ag.lp_linear` profiles use it automatically within the likelihood evaluation. + +With an ordinary bulge and disk there are two intensity dimensions to search. Linear profiles remove both, +without removing either physical component. The intensities are still fitted; they are not fixed or ignored. +We also share the centres here, while retaining separate elliptical components because the image motivates them. +""" + +bulge = af.Model(ag.lp_linear.Sersic) +disk = af.Model(ag.lp_linear.Exponential) +bulge.centre = disk.centre +model = af.Collection( + galaxies=af.Collection( + galaxy=af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk) + ) +) +print(model.info) + +""" +There is no intensity prior in this summary. At each trial geometry the intensities are solved conditionally; +this is not the same as sampling their full uncertainty distribution. Other parameter degeneracies remain, so +linear profiles make the search simpler without making it immune to failure. + +__Search and Analysis__ + +The public modelling interface is unchanged. The Analysis object now includes the linear solve in its calculation +of the likelihood. This adds work per evaluation but can reduce the number of evaluations needed to explore the +model. Overall runtime depends on the data, hardware and search; there is no universal speed-up factor. +""" + +analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True) + +search = af.Nautilus( + path_prefix=Path("howtogalaxy", "chapter_2"), + name="tutorial_4_linear_light_profiles", + unique_tag=dataset_name, + n_live=100, + n_batch=50, +) +result_linear = search.fit(model=model, analysis=analysis) +print(result_linear.info) +aplt.subplot_fit_imaging(fit=result_linear.max_log_likelihood_fit) + +""" +__Intensities__ + +The result summary describes the searched parameters. To inspect the solved intensities, use the galaxies in +`max_log_likelihood_galaxies`. Their linear profiles have been converted to ordinary profiles with the solved +intensities. The fit also provides an explicit conversion property for this purpose. +""" + +galaxies = result_linear.max_log_likelihood_galaxies +print(galaxies[0].bulge.intensity) +fit = result_linear.max_log_likelihood_fit +solved_galaxies = fit.galaxies_linear_light_profiles_to_light_profiles +print(solved_galaxies[0].disk.intensity) + +""" +__Visualisation__ + +An unsolved linear profile has no brightness with which to draw its image. Plot the converted galaxies, or plot +the fit itself, which already contains the calculated model image. Compare the bulge and disk light with the data. +""" + +aplt.plot_array( + array=galaxies.image_2d_from(grid=dataset.grid), title="Solved galaxy image" +) +aplt.subplot_fit_imaging(fit=fit) + +""" +__Galaxy Structure__ + +A single Sersic profile describes a smooth radial decline with one axis ratio and orientation. Real galaxies can +have a round central component and a flatter outer disk; their apparent flattening or orientation can change with +radius. A fixed Sersic shape cannot freely follow these changes, even if its central brightness is a good match. + +An MGE adds Gaussians with different widths. Narrow Gaussians describe the central light and broader Gaussians +describe the outskirts. Their fitted intensities let the radial brightness change more freely than a single +Sersic law. Groups with different elliptical shapes can represent changes in flattening and isophotal twists, +where the orientation of equal-brightness contours varies across the galaxy. + +This flexibility depends on the geometry we allow. Gaussians sharing a centre remain centrally symmetric even +when their angles differ. Asymmetric light requires offset centres or other freedom. An MGE does not automatically +capture every irregular feature simply because it contains many profiles. + +__Basis__ + +A `Basis` groups linear profiles into one component. First build 30 Gaussians with fixed widths spanning 0.01 +arcseconds (one tenth of the pixel scale) to 2.5 arcseconds. They share two centre coordinates and two elliptical +components, so only four parameters describe their non-linear geometry. + +The width range is a modelling choice covering the scales of this example, not a statement that the profiles +end at the mask. Every Gaussian extends beyond its width and the mask boundary. +""" + +total_gaussians = 30 +sigma_list = np.logspace( + np.log10(dataset.pixel_scales[0] / 10.0), np.log10(2.5), total_gaussians +) +centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) +centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) +bulge_gaussians = af.Collection( + af.Model(ag.lp_linear.Gaussian) for _ in range(total_gaussians) +) +for i, gaussian in enumerate(bulge_gaussians): + gaussian.centre.centre_0 = centre_0 + gaussian.centre.centre_1 = centre_1 + gaussian.ell_comps = bulge_gaussians[0].ell_comps + gaussian.sigma = sigma_list[i] +bulge = af.Model(ag.lp_basis.Basis, profile_list=bulge_gaussians) + +""" +Before running a search, turn this model into a concrete trial instance using the median of each prior. +These are example parameter values, not fitted values. The linear solve will find intensities for this geometry, +but cannot change the geometry itself. This distinction is the reason we still need a non-linear search. +""" + +trial_bulge = bulge.instance_from_prior_medians() +trial_galaxies = ag.Galaxies(galaxies=[ag.Galaxy(redshift=0.5, bulge=trial_bulge)]) +trial_fit = ag.FitImaging(dataset=dataset, galaxies=trial_galaxies) +aplt.subplot_fit_imaging(fit=trial_fit) + +""" +The default trial shape is round. Inspect where it leaves light along the elongated disk. More Gaussian widths +can improve a radial profile, but cannot turn a shared round shape into an ellipse or give the bulge and disk +different shapes. Those freedoms must be present in our model. + +__Two Gaussian Groups__ + +Add ten Gaussians for a second group. They share the first group's centre but have their own elliptical components. +The two groups can now represent the rounder centre and flatter outer light with different weights at different +radii. Calling them `bulge` and `disk` is convenient, but does not prove a unique physical decomposition. +""" + +disk_gaussians = af.Collection(af.Model(ag.lp_linear.Gaussian) for _ in range(10)) +disk_sigmas = np.logspace(np.log10(dataset.pixel_scales[0] / 10.0), np.log10(2.5), 10) +for i, gaussian in enumerate(disk_gaussians): + gaussian.centre.centre_0 = centre_0 + gaussian.centre.centre_1 = centre_1 + gaussian.ell_comps = disk_gaussians[0].ell_comps + gaussian.sigma = disk_sigmas[i] +disk = af.Model(ag.lp_basis.Basis, profile_list=disk_gaussians) +model = af.Collection( + galaxies=af.Collection( + galaxy=af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk) + ) +) +print(model.info) + +""" +The 40 intensities are solved linearly and the widths are fixed. Two shared centre coordinates plus two shape +parameters for each group give six non-linear parameters. The longer model summary does not mean a larger search +space than the earlier Sersic-plus-Exponential model. + +Fit this model with Nautilus and inspect the new result. The live-point setting is illustrative; assess its +reliability from the fit and repeat searches when needed. +""" + +search = af.Nautilus( + path_prefix=Path("howtogalaxy", "chapter_2"), + name="tutorial_4_mge", + unique_tag=dataset_name, + n_live=100, + n_batch=50, +) +result_mge = search.fit(model=model, analysis=analysis) +print(result_mge.info) +aplt.subplot_fit_imaging(fit=result_mge.max_log_likelihood_fit) + +""" +__MGE Result__ + +Use the new result to plot the fitted light and residuals. Its converted galaxies contain ordinary Gaussians with +all 40 solved intensities, so they can also be used for subsequent calculations and visualisation. +""" + +galaxies_mge = result_mge.max_log_likelihood_galaxies +aplt.subplot_galaxies(galaxies=galaxies_mge, grid=dataset.grid) + +""" +__Benefits and Limitations__ + +An MGE can follow a more flexible radial light distribution and, with suitable groups, changes in apparent shape. +It does this with a compact non-linear parameter space. Fixed widths and solved intensities remove difficult +search directions, although overlapping Gaussians and geometric parameters can still be degenerate. + +The extra profiles and linear solve cost computation. An MGE is also less directly interpretable than a Sersic +index and effective radius: an individual Gaussian is a mathematical building block, not a separate stellar +population. Choose the representation for the scientific question, not only the appearance of its residuals. + +The workspace example `autogalaxy_workspace/scripts/imaging/features/multi_gaussian_expansion/modeling.py` +explores more flexible MGE models. Our common-centre example cannot represent off-centre star-forming clumps or +arbitrary asymmetric structure. Additional centres add freedom, but choosing a centre for every knot is cumbersome. +Chapter 3 introduces pixelizations to reconstruct more irregular light without prescribing such components. + +__Non-negative Intensities__ + +The linear solve constrains these light-profile intensities to be non-negative, including zero. This avoids +representing positive light through large positive and negative Gaussians that cancel one another. A zero +intensity simply means that a Gaussian is not needed for that trial geometry. This constraint does not guarantee +that the geometry or scientific interpretation is correct. + +__Other Basis Functions__ + +Shapelets provide another way to expand a galaxy's light. Their different functions can describe other structure, +but their flexibility and computational cost must be assessed for the particular dataset. A worked example is in +`autogalaxy_workspace/scripts/imaging/features/shapelets/modeling.py`; it is optional background after this course. + +__Wrap Up__ + +We can simplify the search while retaining, or increasing, flexibility in the light model. The next tutorial +turns back to the data: which measurements should enter the fit, how should contaminants be handled, and how does +the Analysis object turn those choices into a likelihood? +""" diff --git a/scripts/chapter_2_modeling/tutorial_5_data_and_likelihoods.py b/scripts/chapter_2_modeling/tutorial_5_data_and_likelihoods.py new file mode 100644 index 0000000..04875cd --- /dev/null +++ b/scripts/chapter_2_modeling/tutorial_5_data_and_likelihoods.py @@ -0,0 +1,217 @@ +""" +Tutorial 5: Data and Likelihoods +=============================== + +So far we have changed the galaxy model and the search. Now consider the other side of the fit: the measurements +we include and how they are compared with a prediction. The data, model and Analysis object have distinct jobs. +This separation lets the same modelling tools work with different observations and likelihood functions. + +__Contents__ + +- **Masking:** Retain useful constraints without fitting unrelated objects. +- **Extra Galaxy Noise Scaling:** Reduce the weight of contaminated pixels. +- **Analysis:** Connect the prepared data to the model. +- **Interferometer Data:** Apply the same modelling pattern to visibilities. +- **Multiple Datasets:** A pointer to advanced joint modelling. +""" + +# from autogalaxy import setup_notebook; setup_notebook() + +from pathlib import Path +import numpy as np +import autofit as af +import autogalaxy as ag +import autogalaxy.plot as aplt + +""" +__Dataset and Mask__ + +Load the imaging data and retain the region inside the circular mask. The simulator creates the data if needed. +The image, noise map and PSF together describe the observation; none specifies which galaxy model we must fit. +""" + +dataset_name = "simple__sersic" +dataset_path = Path("dataset") / "imaging" / dataset_name +if ag.util.dataset.should_simulate(str(dataset_path)): + import subprocess + import sys + + subprocess.run([sys.executable, "scripts/simulators/sersic.py"], check=True) + +dataset = ag.Imaging.from_fits( + data_path=dataset_path / "data.fits", + noise_map_path=dataset_path / "noise_map.fits", + psf_path=dataset_path / "psf.fits", + pixel_scales=0.1, +) +mask = ag.Mask2D.circular( + shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=6.0 +) +dataset = dataset.apply_mask(mask=mask) + +""" +__Over Sampling__ + +The bright centre changes rapidly across a pixel. Adaptive over sampling evaluates it on a finer grid so that +numerical inaccuracies do not masquerade as poor models. The outskirts need fewer evaluations. +""" + +over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from( + grid=dataset.grid, + sub_size_list=[8, 4, 2], + radial_list=[0.3, 0.6], + centre_list=[(0.0, 0.0)], +) +dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) +aplt.subplot_imaging_dataset(dataset=dataset) + +""" +__Masking__ + +Our first fit used a 3.0-arcsecond radius. Here we use 6.0 arcseconds to include more of the faint outskirts. +Look beyond the bright centre: individually faint pixels can collectively constrain how quickly the light falls +away. A mask that is too tight may discard those constraints. + +There is another reason to include the outskirts. A model may predict light outside the fitted region that the +real image does not contain. Masking that region hides the disagreement from the likelihood. A visually good fit +inside a small mask can therefore conceal a poor description of the galaxy as a whole. + +A larger mask is not automatically better. It includes more pixels to calculate and may admit neighbouring galaxies, +background structure or defects our model does not describe. Choose the fitted region from the data and the +scientific question, then check that reasonable changes to it do not undermine the result. +""" + +model = af.Collection( + galaxies=af.Collection( + galaxy=af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp_linear.Sersic) + ) +) +analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True) + +search = af.Nautilus( + path_prefix=Path("howtogalaxy", "chapter_2"), + name="tutorial_5_larger_mask", + unique_tag=dataset_name, + n_live=100, + n_batch=50, +) +result_mask = search.fit(model=model, analysis=analysis) +print(result_mask.info) +aplt.subplot_fit_imaging(fit=result_mask.max_log_likelihood_fit) + +""" +__Contaminating Light__ + +A nearby galaxy is real signal, but it is not light from the target. If we fit it with the target's profile, the +search may distort the target's size or shape to account for it. We can exclude contaminated regions, reduce their +weight, or explicitly model the neighbour. The right choice depends on overlap and the information we need. + +Load a second image containing a visible neighbour. The simulator also supplies a region identifying its light. +For real data, inspect and define this region yourself, for example with the workspace's data-preparation GUI. +Check the mask against the image rather than assuming a circular region removes every trace of contamination. +""" + +dataset_name = "extra_galaxy" +dataset_path = Path("dataset") / "imaging" / dataset_name +if ag.util.dataset.should_simulate(str(dataset_path)): + import subprocess + import sys + + subprocess.run([sys.executable, "scripts/simulators/extra_galaxy.py"], check=True) +dataset = ag.Imaging.from_fits( + data_path=dataset_path / "data.fits", + noise_map_path=dataset_path / "noise_map.fits", + psf_path=dataset_path / "psf.fits", + pixel_scales=0.1, +) +aplt.subplot_imaging_dataset(dataset=dataset) + +""" +__Extra Galaxy Noise Scaling__ + +Noise scaling keeps the contaminated pixels in the grid but greatly reduces their influence on the fit. The +helper below sets their data to zero and their noise to very large values. This is a deliberate modification of +which measurements constrain the model, not a physical subtraction of the neighbouring galaxy. + +The supplied file follows the workspace's mask-storage convention; `invert=True` makes `False` select the pixels +to scale. Apply this to the freshly loaded image before applying the main mask, so the grids have matching shapes. +""" + +mask_extra_galaxies = ag.Mask2D.from_fits( + file_path=dataset_path / "mask_extra_galaxies.fits", + pixel_scales=0.1, + invert=True, +) +dataset = dataset.apply_noise_scaling(mask=mask_extra_galaxies) +mask = ag.Mask2D.circular( + shape_native=dataset.shape_native, + pixel_scales=dataset.pixel_scales, + radius=6.0, +) +dataset = dataset.apply_mask(mask=mask) +over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from( + grid=dataset.grid, + sub_size_list=[8, 4, 2], + radial_list=[0.3, 0.6], + centre_list=[(0.0, 0.0)], +) +dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) +aplt.subplot_imaging_dataset(dataset=dataset) + +""" +Inspect the data, noise and signal-to-noise panels together. The neighbour's selected pixels should have almost +no weight, while the target remains constrained. This also retains a continuous grid, useful for some later +reconstruction methods. Light outside the selected region, including PSF wings, can still contaminate the fit. +Where the galaxies overlap substantially, fitting both is often preferable. Tutorial 6 illustrates that approach. + +__Analysis as the Interface__ + +Our galaxy model does not change merely because we scale a region's noise. The new Analysis object receives the +prepared dataset and uses its noise map when calculating the likelihood. This is where our data choices enter +the model comparison. A search sees the returned score, not the reasons we chose a mask or excluded a neighbour. +""" + +analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True) + +search = af.Nautilus( + path_prefix=Path("howtogalaxy", "chapter_2"), + name="tutorial_5_noise_scaling", + unique_tag=dataset_name, + n_live=100, + n_batch=50, +) +result_scaled = search.fit(model=model, analysis=analysis) +print(result_scaled.info) +aplt.subplot_fit_imaging(fit=result_scaled.max_log_likelihood_fit) + +""" +Do not compare the absolute likelihood of this fit with the earlier dataset or a differently scaled noise map +as if only the galaxy model had changed. The measurements and their weighting also define the likelihood. + +__Interferometer Data__ + +Chapter 1 introduced interferometer visibilities. The same galaxy model can predict those measurements, but the +comparison changes: `AnalysisInterferometer` Fourier transforms the model light and compares predicted visibilities +with the measured complex values and their uncertainties. Its likelihood is evaluated in visibility space. +The real-space mask defines the image grid used for predictions; it does not select image pixels as observations. + +The pattern remains data + model + Analysis + search. See `autogalaxy_workspace/scripts/interferometer/modeling.py` +for a complete example after this course. The shared interface does not mean that different datasets have the +same noise properties or likelihood calculation. + +__Multiple Datasets__ + +We can also combine Analysis objects. For independent observations, their likelihoods multiply, or equivalently +their log likelihoods add. A joint model can share parameters such as galaxy geometry while allowing others, such +as brightness in different wavebands, to differ between datasets. + +The `autogalaxy_workspace/scripts/multi_dataset` examples develop this approach. It is advanced modelling: +finish HowToGalaxy first, then explore how shared parameters, calibration and any correlations between datasets +affect a joint analysis. No extra Python is needed here to understand the principle. + +__Wrap Up__ + +The data describe measurements and uncertainty; the model describes possible galaxies; Analysis defines how to +compare them. The search explores that model using the resulting likelihood. Keeping these roles clear makes it +easier to decide whether a poor fit needs better data preparation, a different model or more thorough exploration. +""" diff --git a/scripts/chapter_2_modeling/tutorial_5_linear_profiles.py b/scripts/chapter_2_modeling/tutorial_5_linear_profiles.py deleted file mode 100644 index e3d3f49..0000000 --- a/scripts/chapter_2_modeling/tutorial_5_linear_profiles.py +++ /dev/null @@ -1,545 +0,0 @@ -""" -Tutorial 5: Linear Profiles -=========================== - -In the previous tutorial we learned how to balance model complexity with our non-linear search in order to infer -accurate model solutions and avoid failure. We saw how in order to fit a model accurately one may have to -parameterize and fit a simpler model with fewer non-linear parameters, at the expense of fitting the data less -accurately. - -It would be desirable if we could make our model have more flexibility enabling it to fit more complex galaxy -structures, but in a way that does not increase (or perhaps even decreases) the number of non-linear parameters. -This would keep the `nautilus` model-fit efficient and accurate. - -This is possible using linear light profiles, which solve for their `intensity` parameter via efficient linear -algebra, using a process called an inversion. The inversion always computes `intensity` values that give the best -fit to the data (e.g. they minimize the chi-squared and therefore maximize the likelihood). - -This tutorial will first fit a model using two linear light profiles. Because their `intensity` values are solved for -implicitly, this means they are not a dimension of the non-linear parameter space fitted by `nautilus`, therefore -reducing the complexity of parameter space and making the fit faster and more accurate. - -This tutorial will then show how many linear light profiles can be combined into a `Basis`, which comes from the term -'basis function'. By combining many linear light profiles models can be composed which are able to fit complex galaxy -structures (e.g. asymmetries, twists) with just N=6-8 non-linear parameters. - -__Contents__ - -- **Initial Setup:** Load the dataset and apply a mask. -- **Linear Light Profiles:** Fit a model using linear light profiles that solve for intensity via linear algebra. -- **Run Time:** Estimate the run time of the model-fit before starting. -- **Result:** Inspect the result and the solved intensity values. -- **Intensities:** Access the intensity values of linear light profiles after the fit. -- **Visualization:** Visualize the fit using linear light profiles. -- **Basis:** Combine many linear light profiles into a basis for fitting complex structures. -- **Model Fit:** Fit the basis model to the data. -- **Disk MGE:** Use a Multi-Gaussian Expansion for the disk component. -- **Multi Gaussian Expansion Benefits:** Discussion of the advantages of MGE models. -- **Positive Only Solver:** Ensure linear algebra solutions have positive intensity values. -- **Other Basis Functions:** Overview of other basis functions like shapelets. -- **Wrap Up:** Summary of linear light profiles and basis functions. -""" - -# from autogalaxy import setup_notebook; setup_notebook() - -import numpy as np -from pathlib import Path -import autogalaxy as ag -import autogalaxy.plot as aplt -import autofit as af - -""" -__Initial Setup__ - -we'll use the same galaxy data as the previous tutorial, where: - - - The galaxy's bulge is a `Sersic`. - - The galaxy's disk is an `Exponential`. -""" -dataset_name = "simple" -dataset_path = Path("dataset") / "imaging" / dataset_name - -""" -__Dataset Auto-Simulation__ - -If the dataset does not already exist on your system, it will be created by running the corresponding -simulator script. This ensures that all example scripts can be run without manually simulating data first. -""" -if ag.util.dataset.should_simulate(str(dataset_path)): - import subprocess - import sys - - subprocess.run( - [sys.executable, "scripts/simulators/simple.py"], - check=True, - ) - - -dataset = ag.Imaging.from_fits( - data_path=dataset_path / "data.fits", - noise_map_path=dataset_path / "noise_map.fits", - psf_path=dataset_path / "psf.fits", - pixel_scales=0.1, -) - -""" -__Mask__ - -we'll create and use a smaller 2.5" `Mask2D` again. -""" -mask = ag.Mask2D.circular( - shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5 -) - -dataset = dataset.apply_mask(mask=mask) - -""" -__Over Sampling__ - -Apply adaptive over sampling to ensure the calculation is accurate, you can read up on over-sampling in more detail via -the `autogalaxy_workspace/*/guides/advanced/over_sampling.ipynb` notebook. -""" -over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from( - grid=dataset.grid, - sub_size_list=[8, 4, 2], - radial_list=[0.3, 0.6], - centre_list=[(0.0, 0.0)], -) - -dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) - -""" -When plotted, the galaxy's bulge and disk are clearly visible in the centre of the image. -""" -aplt.subplot_imaging_dataset(dataset=dataset) - -""" -__Linear Light Profiles__ - -First, we use a variant of a light profile discussed called a "linear light profile", which is accessed via the -command `ag.lp_linear`. - -The `intensity` values of linear light profiles are solved for via linear algebra. We use the `Sersic` -and `Exponential` linear light profiles, which are identical to the ordinary `Sersic` and `Exponential` -profiles fitted in previous tutorials, except for their `intensity` parameter now being solved for implicitly. - -Because the `intensity` parameter of each light profile is not a free parameter in the model-fit, the dimensionality of -non-linear parameter space is reduced by 1 for each light profile (in this example, 2). This also removes the -degeneracies between the `intensity` and other light profile parameters (e.g. `effective_radius`, `sersic_index`), -making the model-fit more robust. - -This is a rare example where we are able to reduce the complexity of parameter space without making the model itself -any simpler. There is really no downside to using linear light profiles, so I would recommend you adopt them as -standard for your own model-fits from here on! -""" -bulge = af.Model(ag.lp_linear.Sersic) -disk = af.Model(ag.lp_linear.Exponential) - -bulge.centre = disk.centre - -galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk) - -model = af.Collection(galaxies=af.Collection(galaxy=galaxy)) - -""" -The `info` attribute shows the model, including the linear light profiles. - -Note how the `intensity` is no longer listed and does not have a prior associated with it. -""" -print(model.info) - -""" -We now create this search and run it. -""" -search = af.Nautilus( - path_prefix=Path("howtogalaxy", "chapter_2"), - name="tutorial_5_linear_light_profile", - unique_tag=dataset_name, - n_live=100, - n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2. -) - -analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True) - -""" -__Run Time__ - -For standard light profiles, the log likelihood evaluation time is of order ~0.01 seconds for this dataset. - -For linear light profiles, the log likelihood evaluation increases to around ~0.05 seconds per likelihood evaluation. -This is still fast, but it does mean that the fit may take around five times longer to run. - -However, because two free parameters have been removed from the model (the `intensity` of the bulge and -disk), the total number of likelihood evaluations will reduce. Furthermore, the simpler parameter space -likely means that the fit will take less than 10000 likelihood evaluations per free parameter to converge. This is -aided further by the reduction in `n_live` to 100. - -Fits using standard light profiles and linear light profiles therefore take roughly the same time to run. However, -the simpler parameter space of linear light profiles means that the model-fit is more reliable, less susceptible to -converging to an incorrect solution and scales better if even more light profiles are included in the model. - -Run the non-linear search. -""" -print( - "The non-linear search has begun running - checkout the HowToGalaxy/output/howtogalaxy/chapter_2/tutorial_5_linear_light_profile" - " folder for live output of the results, images and model." - " This Jupyter notebook cell will progress once search has completed - this could take some time!" -) - -result_linear_light_profile = search.fit(model=model, analysis=analysis) - -""" -__Result__ - -The `info` attribute shows the resulting model, which does not display the `intensity` values for each light profile. -""" -print(result_linear_light_profile.info) - -""" -__Intensities__ - -The intensities of linear light profiles are not a part of the model parameterization and therefore are not displayed -in the `model.results` file. - -To extract the `intensity` values of a specific component in the model, we use the `max_log_likelihood_galaxies`, -which has already performed the inversion and therefore the galaxy light profiles have their solved for -`intensity`'s associated with them. -""" -galaxies = result_linear_light_profile.max_log_likelihood_galaxies - -print(galaxies[0].bulge.intensity) - -""" -The `Galaxies` contained in the `max_log_likelihood_fit` also has the solved for `intensity` values: -""" -fit = result_linear_light_profile.max_log_likelihood_fit - -galaxies = fit.galaxies - -print(galaxies[0].bulge.intensity) - -""" -__Visualization__ - -Linear light profiles and objects containing them (e.g. galaxies) cannot be plotted because they do not -have an `intensity` value. - -Therefore, the objects created above which replaces all linear light profiles with ordinary light profiles must be -used for visualization: -""" -galaxies = result_linear_light_profile.max_log_likelihood_galaxies - -aplt.plot_array(array=galaxies.image_2d_from(grid=dataset.grid), title="Image") - -aplt.plot_array(array=galaxies[0].image_2d_from(grid=dataset.grid), title="Image") - -""" -__Basis__ - -We can use many linear light profiles to build a `Basis`. - -For example, below, we make a `Basis` out of 30 elliptical Gaussian linear light profiles which: - - - All share the same centre and elliptical components. - - The `sigma` size of the Gaussians increases in log10 increments. - -The `sigma` values are spaced in log10 increments from a tenth of the pixel scale (0.01") to the mask -radius (3.0"), ensuring the Gaussians span all scales the data constrains. -""" -total_gaussians = 30 - -# The sigma values of the Gaussians will be fixed to values spanning a tenth of the pixel scale to the mask radius, 3.0". -mask_radius = 3.0 -log10_sigma_list = np.linspace( - np.log10(dataset.pixel_scales[0] / 10.0), np.log10(mask_radius), total_gaussians -) - -# By defining the centre here, it creates two free parameters that are assigned below to all Gaussians. - -centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) -centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) - -bulge_gaussian_list = [] - -# A list of Gaussian model components whose parameters are customized belows. - -gaussian_list = af.Collection( - af.Model(ag.lp_linear.Gaussian) for _ in range(total_gaussians) -) - -# Iterate over every Gaussian and customize its parameters. - -for i, gaussian in enumerate(gaussian_list): - gaussian.centre.centre_0 = centre_0 # All Gaussians have same y centre. - gaussian.centre.centre_1 = centre_1 # All Gaussians have same x centre. - gaussian.ell_comps = gaussian_list[ - 0 - ].ell_comps # All Gaussians have same elliptical components. - gaussian.sigma = ( - 10 ** log10_sigma_list[i] - ) # All Gaussian sigmas are fixed to values above. - -bulge_gaussian_list += gaussian_list - -# The Basis object groups many light profiles together into a single model component. - -bulge = af.Model( - ag.lp_basis.Basis, - profile_list=bulge_gaussian_list, -) - -""" -One we have a `Basis`, we can treat it like any other light profile in order to create a `Galaxy` and `Galaxies` and -use it to fit data. -""" -galaxy = ag.Galaxy(redshift=0.5, bulge=bulge) - -galaxies = ag.Galaxies(galaxies=[galaxy]) - -fit = ag.FitImaging(dataset=dataset, galaxies=galaxies) - -""" -By plotting the fit, we see that the `Basis` does a reasonable job at capturing the appearance of the galaxy. - -There are imperfections, but this is because we did not fit the model via a non-linear search in order to determine -the optimal values of the Gaussians in the basis. In particular, the Gaussians above were all spherical, when the -galaxy is elliptical. - -We rectify this below, where we use a non-linear search to determine the optimal values of the Gaussians! -""" -aplt.subplot_fit_imaging(fit=fit) - -""" -__Model Fit__ - -To fit a model using `Basis` functions, the API is very similar to that shown throughout this chapter, using both -the `af.Model()` and `af.Collection()` objects. - -In this example we fit a `Basis` model for the bulge where: - - - The bulge is a superposition of 30 parametric linear `Gaussian` profiles [4 parameters]. - - The centres and elliptical components of each family of Gaussians are all linked together. - - The `sigma` size of the Gaussians increases in log10 increments. - -The number of free parameters and therefore the dimensionality of the MGE is just N=4. -""" -total_gaussians = 30 - -# The sigma values of the Gaussians will be fixed to values spanning a tenth of the pixel scale to the mask radius, 3.0". -mask_radius = 3.0 -log10_sigma_list = np.linspace( - np.log10(dataset.pixel_scales[0] / 10.0), np.log10(mask_radius), total_gaussians -) - -# By defining the centre here, it creates two free parameters that are assigned below to all Gaussians. - -centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) -centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) - -bulge_gaussian_list = [] - -# A list of Gaussian model components whose parameters are customized belows. - -gaussian_list = af.Collection( - af.Model(ag.lp_linear.Gaussian) for _ in range(total_gaussians) -) - -# Iterate over every Gaussian and customize its parameters. - -for i, gaussian in enumerate(gaussian_list): - gaussian.centre.centre_0 = centre_0 # All Gaussians have same y centre. - gaussian.centre.centre_1 = centre_1 # All Gaussians have same x centre. - gaussian.ell_comps = gaussian_list[ - 0 - ].ell_comps # All Gaussians have same elliptical components. - gaussian.sigma = ( - 10 ** log10_sigma_list[i] - ) # All Gaussian sigmas are fixed to values above. - -bulge_gaussian_list += gaussian_list - -# The Basis object groups many light profiles together into a single model component. - -bulge = af.Model( - ag.lp_basis.Basis, - profile_list=bulge_gaussian_list, -) - -""" -__Disk MGE__ - -The residuals of the fit above showed us that the galaxy in the data is composed of multiple structures (e.g. a bulge -and disk) which have distinct elliptical coordinates. - -We therefore compose a second `Basis` of 10 Gaussians to represent the `disk`. This is parameterized the same as -the `bulge` (e.g. all Gaussians share the same `centre` and `ell_comps`) but is treated as a completely -independent set of parameters. -""" -total_gaussians = 10 - -# The sigma values of the Gaussians will be fixed to values spanning a tenth of the pixel scale to the mask radius, 3.0". -mask_radius = 3.0 -log10_sigma_list = np.linspace( - np.log10(dataset.pixel_scales[0] / 10.0), np.log10(mask_radius), total_gaussians -) - -disk_gaussian_list = [] - -# A list of Gaussian model components whose parameters are customized belows. - -gaussian_list = af.Collection( - af.Model(ag.lp_linear.Gaussian) for _ in range(total_gaussians) -) - -# Iterate over every Gaussian and customize its parameters. - -for i, gaussian in enumerate(gaussian_list): - gaussian.centre.centre_0 = bulge_gaussian_list[ - 0 - ].centre_0 # All Gaussians have same y centre as bulge. - gaussian.centre.centre_1 = bulge_gaussian_list[ - 0 - ].centre_1 # All Gaussians have same x centre as bulge. - gaussian.ell_comps = gaussian_list[ - 0 - ].ell_comps # All Gaussians have same elliptical components. - gaussian.sigma = ( - 10 ** log10_sigma_list[i] - ) # All Gaussian sigmas are fixed to values above. - -disk_gaussian_list += gaussian_list - -# The Basis object groups many light profiles together into a single model component. - -disk = af.Model( - ag.lp_basis.Basis, - profile_list=disk_gaussian_list, -) - -""" -We now compose the overall model which uses both sets of Gaussians to represent separately the bulge and disk. - -The overall dimensionality of non-linear parameter space is just N=6, which is fairly remarkable if you -think about just how complex the structures are that these two `Basis` of Gaussians can capture! -""" -galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk) - -model = af.Collection(galaxies=af.Collection(galaxy=galaxy)) - - -""" -The `info` attribute shows the model, which is a lot longer than we have seen previously, given that is -composed of many Gaussians! -""" -print(model.info) - -""" -We now fit the model, with just `n_live=50` given the simplicity of parameter space. -""" -search = af.Nautilus( - path_prefix=Path("howtogalaxy", "chapter_2"), - name="tutorial_5_basis", - unique_tag=dataset_name, - n_live=50, - n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2. -) - -print( - "The non-linear search has begun running - checkout the HowToGalaxy/output/howtogalaxy/chapter_2/tutorial_5_basis" - " folder for live output of the results, images and model." - " This Jupyter notebook cell will progress once search has completed - this could take some time!" -) - -result_basis = search.fit(model=model, analysis=analysis) - -""" -__Result__ - -The result `info` attribute shows the result, which is again longer than usual given the large number of Gaussians -used in the fit. -""" -print(result_basis.info) - -""" -Visualizing the fit shows that we successfully fit the data to the noise level. - -Note that the result objects `max_log_likelihood_galaxies` and `max_log_likelihood_fit` automatically convert -all linear light profiles to ordinary light profiles, including every single one of the 40 Gaussians fitted -above. - -This means we can use them directly to perform the visualization below. -""" -print(result_basis.max_log_likelihood_instance) - -aplt.subplot_galaxies( - galaxies=result_basis.max_log_likelihood_galaxies, grid=result_basis.grids.lp -) - -aplt.subplot_fit_imaging(fit=result_basis.max_log_likelihood_fit) - -""" -__Multi Gaussian Expansion Benefits__ - -Symmetric light profiles (e.g. elliptical Sersics) may leave significant residuals, because they fail to capture -irregular and asymmetric morphological features of galaxies (e.g. isophotal twists, an ellipticity which varies radially). -An MGE fully captures these features and can therefore much better represent the emission of complex galaxies. - -The MGE model can be composed in a way that has fewer non-linear parameters than an elliptical Sersic. In this example, -a group of Gaussians is used to represent the `bulge` of the galaxy, which in total correspond to just N=4 non-linear -parameters (a `bulge` and `disk` comprising two linear Sersics has N=10 parameters). - -The MGE model parameterization is also composed such that neither the `intensity` parameters or any of the -parameters controlling the size of the Gaussians (their `sigma` values) are non-linear parameters sampled by Nautilus. -This removes the most significant degeneracies in parameter space, making the model much more reliable and efficient -to fit. - -Therefore, not only does an MGE fit more complex galaxy morphologies, it does so using fewer non-linear parameters -in a much simpler non-linear parameter space which has far less significant parameter degeneracies! - -__Positive Only Solver__ - -Many codes which use linear algebra typically rely on a linear algebra solver which allows for positive and negative -values of the solution (e.g. `np.linalg.solve`), because they are computationally fast. - -This is problematic, as it means that negative surface brightnesses values can be computed to represent a galaxy's -light, which is clearly unphysical. For an MGE, this produces a positive-negative "ringing", where the -Gaussians alternate between large positive and negative values. This is clearly undesirable and unphysical. - -**PyAutoGalaxy** (and therefore all examples above) uses a positive only linear algebra solver which has been -extensively optimized to ensure it is as fast as positive-negative solvers. This ensures that all light profile -intensities are positive and therefore physical. - -__Other Basis Functions__ - -In addition to the Gaussians used in this example, there is another basis function implemented in PyAutoGalaxy -that is commonly used to represent the light of galaxies, called a `Shapelet`. - -Shapelets are basis functions with analytic properties that are appropriate for capturing the exponential / disk-like -features of a galaxy. They do so over a wide range of scales, and can often represent features in galaxies -that a single Sersic function or MGE cannot. - -An example using shapelets is given at `autogalaxy_workspace/scripts/imaging/features/shapelets/modeling.py`. - -Feel free to experiment with using shapelets to model the galaxy yourself. However they incur higher computational -overheads than the MGE and include a free parameter which governs the size of the basis functions and therefore galaxy, -slowing down convergence of the non-linear search. We have found that MGEs perform better than shapelets in most -galaxy modeling problems. - -If you have a desire to fit galaxies with even more complex morphologies we recommend you look at how to reconstruct -galaxies using pixelizations in the `modeling/features` section or chapter 3 of **HowToGalaxy**. - -__Wrap Up__ - -In this tutorial we described how linearizing light profiles allows us to fit more complex light profiles to -galaxies using fewer non-linear parameters, keeping the fit performed by the non-linear search fast, accurate -and robust. - -Perhaps the biggest downside to basis functions is that they are only as good as the features they can capture -in the data. For example, a basis of Gaussians still assumes that they have a well defined centre, but there are -galaxies which may have multiple components with multiple centres (e.g. many star forming knots) which such a -basis cannot capture. - -In chapter 3 of **HowToGalaxy** we introduce non-parametric pixelizations, which reconstruct the data in way -that does not make assumptions like a centre and can thus reconstruct even more complex, asymmetric and irregular -galaxy morphologies. -""" diff --git a/scripts/chapter_2_modeling/tutorial_6_masking.py b/scripts/chapter_2_modeling/tutorial_6_masking.py deleted file mode 100644 index e7b742a..0000000 --- a/scripts/chapter_2_modeling/tutorial_6_masking.py +++ /dev/null @@ -1,154 +0,0 @@ -""" -Tutorial 6: Masking -=================== - -We have learnt everything we need to know about non-linear searches to model a galaxy and infer a good -model solution. Now, lets consider masking in more detail, something we have not given much consideration previously. -We'll also learn a neat trick to improve the speed and accuracy of a non-linear search. - -__Contents__ - -- **Initial Setup:** Load the dataset and apply a mask. -- **Mask:** Apply a custom mask to focus the fit on specific regions. -- **Model + Search + Analysis:** Fit the model using the custom mask. -- **Discussion:** How the mask affects the fit quality and run time. -- **Wrap Up:** Summary of masking strategies for galaxy modeling. -""" - -# from autogalaxy import setup_notebook; setup_notebook() - -from pathlib import Path -import autogalaxy as ag -import autogalaxy.plot as aplt -import autofit as af - -""" -__Initial Setup__ - -we'll use the same galaxy data as tutorials 1 & 2, where: - - - The galaxy's `LightProfile` is a `Sersic`. -""" -dataset_name = "simple__sersic" -dataset_path = Path("dataset") / "imaging" / dataset_name - -""" -__Dataset Auto-Simulation__ - -If the dataset does not already exist on your system, it will be created by running the corresponding -simulator script. This ensures that all example scripts can be run without manually simulating data first. -""" -if ag.util.dataset.should_simulate(str(dataset_path)): - import subprocess - import sys - - subprocess.run( - [sys.executable, "scripts/simulators/sersic.py"], - check=True, - ) - - -dataset = ag.Imaging.from_fits( - data_path=dataset_path / "data.fits", - noise_map_path=dataset_path / "noise_map.fits", - psf_path=dataset_path / "psf.fits", - pixel_scales=0.1, -) - -""" -__Mask__ - -In tutorials 1 and 2 we used a 3.0" circular mask. - -However, there is very faint flux emitted at the outskirts of the galaxy, which the model will benefit from fitting -by using a larger mask. -""" -mask = ag.Mask2D.circular( - shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=6.0 -) - -dataset = dataset.apply_mask(mask=mask) - -aplt.subplot_imaging_dataset(dataset=dataset) - -""" -__Over Sampling__ - -Apply adaptive over sampling to ensure the calculation is accurate, you can read up on over-sampling in more detail via -the `autogalaxy_workspace/*/guides/advanced/over_sampling.ipynb` notebook. -""" -over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from( - grid=dataset.grid, - sub_size_list=[8, 4, 2], - radial_list=[0.3, 0.6], - centre_list=[(0.0, 0.0)], -) - -dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) - -""" -__Model + Search + Analysis__ - -Lets fit the data using this mask, by creating the search as per usual. Note that the `imaging` data with this mask -applied is passed into the `AnalysisImaging` object, ensuring that this is the mask the model-fit uses. -""" -galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp.Sersic) -model = af.Collection(galaxies=af.Collection(galaxy=galaxy)) - -search = af.Nautilus( - path_prefix=Path("howtogalaxy", "chapter_2"), - name="tutorial_6_with_custom_mask", - unique_tag=dataset_name, - n_live=80, - n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2. -) - -analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True) - -search.fit(model=model, analysis=analysis) - -""" -__Discussion__ - -So, we can choose the mask we use in a model-fit. We know that we want the mask to remove as little of the galaxy's light, -but is this the 'right' mask? What is the 'right' mask? Maybe we want a bigger mask? a smaller mask? - -When it comes to choosing a mask, we are essentially balancing two things: computational run-time and accuracy. When we -use a bigger mask the model-fit will take longer to perform. Why? Because a bigger mask includes more image-pixels -in the analysis, and for every additional image-pixel we have to compute its light, blur it with the PSF, compare -it to the data, etc. - -If run-time was not a consideration we would always choose a bigger mask, for two reasons: - - 1) The galaxy may have very faint emission that when you choose the mask you simply do not notice. Overly aggressive - masking runs the risk of us inadvertently masking out some of the galaxy's light, which would otherwise better - constrain the model! - - 2) When the data is fitted with a model image, the fit is performed only within the masked region. For certain galaxies - it is possible that it may produce extraneous emission outside of the masked region that is not actually observed in - the data itself. If this region had not been masked-out, the model would create residuals in these locations and - reduce the value of likelihood appropriately, whereas if it is masked out this reduction in likelihood is - not fed through to the analysis. - -As you use **PyAutoGalaxy** more you will get a feel for how fast a model-fit will run given the quality of data, -model complexity, non-linear search settings, etc. As you develop this intuition, I recommend that you always aim to -use as large of a mask as possible (whilst still achieving reasonable run-times). Aggressive masking will make -**PyAutoGalaxy** run very fast, but could lead you to infer an incorrect model! - -At the end of this chapter, where we introduce 'non-linear search chaining', we will see how chaining makes it -possible to use tighter masks in earlier searches to achieve faster run times. - -If your data includes the light of additional galaxies nearby you may have no choice but to use a smaller -circular mask, because it is important these objects do not interfere with the fit. - -In fact, you can draw custom masks that remove their light entirely. You may now wish to checkout -the `autogalaxy_workspace/*/imaging/data_preparation` package. This includes tools for creating custom masks and -marking the positions on a galaxy (via a GUI) so you can use them in a model-fit. - -__Wrap Up__ - -There is one thing you should bear in mind in terms of masking: - - 1) Customizing the mask for the analysis of one galaxy gets the analysis running fast and can provide accurate - non-linear sampling. However, for a large sample of galaxies, this high level of customization may take a lot of time. -""" diff --git a/scripts/chapter_2_modeling/tutorial_6_search_chaining.py b/scripts/chapter_2_modeling/tutorial_6_search_chaining.py new file mode 100644 index 0000000..33f6723 --- /dev/null +++ b/scripts/chapter_2_modeling/tutorial_6_search_chaining.py @@ -0,0 +1,240 @@ +""" +Tutorial 6: Search Chaining +=========================== + +A neighbouring galaxy can complicate the fit to our target. We need to describe its light, but repeatedly +searching all its parameters while refining the target can waste effort and introduce difficult degeneracies. +Search chaining lets us fit different parts of the scene in stages. + +First we fit a simple target profile and an MGE for the neighbour using a fast Prodigy optimisation. After checking +that fit, we fix the neighbour's fitted geometry and use Nautilus to fit a more flexible MGE for the target. +The second search can concentrate on the target without exploring the neighbour's geometry again. + +This is the main benefit of chaining here: separating well-constrained components can make a realistic model +more robust and manageable. It does not depend on automatically narrowing the priors of the second search. + +__Contents__ + +- **Dataset:** Keep both galaxies in the fit. +- **Search 1:** Obtain a useful description of the neighbour. +- **Inspect Before Chaining:** Check that the first result is suitable to fix. +- **Search 2:** Fix the neighbour's geometry and refine the target. +- **Limits and Pipelines:** Understand the assumptions and extend the workflow. +""" + +# from autogalaxy import setup_notebook; setup_notebook() + +from pathlib import Path +import numpy as np +import autofit as af +import autogalaxy as ag +import autogalaxy.plot as aplt + +""" +__Dataset and Mask__ + +Load the imaging data and retain the region inside the circular mask. The simulator creates the data if needed. +The image, noise map and PSF together describe the observation; none specifies which galaxy model we must fit. +""" + +dataset_name = "extra_galaxy" +dataset_path = Path("dataset") / "imaging" / dataset_name +if ag.util.dataset.should_simulate(str(dataset_path)): + import subprocess + import sys + + subprocess.run([sys.executable, "scripts/simulators/extra_galaxy.py"], check=True) + +dataset = ag.Imaging.from_fits( + data_path=dataset_path / "data.fits", + noise_map_path=dataset_path / "noise_map.fits", + psf_path=dataset_path / "psf.fits", + pixel_scales=0.1, +) +mask = ag.Mask2D.circular( + shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=6.0 +) +dataset = dataset.apply_mask(mask=mask) + +""" +__Over Sampling__ + +The bright centre changes rapidly across a pixel. Adaptive over sampling evaluates it on a finer grid so that +numerical inaccuracies do not masquerade as poor models. The outskirts need fewer evaluations. +""" + +over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from( + grid=dataset.grid, + sub_size_list=[8, 4, 2], + radial_list=[0.3, 0.6], + centre_list=[(0.0, 0.0)], +) +dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) +aplt.subplot_imaging_dataset(dataset=dataset) + +""" +__Keep Both Galaxies__ + +Unlike tutorial 5's noise-scaling example, this fit uses the original data and includes both galaxies in the model. +The target is near (0.0, 0.0), and the visible neighbour near (1.0, 3.5) arcseconds. On your own data, identify +these approximate centres from the image or with the workspace's data-preparation tools. + +Include fine over sampling around both bright centres, since both contribute to the predicted image. +""" + +over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from( + grid=dataset.grid, + sub_size_list=[8, 4, 2], + radial_list=[0.3, 0.6], + centre_list=[(0.0, 0.0), (1.0, 3.5)], +) +dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) + +""" +__Search 1 Model__ + +The target starts as a linear Sersic. The neighbour uses 20 Gaussians with fixed widths and shared centre and +shape, following tutorial 4. The centre priors cover its visually identified location. All Gaussian intensities +are solved together with the target intensity each time the trial geometry is fitted. +""" + +neighbor_gaussians = af.Collection(af.Model(ag.lp_linear.Gaussian) for _ in range(20)) +sigmas = np.logspace(-2.0, np.log10(2.5), 20) +neighbor_centre_0 = af.UniformPrior(lower_limit=0.8, upper_limit=1.2) +neighbor_centre_1 = af.UniformPrior(lower_limit=3.3, upper_limit=3.7) +for i, gaussian in enumerate(neighbor_gaussians): + gaussian.centre.centre_0 = neighbor_centre_0 + gaussian.centre.centre_1 = neighbor_centre_1 + gaussian.ell_comps = neighbor_gaussians[0].ell_comps + gaussian.sigma = sigmas[i] +neighbor = af.Model( + ag.Galaxy, + redshift=0.5, + light=af.Model(ag.lp_basis.Basis, profile_list=neighbor_gaussians), +) +target = af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp_linear.Sersic) +model_1 = af.Collection(galaxies=af.Collection(target=target, neighbor=neighbor)) +print(model_1.info) + +""" +__Fast First Search__ + +Prodigy improves trial models by following directions that increase their fit score, which includes the prior +weight as well as the likelihood. `MultiStartProdigy` tries several starting points so it is less dependent on +one initial guess. It uses JAX, the accelerated numerical engine already enabled in our Analysis objects. + +Here we want a useful fitted neighbour, rather than a detailed range of uncertainty estimates. We use 24 starts +and a ceiling of 300 steps per start as a first pass. These settings are not a guarantee of a good result. +`batch_size=4` limits how many starts are evaluated together to keep memory use manageable. +""" + +analysis_1 = ag.AnalysisImaging(dataset=dataset, use_jax=True) +search_1 = af.MultiStartProdigy( + path_prefix=Path("howtogalaxy", "chapter_2"), + name="tutorial_6_search_1", + unique_tag=dataset_name, + n_starts=24, + batch_size=4, + n_steps=300, + iterations_per_quick_update=50, +) +result_1 = search_1.fit(model=model_1, analysis=analysis_1) +print(result_1.info) +aplt.subplot_fit_imaging(fit=result_1.max_log_likelihood_fit) + +""" +__Inspect Before Chaining__ + +Look especially at the neighbour's centre and outskirts, and at the region where its light overlaps the target. +If systematic residuals remain, improve the first fit before fixing anything. More starts, a better neighbour +model or a more thorough search may be necessary. Chaining a poor result carries its mistakes into the next fit. + +__Fix the Neighbour__ + +`result_1.instance` provides concrete fitted parameter values. Passing its neighbour into the next model fixes +that component's centre and shape, removing its four geometric parameters from the non-linear search. + +This instance still contains linear Gaussian profiles: their intensities are solved again alongside the target +at each likelihood evaluation. We fix the neighbour's geometry, not a completely frozen image. Using converted +ordinary profiles would instead fix the brightnesses too, which is a different modelling choice. +""" + +neighbor_fixed = result_1.instance.galaxies.neighbor + +""" +__Search 2 Model__ + +Replace the target Sersic with a group of 30 Gaussians. This flexible radial light model has four non-linear +parameters: two centre coordinates and two elliptical components. A simultaneous fit with the neighbour's MGE +geometry free would have eight. Fixing the already-fitted neighbour therefore halves this geometric search space. + +This example target is smooth. For a galaxy whose central and outer shapes differ, use the two-group construction +from tutorial 4; the same separation of the neighbour still helps. No result-based prior narrowing is needed. +""" + +target_gaussians = af.Collection(af.Model(ag.lp_linear.Gaussian) for _ in range(30)) +target_sigmas = np.logspace(-2.0, np.log10(6.0), 30) +target_centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) +target_centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) +for i, gaussian in enumerate(target_gaussians): + gaussian.centre.centre_0 = target_centre_0 + gaussian.centre.centre_1 = target_centre_1 + gaussian.ell_comps = target_gaussians[0].ell_comps + gaussian.sigma = target_sigmas[i] +target = af.Model( + ag.Galaxy, + redshift=0.5, + light=af.Model(ag.lp_basis.Basis, profile_list=target_gaussians), +) +model_2 = af.Collection(galaxies=af.Collection(target=target, neighbor=neighbor_fixed)) +print(model_2.info) + +""" +__More Thorough Second Search__ + +Use Nautilus to explore the target's geometric parameters and estimate their uncertainties. The dataset and +likelihood definition are unchanged; the model and search have different roles in this second stage. +""" + +analysis_2 = ag.AnalysisImaging(dataset=dataset, use_jax=True) +search_2 = af.Nautilus( + path_prefix=Path("howtogalaxy", "chapter_2"), + name="tutorial_6_search_2", + unique_tag=dataset_name, + n_live=200, + n_batch=50, +) +result_2 = search_2.fit(model=model_2, analysis=analysis_2) +print(result_2.info) +aplt.subplot_fit_imaging(fit=result_2.max_log_likelihood_fit) + +""" +Inspect both galaxies again. A refined target model can expose weaknesses in the neighbour that were less obvious +before. The first result is useful information, not a guarantee that this separation is valid. + +__Benefits and Limits__ + +When a component can be fitted robustly, fixing its geometry removes unnecessary search directions and lets later +fits concentrate effort on the components of scientific interest. This can bring large improvements in reliability +and runtime, particularly in scenes with several galaxies. A fast first fit and a more thorough second fit also +avoid spending equal effort on every stage. + +The second result is conditional on the fixed neighbour geometry. Its uncertainty does not automatically include +uncertainty in those fixed values. If blending makes the components strongly dependent, repeat the second fit with +plausible neighbour geometries or perform a final joint fit with the relevant parameters free. Inspecting each +stage is essential; more stages do not automatically make a fit more trustworthy. + +__From Searches to Pipelines__ + +A pipeline packages repeated preparation, fits and checks into a reusable sequence. Chapter 4 applies these ideas +to systems with more galaxies. The workspace's `scripts/guides/modeling/chaining.py` provides further API examples. + +The SLaM pipelines in PyAutoLens apply related component-by-component modelling to lensing. They are a useful +example of how far chaining can be developed, but are not required for learning galaxy morphology here. + +__Wrap Up__ + +The chapter's tools work together: inspect the data, choose an adequate model, define its comparison through an +Analysis object, and organise searches so the difficult parts are explored reliably. Search chaining helps strike +the balance between flexibility and tractability without requiring every component to be fitted afresh at every stage. +""" diff --git a/scripts/chapter_2_modeling/tutorial_7_results.py b/scripts/chapter_2_modeling/tutorial_7_results.py deleted file mode 100644 index 85201f4..0000000 --- a/scripts/chapter_2_modeling/tutorial_7_results.py +++ /dev/null @@ -1,163 +0,0 @@ -""" -Tutorial 7: Results -=================== - -In the previous tutorials, each search returned a `Result` object, which we used to plot the maximum log likelihood -fit of each model-fit. In this tutorial, we'll take a look at the result object in a little more detail. - -__Contents__ - -- **Initial Setup:** Perform a model-fit to obtain a Result object. -- **Galaxies & Fit:** Access the maximum likelihood galaxies and fit from the result. -- **Samples:** Inspect the non-linear search samples, including parameter estimates and errors. -- **Workspace:** Pointers to more detailed results examples in the workspace. -- **Database:** Overview of the database functionality for managing large numbers of results. -- **Wrap Up:** Summary of the Result object and its key attributes. -""" - -# from autogalaxy import setup_notebook; setup_notebook() - -from pathlib import Path -import autogalaxy as ag -import autogalaxy.plot as aplt -import autofit as af - -""" -__Initial Setup__ - -Lets repeat the simple Sersic model-fit performed earlier in this chapter to get a `Result` object. -""" -dataset_name = "simple__sersic" -dataset_path = Path("dataset") / "imaging" / dataset_name - -""" -__Dataset Auto-Simulation__ - -If the dataset does not already exist on your system, it will be created by running the corresponding -simulator script. This ensures that all example scripts can be run without manually simulating data first. -""" -if ag.util.dataset.should_simulate(str(dataset_path)): - import subprocess - import sys - - subprocess.run( - [sys.executable, "scripts/simulators/sersic.py"], - check=True, - ) - - -dataset = ag.Imaging.from_fits( - data_path=dataset_path / "data.fits", - noise_map_path=dataset_path / "noise_map.fits", - psf_path=dataset_path / "psf.fits", - pixel_scales=0.1, -) - -mask = ag.Mask2D.circular( - shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=3.0 -) - -dataset = dataset.apply_mask(mask=mask) - -over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from( - grid=dataset.grid, - sub_size_list=[8, 4, 2], - radial_list=[0.3, 0.6], - centre_list=[(0.0, 0.0)], -) - -dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) - -model = af.Collection( - galaxies=af.Collection(galaxy=af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp.Sersic)) -) - -search = af.Nautilus( - path_prefix=Path("howtogalaxy", "chapter_2"), - name="tutorial_7_results", - unique_tag=dataset_name, - n_live=80, - n_batch=50, # GPU batching and VRAM use explained in chapter 2 tutorial 2. -) - -analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True) - -result = search.fit(model=model, analysis=analysis) - -""" -__Galaxies & Fit__ - -In the previous tutorials, we saw that this result contains the maximum log likelihood fit, which provide -a fast way to visualize the result. - -It also contains the maximum log likelihood galaxies. -""" -aplt.subplot_galaxies( - galaxies=result.max_log_likelihood_galaxies, grid=mask.derive_grid.all_false -) - -aplt.subplot_fit_imaging(fit=result.max_log_likelihood_fit) - -""" -__Samples__ - -The result contains a lot more information about the model-fit. - -For example, the `Samples` object contains all of the non-linear search samples, including the parameters -of every successful model evaluation and their log likelihood values. These are used for computing information -about the model-fit, such as the most probable parameter estimates and the error inferred for every parameter. -""" -print(result.samples) -print("Parameters of 1st Sample:") -print(result.samples.parameter_lists[0][:]) -print("Log Likelihood of 1st Sample:") -print(result.samples.log_likelihood_list[0]) - -""" -__Workspace__ - -We are not going into any more detail on the result variable in this tutorial, or in the **HowToGalaxy** lectures. - -A comprehensive description of the results can be found at the following packages: - - `autogalaxy_workspace/*/results` - -The results API for CCD imaging data is the same as for other data types (e.g. interferometer). This -package can therefore be used to learn the API and then translate to other data types. - -__Database__ - -Once a search has completed running, we have a set of results on our hard disk which we can manually inspect and -analyse. Alternatively, we can return the results from the search.fit() method and manipulate them in a Python script -or notebook. - -However, imagine you have a large dataset consisting of many images of galaxies. You analyse each image -individually using a search, producing a large library of results on your hard disk. There will be lots of paths and -directories to navigate, and at some point there will simply be too many results for it to be an efficient use of your -time to analyse the results by sifting through the outputs on your hard disk one-by-one. - -**PyAutoGalaxy**'s database tools solve this problem, by making it possible for us to write the results to a .sqlite -database file and load the results from hard-disk to a Python script or Jupyter notebook. This database supports -advanced queries, so specific results can be loaded and inspected. - -We won't go into any more detail on the database in this tutorial. If you think the database will be useful, checkout -the full set of database tutorials which can be found in the folder `autogalaxy_workspace/*/guides/results/database`. - -Here, you'll learn how to: - - - Use the database to query for results which fit a certain model or give a certain result. - - - Use the `Samples` to produce many different results from the fit, including error estimates on parameters and - plots of the probability density function of parameters in 1D and 2D. - - - Visualize results, for example the fit to a galaxy dataset. - - -__Wrap Up__ - -Even if you are only modeling a small sample of galaxies, if you anticipate using **PyAutoGalaxy** for the long-term I -strongly recommend you begin using the database to inspect and analyse your result. - -This is because it makes it simple to perform all analysis in a Jupyter notebook, which is the most flexible and -versatile way to check results and make figures. -""" diff --git a/scripts/chapter_2_modeling/tutorial_7_summary.py b/scripts/chapter_2_modeling/tutorial_7_summary.py new file mode 100644 index 0000000..bffeb76 --- /dev/null +++ b/scripts/chapter_2_modeling/tutorial_7_summary.py @@ -0,0 +1,22 @@ +""" +Tutorial 7: Summary +=================== + +__Summary__ + +You have completed chapter 2. You can now define galaxy models and priors, connect them to data through Analysis +objects, and use searches to obtain and inspect fits. + +The central challenge is balancing realism, reliable exploration and runtime. Visual inspection helps motivate +priors and reveal inadequate models. Linear profiles and MGEs can describe flexible light distributions with +fewer non-linear parameters. Data preparation determines which measurements constrain the model. Search chaining +lets different components be fitted in stages, while requiring care about the uncertainty of fixed components. + +Try adapting the modelling examples in `autogalaxy_workspace/scripts/imaging` to your own data, or use the +simulators to make a controlled experiment. Once your fits are reliable, the workspace's results guides explain +how to load and analyse them in depth. Multiple-dataset modelling is another advanced topic for after this course. + +Chapter 3 introduces pixelizations for reconstructing more irregular light, including features that a common-centre +MGE cannot describe. Chapter 4 develops modelling of scenes containing multiple galaxies. The optional searches +and speed tutorials are available when you need them; historical prior passing is not required reading. +""" diff --git a/scripts/chapter_2_modeling/tutorial_8_need_for_speed.py b/scripts/chapter_2_modeling/tutorial_8_need_for_speed.py deleted file mode 100755 index 9b3a083..0000000 --- a/scripts/chapter_2_modeling/tutorial_8_need_for_speed.py +++ /dev/null @@ -1,165 +0,0 @@ -""" -Tutorial 8: Need For Speed -========================== - -In this chapter, we have learnt how to model galaxies and how to balance complexity and realism to ensure that we -infer a good model. - -For fitting more complex models, the final challenge that we face is keeping the run-time low. One can easily end -up in a situation where a model-fit takes days, or longer, to fit just one image. For fitting complex models and high -resolution datasets this is somewhat unavoidable. However, it is worth us discussing what drives the long run-times of -the modeling process and how we might speed it up. - -We have kept an eye on the log likelihood evaluation times and therefore expected overall run-time of the fits -performed in this chapter. Lets quickly remind ourselves of the main factors that drive the run-time, and how we -might reduce it. - -The overall run-time of a model-fit is, to a good approximation, a simple product of two numbers: - - - The number of log likelihood evaluations the non-linear search performs before it converges. - - - The time each individual log likelihood evaluation takes. - -Everything we discuss below reduces one (or both) of these numbers. - -__Contents__ - -- **Searching Non-linear Parameter Space:** What drives the number of likelihood evaluations a search performs. -- **Cost Per Evaluation:** What drives the time a single log likelihood evaluation takes. -- **JAX:** How **PyAutoGalaxy** compiles the likelihood function with JAX and runs it on CPUs and GPUs. -- **Run Time Estimation:** How to estimate the overall run-time of a fit before committing to it. -- **Data Quantity:** How the amount of data fitted, and the mask applied to it, drives run-times. -- **Wrap Up:** Summary of the script and next steps. - -__Searching Non-linear Parameter Space__ - -The time it takes for the non-linear search to sample parameter space and find the high likelihood models is driven by: - - - Dimensionality: A more complex parameter space (e.g. more parameters) takes longer to search. - - Priors: The broader the priors on each parameter the longer the search. - - Settings: Non-linear search settings which sample parameter space more thoroughly (e.g. a higher `n_live`) lead to - longer run-times. - -When we use only one search to fit a model, we are somewhat restricted in how we can try to achieve faster run -times by changing these 3 aspects of the search. We have already seen one powerful exception: the linear light -profiles of tutorial 5 remove every `intensity` parameter from the non-linear parameter space, reducing its -dimensionality and removing some of its most difficult degeneracies at the same time. - -The final two tutorials of this chapter (tutorials 9 and 10) introduce 'non-linear search chaining', which fits -a model using multiple searches that are performed back-to-back, passing the results of earlier searches to -later ones. A key motivation for this is that it gives us a lot more flexibility in juggling the dimensionality, -priors and settings so as to perform faster and more efficient modeling. - -In the optional **HowToGalaxy** tutorial `chapter_optional/tutorial_searches.py` we discuss other non-linear searches -supported by **PyAutoGalaxy** which use a different approach to sample parameter space than `Nautilus`. For those -familiar with statistical inference, this includes maximum likelihood estimators and MCMC algorithms. - -For galaxy modeling, there are maximum likelihood estimator methods (e.g. the Levenberg-Marquardt) that for simple -models (e.g. a single `Sersic`) can often reliably infer the maximum likelihood model, using ten times or fewer -likelihood evaluations than `Nautilus` and therefore running over ten times faster. However, these methods do -not infer reliable errors and are prone to becoming trapped in local maxima. Nevertheless, users modeling large -galaxy samples may wish to investigate these methods. - -__Cost Per Evaluation__ - -The second number is the time a single log likelihood evaluation takes, which is set by every operation -**PyAutoGalaxy** performs to fit the galaxy data with a model, for example: - - - Computing the intensity values of every light profile on the image's grid of (y,x) coordinates. - - Over-sampling: sub-dividing image pixels into finer sub-pixels where the light profile changes rapidly (e.g. the - centre of the galaxy), which multiplies the number of intensity evaluations performed. - - Convolving the model image of the galaxies with the telescope's PSF to compare it to the data. The larger the - PSF, the more expensive this convolution becomes. - - For linear light profiles, basis functions like the MGE of tutorial 5 and the pixelizations of chapter 3, solving - the linear algebra of the inversion, which computes the `intensity` values that best fit the data. - -More complex fitting techniques therefore cost more per evaluation: a couple of standard light profiles are cheap, -an MGE costs more (its inversion solves for many Gaussians), and pixelized reconstructions cost the most. -As we saw in tutorial 5, this trade often still favours the more advanced technique, because the simpler parameter -space it produces reduces the number of evaluations the search needs. - -__JAX__ - -How are these operations made fast? **PyAutoGalaxy** uses JAX (https://github.com/jax-ml/jax), Google's numerical -computing library, which just-in-time (JIT) compiles the entire log likelihood function into optimized machine code. - -JIT compilation means the first time the likelihood function is called, JAX traces through every operation it -performs (light profile evaluation, over-sampling, PSF convolution, the linear algebra of an inversion) and compiles -them into a single optimized program. This compilation is a one-off overhead, typically taking seconds to a couple -of minutes depending on model complexity. Every one of the tens of thousands of likelihood evaluations that follow -then reuses the compiled program and runs dramatically faster than ordinary Python. When a search begins you will -see a log message like `JAX jit compiling vectorized (vmap) likelihood function, could take seconds or minutes...` --- that is the compilation happening. - -JAX's second superpower is that the same compiled code runs on either a CPU or a GPU. On a GPU, likelihood -evaluations are not only faster individually but can be batched, with many evaluated simultaneously (the -`n_batch` search input we have set throughout this chapter controls the size of these batches). GPU speed-ups -over CPU of an order of magnitude or more are common, and they grow with the size of the dataset and model. If you -have access to a GPU (even a modest laptop GPU), it is the single biggest speed-up available to you. - -You do not need to do anything to switch this on. JAX installs with `autogalaxy` by default, and every -`AnalysisImaging` object we have created in this chapter defaults to `use_jax=True` and the search compiles and -batches the likelihood function automatically. You can force the plain NumPy path with -`ag.AnalysisImaging(dataset=dataset, use_jax=False)` (or by setting the environment variable -`PYAUTO_DISABLE_JAX=1`), which is mainly useful for debugging, as NumPy errors and stack traces are much easier -to read than JAX ones. - -The one trade-off to keep in mind is the compilation overhead itself. For a full model-fit performing tens of -thousands of likelihood evaluations it is negligible. For a quick one-off calculation (e.g. fitting galaxies to -data once via a `FitImaging`, as we did in chapter 1) compilation can take longer than the calculation it speeds -up, which is why short interactive computations sometimes feel slower than you might expect the first time they run. - -Long-time users may remember that **PyAutoGalaxy** previously used `numba`, which recompiles individual Python -functions into fast machine code. JAX supersedes it: rather than accelerating functions one at a time, it compiles -and optimizes the likelihood function end-to-end, and adds GPU support and batching on top. - -Therefore, **PyAutoGalaxy** is pretty well optimized and there are no 'low hanging fruit' speed ups available by -writing the code in a different language. - -__Run Time Estimation__ - -Because run-time is the product of the two numbers above, we can estimate it before committing to a fit: - - - Time the log likelihood evaluation: perform a fit of the model to the data once (e.g. via a `FitImaging`) and - time it, remembering to discard the first call, which includes JIT compilation. - - - Estimate the number of evaluations: for `Nautilus` a reasonable rule of thumb is of order 10000 evaluations per - free parameter, with simpler parameter spaces (e.g. linear light profiles, chained searches with tight priors) - converging in fewer. - -Multiplying the two gives a ballpark overall run-time. In tutorial 2 we used exactly this arithmetic: a log -likelihood evaluation time of ~0.05 seconds and 50000-100000 evaluations gave expected run-times of roughly 30 -minutes on CPU and 10 minutes on GPU. If your own estimate comes out at days or weeks, that is the moment to -simplify the model, tighten the search settings, reach for search chaining or find a GPU -- before starting the -fit, not after. - -On a GPU, there is one other pre-flight check: `analysis.print_vram_use(model=model, batch_size=search.batch_size)` -estimates whether the fit will fit within the GPU's memory for your chosen batch size. - -__Data Quantity__ - -The final factor driving run-speed is the quantity of data that is fitted. For every image-pixel that we fit, -we have to compute the light profile intensities and convolve them with the telescope's PSF. The larger that PSF is, -the more convolution operations we have to perform too. - -In the previous exercises, we used images with a pixel scale of 0.1". This value is relatively low resolution: most -Hubble Space Telescope images have a pixel scale of 0.05", which is four times the number of pixels! Some telescopes -observe at scales of 0.03" or, dare I say it, 0.01". At these resolutions things can *really* slow down, if we -do not think carefully about run speed beforehand. - -There are ways that we can reduce the number of image-pixels we fit, via masking. If we mask out more of the image, -we will fit fewer pixels and **PyAutoGalaxy** will run faster. If you want the best, most perfect model possible, -aggressive masking and cutting the data in this way is a bad idea, as discussed in tutorial 6. - -__Wrap Up__ - -This tutorial simply wanted to get you thinking about *why* a model takes as long to fit as it does: the number -of likelihood evaluations the search performs, times the cost of each evaluation, with JAX's compiled likelihood -function (and a GPU, if you have one) driving the latter down as far as it will go. - -The remaining tutorials of this chapter attack the other half of the product: search chaining (tutorial 9) and prior -passing (tutorial 10) reduce the number of evaluations needed to fit complex models, laying the groundwork for the -pixelized reconstructions of chapter 3. -""" - -# from autogalaxy import setup_notebook; setup_notebook() diff --git a/scripts/chapter_2_modeling/tutorial_9_search_chaining.py b/scripts/chapter_2_modeling/tutorial_9_search_chaining.py deleted file mode 100644 index c1cd413..0000000 --- a/scripts/chapter_2_modeling/tutorial_9_search_chaining.py +++ /dev/null @@ -1,326 +0,0 @@ -""" -Tutorial 9: Search Chaining -=========================== - -Throughout this chapter, we have fitted the data using just one non-linear search. The previous tutorial discussed -the run-time cost of doing this: with a single search, the dimensionality of the model, the priors on its parameters -and the search settings must all be juggled at once, leaving us little flexibility to trade them off against one -another. - -In this closing part of the chapter, we introduce a technique called 'non-linear search chaining', which fits a -model using a sequence of non-linear searches. The initial searches fit simpler models whose parameter spaces can -be more accurately and efficiently sampled. The results of this search are then passed to later searches which fit -models of gradually increasing complexity. - -Lets think back to tutorial 4 of this chapter. We learnt there were three approaches one could take fitting a model -accurately if we found that a model fit failed. These were: - - 1) Tuning our priors to the galaxy we're fitting. - 2) Making our model less complex. - 3) Searching non-linear parameter space for longer. - -However, each of the above approaches has disadvantages. The more we tune our priors, the less we can generalize our -analysis to a different galaxy. The less complex we make our model, the less realistic it is. And if we rely too -much on searching parameter space for longer, we could end up with search`s that take days, weeks or months to run. - -In this tutorial, we are going to show how search chaining combines these 3 approaches such that we can fit -complex and realistic models in a way that can be generalized to many different galaxies. To do this, -we'll run 2 searches, and chain the model inferred in the first search to the priors of the second search`s -model. - -Our first search will make the same bulge-disk alignment assumption we made in tutorial 4 of this chapter. We saw -that this gives a reasonable model. However, we'll make a couple of extra simplifying assumptions, to really try and -bring our model complexity down and get the non-linear search running fast. - -The model we infer above will therefore be a lot less realistic. But it does not matter, because in the second search -we are going to relax these assumptions and fit the more realistic model. The beauty is that, by running the first -search, we can use its results to tune the priors of our second search. For example: - - 1) The first search should give us a pretty good idea of the galaxy's bulge and disk profiles, for example its - centre, ellipticity and effective radius. - -__Contents__ - -- **Initial Setup:** Load the dataset and apply a mask. -- **Dataset Auto-Simulation:** Simulate the dataset via its simulator script if it is not on your hard-disk. -- **Model:** Compose a simplified model for the first search with aligned bulge-disk assumptions. -- **Search + Analysis:** Run the first search with the simplified model. -- **Result:** Inspect the result of the first search. -- **Prior Passing:** Manually pass results from search 1 as priors for search 2. -- **Result:** Inspect the final result of the chained search. -- **Wrap Up:** Summary of how search chaining improves model-fitting reliability. -""" - -# from autogalaxy import setup_notebook; setup_notebook() - -import numpy as np -from pathlib import Path -import autogalaxy as ag -import autogalaxy.plot as aplt -import autofit as af - -""" -__Initial Setup__ - -we'll use the same galaxy data as tutorial 4 of this chapter, where: - - - The galaxy's bulge is a `Sersic`. - - The galaxy's disk is an `Exponential`. -""" -dataset_name = "simple" -dataset_path = Path("dataset") / "imaging" / dataset_name - -""" -__Dataset Auto-Simulation__ - -If the dataset does not already exist on your system, it will be created by running the corresponding -simulator script. This ensures that all example scripts can be run without manually simulating data first. -""" -if ag.util.dataset.should_simulate(str(dataset_path)): - import subprocess - import sys - - subprocess.run( - [sys.executable, "scripts/simulators/simple.py"], - check=True, - ) - - -dataset = ag.Imaging.from_fits( - data_path=dataset_path / "data.fits", - noise_map_path=dataset_path / "noise_map.fits", - psf_path=dataset_path / "psf.fits", - pixel_scales=0.1, -) - -mask = ag.Mask2D.circular( - shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.5 -) - -dataset = dataset.apply_mask(mask=mask) - -over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from( - grid=dataset.grid, - sub_size_list=[8, 4, 2], - radial_list=[0.3, 0.6], - centre_list=[(0.0, 0.0)], -) - -dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) - -aplt.subplot_imaging_dataset(dataset=dataset) - -""" -__Model__ - -As we've eluded to before, one can look at an image and immediately identify the centre of the galaxy. It's -that bright blob of light in the middle! Given that we know we're going to make the model more complex in the -next search, lets take a more liberal approach than before and fix the centre of the bulge and -disk to $(y,x)$ = (0.0", 0.0").. - -Now, you might be thinking, doesn`t this prevent our search from generalizing to other galaxies? What if the -centre of their galaxy isn't at (0.0", 0.0")? - -Well, this is true if our dataset reduction centres the galaxy somewhere else. But we get to choose where we -centre it when we make the image. Therefore, I`d recommend you always centre the galaxy at the same location, -and (0.0", 0.0") seems the best choice! -""" -bulge = af.Model(ag.lp_linear.Sersic) -disk = af.Model(ag.lp_linear.Exponential) - -""" -You haven't actually seen a line like this one before. By setting a parameter to a number (and not a prior) it is be -removed from non-linear parameter space and always fixed to that value. Pretty neat, huh? -""" -bulge.centre_0 = 0.0 -bulge.centre_1 = 0.0 -disk.centre_0 = 0.0 -disk.centre_1 = 0.0 - -""" -Lets also use the same approach as tutorial 4 of this chapter and align the ellipticity of the bulge and disk, -removing another two parameters from the model. -""" -disk.ell_comps = bulge.ell_comps - -""" -We also know that the bulges of many galaxies are well described by a Sersic index of around 4 (a de Vaucouleurs -profile). Lets fix it to 4 this time. -""" -bulge.sersic_index = 4.0 - -galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk) - -model_1 = af.Collection(galaxies=af.Collection(galaxy=galaxy)) - -""" -The `info` attribute shows the model in a readable format. -""" -print(model_1.info) - -""" -__Search + Analysis__ - -Now lets create the search and analysis. -""" -search_1 = af.Nautilus( - path_prefix=Path("howtogalaxy", "chapter_2"), - name="tutorial_9_search_chaining_1", - unique_tag=dataset_name, - n_live=100, - n_batch=50, # GPU batching and VRAM use explained in tutorial 2 of this chapter. -) - -analysis_1 = ag.AnalysisImaging(dataset=dataset, use_jax=True) - -""" -Lets run the search, noting that our liberal approach to reducing the model complexity has reduced it to just -4 parameters. -""" -print( - "The non-linear search has begun running - checkout the output/howtogalaxy/chapter_2" - " folder for live output of the results, images and model." - " This Jupyter notebook cell will progress once search has completed - this could take some time!" -) - -result_1 = search_1.fit(model=model_1, analysis=analysis_1) - -print("Search has finished run - you may now continue the notebook.") - -""" -__Result__ - -The results are summarised in the `info` attribute. -""" -print(result_1.info) - -""" -And indeed, we get a reasonably good model and fit to the data, in a much shorter space of time! -""" -aplt.subplot_fit_imaging(fit=result_1.max_log_likelihood_fit) - -""" -__Prior Passing__ - -Now all we need to do is look at the results of search 1 and pass the results as priors for search 2. Lets setup -a custom search that does exactly that. - -`TruncatedGaussianPrior`'s are a nice way to pass priors. They tell the non-linear search where to look, but leave open the -possibility that there might be a better solution nearby. In contrast, `UniformPrior`'s put hard limits on what values a -parameter can or can`t take. It makes it more likely we will accidentally cut-out the global maxima solution. - -Note that below the `disk` has become a `Sersic`. -""" -bulge = af.Model(ag.lp_linear.Sersic) -disk = af.Model(ag.lp_linear.Sersic) - -""" -What I've done below is looked at the results of search 1 and manually specified a prior for every parameter. If a -parameter was fixed in the previous search, its prior is based around the previous value. Don't worry about the sigma -values for now, I've chosen values that I know will ensure reasonable sampling, but we'll cover this later. - -__BULGE PRIORS:__ -""" -bulge.centre.centre_0 = af.TruncatedGaussianPrior( - mean=0.0, sigma=0.1, lower_limit=-np.inf, upper_limit=np.inf -) -bulge.centre.centre_1 = af.TruncatedGaussianPrior( - mean=0.0, sigma=0.1, lower_limit=-np.inf, upper_limit=np.inf -) -bulge.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior( - mean=0.11, sigma=0.2, lower_limit=-1.0, upper_limit=1.0 -) -bulge.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior( - mean=0.05, sigma=0.2, lower_limit=-1.0, upper_limit=1.0 -) -bulge.effective_radius = af.TruncatedGaussianPrior( - mean=0.75, sigma=0.4, lower_limit=0.0, upper_limit=np.inf -) -bulge.sersic_index = af.TruncatedGaussianPrior( - mean=4.0, sigma=2.0, lower_limit=0.0, upper_limit=np.inf -) - -""" -__DISK PRIORS:__ -""" -disk.centre.centre_0 = af.TruncatedGaussianPrior( - mean=0.0, sigma=0.1, lower_limit=-np.inf, upper_limit=np.inf -) -disk.centre.centre_1 = af.TruncatedGaussianPrior( - mean=0.0, sigma=0.1, lower_limit=-np.inf, upper_limit=np.inf -) -disk.ell_comps.ell_comps_0 = af.TruncatedGaussianPrior( - mean=0.11, sigma=0.2, lower_limit=-1.0, upper_limit=1.0 -) -disk.ell_comps.ell_comps_1 = af.TruncatedGaussianPrior( - mean=0.05, sigma=0.2, lower_limit=-1.0, upper_limit=1.0 -) -disk.effective_radius = af.TruncatedGaussianPrior( - mean=1.52, sigma=0.4, lower_limit=0.0, upper_limit=np.inf -) -disk.sersic_index = af.TruncatedGaussianPrior( - mean=1.0, sigma=2.0, lower_limit=0.0, upper_limit=np.inf -) - -""" -We now compose the model with these components that have had their priors customized. -""" -galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge, disk=disk) - -model_2 = af.Collection(galaxies=af.Collection(galaxy=galaxy)) - -""" -The `info` attribute shows the model, including the priors specified above. -""" -print(model_2.info) - -""" -Lets setup and run the search. As expected, it gives us the correct model. However, it does so significantly -faster than we are used to! -""" -search_2 = af.Nautilus( - path_prefix=Path("howtogalaxy", "chapter_2"), - name="tutorial_9_search_chaining_2", - unique_tag=dataset_name, - n_live=100, - n_batch=50, # GPU batching and VRAM use explained in tutorial 2 of this chapter. -) - -analysis_2 = ag.AnalysisImaging(dataset=dataset, use_jax=True) - -print( - "The non-linear search has begun running - checkout the output/howtogalaxy/chapter_2" - " folder for live output of the results, images and model." - " This Jupyter notebook cell will progress once search has completed - this could take some time!" -) - -result_2 = search_2.fit(model=model_2, analysis=analysis_2) - -print("Search has finished run - you may now continue the notebook.") - -""" -__Result__ - -We can again inspect the results via the `info` attribute. -""" -print(result_2.info) - -""" -And a plot of the image shows we get a good model again! -""" -aplt.subplot_fit_imaging(fit=result_2.max_log_likelihood_fit) - -""" -__Wrap Up__ - -Chaining two searches together was a huge success. We managed to fit a complex and realistic model, but were able to -begin by making simplifying assumptions that eased our search of non-linear parameter space. We could apply search 1 to -pretty much any galaxy and therefore get ourselves a decent model with which to tune search 2`s priors. - -You are probably thinking though that there is one huge, giant, glaring flaw in all of this that I've not mentioned. -Search 2 can`t be generalized to another galaxy, because its priors are tuned to the image we fitted. If we had a lot -of galaxies, we`d have to write a new search for every single one. This isn't ideal, is it? - -Fortunately, we can pass priors in **PyAutoGalaxy** without specifying the specific values. The API for this technique, -called prior passing, is the topic of the next tutorial. -""" diff --git a/scripts/chapter_optional/tutorial_need_for_speed.py b/scripts/chapter_optional/tutorial_need_for_speed.py new file mode 100644 index 0000000..7815ec3 --- /dev/null +++ b/scripts/chapter_optional/tutorial_need_for_speed.py @@ -0,0 +1,82 @@ +""" +Optional Tutorial: Need for Speed +================================= + +Return to this tutorial when a fit is too slow for your scientific needs. Faster likelihood calculations help, +but a well-organised model and search often matter just as much. Hardware cannot make an inappropriate model fit. + +__Contents__ + +- **Search Effort:** Reduce unnecessary exploration without hiding uncertainty. +- **Likelihood Cost:** Understand the calculation for each trial model. +- **JAX and Batching:** Account for compilation, hardware and memory. +- **Measuring Runtime:** Use representative runs rather than fixed rules. +- **Data Quantity:** Retain the measurements needed for your science. + +__Search Effort__ + +More free parameters, broad priors and difficult degeneracies can increase the work needed to explore a model. +More live points generally make exploration more thorough at additional cost. There is no reliable universal +rule such as a fixed number of likelihood evaluations per parameter. + +Linear profiles remove intensities from the non-linear search. Search chaining can fix well-constrained component +geometry so subsequent searches concentrate on the remaining problem. Both can improve reliability as well as +runtime. Narrow priors or fewer live points may shorten a run while concealing good solutions: check the result. + +Prodigy can be useful for quickly finding a fitted component, as in chapter 2 tutorial 6. It does not replace a +sampler when you need uncertainty estimates. The optional searches tutorial explains the distinction. + +__Likelihood Cost__ + +Each evaluation predicts the galaxy light, accounts for the instrument and compares it with the data. Costs +include profile evaluation, over sampling, PSF convolution and, for linear profiles or pixelizations, a linear solve. +For interferometry, transforming predicted light into visibilities introduces different costs. + +More profiles or reconstruction elements usually mean more work, but the overall fit can still be faster if the +resulting parameter space is easier to search. Measure the full workflow rather than judging only one operation. + +__JAX and Batching__ + +JAX compiles supported likelihood calculations into a form that can be reused efficiently on CPUs or compatible +GPUs. The first compilation costs time. Changed shapes or model structures can require compilation again, so +this cost is not necessarily paid only once during an entire session. + +Nautilus can evaluate batches of trial models; gradient optimisers can evaluate several starts together. This +parallel work may suit a GPU well, but a GPU is not automatically faster for every small dataset or model. Device +support, numerical precision, memory and compilation all matter. Installing the appropriate accelerator runtime +is also necessary; having a GPU in the machine alone does not mean JAX is using it. + +For Nautilus, `n_batch` controls batching. For `MultiStartProdigy`, explicitly choose `batch_size`; setting it to +`None` processes all starts together and may require much more memory. The practicalities tutorial shows +`analysis.print_vram_use(model=model, batch_size=search.batch_size)`. Treat it as a likelihood memory estimate, +not the total process requirement or a guarantee that gradient calculations will fit in the same memory. + +A NumPy path remains available via `use_jax=False` for supported analyses, useful for debugging or comparison. +Gradient searches require the accelerated differentiable path. Older advice based only on ordinary Python or +Numba likelihood timings does not describe the compiled, batched workflow. + +__Measuring Runtime__ + +Run a representative model on the machine you intend to use. Separate initial compilation from subsequent +execution, and include search overhead and output updates when estimating the time to completion. If timing +individual JAX operations, wait for the device to finish: dispatch time alone is not execution time. + +Timing a standalone `FitImaging` call is not a benchmark of the compiled batched search. A rough estimate based on +cost per evaluation times evaluation count is useful only when both numbers refer to the same execution path; +for batches, use batch throughput rather than multiplying by a single-call timing. + +Inspect `search.summary` and logs, then compare representative runs with different batch sizes or model choices. +Do not compare a compilation-heavy first run against a cached or resumed run as though both did the same work. +Frequent visualisation and file writes can also dominate short fits; adjust update intervals when appropriate. + +__Data Quantity__ + +Halving the pixel scale at fixed field of view gives four times as many pixels. Finer over sampling, a larger PSF +or a larger fitted region can add work too. However, retaining faint outskirts can be essential to constrain a +galaxy's size. Do not mask away informative residuals merely to make a fit faster. + +__Wrap Up__ + +Use the data-and-likelihood lesson to decide which measurements belong in the fit, then assess numerical accuracy +and runtime together. Speed is useful when it lets you test more credible models and check them more carefully. +""" diff --git a/scripts/chapter_optional/tutorial_prior_passing.py b/scripts/chapter_optional/tutorial_prior_passing.py new file mode 100644 index 0000000..d435f63 --- /dev/null +++ b/scripts/chapter_optional/tutorial_prior_passing.py @@ -0,0 +1,50 @@ +""" +Optional Historical Tutorial: Prior Passing +=========================================== + +This is historical background, not part of the recommended HowToGalaxy learning path. Older versions of the +PyAutoGalaxy / PyAutoLens workflow automatically narrowed priors between searches. That default behaviour has +been disabled. New readers are discouraged from investing time in the old prior-passing recipes: learn the +component-separation approach in chapter 2 tutorial 6 instead. + +__Contents__ + +- **Historical Behaviour:** Why older tutorials describe Gaussian priors centred on results. +- **Current Behaviour:** Distinguish fixed instances, default priors and explicit centred models. +- **Why It Is Optional:** Understand the assumptions before reusing information from a fit. + +__Historical Behaviour__ + +Older workflows used a first fit to create Gaussian priors for a later one. The Gaussian mean was based on the +first result, and its width used uncertainty and configurable width modifiers. An absolute modifier supplied a +width in parameter units; a relative modifier scaled with the inferred value. This was intended to guide later +searches towards plausible regions without manually copying every parameter. + +This history explains older references to `result.model` as automatic prior passing. Those descriptions are not +instructions for the current API, and should not be used to interpret a modern chained fit. + +__Current Behaviour__ + +`result.instance` supplies concrete fitted parameter values. Using a component from it fixes those values in the +next model. Linear-profile intensities remain solved inside the likelihood unless converted to ordinary profiles. +This is the behaviour used in the core chaining tutorial. + +`result.model` instead supplies a model with default priors for free parameters; it does not automatically centre +those priors on the previous fit. Fixed parameters and model structure still matter, so inspect `model.info`. + +Explicit centred-model tools such as `result.model_centred`, `model_centred_absolute` and `model_centred_relative` +remain available for advanced use. Automatic default narrowing has been disabled; the capability has not been +removed entirely. See `autogalaxy_workspace/scripts/guides/modeling/chaining.py` for the current API. + +__Why It Is Optional__ + +Narrowing priors around an earlier solution can exclude better solutions or carry its mistakes forward. Reusing +the same data to construct a prior and then fitting those data again also needs careful statistical interpretation; +it is not automatically equivalent to a joint analysis with independent prior information. + +__Wrap Up__ + +Search chaining remains valuable without this step. It lets well-constrained components be dealt with separately, +reduces the parameter space of later fits and allows different search effort at different stages. Those are the +ideas to retain for modelling real galaxies. +""" diff --git a/scripts/chapter_optional/tutorial_searches.py b/scripts/chapter_optional/tutorial_searches.py index e927293..67a2c40 100644 --- a/scripts/chapter_optional/tutorial_searches.py +++ b/scripts/chapter_optional/tutorial_searches.py @@ -1,53 +1,54 @@ """ -Tutorial: Alternative Searches -============================== +Optional Tutorial: Alternative Searches +======================================= -Up to now, we've always used the non-linear search Nautilus and not considered the input parameters that control its -sampling. In this tutorial, we'll consider how we can change these setting to balance finding the global maxima -solution with fast run time. - -We will also discuss other types of non-linear searches, such as MCMC and optimizers, which we can use to perform -modeling. So far, we have not found any of these alternatives to give anywhere near as robust and efficient results as -Nautilus, and we recommend users use Nautilus unless they are particularly interested in investigating different -model-fitting techniques. +You can complete HowToGalaxy using Nautilus without studying search algorithms in detail. Return here if you want +to understand the fast Prodigy stage of search chaining, or compare alternative approaches for your own work. __Contents__ -- **Nested Sampling:** Customize Nautilus settings and use Dynesty as an alternative nested sampler. -- **Optimizers:** Use maximum likelihood optimizers like LBFGS for fast but less robust fitting. -- **MCMC:** Use Markov Chain Monte Carlo methods like Emcee for parameter estimation. +- **Optimisation:** Improve trial models towards a best fit with Prodigy. +- **Nested Sampling:** Explore parameter ranges with Nautilus. +- **MCMC:** Another way to estimate parameter distributions. + +__Optimisation__ + +An optimiser repeatedly proposes changes to a trial galaxy, checks whether its score improves, and moves towards +better solutions. Imagine adjusting the size and shape so that the predicted light increasingly resembles the +image. Repeating this process aims to find the best-fitting model, rather than trying to describe every plausible +model in detail. Individual steps need not always improve the likelihood. + +Prodigy uses gradients to choose useful directions. `MultiStartProdigy` repeats this from several starting models, +reducing the risk that one poor start determines the answer. Its score includes prior weight as well as likelihood +(a maximum-a-posteriori optimisation). It uses JAX, the numerical engine that accelerates these calculations and +provides the gradients; you do not need to study JAX to run it. + +The result can give a useful galaxy size, but does not by itself tell us how precisely that size is measured. +It also cannot guarantee the best solution was found. Inspect residuals and test different starts or settings. """ # from autogalaxy import setup_notebook; setup_notebook() from pathlib import Path +import numpy as np +import autofit as af import autogalaxy as ag import autogalaxy.plot as aplt -import autofit as af """ -we'll use the `simple__sersic` imaging data of a galaxy, where: +__Dataset and Mask__ - - The galaxy's light is a `Sersic`. +Load the imaging data and retain the region inside the circular mask. The simulator creates the data if needed. +The image, noise map and PSF together describe the observation; none specifies which galaxy model we must fit. """ + dataset_name = "simple__sersic" dataset_path = Path("dataset") / "imaging" / dataset_name - -""" -__Dataset Auto-Simulation__ - -If the dataset does not already exist on your system, it will be created by running the corresponding -simulator script. This ensures that all example scripts can be run without manually simulating data first. -""" if ag.util.dataset.should_simulate(str(dataset_path)): import subprocess import sys - subprocess.run( - [sys.executable, "scripts/simulators/sersic.py"], - check=True, - ) - + subprocess.run([sys.executable, "scripts/simulators/sersic.py"], check=True) dataset = ag.Imaging.from_fits( data_path=dataset_path / "data.fits", @@ -55,236 +56,106 @@ psf_path=dataset_path / "psf.fits", pixel_scales=0.1, ) - -""" -we'll create and use a 2.6" `Mask2D`. -""" mask = ag.Mask2D.circular( - shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=2.6 + shape_native=dataset.shape_native, pixel_scales=dataset.pixel_scales, radius=3.0 ) - dataset = dataset.apply_mask(mask=mask) -aplt.subplot_imaging_dataset(dataset=dataset) - """ -__Nested Sampling__ - -Lets first perform the model-fit using Nautilus, but look at different parameters that control how long it takes to run. -We'll therefore discuss in a bit more detail how Nautilus works, but still keep this description conceptually simple -and avoid technical terms and jargon. For a complete description of Nautilus you should check out the Nautilus -publication `https://arxiv.org/abs/2306.16923`. - -nlive: - -Nautilus is a `nested sampling` algorithm. As we described in chapter 2, it throws down a set of `live points` in -parameter space, where each live point corresponds to a model with a given set of parameters. These points are -initially distributed according to our priors, hence why tuning our priors allows us to sample parameter space faster. - -The number of live points is set by the parameter `n_live`. More points provide a more thorough sampling of -parameter space, increasing the probability that we locate the global maxima solution. Therefore, if you think your -model-fit has gone to a local maxima, you should try increasing `n_live`. The downside of this is Nautilus will -take longer to sample parameter space and converge on a solution. Ideally, we will use as few live points as possible -to locate the global maxima as quickly as possible. - -f_live: - -A nested sampling algorithm estimates the *Bayesian Evidence* of the model-fit, which is a quantity the non-linear -search algorithms we introduce later do not. The Bayesian evidence quantifies how well the model as a whole fits -the data, following a principle called Occam's Razor (`https://simple.wikipedia.org/wiki/Occam%27s_razor`). This -penalizes models for being more complex (e.g. more parameters) and requires that their additional complexity improve -their overall fit to the data compared to a simpler model. By comparing the Bayesian evidence of -different models one can objectively choose the model that best fits the data. - -A nested sampling algorithm stops sampling when it estimates that continuing sampling will not increase the Bayesian -evidence (called the `log_evidence`) by more than the `f_live`. As Nautilus progresses and converges on the -solution, the rate of increase of the estimated Bayesian evidence slows down. Therefore, higher `f_live`s -mean Nautilus terminate sooner. - -A high `f_live` will make the errors estimated on every parameter unreliable and its value must be kept -below 0.8 for reliable error estimates. However, when chaining searches, we typically *do not care* about the errors -in the first search, therefore setting a high evidence tolerance can be an effective means to make Nautilus converge -faster (we'll estimate reliable errors in the second search when the `f_live` is 0.8 or less). +__Over Sampling__ +The bright centre changes rapidly across a pixel. Adaptive over sampling evaluates it on a finer grid so that +numerical inaccuracies do not masquerade as poor models. The outskirts need fewer evaluations. +""" -Lets perform two fits, where: +over_sample_size = ag.util.over_sample.over_sample_size_via_radial_bins_from( + grid=dataset.grid, + sub_size_list=[8, 4, 2], + radial_list=[0.3, 0.6], + centre_list=[(0.0, 0.0)], +) +dataset = dataset.apply_over_sampling(over_sample_size_lp=over_sample_size) +aplt.subplot_imaging_dataset(dataset=dataset) - - One has many live points and a higher evidence tolerance, causing the non-linear search to - take a longer time to run. - - - One has few live points, a high sampling efficiency and evidence tolerance, causing the non-linear search to - converge and end quicker. -""" model = af.Collection( galaxies=af.Collection( - galaxy=af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp.Sersic), + galaxy=af.Model(ag.Galaxy, redshift=0.5, bulge=ag.lp_linear.Sersic) ) ) - -search = af.Nautilus( +analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True) +search = af.MultiStartProdigy( path_prefix=Path("howtogalaxy", "chapter_optional"), - name="tutorial_searches_slow", + name="tutorial_searches_prodigy", unique_tag=dataset_name, - n_live=400, - n_batch=50, # GPU model fits are batched and run simultaneously (see chapter 2 tutorial 2). -) - -analysis = ag.AnalysisImaging(dataset=dataset, use_jax=True) - -print( - "The non-linear search has begun running - checkout the HowToGalaxy/output" - " folder for live output of the results, images and model." - " This Jupyter notebook cell will progress once search has completed - this could take some time!" + n_starts=24, + batch_size=4, + n_steps=300, ) +result_prodigy = search.fit(model=model, analysis=analysis) +print(result_prodigy.info) +aplt.subplot_fit_imaging(fit=result_prodigy.max_log_likelihood_fit) -result_slow = search.fit(model=model, analysis=analysis) - -""" -Lets check that we get a good model and fit to the data. """ -aplt.subplot_fit_imaging(fit=result_slow.max_log_likelihood_fit) +__Nested Sampling__ -""" -We can use the result to tell us how many iterations Nautilus took to convergence on the solution. -""" -print("Total Nautilus Iterations (If you skip running the search, this is ~ 500000):") -print(result_slow.samples.total_samples) +Nautilus spends effort exploring the range of plausible parameters, supporting uncertainty estimates as well as +a best fit. This extra information is useful when making scientific measurements. It also estimates Bayesian +evidence, used for model comparison, and has stopping criteria rather than a prescribed number of steps. +Increase `n_live` when exploration is inadequate, but judge convergence from repeated fits and diagnostics as well. +No fixed live-point count guarantees reliable uncertainties for every model. The following runs the same galaxy +model with Nautilus so that you can inspect its fit and parameter ranges alongside the optimiser's result. """ -Now lets run the search with fast settings, so we can compare the total number of iterations required. -""" + search = af.Nautilus( path_prefix=Path("howtogalaxy", "chapter_optional"), - name="tutorial_searches_fast", + name="tutorial_searches_nautilus", unique_tag=dataset_name, - n_live=75, - n_batch=50, # GPU model fits are batched and run simultaneously (see chapter 2 tutorial 2). + n_live=200, + n_batch=50, ) - -print( - "The non-linear search has begun running - checkout the HowToGalaxy/output" - " folder for live output of the results, images and model." - " This Jupyter notebook cell will progress once search has completed - this could take some time!" -) - -result_fast = search.fit(model=model, analysis=analysis) - -print("Search has finished run - you may now continue the notebook.") - -""" -Lets check that this search, despite its faster sampling settings, still gives us the global maxima solution. -""" -aplt.subplot_fit_imaging(fit=result_fast.max_log_likelihood_fit) - -""" -And now lets confirm it uses significantly fewer iterations. -""" -print("Total Nautilus Iterations:") -print("Slow settings: ~500000") -print(result_slow.samples.total_samples) -print("Fast settings: ", result_fast.samples.total_samples) +result_nautilus = search.fit(model=model, analysis=analysis) +print(result_nautilus.info) +aplt.subplot_fit_imaging(fit=result_nautilus.max_log_likelihood_fit) """ -__Optimizers__ - -Nested sampling algorithms like Nautilus provides the errors on all of the model parameters, by fully mapping out all -of the high likelihood regions of parameter space. This provides knowledge on the complete *range* of models that do -and do not provide high likelihood fits to the data, but takes many extra iterations to perform. If we require precise -error estimates (perhaps this is our final model fit before we publish the results in a paper), these extra -iterations are acceptable. - -However, we often don't care about the errors. For example, in the previous tutorial when chaining searches, the only -result we used from the fit performed in the first search was the maximum log likelihood model, omitting the errors -entirely! Its seems wasteful to use a nested sampling algorithm like Nautilus to map out the entirity of parameter -space when we don't use this information! - -There are a class of non-linear searches called `optimizers`, which seek to optimize just one thing, the log -likelihood. They want to find the model that maximizes the log likelihood, with no regard for the errors, thus not -wasting time mapping out in intricate detail every facet of parameter space. - -PyAutoFit supports a number of optimizers, which can be used as an alternative to nested sampling when only the -maximum likelihood model is needed. These include `LBFGS` and `BFGS` (from scipy), which descend the likelihood from a -single starting point. A single-start optimizer generally needs a good starting point to work well, and in our -experience the parameter spaces fitted by models are often too complex for it without careful setup of initialization -priors. - -PyAutoFit also supports multi-start gradient optimizers (`MultiStartProdigy`, `MultiStartAdam`, `MultiStartADABelief` -and `MultiStartLion`), which use JAX to launch many optimizations from starting points spread across parameter space -in parallel and return the best one. This makes them far more robust to complex parameter spaces, and -`MultiStartProdigy` is the optimizer used by many of the `start_here.py` examples in the `autogalaxy_workspace`. Like any optimizer, they -return only the best-fit model with no errors. The `autogalaxy_workspace` script `scripts/guides/modeling/searches.py` describes -every search, including these optimizers, in detail. - __MCMC__ -For users familiar with Markov Chain Monte Carlo (MCMC) non-linear samplers, PyAutoFit supports the non-linear -searches `Emcee` and `Zeus`. Like LBFGS, these also need a good starting point, and are generally less effective at -modeling than Nautilus. +Markov chain Monte Carlo methods explore distributions of parameters by proposing successive moves and accepting +or rejecting them according to their probabilities. Emcee uses an ensemble of walkers. Walkers can move to lower +likelihoods as well as higher ones; their aim is to sample the distribution, not only climb towards its peak. -I've included an example runs of Emcee and Zeus below, where the model is set up using `UniformPriors` to give -the starting point of the MCMC walkers. +A sensible starting region can help. Here the bounds describe an initial spread around values suggested by the +image; they do not replace the model priors. This demonstration uses a finite number of steps, which is not a +claim of convergence. Before interpreting uncertainty estimates, examine mixing, autocorrelation and whether +longer runs agree. Multiple walkers do not guarantee escape from separated regions of good fits. """ -bulge = af.Model(ag.lp.Sersic) -bulge.centre.centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) -bulge.centre.centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) -bulge.ell_comps.ell_comps_0 = af.UniformPrior(lower_limit=-0.3, upper_limit=0.3) -bulge.ell_comps.ell_comps_1 = af.UniformPrior(lower_limit=-0.3, upper_limit=0.3) -bulge.intensity = af.UniformPrior(lower_limit=0.5, upper_limit=1.5) -bulge.effective_radius = af.UniformPrior(lower_limit=0.2, upper_limit=1.6) -bulge.sersic_index = af.UniformPrior(lower_limit=3.0, upper_limit=5.0) - -galaxy = af.Model(ag.Galaxy, redshift=0.5, bulge=bulge) - -model = af.Collection(galaxies=af.Collection(galaxy=galaxy)) - -search = af.Zeus( - path_prefix=Path("howtogalaxy", "chapter_optional"), - name="tutorial_searches_zeus", - unique_tag=dataset_name, - nwalkers=50, - nsteps=1000, -) -print( - "Zeus has begun running - checkout the HowToGalaxy/output" - " folder for live output of the results, images and model." - " This Jupyter notebook cell will progress once search has completed - this could take some time!" +initializer = af.InitializerParamBounds( + { + model.galaxies.galaxy.bulge.centre.centre_0: (-0.05, 0.05), + model.galaxies.galaxy.bulge.centre.centre_1: (-0.05, 0.05), + model.galaxies.galaxy.bulge.effective_radius: (0.5, 1.5), + model.galaxies.galaxy.bulge.sersic_index: (2.0, 5.0), + } ) - -result_zeus = search.fit(model=model, analysis=analysis) - -print("Zeus has finished run - you may now continue the notebook.") - -aplt.subplot_fit_imaging(fit=result_zeus.max_log_likelihood_fit) - - search = af.Emcee( path_prefix=Path("howtogalaxy", "chapter_optional"), name="tutorial_searches_emcee", unique_tag=dataset_name, nwalkers=50, nsteps=1000, + initializer=initializer, ) - -print( - "The non-linear search has begun running - checkout the HowToGalaxy/output" - " folder for live output of the results, images and model." - " This Jupyter notebook cell will progress once search has completed - this could take some time!" -) - result_emcee = search.fit(model=model, analysis=analysis) - -print("The search has finished run - you may now continue the notebook.") - +print(result_emcee.info) aplt.subplot_fit_imaging(fit=result_emcee.max_log_likelihood_fit) """ __Wrap Up__ -This tutorial showed how the same model can be fitted using different non-linear searches (e.g. `Nautilus`, `Zeus`, -`Emcee`). Each search explores parameter space in a different way, and the best choice depends on the -dimensionality and complexity of the model you are fitting. - -For the vast majority of models in **PyAutoGalaxy**, the default nested sampling search `Nautilus` is recommended, as -it is robust, efficient and requires little manual tuning. +A quick optimisation is useful when you need a fitted component or want to check a model setup. A sampler is useful +when you need ranges of plausible parameters and uncertainty estimates. Both require checking the result. +The workspace guide `autogalaxy_workspace/scripts/guides/modeling/searches.py` covers additional searches and settings. +For the core lessons, keep your attention on the galaxy model and the quality of its fit. """ diff --git a/start_here.ipynb b/start_here.ipynb index 9f996c2..9e578fb 100644 --- a/start_here.ipynb +++ b/start_here.ipynb @@ -19,10 +19,9 @@ "\n", "- Chapter 1: Introduction to galaxy morphology \u2014 grids, light profiles, galaxies, simulated data, and how\n", " fitting works.\n", - "- Chapter 2: Bayesian inference and non-linear searches \u2014 how to fit a galaxy model to CCD imaging data.\n", - "- Chapter 3: Search chaining \u2014 automated pipelines that fit complex systems by chaining multiple searches.\n", - "- Chapter 4: Pixelized galaxy reconstruction \u2014 reconstructing galaxies with irregular morphology using\n", - " inversions and regularization.\n", + "- Chapter 2: Practical galaxy modelling \u2014 data, models, likelihoods, linear profiles and search chaining.\n", + "- Chapter 3: Pixelized galaxy reconstruction \u2014 irregular morphology, inversions and regularization.\n", + "- Chapter 4: Scaling up galaxies \u2014 modelling multiple galaxies and cluster fields.\n", "\n", "Each chapter is organised into numbered tutorial files: `chapter__/tutorial__.py` (Python script)\n", "or the matching `.ipynb` in `notebooks/`. Tutorials build on each other within a chapter and assume you have\n", @@ -38,7 +37,7 @@ "3. Work through `chapter_2_modeling`.\n", "4. At this point you can start modeling real galaxies using scripts in the separate\n", " `autogalaxy_workspace` repository \u2014 you know enough to be productive.\n", - "5. Come back for `chapter_3_search_chaining` and `chapter_4_pixelizations` when you want to tackle more\n", + "5. Come back for `chapter_3_pixelizations` and `chapter_4_scaling_up_galaxies` when you want to tackle more\n", " complex systems.\n", "\n", "__Notebooks vs Scripts__\n", diff --git a/start_here.py b/start_here.py index 8689ce7..f701393 100644 --- a/start_here.py +++ b/start_here.py @@ -14,10 +14,9 @@ - Chapter 1: Introduction to galaxy morphology — grids, light profiles, galaxies, simulated data, and how fitting works. -- Chapter 2: Bayesian inference and non-linear searches — how to fit a galaxy model to CCD imaging data. -- Chapter 3: Search chaining — automated pipelines that fit complex systems by chaining multiple searches. -- Chapter 4: Pixelized galaxy reconstruction — reconstructing galaxies with irregular morphology using - inversions and regularization. +- Chapter 2: Practical galaxy modelling — data, models, likelihoods, linear profiles and search chaining. +- Chapter 3: Pixelized galaxy reconstruction — irregular morphology, inversions and regularization. +- Chapter 4: Scaling up galaxies — modelling multiple galaxies and cluster fields. Each chapter is organised into numbered tutorial files: `chapter__/tutorial__.py` (Python script) or the matching `.ipynb` in `notebooks/`. Tutorials build on each other within a chapter and assume you have @@ -33,7 +32,7 @@ 3. Work through `chapter_2_modeling`. 4. At this point you can start modeling real galaxies using scripts in the separate `autogalaxy_workspace` repository — you know enough to be productive. -5. Come back for `chapter_3_search_chaining` and `chapter_4_pixelizations` when you want to tackle more +5. Come back for `chapter_3_pixelizations` and `chapter_4_scaling_up_galaxies` when you want to tackle more complex systems. __Notebooks vs Scripts__ diff --git a/workspace_index.json b/workspace_index.json index 04dc1b1..11d9aac 100644 --- a/workspace_index.json +++ b/workspace_index.json @@ -100,186 +100,114 @@ "summary": "In this chapter, we have learnt that:", "title": "Tutorial 5: Summary" }, - { - "contents": [ - "Initial Setup", - "Dataset Auto-Simulation", - "Model", - "Search", - "Result (Search 1)", - "Prior Passing", - "Result", - "Wrap Up", - "Detailed Explanation Of Prior Passing", - "EXAMPLE" - ], - "cross_refs": [ - "autogalaxy_workspace/scripts/guides/modeling/chaining.py" - ], - "notebook": "notebooks/chapter_2_modeling/tutorial_10_prior_passing.ipynb", - "path": "scripts/chapter_2_modeling/tutorial_10_prior_passing.py", - "summary": "In the previous tutorial, we used non-linear search chaining to break the model-fitting procedure down into two non-linear searches. This used an initial search to fit a simple model, whose results were used to tune and initialize the priors of a more complex model that was fitted by the second search.", - "title": "Tutorial 10: Prior Passing" - }, { "contents": [ "Parameter Space", - "Non-Linear Search", - "Search Types", - "Deeper Background", - "Data", - "Model", - "Priors", + "Dataset and Mask", + "Model and Priors", "Analysis", - "Searches", - "Maximum Likelihood Estimation (MLE)", - "Markov Chain Monte Carlo (MCMC)", "Nested Sampling", - "Result", - "Samples", - "Customizing Searches", - "Wrap Up" - ], - "cross_refs": [ - "/imaging/likelihood_function.ipynb" + "Result" ], + "cross_refs": [], "notebook": "notebooks/chapter_2_modeling/tutorial_1_non_linear_search.ipynb", "path": "scripts/chapter_2_modeling/tutorial_1_non_linear_search.py", - "summary": "The starting point for most scientific analysis conducted by an Astronomer is that they have observations of a galaxy using a telescope like the Hubble Space Telescope, and seek to learn about the galaxy and the Universe from these observations. With **PyAutoGalaxy**, we seek to learn about the galaxy's structure and morphology, asking questions like how big is the galaxy, is it disky or bulgy, and how is its light distributed?", + "summary": "In chapter 1, you adjusted a galaxy model by hand and inspected how well its image matched the data. Now we will ask a search to do this for us. Our aim is still to learn about the galaxy: its size, shape and concentration.", "title": "Tutorial 1: Non-linear Search" }, { - "contents": [], + "contents": [ + "Dataset and Mask", + "Model", + "Search Settings", + "Analysis and Run Times", + "VRAM Use", + "Output Folder", + "Unique Identifier", + "Results and Configuration" + ], "cross_refs": [ - "/guides/advanced/over_sampling.ipynb", + "autogalaxy_workspace/scripts/guides/results/start_here.py", "scripts/chapter_2_modeling/tutorial_2_practicalities.py" ], "notebook": "notebooks/chapter_2_modeling/tutorial_2_practicalities.ipynb", "path": "scripts/chapter_2_modeling/tutorial_2_practicalities.py", - "summary": "In the last tutorial, we introduced foundational statistical concepts essential for model-fitting, such as parameter spaces, likelihoods, priors, and non-linear searches. Understanding these statistical concepts is crucial for performing model fits effectively.", + "summary": "A galaxy can contain a compact bulge and an extended disk. We now fit both, while learning how to run a search, manage its memory use and inspect its output. These practical skills let us assess a model as the fit progresses.", "title": "Tutorial 2: Practicalities" }, { "contents": [ - "Initial Setup", - "Model + Search + Analysis", - "Result", - "Global and Local Maxima", - "Wrap Up" + "A Reference Fit", + "An Inadequate Search", + "Local Maxima", + "Prior Tuning", + "Reducing Complexity", + "Look Harder", + "Benefits and Weaknesses" ], - "cross_refs": [ - "/guides/advanced/over_sampling.ipynb" - ], - "notebook": "notebooks/chapter_2_modeling/tutorial_3_realism_and_complexity.ipynb", - "path": "scripts/chapter_2_modeling/tutorial_3_realism_and_complexity.py", - "summary": "In the previous two tutorials, we fitted a fairly basic model: the galaxy's light was a single bulge component. In real observations we know that galaxies are observed to have multiple different morphological structures.", - "title": "Tutorial 3: Realism and Complexity" - }, - { - "contents": [ - "Initial Setup", - "Approach 1: Prior Tuning", - "Approach 2: Reducing Complexity", - "Approach 3: Look Harder" - ], - "cross_refs": [ - "/guides/advanced/over_sampling.ipynb", - "HowToGalaxy/chapter_optional/tutorial_searches.ipynb" - ], - "notebook": "notebooks/chapter_2_modeling/tutorial_4_dealing_with_failure.ipynb", - "path": "scripts/chapter_2_modeling/tutorial_4_dealing_with_failure.py", - "summary": "In the previous tutorial we intentionally made our non-linear search infer a local maxima solution and therefore return a physically incorrect model. In this tutorial, we will pretend that we have modeled our galaxy and inferred a local maxima. We introduce three approaches one can take that changes how we fit the model, all of which have the aim of ensuring we infer the global maxima:", - "title": "Tutorial 4: Dealing With Failure" + "cross_refs": [], + "notebook": "notebooks/chapter_2_modeling/tutorial_3_why_modeling_is_hard.ipynb", + "path": "scripts/chapter_2_modeling/tutorial_3_why_modeling_is_hard.py", + "summary": "The bulge and disk in tutorial 2 made our model more realistic, but also harder to fit. Their centres, shapes, brightnesses and sizes can trade off. A search can find a plausible galaxy without finding the best explanation available within the model.", + "title": "Tutorial 3: Why Modeling Is Hard" }, { "contents": [ - "Initial Setup", "Linear Light Profiles", - "Run Time", - "Result", - "Intensities", - "Visualization", + "Results and Intensities", + "Galaxy Structure", "Basis", - "Model Fit", - "Disk MGE", - "Multi Gaussian Expansion Benefits", - "Positive Only Solver", - "Other Basis Functions", - "Wrap Up" + "Two Gaussian Groups", + "Benefits and Limitations" ], "cross_refs": [ - "/guides/advanced/over_sampling.ipynb", + "autogalaxy_workspace/scripts/imaging/features/multi_gaussian_expansion/modeling.py", "autogalaxy_workspace/scripts/imaging/features/shapelets/modeling.py" ], - "notebook": "notebooks/chapter_2_modeling/tutorial_5_linear_profiles.ipynb", - "path": "scripts/chapter_2_modeling/tutorial_5_linear_profiles.py", - "summary": "In the previous tutorial we learned how to balance model complexity with our non-linear search in order to infer accurate model solutions and avoid failure. We saw how in order to fit a model accurately one may have to parameterize and fit a simpler model with fewer non-linear parameters, at the expense of fitting the data less accurately.", - "title": "Tutorial 5: Linear Profiles" + "notebook": "notebooks/chapter_2_modeling/tutorial_4_linear_profiles.ipynb", + "path": "scripts/chapter_2_modeling/tutorial_4_linear_profiles.py", + "summary": "In tutorial 3, simplifying the bulge and disk geometry made the search easier but restricted the galaxies it could represent. Linear light profiles offer a different opportunity: keep the same profile shapes and solve their intensities directly, removing those dimensions from the non-linear search.", + "title": "Tutorial 4: Linear Profiles" }, { "contents": [ - "Initial Setup", - "Mask", - "Model + Search + Analysis", - "Discussion", - "Wrap Up" + "Masking", + "Extra Galaxy Noise Scaling", + "Analysis", + "Interferometer Data", + "Multiple Datasets" ], "cross_refs": [ - "/guides/advanced/over_sampling.ipynb" + "autogalaxy_workspace/scripts/interferometer/modeling.py" ], - "notebook": "notebooks/chapter_2_modeling/tutorial_6_masking.ipynb", - "path": "scripts/chapter_2_modeling/tutorial_6_masking.py", - "summary": "We have learnt everything we need to know about non-linear searches to model a galaxy and infer a good model solution. Now, lets consider masking in more detail, something we have not given much consideration previously. We'll also learn a neat trick to improve the speed and accuracy of a non-linear search.", - "title": "Tutorial 6: Masking" + "notebook": "notebooks/chapter_2_modeling/tutorial_5_data_and_likelihoods.ipynb", + "path": "scripts/chapter_2_modeling/tutorial_5_data_and_likelihoods.py", + "summary": "So far we have changed the galaxy model and the search. Now consider the other side of the fit: the measurements we include and how they are compared with a prediction. The data, model and Analysis object have distinct jobs. This separation lets the same modelling tools work with different observations and likelihood functions.", + "title": "Tutorial 5: Data and Likelihoods" }, { "contents": [ - "Initial Setup", - "Galaxies & Fit", - "Samples", - "Workspace", - "Database", - "Wrap Up" - ], - "cross_refs": [], - "notebook": "notebooks/chapter_2_modeling/tutorial_7_results.ipynb", - "path": "scripts/chapter_2_modeling/tutorial_7_results.py", - "summary": "In the previous tutorials, each search returned a `Result` object, which we used to plot the maximum log likelihood fit of each model-fit. In this tutorial, we'll take a look at the result object in a little more detail.", - "title": "Tutorial 7: Results" - }, - { - "contents": [ - "Searching Non-linear Parameter Space", - "Cost Per Evaluation", - "JAX", - "Run Time Estimation", - "Data Quantity", - "Wrap Up" + "Dataset", + "Search 1", + "Inspect Before Chaining", + "Search 2", + "Limits and Pipelines" ], "cross_refs": [ - "chapter_optional/tutorial_searches.py" + "scripts/guides/modeling/chaining.py" ], - "notebook": "notebooks/chapter_2_modeling/tutorial_8_need_for_speed.ipynb", - "path": "scripts/chapter_2_modeling/tutorial_8_need_for_speed.py", - "summary": "In this chapter, we have learnt how to model galaxies and how to balance complexity and realism to ensure that we infer a good model.", - "title": "Tutorial 8: Need For Speed" + "notebook": "notebooks/chapter_2_modeling/tutorial_6_search_chaining.ipynb", + "path": "scripts/chapter_2_modeling/tutorial_6_search_chaining.py", + "summary": "A neighbouring galaxy can complicate the fit to our target. We need to describe its light, but repeatedly searching all its parameters while refining the target can waste effort and introduce difficult degeneracies. Search chaining lets us fit different parts of the scene in stages.", + "title": "Tutorial 6: Search Chaining" }, { - "contents": [ - "Initial Setup", - "Dataset Auto-Simulation", - "Model", - "Search + Analysis", - "Result", - "Prior Passing", - "Result", - "Wrap Up" - ], + "contents": [], "cross_refs": [], - "notebook": "notebooks/chapter_2_modeling/tutorial_9_search_chaining.ipynb", - "path": "scripts/chapter_2_modeling/tutorial_9_search_chaining.py", - "summary": "Throughout this chapter, we have fitted the data using just one non-linear search. The previous tutorial discussed the run-time cost of doing this: with a single search, the dimensionality of the model, the priors on its parameters and the search settings must all be juggled at once, leaving us little flexibility to trade them off against one another.", - "title": "Tutorial 9: Search Chaining" + "notebook": "notebooks/chapter_2_modeling/tutorial_7_summary.ipynb", + "path": "scripts/chapter_2_modeling/tutorial_7_summary.py", + "summary": "(no summary in script docstring)", + "title": "Tutorial 7: Summary" }, { "contents": [ @@ -395,18 +323,45 @@ }, { "contents": [ + "Search Effort", + "Likelihood Cost", + "JAX and Batching", + "Measuring Runtime", + "Data Quantity" + ], + "cross_refs": [], + "notebook": "notebooks/chapter_optional/tutorial_need_for_speed.ipynb", + "path": "scripts/chapter_optional/tutorial_need_for_speed.py", + "summary": "Return to this tutorial when a fit is too slow for your scientific needs. Faster likelihood calculations help, but a well-organised model and search often matter just as much. Hardware cannot make an inappropriate model fit.", + "title": "Optional Tutorial: Need for Speed" + }, + { + "contents": [ + "Historical Behaviour", + "Current Behaviour", + "Why It Is Optional" + ], + "cross_refs": [ + "autogalaxy_workspace/scripts/guides/modeling/chaining.py" + ], + "notebook": "notebooks/chapter_optional/tutorial_prior_passing.ipynb", + "path": "scripts/chapter_optional/tutorial_prior_passing.py", + "summary": "This is historical background, not part of the recommended HowToGalaxy learning path. Older versions of the PyAutoGalaxy / PyAutoLens workflow automatically narrowed priors between searches. That default behaviour has been disabled. New readers are discouraged from investing time in the old prior-passing recipes: learn the component-separation approach in chapter 2 tutorial 6 instead.", + "title": "Optional Historical Tutorial: Prior Passing" + }, + { + "contents": [ + "Optimisation", "Nested Sampling", - "Optimizers", "MCMC" ], "cross_refs": [ - "scripts/guides/modeling/searches.py", - "start_here.py" + "autogalaxy_workspace/scripts/guides/modeling/searches.py" ], "notebook": "notebooks/chapter_optional/tutorial_searches.ipynb", "path": "scripts/chapter_optional/tutorial_searches.py", - "summary": "Up to now, we've always used the non-linear search Nautilus and not considered the input parameters that control its sampling. In this tutorial, we'll consider how we can change these setting to balance finding the global maxima solution with fast run time.", - "title": "Tutorial: Alternative Searches" + "summary": "You can complete HowToGalaxy using Nautilus without studying search algorithms in detail. Return here if you want to understand the fast Prodigy stage of search chaining, or compare alternative approaches for your own work.", + "title": "Optional Tutorial: Alternative Searches" }, { "contents": [