diff --git a/AGENTS.md b/AGENTS.md index 7e393ff..6906b6c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,7 @@ interpret probabilistic models from first principles. It is the teaching compani ## Repository Structure - `scripts/` — Runnable Python tutorial scripts: - - `chapter_1_introduction/` — Models, fitting data, non-linear searches, results and samples, and a prose-only scientific workflow closing tutorial + - `chapter_1_introduction/` — Models, fitting data, non-linear searches, results and samples, gradients and JAX autodiff, the details that make a fit succeed or fail, a prose-only scientific workflow closing tutorial, and an optional Bayesian formalism tutorial - `chapter_3_graphical_models/` — Individual / graphical / hierarchical models, Expectation Propagation - `simulators/` — Simulator scripts that generate the tutorial 1D datasets at runtime - `notebooks/` — Jupyter versions, generated from `scripts/` (do not edit directly) @@ -64,7 +64,7 @@ The navigator catalogue — `llms-full.txt` + `workspace_index.json` — is what gates; it is rebuilt by the same PyAutoHands generate/merge flow that builds the notebooks. Commit regenerated notebooks and catalogue alongside the script changes. -`tutorial_6_scientific_workflow.py` is prose-only by design: its generated notebook must contain no +`tutorial_8_scientific_workflow.py` is prose-only by design: its generated notebook must contain no code cells, including Colab setup. Verify this after regeneration. ## Bulk-edit safety diff --git a/config/build/markdown_examples.yaml b/config/build/markdown_examples.yaml index ce46b26..65214cf 100644 --- a/config/build/markdown_examples.yaml +++ b/config/build/markdown_examples.yaml @@ -14,5 +14,11 @@ max_minutes: 120 - script: scripts/chapter_1_introduction/tutorial_5_results_and_samples.py max_minutes: 90 -- script: scripts/chapter_1_introduction/tutorial_6_scientific_workflow.py +- script: scripts/chapter_1_introduction/tutorial_6_gradients.py + max_minutes: 60 +- script: scripts/chapter_1_introduction/tutorial_7_the_details.py + max_minutes: 60 +- script: scripts/chapter_1_introduction/tutorial_8_scientific_workflow.py max_minutes: 1 +- script: scripts/chapter_1_introduction/tutorial_optional_bayesian_formalism.py + max_minutes: 30 diff --git a/config/build/profile_smoke.yaml b/config/build/profile_smoke.yaml index d79e81d..52a10d7 100644 --- a/config/build/profile_smoke.yaml +++ b/config/build/profile_smoke.yaml @@ -26,7 +26,14 @@ defaults: # ever matched a file here. # # Do not copy override patterns between repos; a pattern that matches nothing -# is silently inert, not an override. `overrides: []` is written explicitly -# because env_config.py reads `.get("overrides", [])` — a bare `overrides:` -# key would load as None and raise on iteration.) -overrides: [] +# is silently inert, not an override. Patterns without a '/' match the file +# stem exactly, so the two entries below match only the chapter 1 gradient +# tutorials. Never leave the `overrides:` key with an empty value — a bare +# `overrides:` loads as None; write `overrides: []` if every entry is removed.) +overrides: + # The gradient tutorials teach JAX autodiff searches (MultiStartAdam, BlackJAXNUTS), + # which refuse to run with use_jax=False, so JAX stays on for them. + - pattern: "tutorial_6_gradients" + set: {PYAUTO_DISABLE_JAX: "0"} + - pattern: "tutorial_7_the_details" + set: {PYAUTO_DISABLE_JAX: "0"} diff --git a/llms-full.txt b/llms-full.txt index 530a5f4..6f3fd71 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -20,7 +20,13 @@ AUTO-GENERATED by PyAutoHands — do not edit by hand; regenerate with generate. - Contents: Data, Model, Analysis, Alternative Syntax, Collection, Search, Model Fit, Result, Why Modeling is Hard, Prior Tuning, Reducing Complexity, Search More Thoroughly, Summary, Run Times, Model Mismatch, Astronomy Example, Wrap Up - [Tutorial 5: Results And Samples](scripts/chapter_1_introduction/tutorial_5_results_and_samples.py): In this tutorial, we'll cover all of the output that comes from a non-linear search's `Result` object. - Contents: Data, Reused Functions, Model Fit, Result, Samples, Parameters, Figures of Merit, Instances, Vectors, Labels, Posterior / PDF, Plot, Errors, PDF, Other Results, Sample Instance, Bayesian Evidence, Derived Errors (PDF from samples), Samples Filtering, Latex -- [Tutorial 6: Scientific Workflow](scripts/chapter_1_introduction/tutorial_6_scientific_workflow.py): You can now compose a model, fit it to data and interpret its results. A scientific study often repeats these steps for many datasets, competing models and different non-linear searches. The next challenge is keeping those fits organized so that you can understand and compare them. +- [Tutorial 6: Gradients](scripts/chapter_1_introduction/tutorial_6_gradients.py): In tutorial 3, describing how a maximum likelihood estimator works, we said it "evaluates the likelihood at nearby points to estimate the gradient, determining the direction in which to move up in parameter space". That sentence slipped by quickly, but it hides one of the most important ideas in model-fitting: the search does not have to be blind, because the likelihood surface has a slope, and the slope tells us which way is up. + - Contents: Data, Model, Analysis, Gradients, Finite Differencing, JAX and Autodiff, Maximum Likelihood Estimation (MLE), Markov Chain Monte Carlo (MCMC), Nested Sampling, Errors From Curvature, Wrap Up +- [Tutorial 7: The Details](scripts/chapter_1_introduction/tutorial_7_the_details.py): In tutorial 6 we opened up the non-linear search and looked at how it moves. We saw that some searches only ever ask the likelihood function "what is the value here?", whilst gradient based searches also ask "and which way is uphill?", and that **PyAutoFit** can answer the second question exactly by using JAX to differentiate the likelihood function. + - Contents: Data, Model, Analysis, Parameterization, Assertions, Plateaus, Comparing Searches, Clipping, NaN Diagnostics, Unit Cube Vs Physical, Summary +- [Tutorial 8: Scientific Workflow](scripts/chapter_1_introduction/tutorial_8_scientific_workflow.py): You can now compose a model, fit it to data and interpret its results. A scientific study often repeats these steps for many datasets, competing models and different non-linear searches. The next challenge is keeping those fits organized so that you can understand and compare them. +- [Tutorial Optional: Bayesian Formalism](scripts/chapter_1_introduction/tutorial_optional_bayesian_formalism.py): Every tutorial in this chapter has been an exercise in Bayesian inference, and not one of them wrote down a single equation of probability theory. That was deliberate. The **HowToFit** lectures are built on the conviction that you can learn to fit models to data properly, and interpret the results correctly, without first sitting through a course on Bayesian statistics. + - Contents: Bayes Theorem, Data, The Model, The Likelihood, The Prior, The Posterior, Maximum Likelihood Vs Maximum A Posteriori, Marginalization, The Evidence, Gradients, Wrap Up ## chapter_3_graphical_models diff --git a/llms.txt b/llms.txt index d0a96c9..6f3ce32 100644 --- a/llms.txt +++ b/llms.txt @@ -37,6 +37,9 @@ analysis?" below). - **How does a non-linear search work?** → [scripts/chapter_1_introduction/tutorial_3_non_linear_search.py](scripts/chapter_1_introduction/tutorial_3_non_linear_search.py): Parameter space, priors, MLE / MCMC / nested sampling, and which to use. - **Why do model fits fail, and how do I fix them?** → [scripts/chapter_1_introduction/tutorial_4_why_modeling_is_hard.py](scripts/chapter_1_introduction/tutorial_4_why_modeling_is_hard.py): Prior tuning, reducing complexity, searching more thoroughly. - **What's in the `Result` / how do I read samples?** → [scripts/chapter_1_introduction/tutorial_5_results_and_samples.py](scripts/chapter_1_introduction/tutorial_5_results_and_samples.py): Samples, instances, PDFs, errors, Bayesian evidence, LaTeX output. +- **How does a search know which way is "up" / what is a gradient?** → [scripts/chapter_1_introduction/tutorial_6_gradients.py](scripts/chapter_1_introduction/tutorial_6_gradients.py): Gradients of the log likelihood, finite differencing, JAX autodiff, gradient vs non-gradient searches, errors from curvature. +- **My fit looks reasonable but the answer is wrong — what am I missing?** → [scripts/chapter_1_introduction/tutorial_7_the_details.py](scripts/chapter_1_introduction/tutorial_7_the_details.py): Parameterization and mirror solutions, assertions, plateaus, clipping, NaN diagnostics, the unit cube. +- **Where is the Bayesian maths behind all of this?** → [scripts/chapter_1_introduction/tutorial_optional_bayesian_formalism.py](scripts/chapter_1_introduction/tutorial_optional_bayesian_formalism.py): Bayes' theorem, likelihood, prior, posterior, marginalization and evidence, mapped onto what chapter 1 already computed. - **I have many datasets with a shared parameter — what's the right tool?** → [scripts/chapter_3_graphical_models/tutorial_2_graphical_model.py](scripts/chapter_3_graphical_models/tutorial_2_graphical_model.py): Factor graphs and graphical models vs one-by-one fits. - **What is a hierarchical model / Expectation Propagation?** → [scripts/chapter_3_graphical_models/tutorial_4_hierachical_models.py](scripts/chapter_3_graphical_models/tutorial_4_hierachical_models.py) then [tutorial_5_expectation_propagation.py](scripts/chapter_3_graphical_models/tutorial_5_expectation_propagation.py). diff --git a/markdown/README.md b/markdown/README.md index 1036f21..1ff4f37 100644 --- a/markdown/README.md +++ b/markdown/README.md @@ -8,6 +8,6 @@ Every page below is the corresponding example script **fully executed**, rendere - [Tutorial 3: Non Linear Search](chapter_1_introduction/tutorial_3_non_linear_search.md) — from `scripts/chapter_1_introduction/tutorial_3_non_linear_search.py` - [Tutorial 4: Why Modeling Is Hard](chapter_1_introduction/tutorial_4_why_modeling_is_hard.md) — from `scripts/chapter_1_introduction/tutorial_4_why_modeling_is_hard.py` - [Tutorial 5: Results And Samples](chapter_1_introduction/tutorial_5_results_and_samples.md) — from `scripts/chapter_1_introduction/tutorial_5_results_and_samples.py` -- [Tutorial 6: Scientific Workflow](chapter_1_introduction/tutorial_6_scientific_workflow.md) — from `scripts/chapter_1_introduction/tutorial_6_scientific_workflow.py` +- [Tutorial 8: Scientific Workflow](chapter_1_introduction/tutorial_8_scientific_workflow.md) — from `scripts/chapter_1_introduction/tutorial_8_scientific_workflow.py` These pages are regenerated manually by PyAutoHands's `generate_markdown.py` when a curated script changes. diff --git a/markdown/chapter_1_introduction/start_here.md b/markdown/chapter_1_introduction/start_here.md index 991f377..996868b 100644 --- a/markdown/chapter_1_introduction/start_here.md +++ b/markdown/chapter_1_introduction/start_here.md @@ -48,7 +48,7 @@ interpretation. The chapter includes: `tutorial_5_results_and_samples.py`: Interpreting model-fit results and using the samples for scientific analysis. -`tutorial_6_scientific_workflow.py`: A short, prose-only introduction to organizing and comparing many model fits, +`tutorial_8_scientific_workflow.py`: A short, prose-only introduction to organizing and comparing many model fits, with links to the scientific workflow guide and workspace example. An applied astronomy-focused example (previously tutorial 8) now lives in diff --git a/markdown/chapter_1_introduction/tutorial_6_scientific_workflow.md b/markdown/chapter_1_introduction/tutorial_8_scientific_workflow.md similarity index 85% rename from markdown/chapter_1_introduction/tutorial_6_scientific_workflow.md rename to markdown/chapter_1_introduction/tutorial_8_scientific_workflow.md index 9a4a088..a632046 100644 --- a/markdown/chapter_1_introduction/tutorial_6_scientific_workflow.md +++ b/markdown/chapter_1_introduction/tutorial_8_scientific_workflow.md @@ -1,9 +1,9 @@ -> ✏️ **This page is auto-generated from [`scripts/chapter_1_introduction/tutorial_6_scientific_workflow.py`](../../scripts/chapter_1_introduction/tutorial_6_scientific_workflow.py) — do not edit it directly.** +> ✏️ **This page is auto-generated from [`scripts/chapter_1_introduction/tutorial_8_scientific_workflow.py`](../../scripts/chapter_1_introduction/tutorial_8_scientific_workflow.py) — do not edit it directly.** > It shows the example fully executed, with its real output images. -> Run it yourself via the [Python script](../../scripts/chapter_1_introduction/tutorial_6_scientific_workflow.py) or the [Jupyter notebook](../../notebooks/chapter_1_introduction/tutorial_6_scientific_workflow.ipynb). +> Run it yourself via the [Python script](../../scripts/chapter_1_introduction/tutorial_8_scientific_workflow.py) or the [Jupyter notebook](../../notebooks/chapter_1_introduction/tutorial_8_scientific_workflow.ipynb). -Tutorial 6: Scientific Workflow -============================== +Tutorial 8: Scientific Workflow +=============================== You can now compose a model, fit it to data and interpret its results. A scientific study often repeats these steps for many datasets, competing models and different non-linear searches. The next challenge is diff --git a/notebooks/README.md b/notebooks/README.md index e8ed038..4d4d138 100644 --- a/notebooks/README.md +++ b/notebooks/README.md @@ -2,7 +2,7 @@ The `scripts` folder contains **HowToFit** lectures, which teach a new user how # Folders -- `chapter_1_introduction`: Introduction lectures describing how to compose and fit models in **PyAutoFit**, ending with a prose-only introduction to scientific workflows. +- `chapter_1_introduction`: Introduction lectures describing how to compose and fit models in **PyAutoFit**, use gradients to fit them more efficiently and handle the details that make a fit succeed or fail, ending with a prose-only introduction to scientific workflows and an optional tutorial on the Bayesian formalism. - `chapter_3_graphical_models`: How to compose and fit graphical models which fit many datasets simultaneously, including hierarchical models and Expectation Propagation. - `simulators`: Simulator scripts that generate the tutorial 1D datasets at runtime. @@ -55,6 +55,8 @@ able to: 4. Fit a model to data using a non-linear search. 5. Compose and fit more complex models using **PyAutoFit**'s model composition API. 6. Analyse the results of a model-fit, including parameter estimates and errors. +7. Use gradients of the log likelihood, computed with JAX automatic differentiation, to fit models with gradient based searches. +8. Recognise and fix the details that make a fit fail: degenerate parameterizations, plateaus, clipping and NaNs, and the unit cube. # Overview of Chapter 3 (Advanced) diff --git a/notebooks/chapter_1_introduction/README.md b/notebooks/chapter_1_introduction/README.md index fa87227..bb1c995 100644 --- a/notebooks/chapter_1_introduction/README.md +++ b/notebooks/chapter_1_introduction/README.md @@ -17,4 +17,10 @@ The chapter contains the following tutorials: - [Tutorial 5: Results and Samples](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.8.1/notebooks/chapter_1_introduction/tutorial_5_results_and_samples.ipynb) — Interpreting model-fit results and using the samples for scientific analysis. -- [Tutorial 6: Scientific Workflow](../../notebooks/chapter_1_introduction/tutorial_6_scientific_workflow.ipynb) — A prose-only introduction to organizing and comparing many fits, with links to the full guide and workspace example. +- [Tutorial 6: Gradients](../../notebooks/chapter_1_introduction/tutorial_6_gradients.ipynb) — How gradients tell a search which way is up, JAX autodiff, and how gradients change MLE, MCMC and nested sampling. + +- [Tutorial 7: The Details](../../notebooks/chapter_1_introduction/tutorial_7_the_details.ipynb) — Parameterization, plateaus, assertions, clipping, NaN diagnostics and the unit cube — the details that decide whether a fit converges. + +- [Tutorial 8: Scientific Workflow](../../notebooks/chapter_1_introduction/tutorial_8_scientific_workflow.ipynb) — A prose-only introduction to organizing and comparing many fits, with links to the full guide and workspace example. + +- [Tutorial Optional: Bayesian Formalism](../../notebooks/chapter_1_introduction/tutorial_optional_bayesian_formalism.ipynb) — How everything in chapter 1 maps onto Bayes' theorem. diff --git a/notebooks/chapter_1_introduction/start_here.ipynb b/notebooks/chapter_1_introduction/start_here.ipynb index 41e3467..5d253b0 100644 --- a/notebooks/chapter_1_introduction/start_here.ipynb +++ b/notebooks/chapter_1_introduction/start_here.ipynb @@ -26,8 +26,9 @@ "\n", "The HowToFit lectures cover an introductory chapter and an advanced chapter:\n", "\n", - "**Chapter 1: Introduction**: How to fit a model to data, perform statistical inference, and interpret the results\n", - "for scientific analysis, ending with an introduction to scientific workflows.\n", + "**Chapter 1: Introduction**: How to fit a model to data, perform statistical inference, interpret the results\n", + "for scientific analysis and use gradients to fit models more efficiently, ending with an introduction to\n", + "scientific workflows.\n", "\n", "**Chapter 3: Graphical Models**: Simultaneous model fitting of large datasets, scaling up to models with tens of\n", "thousands of parameters.\n", @@ -50,9 +51,17 @@ "\n", "`tutorial_5_results_and_samples.py`: Interpreting model-fit results and using the samples for scientific analysis.\n", "\n", - "`tutorial_6_scientific_workflow.py`: A short, prose-only introduction to organizing and comparing many model fits,\n", + "`tutorial_6_gradients.py`: How gradients tell a search which way is up, JAX autodiff, and how gradients change\n", + "MLE, MCMC and nested sampling.\n", + "\n", + "`tutorial_7_the_details.py`: Parameterization, plateaus, assertions, clipping, NaN diagnostics and the unit cube,\n", + "the details that decide whether a fit converges.\n", + "\n", + "`tutorial_8_scientific_workflow.py`: A short, prose-only introduction to organizing and comparing many model fits,\n", "with links to the scientific workflow guide and workspace example.\n", "\n", + "`tutorial_optional_bayesian_formalism.py`: How everything in chapter 1 maps onto Bayes' theorem.\n", + "\n", "An applied astronomy-focused example (previously tutorial 8) now lives in\n", "`autofit_workspace_developer/scripts/howtofit/chapter_1_introduction/tutorial_8_astronomy_example.py`,\n", "alongside the larger `autofit_workspace_developer/projects/cosmology/` example. These depend on astronomy-specific datasets\n", diff --git a/notebooks/chapter_1_introduction/tutorial_6_gradients.ipynb b/notebooks/chapter_1_introduction/tutorial_6_gradients.ipynb new file mode 100644 index 0000000..8989f49 --- /dev/null +++ b/notebooks/chapter_1_introduction/tutorial_6_gradients.ipynb @@ -0,0 +1,1281 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Tutorial 6: Gradients\n", + "=====================\n", + "\n", + "In tutorial 3, describing how a maximum likelihood estimator works, we said it \"evaluates the likelihood at nearby\n", + "points to estimate the gradient, determining the direction in which to move up in parameter space\". That sentence\n", + "slipped by quickly, but it hides one of the most important ideas in model-fitting: the search does not have to be\n", + "blind, because the likelihood surface has a slope, and the slope tells us which way is up.\n", + "\n", + "In tutorial 5 we saw the other half of the story: errors, computed by marginalizing over the Probability Density\n", + "Function of the samples. Errors came from samples, and samples are expensive. Here we make the gradient explicit,\n", + "hand it to three types of non-linear search, and end by computing errors without drawing a single sample.\n", + "\n", + "__Overview__\n", + "\n", + "In this tutorial, we will introduce gradients and use them to fit a 1D Gaussian profile to noisy data. Specifically,\n", + "we will:\n", + "\n", + "- Introduce the \"gradient\" of the log likelihood and plot it on a slice through parameter space.\n", + "\n", + "- Compute a gradient by \"finite differencing\", and see why the answer depends on the step size.\n", + "\n", + "- Use JAX to differentiate the `log_likelihood_function` exactly, via \"automatic differentiation\".\n", + "\n", + "- Compare searches which use gradients with those which do not.\n", + "\n", + "- Estimate errors from the second derivatives of the log likelihood.\n", + "\n", + "__Contents__\n", + "\n", + "This tutorial is split into the following sections:\n", + "\n", + "- **Data**: Load and plot the 1D Gaussian dataset fitted throughout the chapter.\n", + "- **Model**: The `Gaussian` model component, now written so it can run on NumPy or JAX.\n", + "- **Analysis**: The `Analysis` class with a log likelihood function that can be differentiated.\n", + "- **Gradients**: Extending the parameter-space picture of tutorial 3 with the idea that a search can know which way \"up\" is at every point.\n", + "- **Finite Differencing**: Computing a gradient numerically by nudging each parameter and re-evaluating the likelihood.\n", + "- **JAX and Autodiff**: Why analytic gradients are impractical, and how JAX differentiates the likelihood function under the hood.\n", + "- **Maximum Likelihood Estimation (MLE)**: Comparing a finite-difference optimizer (`LBFGS`) with a multi-start autodiff optimizer (`MultiStartAdam`).\n", + "- **Markov Chain Monte Carlo (MCMC)**: Comparing walkers that ignore gradients (`Emcee`) with Hamiltonian sampling that follows them (`BlackJAXNUTS`).\n", + "- **Nested Sampling**: Why nested sampling does not use gradients, and how JAX still speeds it up (`Nautilus`).\n", + "- **Errors From Curvature**: Using second derivatives at the maximum likelihood solution to estimate parameter errors and comparing them with the errors from samples in tutorial 5.\n", + "- **Wrap Up**: Concluding the tutorial with a recap of how gradients change each search." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Google Colab Setup__\n", + "\n", + "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", + "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", + "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", + "your own installation) it does nothing, and you can run it safely.\n", + "\n", + "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", + "type\" -> \"Hardware accelerator\" before running the notebook." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "try:\n", + " import google.colab\n", + "except ImportError:\n", + " from autofit 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(\"howtofit\")" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from autofit import setup_notebook; setup_notebook()\n", + "\n", + "from os import path\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "import autofit as af\n", + "import autofit.plot as aplt" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Data__\n", + "\n", + "Load and plot the dataset from the `HowToFit/dataset` folder." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "dataset_path = path.join(\"dataset\", \"example_1d\", \"gaussian_x1\")" + ], + "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 not path.exists(dataset_path):\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.run(\n", + " [sys.executable, \"scripts/simulators/simulators.py\"],\n", + " check=True,\n", + " )\n", + "\n", + "data = af.util.numpy_array_from_json(file_path=path.join(dataset_path, \"data.json\"))\n", + "noise_map = af.util.numpy_array_from_json(\n", + " file_path=path.join(dataset_path, \"noise_map.json\")\n", + ")\n", + "\n", + "xvalues = np.arange(data.shape[0])\n", + "\n", + "plt.errorbar(\n", + " xvalues,\n", + " data,\n", + " yerr=noise_map,\n", + " linestyle=\"\",\n", + " color=\"k\",\n", + " ecolor=\"k\",\n", + " elinewidth=1,\n", + " capsize=2,\n", + ")\n", + "plt.title(\"1D Gaussian dataset.\")\n", + "plt.xlabel(\"x values of profile\")\n", + "plt.ylabel(\"Profile Normalization\")\n", + "plt.show()\n", + "plt.clf()" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Model__\n", + "\n", + "This is the same dataset we fitted in tutorials 2 and 3, whose true parameters are `centre=50.0`,\n", + "`normalization=25.0` and `sigma=10.0`. We lean on those values here, because a gradient is always a gradient *at a\n", + "point*, and the truth is the most interesting point to stand at.\n", + "\n", + "We re-paste the `Gaussian` class in full, as the chapter always does. There is exactly one change from tutorials 1\n", + "to 5: `model_data_from` takes an extra argument `xp`, which defaults to `np`, and every operation inside it is\n", + "written as `xp.subtract`, `xp.multiply`, `xp.divide`, `xp.sqrt`, `xp.exp` and `xp.square`. The `xp` argument asks\n", + "\"which array library should I compute with?\", and later we pass it a library which gives us gradients for free." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "class Gaussian:\n", + " def __init__(\n", + " self,\n", + " centre: float = 30.0, # <- **PyAutoFit** recognises these constructor arguments\n", + " normalization: float = 1.0, # <- are the Gaussian`s model parameters.\n", + " sigma: float = 5.0,\n", + " ):\n", + " \"\"\"\n", + " Represents a 1D Gaussian profile.\n", + "\n", + " This is a model-component of example models in the **HowToFit** lectures and is used to perform model-fitting\n", + " of example datasets.\n", + "\n", + " Parameters\n", + " ----------\n", + " centre\n", + " The x coordinate of the profile centre.\n", + " normalization\n", + " Overall normalization of the profile.\n", + " sigma\n", + " The sigma value controlling the size of the Gaussian.\n", + " \"\"\"\n", + " self.centre = centre\n", + " self.normalization = normalization\n", + " self.sigma = sigma\n", + "\n", + " def model_data_from(self, xvalues: np.ndarray, xp=np) -> np.ndarray:\n", + " \"\"\"\n", + " Returns a 1D Gaussian on an input list of Cartesian x coordinates.\n", + "\n", + " The input xvalues are translated to a coordinate system centred on the Gaussian, via its `centre`.\n", + "\n", + " The output is referred to as the `model_data` to signify that it is a representation of the data from the\n", + " model.\n", + "\n", + " Parameters\n", + " ----------\n", + " xvalues\n", + " The x coordinates in the original reference frame of the data.\n", + " xp\n", + " The array library the calculation is performed with, which is NumPy by default and JAX when the\n", + " model data is being differentiated.\n", + "\n", + " Returns\n", + " -------\n", + " np.array\n", + " The Gaussian values at the input x coordinates.\n", + " \"\"\"\n", + " transformed_xvalues = xp.subtract(xvalues, self.centre)\n", + " return xp.multiply(\n", + " xp.divide(self.normalization, self.sigma * xp.sqrt(2.0 * np.pi)),\n", + " xp.exp(-0.5 * xp.square(xp.divide(transformed_xvalues, self.sigma))),\n", + " )\n" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We compose the model exactly as in tutorial 3, with uniform priors. They are wider than tutorial 3's, where\n", + "`normalization` and `sigma` ran from 0.0 to 10.0, so the true values sit inside parameter space rather than on its\n", + "edge.\n", + "\n", + "We also print `model.model_component_and_parameter_names`, the order of the parameters when the model is expressed\n", + "as a plain vector. This matters throughout, because gradients are vectors too and their entries share that order." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model = af.Model(Gaussian)\n", + "\n", + "model.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + "model.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=50.0)\n", + "model.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0)\n", + "\n", + "print(\"Order of the parameters in a model vector:\")\n", + "print(model.model_component_and_parameter_names)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Analysis__\n", + "\n", + "The `Analysis` class plays the same role it did in tutorial 3, receiving the data and defining the\n", + "`log_likelihood_function`. There are two small changes, and they are the reason this tutorial exists.\n", + "\n", + "First, `__init__` takes a `use_jax` input which it passes to `super().__init__(use_jax=use_jax)`, the switch saying\n", + "which array library the analysis computes with: NumPy when `use_jax=False`, the default, and JAX when `use_jax=True`.\n", + "\n", + "Second, the `log_likelihood_function` uses `self._xp` rather than `np`. `self._xp` is the library that switch\n", + "selected, passed into the `Gaussian` via its `xp` argument so the whole calculation uses one library. Note we write\n", + "`self._xp.sum(...)` and not the builtin `sum(...)`, which iterates the array one element at a time. The environment\n", + "variable `PYAUTO_DISABLE_JAX=1` forces every analysis back to NumPy." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "class Analysis(af.Analysis):\n", + " def __init__(self, data: np.ndarray, noise_map: np.ndarray, use_jax: bool = False):\n", + " \"\"\"\n", + " The `Analysis` class acts as an interface between the data and model in **PyAutoFit**.\n", + "\n", + " Its `log_likelihood_function` defines how the model is fitted to the data and it is called many times by\n", + " the non-linear search fitting algorithm.\n", + "\n", + " Parameters\n", + " ----------\n", + " data\n", + " A 1D numpy array containing the data (e.g. a noisy 1D signal) fitted in the workspace examples.\n", + " noise_map\n", + " A 1D numpy array containing the noise values of the data, used for computing the goodness of fit\n", + " metric, the log likelihood.\n", + " use_jax\n", + " If `True` the log likelihood is computed with JAX, meaning it can be differentiated, and if `False`\n", + " it is computed with NumPy.\n", + " \"\"\"\n", + " super().__init__(use_jax=use_jax)\n", + "\n", + " self.data = data\n", + " self.noise_map = noise_map\n", + "\n", + " def log_likelihood_function(self, instance) -> float:\n", + " \"\"\"\n", + " Returns the log likelihood of a fit of a 1D Gaussian to the dataset.\n", + "\n", + " The calculation is identical to the one performed in tutorial 3, except every operation is performed with\n", + " `self._xp`, the array library chosen by the `use_jax` input, instead of NumPy.\n", + " \"\"\"\n", + " xp = self._xp\n", + "\n", + " xvalues = xp.arange(self.data.shape[0])\n", + "\n", + " model_data = instance.model_data_from(xvalues=xvalues, xp=xp)\n", + " residual_map = self.data - model_data\n", + " chi_squared_map = (residual_map / self.noise_map) ** 2.0\n", + " chi_squared = xp.sum(chi_squared_map)\n", + " noise_normalization = xp.sum(xp.log(2 * np.pi * self.noise_map**2.0))\n", + " log_likelihood = -0.5 * (chi_squared + noise_normalization)\n", + "\n", + " return log_likelihood\n" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We create two analysis objects from the same data, one computing with NumPy and one with JAX. They compute the same\n", + "number. We use the NumPy one for the next two sections, and the JAX one when we start differentiating." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "analysis = Analysis(data=data, noise_map=noise_map)\n", + "analysis_jax = Analysis(data=data, noise_map=noise_map, use_jax=True)\n", + "\n", + "instance = model.instance_from_vector(vector=[50.0, 25.0, 10.0])\n", + "\n", + "print(\"Log likelihood of the true model, computed with NumPy:\")\n", + "print(analysis.log_likelihood_function(instance=instance))" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Gradients__\n", + "\n", + "In tutorial 3 we pictured model-fitting as an exploration of a \"parameter space\": a surface, one axis per free\n", + "parameter, whose height is the log likelihood. Our job was to find its peak, and the searches we used explored it\n", + "essentially blind, evaluating points and remembering which came back high.\n", + "\n", + "But a surface has more structure than that. At any point there is a slope: walk a tiny distance in the `centre`\n", + "direction and the log likelihood changes by some amount, walk the same distance in `sigma` and it changes by a\n", + "different amount. One such number per parameter gives the \"gradient\", a vector pointing in the direction the log\n", + "likelihood increases fastest, whose length says how steeply.\n", + "\n", + "The gradient of a function \\( f \\) with respect to parameters \\( x, y, z \\) is written:\n", + "\n", + "\\[ \\nabla f = \\left( \\frac{\\partial f}{\\partial x}, \\frac{\\partial f}{\\partial y}, \\frac{\\partial f}{\\partial z} \\right) \\]\n", + "\n", + "Where:\n", + "\n", + "- \\( \\nabla f \\): the gradient, a vector with one entry per parameter.\n", + "- \\( \\partial f / \\partial x \\): the \"partial derivative\" of \\( f \\) with respect to \\( x \\), how much \\( f \\)\n", + " changes when \\( x \\) changes and everything else is held fixed.\n", + "\n", + "The gradient is a list of slopes, one per parameter, measured at the same point. A search which knows it does not\n", + "have to guess which way to move, it can simply walk uphill!\n", + "\n", + "Below we fix `normalization` and `sigma` at their true values and vary only `centre`, a 1D \"slice\" through the three\n", + "dimensional parameter space." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "centre_list = np.linspace(40.0, 60.0, 100)\n", + "\n", + "log_likelihood_list = []\n", + "\n", + "for centre in centre_list:\n", + " instance = model.instance_from_vector(vector=[centre, 25.0, 10.0])\n", + " log_likelihood_list.append(analysis.log_likelihood_function(instance=instance))\n", + "\n", + "plt.plot(centre_list, log_likelihood_list, color=\"k\")\n", + "plt.title(\"Log likelihood as a function of the Gaussian centre.\")\n", + "plt.xlabel(\"centre\")\n", + "plt.ylabel(\"Log Likelihood\")\n", + "plt.show()\n", + "plt.close()" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The slice is a smooth hill peaking almost exactly at the true `centre` of 50.0, falling away steeply because an\n", + "offset Gaussian produces enormous residuals.\n", + "\n", + "Now the important part. Pick a point on that hill, say `centre=44.0`, and ask \"if I step a little to the right, does\n", + "the log likelihood go up or down, and by how much?\". The answer is the slope of the curve there, drawn below as the\n", + "straight line touching the curve at that point, the \"tangent line\"." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "centre_point = 44.0\n", + "step = 0.01\n", + "\n", + "instance_up = model.instance_from_vector(vector=[centre_point + step, 25.0, 10.0])\n", + "instance_down = model.instance_from_vector(vector=[centre_point - step, 25.0, 10.0])\n", + "\n", + "slope = (\n", + " analysis.log_likelihood_function(instance=instance_up)\n", + " - analysis.log_likelihood_function(instance=instance_down)\n", + ") / (2.0 * step)\n", + "\n", + "instance_point = model.instance_from_vector(vector=[centre_point, 25.0, 10.0])\n", + "log_likelihood_point = analysis.log_likelihood_function(instance=instance_point)\n", + "\n", + "print(f\"Slope of the log likelihood at centre = {centre_point}: {slope}\")\n", + "\n", + "tangent_centre_list = np.linspace(centre_point - 3.0, centre_point + 3.0, 10)\n", + "tangent_list = log_likelihood_point + slope * (tangent_centre_list - centre_point)\n", + "\n", + "plt.plot(centre_list, log_likelihood_list, color=\"k\")\n", + "plt.plot(tangent_centre_list, tangent_list, color=\"r\")\n", + "plt.scatter(centre_point, log_likelihood_point, color=\"r\")\n", + "plt.title(\"The tangent line shows which way is up at a point.\")\n", + "plt.xlabel(\"centre\")\n", + "plt.ylabel(\"Log Likelihood\")\n", + "plt.show()\n", + "plt.close()" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The red line is the gradient made visible. It slopes upwards to the right and its value is positive, which together\n", + "say that increasing `centre` from 44.0 increases the log likelihood. A search standing here does not need to try\n", + "both directions to learn that, and the size of the number tells it the surface is steep enough for a decent step.\n", + "\n", + "The same holds for every parameter. Below we slice in `sigma` instead, giving a hill of a different shape and\n", + "therefore different slopes." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "sigma_list = np.linspace(5.0, 15.0, 100)\n", + "\n", + "log_likelihood_list = []\n", + "\n", + "for sigma in sigma_list:\n", + " instance = model.instance_from_vector(vector=[50.0, 25.0, sigma])\n", + " log_likelihood_list.append(analysis.log_likelihood_function(instance=instance))\n", + "\n", + "plt.plot(sigma_list, log_likelihood_list, color=\"k\")\n", + "plt.title(\"Log likelihood as a function of the Gaussian sigma.\")\n", + "plt.xlabel(\"sigma\")\n", + "plt.ylabel(\"Log Likelihood\")\n", + "plt.show()\n", + "plt.close()" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Our model has three parameters, so its gradient has three entries, one per slice of the kind we just drew, ordered\n", + "as the parameter names we printed earlier:\n", + "\n", + "\\[ \\left( \\frac{\\partial \\log L}{\\partial centre}, \\frac{\\partial \\log L}{\\partial normalization}, \\frac{\\partial \\log L}{\\partial \\sigma} \\right) \\]\n", + "\n", + "The five-Gaussian model of tutorial 4 has a gradient with 15 entries; a lens model in astronomy might have 50. It\n", + "always has as many entries as the model has free parameters, and always belongs to one specific point. Move to a\n", + "new point and you get a new gradient!\n", + "\n", + "__Finite Differencing__\n", + "\n", + "So how do we compute a gradient? The most direct way is the one we just used for the tangent line: nudge a parameter\n", + "by a small amount \\( h \\), evaluate the log likelihood, nudge it the other way, evaluate again, and take the\n", + "difference. This is \"finite differencing\", in the \"central difference\" form:\n", + "\n", + "\\[ \\frac{\\partial f}{\\partial x} \\approx \\frac{f(x + h) - f(x - h)}{2h} \\]\n", + "\n", + "Where:\n", + "\n", + "- \\( h \\): the step size, a small number chosen by us.\n", + "- \\( f(x + h) \\): the log likelihood with the parameter increased by \\( h \\), everything else held fixed.\n", + "- \\( f(x - h) \\): the log likelihood with the parameter decreased by \\( h \\).\n", + "\n", + "In words: measure how much the function changed over a small interval and divide by the width of that interval.\n", + "Below we write this out for all three parameters, returning a list of three slopes: a gradient." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "def log_likelihood_from_vector_numpy(vector):\n", + " \"\"\"\n", + " Returns the log likelihood of a model defined by an input vector of parameter values, computed with NumPy.\n", + " \"\"\"\n", + " instance = model.instance_from_vector(vector=list(vector))\n", + "\n", + " return analysis.log_likelihood_function(instance=instance)\n", + "\n", + "\n", + "def gradient_via_finite_difference_from(vector, h=1.0e-3):\n", + " \"\"\"\n", + " Returns the gradient of the log likelihood at an input vector of parameter values, computed via central finite\n", + " differences with a step size `h`.\n", + " \"\"\"\n", + " gradient = []\n", + "\n", + " for index in range(len(vector)):\n", + " vector_up = list(vector)\n", + " vector_up[index] += h\n", + "\n", + " vector_down = list(vector)\n", + " vector_down[index] -= h\n", + "\n", + " log_likelihood_up = log_likelihood_from_vector_numpy(vector=vector_up)\n", + " log_likelihood_down = log_likelihood_from_vector_numpy(vector=vector_down)\n", + "\n", + " gradient.append((log_likelihood_up - log_likelihood_down) / (2.0 * h))\n", + "\n", + " return gradient\n" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We evaluate the gradient at a point some way from the true solution, `centre=44.0`, `normalization=20.0`\n", + "and `sigma=8.0`, roughly where a search might find itself part way through a fit." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "vector = [44.0, 20.0, 8.0]\n", + "\n", + "gradient = gradient_via_finite_difference_from(vector=vector)\n", + "\n", + "print(\"Gradient of the log likelihood at [44.0, 20.0, 8.0]:\\n\")\n", + "print(f\"d(log likelihood) / d(centre) = {gradient[0]}\")\n", + "print(f\"d(log likelihood) / d(normalization) = {gradient[1]}\")\n", + "print(f\"d(log likelihood) / d(sigma) = {gradient[2]}\")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The signs tell a search to increase `centre`, decrease `normalization` and increase `sigma`. Compared to the true\n", + "values of 50.0, 25.0 and 10.0 that is sensible in two of the three parameters: the gradient is a local instruction,\n", + "under no obligation to point straight at the peak.\n", + "\n", + "There is a catch. We had to choose \\( h \\), and the answer depends on that choice. Below we compute the gradient\n", + "with respect to `centre` for step sizes spanning ten orders of magnitude." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Step size h d(log likelihood) / d(centre)\\n\")\n", + "\n", + "for h in [10.0, 1.0, 0.1, 1.0e-3, 1.0e-6, 1.0e-9]:\n", + " gradient = gradient_via_finite_difference_from(vector=vector, h=h)\n", + "\n", + " print(f\"{h:<18.0e} {gradient[0]}\")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The table shows the two failure modes of finite differencing, one at each end.\n", + "\n", + "When \\( h \\) is too large, the two evaluations are so far apart that the line between them is not the slope at our\n", + "point at all, it is the average slope over a wide interval. The answer is \"biased\".\n", + "\n", + "When \\( h \\) is too small, the two log likelihoods subtracted are almost identical numbers. A computer stores them\n", + "to about sixteen significant figures, so subtracting them keeps mostly round-off noise, which dividing by a tiny\n", + "number then amplifies. The answer becomes erratic.\n", + "\n", + "Somewhere in the middle is a sweet spot, visible as the region where the answer stops changing, but its location\n", + "depends on the units of the parameter, the scale of the data and the model, so it must be found by trial and error\n", + "for every new problem. That is not a comfortable position to be in!\n", + "\n", + "There is a second cost. Each parameter needs two evaluations, so a gradient for a model with \\( N \\) parameters\n", + "costs \\( 2N \\) evaluations, which for a 50-parameter model whose likelihood takes a second is over a minute of\n", + "computation to work out which way to take one step.\n", + "\n", + "This is exactly what the `LBFGS` search of tutorial 3 was doing, silently, on your behalf. It \"evaluates the\n", + "likelihood at nearby points to estimate the gradient\", and now we know what that means: finite differencing, with a\n", + "step size it chose for us.\n", + "\n", + "__JAX and Autodiff__\n", + "\n", + "If finite differencing is unreliable and expensive, why not write the derivative down? For our 1D Gaussian we could.\n", + "But no interesting log likelihood is a short equation. A realistic one is a long chain of operations: in astronomy,\n", + "ray tracing light through a gravitational lens, convolving with the telescope's point spread function, solving a\n", + "large linear system to reconstruct a source, and only then comparing to data. Differentiating that by hand means\n", + "applying the chain rule hundreds of times and maintaining the result every time the model changes. It is\n", + "impractical, and error prone in a way which is hard to detect, because a subtly wrong gradient still points roughly\n", + "uphill and still produces a plausible looking fit.\n", + "\n", + "\"Automatic differentiation\", or \"autodiff\", solves this. Every calculation is built from a handful of elementary\n", + "operations whose derivatives we know, so a library which records those operations as they run can apply the chain\n", + "rule to that record and produce the exact derivative of whatever was computed.\n", + "\n", + "This is what JAX does, and it is why our `Gaussian` was written in terms of `xp` and our `Analysis` in terms\n", + "of `self._xp`. When `use_jax=True`, `xp` is `jax.numpy`, whose operations record themselves as they execute, and the\n", + "derivative that comes out is exact and costs a small fixed multiple of one likelihood evaluation, however many\n", + "parameters the model has.\n", + "\n", + "Below we build a function mapping a vector of parameters to a log likelihood and ask JAX to differentiate it. That\n", + "is the whole API: `jax.grad(f)` returns a function which, called at a point, returns the gradient of `f` there." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import jax\n", + "import jax.numpy as jnp\n", + "\n", + "\n", + "def log_likelihood_from_vector(vector):\n", + " \"\"\"\n", + " Returns the log likelihood of a model defined by an input vector of parameter values, computed with JAX.\n", + " \"\"\"\n", + " instance = model.instance_from_vector(vector=vector, xp=jnp)\n", + "\n", + " return analysis_jax.log_likelihood_function(instance=instance)\n", + "\n", + "\n", + "gradient_jax = jax.grad(log_likelihood_from_vector)(jnp.array(vector))\n", + "\n", + "gradient_finite_difference = gradient_via_finite_difference_from(vector=vector)\n", + "\n", + "print(\"Gradient at [44.0, 20.0, 8.0] via automatic differentiation:\")\n", + "print(gradient_jax)\n", + "\n", + "print(\"\\nGradient at [44.0, 20.0, 8.0] via finite differencing:\")\n", + "print(gradient_finite_difference)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The two gradients agree to several decimal places, the sanity check that matters: autodiff computes the same\n", + "quantity we computed by hand, exactly and in one pass rather than approximately and in six. Where they disagree it\n", + "is the finite-difference answer that is wrong, because it carries the error we chose when we picked \\( h \\).\n", + "\n", + "JAX has a second trick. `jax.jit` compiles a function into optimised machine code the first time it is called and\n", + "reuses that code on every subsequent call, so for a search calling the likelihood thousands of times a one-off\n", + "compilation cost is an excellent trade. Below we time a hundred compiled calls against a hundred uncompiled ones." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import time\n", + "\n", + "log_likelihood_jit = jax.jit(log_likelihood_from_vector)\n", + "\n", + "start = time.time()\n", + "log_likelihood_jit(jnp.array(vector))\n", + "print(f\"Time of the first (compiling) call: {time.time() - start} seconds\")\n", + "\n", + "start = time.time()\n", + "for i in range(100):\n", + " log_likelihood_jit(jnp.array(vector))\n", + "print(f\"Time of 100 compiled calls: {time.time() - start} seconds\")\n", + "\n", + "start = time.time()\n", + "for i in range(100):\n", + " log_likelihood_from_vector(jnp.array(vector))\n", + "print(f\"Time of 100 uncompiled calls: {time.time() - start} seconds\")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Maximum Likelihood Estimation (MLE)__\n", + "\n", + "We now have gradients. Let us give them to the three families of search we met in tutorial 3.\n", + "\n", + "We start with `LBFGS`, passing it the NumPy analysis, because `LBFGS` cannot use JAX gradients: it estimates the\n", + "gradient itself by finite differencing, exactly as we did by hand, so every iteration costs \\( 2N + 1 \\)\n", + "evaluations. It also starts from a single point, the centre of the priors. In tutorial 3 that was enough to trap it\n", + "in a local maximum; with the wider priors here it does better, but a single walker walking uphill can still only\n", + "find the peak it happens to be standing on." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "search = af.LBFGS()\n", + "\n", + "print(\n", + " \"\"\"\n", + " The non-linear search has begun running.\n", + " This Jupyter notebook cell with progress once the search has completed - this could take a few minutes!\n", + " \"\"\"\n", + ")\n", + "\n", + "start = time.time()\n", + "\n", + "result = search.fit(model=model, analysis=analysis)\n", + "\n", + "print(\"The search has finished run - you may now continue the notebook.\")\n", + "print(f\"LBFGS run time: {time.time() - start} seconds\")\n", + "\n", + "print(result.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now the gradient-aware alternative, `MultiStartAdam`. Two words in that name describe what it does differently.\n", + "\n", + "\"Multi start\" means it starts not from one point but from many, scattered across the priors. Each start is a \"lane\"\n", + "walking uphill independently, so a lane which walks into a local maximum loses to the lanes which found something\n", + "better, addressing the failure mode that trapped `LBFGS` in tutorial 3.\n", + "\n", + "\"Adam\" is the algorithm each lane steps with, a gradient method used to train neural networks, which follows the\n", + "exact autodiff gradient and adapts its step size per parameter. Because the gradients come from JAX, every lane is\n", + "advanced together in one compiled call using `vmap`, so twelve lanes cost far less than twelve times one lane.\n", + "\n", + "This search is given a `name` and `path_prefix`, so its results are written to the `output` folder as tutorial 5\n", + "did, because there is a file in there we are about to read." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "search = af.MultiStartAdam(\n", + " name=\"tutorial_6_gradients_adam\",\n", + " path_prefix=\"chapter_1_introduction\",\n", + " n_starts=12, # The number of independent lanes which walk uphill from different starting points.\n", + " n_steps=200, # The maximum number of gradient steps each lane takes.\n", + " learning_rate=0.5, # How far each lane moves per step, in units of the adapted gradient.\n", + " batch_size=None, # None evaluates every lane in one compiled call; pass an integer to cap memory on large models.\n", + ")\n", + "\n", + "print(\n", + " \"\"\"\n", + " The non-linear search has begun running.\n", + " Checkout the HowToFit/output/chapter_1_introduction/tutorial_6_gradients_adam\n", + " folder for live output of the results.\n", + " This Jupyter notebook cell with progress once the search has completed - this could take a few minutes!\n", + " \"\"\"\n", + ")\n", + "\n", + "start = time.time()\n", + "\n", + "result = search.fit(model=model, analysis=analysis_jax)\n", + "\n", + "print(\"The search has finished run - you may now continue the notebook.\")\n", + "print(f\"MultiStartAdam run time: {time.time() - start} seconds\")\n", + "\n", + "print(result.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let us plot the maximum likelihood fit, which should look familiar from tutorial 3." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model_data = result.max_log_likelihood_instance.model_data_from(xvalues=xvalues)\n", + "\n", + "plt.errorbar(\n", + " x=xvalues,\n", + " y=data,\n", + " yerr=noise_map,\n", + " linestyle=\"\",\n", + " color=\"k\",\n", + " ecolor=\"k\",\n", + " elinewidth=1,\n", + " capsize=2,\n", + ")\n", + "plt.plot(xvalues, model_data, color=\"r\")\n", + "plt.title(\"MultiStartAdam model fit to 1D Gaussian dataset.\")\n", + "plt.xlabel(\"x values of profile\")\n", + "plt.ylabel(\"Profile normalization\")\n", + "plt.show()\n", + "plt.close()" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Because this search wrote its results to hard disk, its output folder contains a file called `search.summary`: how\n", + "long the search took, how long one log likelihood evaluation took and, for gradient searches, diagnostics on how\n", + "often things went wrong. We read it back below." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "search_summary_path = path.join(str(search.paths.output_path), \"search.summary\")\n", + "\n", + "if path.exists(search_summary_path):\n", + " with open(search_summary_path) as f:\n", + " print(f.read())" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The block at the bottom, headed `Resampling Info`, contains two entries only a gradient search can report:\n", + "\n", + "- `Value-NaN Lane-Steps`: the number of times a lane stepped somewhere the log likelihood could not be computed at\n", + " all, most often because it stepped outside the priors.\n", + "\n", + "- `Gradient-NaN Lane-Steps`: the number of times the log likelihood *was* computable but its gradient was not. This\n", + " is the sneakier of the two, because such a lane does not crash or die, it simply stops moving while continuing to\n", + " look perfectly healthy.\n", + "\n", + "Both counters are usually small and harmless, but they are the vocabulary you need to diagnose a gradient fit that\n", + "has gone quietly wrong. Tutorial 7 explains where they come from and what to do about them.\n", + "\n", + "__Markov Chain Monte Carlo (MCMC)__\n", + "\n", + "In tutorial 3 we used `Emcee`, whose walkers propose a step, compute the likelihood there and accept or reject the\n", + "move by comparing it to where they are. Notice what is missing: the walkers never ask which way is up. That is a\n", + "strength, because `Emcee` works on any likelihood you can evaluate, and a weakness, because in many dimensions a\n", + "random step is overwhelmingly likely to point somewhere worse, so most proposals are rejected." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "search = af.Emcee(\n", + " nwalkers=20, # The number of walkers we'll use to sample parameter space.\n", + " nsteps=500, # The number of steps each walker takes.\n", + ")\n", + "\n", + "print(\n", + " \"\"\"\n", + " The non-linear search has begun running.\n", + " This Jupyter notebook cell with progress once the search has completed - this could take a few minutes!\n", + " \"\"\"\n", + ")\n", + "\n", + "start = time.time()\n", + "\n", + "result = search.fit(model=model, analysis=analysis)\n", + "\n", + "print(\"The search has finished run - you may now continue the notebook.\")\n", + "print(f\"Emcee run time: {time.time() - start} seconds\")\n", + "\n", + "print(result.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now the gradient-aware alternative, `BlackJAXNUTS`, which is Hamiltonian Monte Carlo. The physical picture behind it\n", + "is genuinely helpful.\n", + "\n", + "Imagine the likelihood surface turned upside down, so its peak becomes a valley, and place a ball on the resulting\n", + "landscape. Give it a random flick and let it roll: it accelerates down slopes, coasts up the other side and travels\n", + "a long way while staying in regions the landscape favours. That trajectory is computed from the gradient at each\n", + "moment, which is what autodiff hands us for free. Where the ball stops becomes the next sample, and because it\n", + "travelled a long, informed distance rather than a small random hop, consecutive samples are far less similar.\n", + "\n", + "\"NUTS\" stands for the No U-Turn Sampler, which solves the awkward choice here: how long to let the ball roll. Roll\n", + "too briefly and you wasted the gradient; roll too long and the ball curves back on itself. NUTS stops the trajectory\n", + "when it starts doubling back. Being a gradient method, it needs the JAX analysis." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "search = af.BlackJAXNUTS(\n", + " num_warmup=200, # Steps used to tune the sampler, which are then discarded.\n", + " num_samples=300, # Steps kept as samples of the posterior.\n", + ")\n", + "\n", + "print(\n", + " \"\"\"\n", + " The non-linear search has begun running.\n", + " This Jupyter notebook cell with progress once the search has completed - this could take a few minutes!\n", + " \"\"\"\n", + ")\n", + "\n", + "start = time.time()\n", + "\n", + "result = search.fit(model=model, analysis=analysis_jax)\n", + "\n", + "print(\"The search has finished run - you may now continue the notebook.\")\n", + "print(f\"BlackJAXNUTS run time: {time.time() - start} seconds\")\n", + "\n", + "print(result.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Hamiltonian sampling comes with its own diagnostics, stored in the `samples_info` dictionary. Three are worth\n", + "knowing:\n", + "\n", + "- `n_divergent`: the number of trajectories which \"diverged\", meaning the ball flew off to infinity instead of\n", + " following the landscape. A handful is tolerable; many means the steps are too large and the samples cannot be\n", + " trusted.\n", + "\n", + "- `ess_min`: the \"effective sample size\" of the worst constrained parameter. Consecutive samples are correlated, so\n", + " 300 samples are worth fewer than 300 independent draws, and this says how many they are worth.\n", + "\n", + "- `mean_acceptance`: the fraction of proposed trajectories accepted, which for NUTS should sit high, around the 0.8\n", + " the warm up phase tunes towards. A low value means the sampler is struggling." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "samples = result.samples\n", + "\n", + "print(\"Diagnostics of the Hamiltonian Monte Carlo fit:\\n\")\n", + "print(f\"Number of divergent trajectories = {samples.samples_info.get('n_divergent')}\")\n", + "print(f\"Minimum effective sample size = {samples.samples_info.get('ess_min')}\")\n", + "print(\n", + " f\"Mean acceptance rate = {samples.samples_info.get('mean_acceptance')}\"\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Because NUTS maps out the posterior, we can plot the Probability Density Functions of its samples with `corner.py`,\n", + "wrapped via the `aplt.corner_cornerpy` function, exactly as we did for `Emcee` in tutorial 5." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "aplt.corner_cornerpy(samples=result.samples)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Nested Sampling__\n", + "\n", + "Finally, nested sampling, the interesting case, because gradients do not help it at all.\n", + "\n", + "Recall from tutorial 3 how it works: a set of \"live points\" is drawn from the priors, the lowest likelihood one is\n", + "discarded, and a replacement is drawn from the priors subject to having a higher likelihood. Repeat, and the live\n", + "points contract onto the peak. There is no walker in that description and therefore nothing to steer. The algorithm\n", + "never asks \"which way is up from here\", it asks \"give me any point better than this one\".\n", + "\n", + "JAX still helps, for a different reason. `Nautilus` proposes points in batches, and with a JAX analysis\n", + "**PyAutoFit** evaluates a whole batch in one compiled call rather than looping in Python, which is the\n", + "`use_jax_vmap=True` input, on by default. Gradients change *how a search explores*; JAX compilation changes *how\n", + "fast the likelihood is evaluated*, and nested sampling benefits only from the second." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "search = af.Nautilus(\n", + " n_live=150, # The number of live points used to explore parameter space.\n", + " n_eff=200, # The effective sample size the search runs until it reaches.\n", + ")\n", + "\n", + "print(\n", + " \"\"\"\n", + " The non-linear search has begun running.\n", + " This Jupyter notebook cell with progress once the search has completed - this could take a few minutes!\n", + " \"\"\"\n", + ")\n", + "\n", + "start = time.time()\n", + "\n", + "result = search.fit(model=model, analysis=analysis_jax)\n", + "\n", + "print(\"The search has finished run - you may now continue the notebook.\")\n", + "print(f\"Nautilus run time: {time.time() - start} seconds\")\n", + "\n", + "print(result.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Errors From Curvature__\n", + "\n", + "In tutorial 5 we computed errors from the samples, by marginalizing over each parameter's 1D Probability Density\n", + "Function. That assumes nothing about the posterior's shape, but it requires the samples, which are thousands of\n", + "likelihood evaluations of work.\n", + "\n", + "Gradients offer a shortcut. The first derivative gives the slope; the second gives the \"curvature\", how quickly the\n", + "slope itself changes. At the peak the slope is zero, so the curvature is all there is, and it says how sharply the\n", + "likelihood falls away as we step off the peak. A sharply curved peak means a small error, a gently curved one a\n", + "large error. The error is the curvature, read backwards.\n", + "\n", + "For several parameters the second derivatives form a matrix called the \"Hessian\", which `jax.hessian` computes by\n", + "the same autodiff machinery as `jax.grad`. The errors follow from:\n", + "\n", + "\\[ C = -H^{-1}, \\qquad \\sigma_{i} = \\sqrt{C_{ii}} \\]\n", + "\n", + "Where:\n", + "\n", + "- \\( H \\): the Hessian, the matrix of second derivatives of the log likelihood at the peak.\n", + "- \\( C \\): the covariance matrix, the negative inverse of the Hessian.\n", + "- \\( \\sigma_{i} \\): the 1 sigma error on parameter \\( i \\), the square root of the \\( i \\)th diagonal entry\n", + " of \\( C \\).\n", + "\n", + "In words: invert the curvature, flip its sign, and the square roots of its diagonal are the errors. We evaluate this\n", + "at the maximum likelihood vector found by `Nautilus`." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "samples = result.samples\n", + "\n", + "max_log_likelihood_vector = samples.max_log_likelihood(as_instance=False)\n", + "\n", + "hessian = jax.hessian(log_likelihood_from_vector)(\n", + " jnp.array(max_log_likelihood_vector, dtype=float)\n", + ")\n", + "\n", + "covariance = -jnp.linalg.inv(hessian)\n", + "\n", + "errors_from_curvature = jnp.sqrt(jnp.diag(covariance))\n", + "\n", + "print(\"Errors from the curvature of the likelihood (Laplace approximation):\\n\")\n", + "print(f\"centre = {errors_from_curvature[0]}\")\n", + "print(f\"normalization = {errors_from_curvature[1]}\")\n", + "print(f\"sigma = {errors_from_curvature[2]}\")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now the comparison. Below we print the errors the `Nautilus` samples give, with the `errors_at_upper_sigma` and\n", + "`errors_at_lower_sigma` methods of tutorial 5. Tutorial 5 used `sigma=3.0`, because a result quoted in a paper wants\n", + "a conservative interval; we use `sigma=1.0`, because that is what the curvature calculation produces." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "errors_at_upper_sigma = samples.errors_at_upper_sigma(sigma=1.0, as_instance=False)\n", + "errors_at_lower_sigma = samples.errors_at_lower_sigma(sigma=1.0, as_instance=False)\n", + "\n", + "print(\"Errors from the samples (upper, at 1.0 sigma confidence):\")\n", + "print(errors_at_upper_sigma)\n", + "\n", + "print(\"\\nErrors from the samples (lower, at 1.0 sigma confidence):\")\n", + "print(errors_at_lower_sigma)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The two sets of numbers agree closely, and that is not a coincidence, it is the \"Laplace approximation\" working:\n", + "near its peak a well behaved likelihood looks like a Gaussian, whose width the curvature sets. If the posterior\n", + "really is Gaussian, the curvature knows everything the samples know.\n", + "\n", + "The catch is in the words \"if\" and \"near\". The curvature is measured at a single point, so it describes only the\n", + "peak it was measured on. If the posterior has a second peak the Hessian has no idea; if it is skewed, cut off by a\n", + "prior edge, or banana shaped because two parameters are degenerate, a symmetric Gaussian centred on the peak\n", + "misdescribes it, and the errors are wrong in ways the numbers do not reveal. Sampling assumes none of that.\n", + "\n", + "One last check is visual rather than numerical. Instead of summarising the posterior at all, we can take a handful\n", + "of the models it contains and plot each over the data. Below we use the final five samples the search accepted,\n", + "which for nested sampling are its highest likelihood ones, turning each into an instance with\n", + "`sample.instance_for_model` as tutorial 5 did. If the draws all trace the data closely, and their spread is\n", + "comparable to the error bars, the fit is telling a consistent story. This is a \"posterior predictive check\", and it\n", + "catches what no single number can." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.errorbar(\n", + " x=xvalues,\n", + " y=data,\n", + " yerr=noise_map,\n", + " linestyle=\"\",\n", + " color=\"k\",\n", + " ecolor=\"k\",\n", + " elinewidth=1,\n", + " capsize=2,\n", + ")\n", + "\n", + "for sample in samples.sample_list[-5:]:\n", + " instance = sample.instance_for_model(model=samples.model)\n", + "\n", + " plt.plot(xvalues, instance.model_data_from(xvalues=xvalues), \"--\")\n", + "\n", + "plt.title(\"Five models from the posterior, plotted over the data.\")\n", + "plt.xlabel(\"x values of profile\")\n", + "plt.ylabel(\"Profile normalization\")\n", + "plt.show()\n", + "plt.close()" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Wrap Up__\n", + "\n", + "This tutorial took the one sentence tutorial 3 used to describe how an MLE search moves and unpacked it:\n", + "\n", + "1. **Gradients**: the gradient of the log likelihood is a vector with one entry per free parameter, evaluated at a\n", + "point, pointing in the direction the likelihood increases fastest.\n", + "\n", + "2. **Finite differencing versus autodiff**: a gradient can be estimated by nudging each parameter and re-evaluating,\n", + "but this costs \\( 2N \\) evaluations and forces a step size which is biased if too large and noisy if too small.\n", + "Autodiff applies the chain rule to the operations the likelihood performs, giving the exact gradient for a small fixed\n", + "multiple of the cost of one evaluation, whatever the number of parameters.\n", + "\n", + "3. **MLE**: `LBFGS` finite differences its own gradient from a single starting point, which is expensive and\n", + "fragile. `MultiStartAdam` follows exact gradients from many starting points at once, evaluated together in one\n", + "compiled call, making it far harder to trap in a local maximum.\n", + "\n", + "4. **MCMC**: `Emcee` proposes random steps and accepts or rejects them, never asking which way is up.\n", + "`BlackJAXNUTS` rolls a ball across the landscape using the gradient to shape its trajectory, producing far less\n", + "correlated samples for the same number of steps.\n", + "\n", + "5. **Nested sampling**: `Nautilus` replaces low likelihood live points with higher likelihood ones drawn from the\n", + "priors, a procedure with no direction of travel for a gradient to inform. JAX speeds it up by evaluating batches of\n", + "points in one compiled call, but the algorithm is unchanged.\n", + "\n", + "6. **Curvature errors**: the second derivatives at the peak give a covariance matrix and hence 1 sigma errors on\n", + "every parameter, essentially for free. They agree with the errors from samples whenever the peak is single and\n", + "Gaussian shaped, and quietly mislead when it is not.\n", + "\n", + "Gradients are therefore not a different way of fitting models, they are extra information about the same likelihood\n", + "surface we have explored since tutorial 3, and each family of search makes its own use of it, or none at all.\n", + "\n", + "Whether a gradient fit succeeds depends on details we have skated over: what happens when a search steps outside its\n", + "priors, when two parameters are degenerate, or when the likelihood is defined somewhere its gradient is not.\n", + "Tutorial 7 looks at the details that decide whether these searches succeed." + ] + } + ], + "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" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file diff --git a/notebooks/chapter_1_introduction/tutorial_7_the_details.ipynb b/notebooks/chapter_1_introduction/tutorial_7_the_details.ipynb new file mode 100644 index 0000000..0bfa242 --- /dev/null +++ b/notebooks/chapter_1_introduction/tutorial_7_the_details.ipynb @@ -0,0 +1,1563 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Tutorial 7: The Details\n", + "=======================\n", + "\n", + "In tutorial 6 we opened up the non-linear search and looked at how it moves. We saw that some searches only ever ask\n", + "the likelihood function \"what is the value here?\", whilst gradient based searches also ask \"and which way is uphill?\",\n", + "and that **PyAutoFit** can answer the second question exactly by using JAX to differentiate the likelihood function.\n", + "\n", + "This tutorial is about everything else: the details sitting underneath every model-fit. How your model is\n", + "parameterized, what happens when two parameter combinations describe the same data, what a search does when a\n", + "parameter stops mattering, and what parameter space looks like from the search's point of view.\n", + "\n", + "I want to be upfront. Most of the time none of this matters, and a sensible model fitted with a sensible search\n", + "gives a sensible answer. The reason to learn these details is that when they do matter they are hard to spot,\n", + "because the failure mode is not an error message but a wrong answer that looks completely reasonable.\n", + "\n", + "__Overview__\n", + "\n", + "In this tutorial, we will look at the details that make a model-fit succeed or fail, specifically:\n", + "\n", + "- Composing a model whose components can swap roles, producing mirror solutions, and removing them with an\n", + " \"assertion\".\n", + "\n", + "- Creating a \"plateau\", a flat region of parameter space where a parameter has no effect, and removing it.\n", + "\n", + "- Running the same problem with three searches, and using the disagreement between them as a diagnostic.\n", + "\n", + "- Making the likelihood return `NaN` on purpose, and reading the `NaN` diagnostics a gradient search writes out.\n", + "\n", + "- Looking at parameter space the way a search does, through the \"unit cube\" defined by the priors.\n", + "\n", + "__Contents__\n", + "\n", + "This tutorial is split into the following sections:\n", + "\n", + "- **Data**: Load the two-Gaussian dataset used to study degenerate parameterizations.\n", + "- **Model**: The JAX-capable `Gaussian` model component from tutorial 6.\n", + "- **Analysis**: The `Analysis` class, fitting a `Collection` of profiles on NumPy or JAX.\n", + "- **Parameterization**: How two model components that can swap roles produce mirror solutions, and why that hurts a search.\n", + "- **Assertions**: Removing mirror solutions with `add_assertion` and what happens to a sample that violates one.\n", + "- **Plateaus**: How a parameter whose effect vanishes (a normalization of zero) creates a flat region of parameter space, and how to remove it.\n", + "- **Comparing Searches**: Running the same problems with MCMC, nested sampling and gradient descent to see how each is affected, and why comparing searches is a diagnostic in itself.\n", + "- **Clipping**: Parameter combinations that are unphysical even when every individual prior is sensible, the NaN likelihoods they produce, and the resample figure of merit each search substitutes.\n", + "- **NaN Diagnostics**: Reading the value-NaN and gradient-NaN counters in `search.summary`, and why a finite likelihood does not guarantee a finite gradient.\n", + "- **Unit Cube Vs Physical**: How a search actually sees parameter space through the priors, and why that changes how it explores.\n", + "- **Summary**: When these details matter, and what attending to them buys you." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Google Colab Setup__\n", + "\n", + "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", + "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", + "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", + "your own installation) it does nothing, and you can run it safely.\n", + "\n", + "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", + "type\" -> \"Hardware accelerator\" before running the notebook." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "try:\n", + " import google.colab\n", + "except ImportError:\n", + " from autofit 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(\"howtofit\")" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from autofit import setup_notebook; setup_notebook()\n", + "\n", + "from os import path\n", + "import time\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "import autofit as af\n", + "import autofit.plot as aplt" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Data__\n", + "\n", + "Load and plot the dataset from the `HowToFit/dataset` folder.\n", + "\n", + "We use the `gaussian_x2` dataset, simulated from two Gaussians sharing a centre of 50.0. The first has a\n", + "normalization of 20.0 and a sigma of 1.0, a narrow spike; the second a normalization of 40.0 and a sigma of 5.0, a\n", + "broader bump underneath. The two are summed and noise added, as in tutorials 2 and 4. Two identical model components\n", + "fitted to two component data is the simplest example of the parameterization problem we study first." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "dataset_path = path.join(\"dataset\", \"example_1d\", \"gaussian_x2\")" + ], + "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 not path.exists(dataset_path):\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.run(\n", + " [sys.executable, \"scripts/simulators/simulators.py\"],\n", + " check=True,\n", + " )\n", + "\n", + "data = af.util.numpy_array_from_json(file_path=path.join(dataset_path, \"data.json\"))\n", + "noise_map = af.util.numpy_array_from_json(\n", + " file_path=path.join(dataset_path, \"noise_map.json\")\n", + ")\n", + "\n", + "xvalues = np.arange(data.shape[0])\n", + "\n", + "plt.errorbar(\n", + " xvalues,\n", + " data,\n", + " yerr=noise_map,\n", + " linestyle=\"\",\n", + " color=\"k\",\n", + " ecolor=\"k\",\n", + " elinewidth=1,\n", + " capsize=2,\n", + ")\n", + "plt.title(\"1D dataset containing two blended Gaussians.\")\n", + "plt.xlabel(\"x values of profile\")\n", + "plt.ylabel(\"Profile Normalization\")\n", + "plt.show()\n", + "plt.clf()" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Model__\n", + "\n", + "The narrow spike sits on top of the broader bump, but only just. The two components are blended, and by eye it is\n", + "hard to say where one ends and the other begins. That blending is what makes the parameter space interesting.\n", + "\n", + "We now re-define the `Gaussian` class, using the version introduced in tutorial 6, which is identical to the class\n", + "used since tutorial 1 except that `model_data_from` takes an extra argument `xp` and is written in `xp.` functions.\n", + "As tutorial 6 showed, `xp` is whichever array library the fit is running with: `numpy` by default, `jax.numpy` when\n", + "the `Analysis` has been told to use JAX." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "class Gaussian:\n", + " def __init__(\n", + " self,\n", + " centre: float = 30.0, # <- **PyAutoFit** recognises these constructor arguments\n", + " normalization: float = 1.0, # <- are the Gaussian`s model parameters.\n", + " sigma: float = 5.0,\n", + " ):\n", + " \"\"\"\n", + " Represents a 1D Gaussian profile.\n", + "\n", + " This is a model-component of example models in the **HowToFit** lectures and is used to perform model-fitting\n", + " of example datasets.\n", + "\n", + " Parameters\n", + " ----------\n", + " centre\n", + " The x coordinate of the profile centre.\n", + " normalization\n", + " Overall normalization of the profile.\n", + " sigma\n", + " The sigma value controlling the size of the Gaussian.\n", + " \"\"\"\n", + " self.centre = centre\n", + " self.normalization = normalization\n", + " self.sigma = sigma\n", + "\n", + " def model_data_from(self, xvalues: np.ndarray, xp=np) -> np.ndarray:\n", + " \"\"\"\n", + " Returns a 1D Gaussian on an input list of Cartesian x coordinates.\n", + "\n", + " The input xvalues are translated to a coordinate system centred on the Gaussian, via its `centre`.\n", + "\n", + " The output is referred to as the `model_data` to signify that it is a representation of the data from the\n", + " model.\n", + "\n", + " Parameters\n", + " ----------\n", + " xvalues\n", + " The x coordinates in the original reference frame of the data.\n", + " xp\n", + " The array library the calculation is performed with, `numpy` by default and `jax.numpy` when the fit\n", + " is being performed with JAX.\n", + "\n", + " Returns\n", + " -------\n", + " np.array\n", + " The Gaussian values at the input x coordinates.\n", + " \"\"\"\n", + " transformed_xvalues = xp.subtract(xvalues, self.centre)\n", + " return xp.multiply(\n", + " xp.divide(self.normalization, self.sigma * xp.sqrt(2.0 * np.pi)),\n", + " xp.exp(-0.5 * xp.square(xp.divide(transformed_xvalues, self.sigma))),\n", + " )\n" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Analysis__\n", + "\n", + "The `Analysis` class below is the tutorial 4 version, which sums the model data of every profile in the instance,\n", + "combined with the tutorial 6 version, which accepts `use_jax` and passes it to `af.Analysis` via `super().__init__`.\n", + "\n", + "Two details matter. The first is `self._xp`, an attribute created for us by `af.Analysis` which is `numpy` when\n", + "`use_jax=False` and `jax.numpy` when `use_jax=True`. Every array operation in the likelihood goes through it, which\n", + "is why we write `self._xp.sum` rather than the built-in `sum`. The second is `model_data_from_instance`: the\n", + "`instance` is an iterable `Collection`, so we sum the model data of every profile it contains without knowing how\n", + "many there are.\n", + "\n", + "We create the `Analysis` at the end of the cell below, leaving `use_jax` at its default of `False` until we need\n", + "gradients." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "class Analysis(af.Analysis):\n", + " def __init__(self, data: np.ndarray, noise_map: np.ndarray, use_jax: bool = False):\n", + " \"\"\"\n", + " The `Analysis` class acts as an interface between the data and model in **PyAutoFit**.\n", + "\n", + " Parameters\n", + " ----------\n", + " data\n", + " A 1D numpy array containing the data (e.g. a noisy 1D signal) fitted in the workspace examples.\n", + " noise_map\n", + " A 1D numpy array containing the noise values of the data, used for computing the goodness of fit\n", + " metric, the log likelihood.\n", + " use_jax\n", + " If `True` the log likelihood function is computed with `jax.numpy`, making it differentiable and\n", + " therefore usable by the gradient based searches introduced in tutorial 6.\n", + " \"\"\"\n", + " super().__init__(use_jax=use_jax)\n", + "\n", + " self.data = data\n", + " self.noise_map = noise_map\n", + "\n", + " def model_data_from_instance(self, instance):\n", + " \"\"\"\n", + " Returns the summed model data of every profile in an instance.\n", + "\n", + " The `instance` is a `Collection`, which is iterable, so a list comprehension over it returns the model data\n", + " of every profile it contains.\n", + " \"\"\"\n", + " xvalues = self._xp.arange(self.data.shape[0])\n", + "\n", + " return sum(\n", + " [\n", + " profile.model_data_from(xvalues=xvalues, xp=self._xp)\n", + " for profile in instance\n", + " ]\n", + " )\n", + "\n", + " def log_likelihood_function(self, instance) -> float:\n", + " \"\"\"\n", + " Returns the log likelihood of a fit of a collection of 1D profiles to the dataset.\n", + "\n", + " Every array operation uses `self._xp`, which is `numpy` for an ordinary fit and `jax.numpy` for a fit which\n", + " uses JAX. The log likelihood is therefore differentiable whenever `use_jax=True` was passed to `__init__`.\n", + " \"\"\"\n", + " model_data = self.model_data_from_instance(instance=instance)\n", + "\n", + " residual_map = self.data - model_data\n", + " chi_squared_map = (residual_map / self.noise_map) ** 2.0\n", + " chi_squared = self._xp.sum(chi_squared_map)\n", + " noise_normalization = self._xp.sum(\n", + " self._xp.log(2 * np.pi * self.noise_map**2.0)\n", + " )\n", + " log_likelihood = -0.5 * (chi_squared + noise_normalization)\n", + "\n", + " return log_likelihood\n", + "\n", + "\n", + "analysis = Analysis(data=data, noise_map=noise_map)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Parameterization__\n", + "\n", + "\"Parameterization\" means the specific choice of parameters we use to describe our model. It is easy to think of a\n", + "model as a fixed thing, but it is not: the same physical model can be written down in many different ways, and the\n", + "choice we make changes the shape of parameter space that the search has to explore.\n", + "\n", + "Our dataset contains two Gaussians, so the obvious model is a `Collection` of two `Gaussian` components, with\n", + "identical priors on both. This is the model composition API from tutorial 1, and it is the same six free parameter\n", + "model that tutorial 2 fitted by hand." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model = af.Collection(gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian))\n", + "\n", + "for gaussian in [model.gaussian_0, model.gaussian_1]:\n", + " gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + " gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + " gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0)\n", + "\n", + "print(model.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There is a problem hiding in that model. The two components are interchangeable: nothing says `gaussian_0` is the\n", + "narrow one and `gaussian_1` the broad one. Swap all six values over and we get exactly the same summed model data,\n", + "because addition does not care about the order of its arguments, which means the same residuals, the same\n", + "chi-squared and the same log likelihood.\n", + "\n", + "Let's confirm it, using the parameter ordering of the model vector which, as tutorial 1 showed, is given by\n", + "`model.model_component_and_parameter_names`." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(model.model_component_and_parameter_names)\n", + "\n", + "vector_ordered = [50.0, 20.0, 1.0, 50.0, 40.0, 5.0]\n", + "vector_swapped = [50.0, 40.0, 5.0, 50.0, 20.0, 1.0]\n", + "\n", + "instance_ordered = model.instance_from_vector(vector=vector_ordered)\n", + "instance_swapped = model.instance_from_vector(vector=vector_swapped)\n", + "\n", + "print(\"Log likelihood of the ordered model: \")\n", + "print(analysis.log_likelihood_function(instance=instance_ordered))\n", + "print(\"Log likelihood of the swapped model: \")\n", + "print(analysis.log_likelihood_function(instance=instance_swapped))" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The two log likelihoods are identical to the last decimal place. They are not merely similar, they are the same\n", + "number, because the two vectors produce the same model data.\n", + "\n", + "This is a \"degeneracy\", and this one is a \"label switching\" degeneracy: the labels `gaussian_0` and `gaussian_1` are\n", + "arbitrary, so every solution has a mirror image partner elsewhere. Our six dimensional parameter space does not\n", + "contain one peak, it contains two identical peaks related by a reflection.\n", + "\n", + "Why does this hurt? Recall the searches of tutorial 3. Every search has to decide which of the two peaks to spend\n", + "its effort on, and nothing in the data prefers one over the other. A search that commits to one peak gives an\n", + "answer whose component labels are a coin toss; a search that splits its effort between both returns a posterior\n", + "that is a smeared average of two solutions rather than an estimate of either, whose \"errors\" are not errors at all\n", + "but a measure of the distance between the mirrors. Either way we have paid for a second copy of the answer.\n", + "\n", + "Let's fit with `DynestyStatic`, the nested sampling search from tutorial 3." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "search = af.DynestyStatic(\n", + " sample=\"rwalk\", # This makes dynesty run faster, dont worry about what it means for now!\n", + ")\n", + "\n", + "print(\n", + " \"\"\"\n", + " The non-linear search has begun running.\n", + " This Jupyter notebook cell with progress once the search has completed - this could take a few minutes!\n", + " \"\"\"\n", + ")\n", + "\n", + "start = time.time()\n", + "\n", + "result_flip = search.fit(model=model, analysis=analysis)\n", + "\n", + "print(f\"Dynesty run time: {time.time() - start} seconds\")\n", + "print(\"The search has finished run - you may now continue the notebook.\")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The corner plot below shows the Probability Density Functions (PDF's) of the result, via the `corner.py` wrapper\n", + "`aplt.corner_cornerpy` we met in tutorial 5. The run is short, so there may be too few samples for `corner.py` to\n", + "draw contours; the scatter plot afterwards makes the point without them, putting every sample's `gaussian_0.sigma`\n", + "against its `gaussian_1.sigma`.\n", + "\n", + "Its diagonal is the line where the two sigmas are equal, and the two mirror solutions sit on opposite sides of it.\n", + "What you will almost certainly see is the great majority of samples piled on one side, with a thin scatter of early\n", + "exploration samples on the other: the search committed to one mirror. Which one is a coin toss, and I got each of\n", + "them on different runs while writing this tutorial." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "aplt.corner_cornerpy(samples=result_flip.samples)\n", + "\n", + "sigma_0_list = [parameters[2] for parameters in result_flip.samples.parameter_lists]\n", + "sigma_1_list = [parameters[5] for parameters in result_flip.samples.parameter_lists]\n", + "\n", + "plt.scatter(sigma_0_list, sigma_1_list, s=1, color=\"k\")\n", + "plt.title(\"Samples of the two sigmas, split by the two mirror solutions.\")\n", + "plt.xlabel(\"gaussian_0 sigma\")\n", + "plt.ylabel(\"gaussian_1 sigma\")\n", + "plt.show()\n", + "plt.clf()\n", + "\n", + "ordered_count = sum(\n", + " sigma_0 < sigma_1 for sigma_0, sigma_1 in zip(sigma_0_list, sigma_1_list)\n", + ")\n", + "\n", + "print(f\"Samples with gaussian_0 narrower than gaussian_1: {ordered_count}\")\n", + "print(\n", + " f\"Samples with gaussian_0 broader than gaussian_1: {len(sigma_0_list) - ordered_count}\"\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The maximum log likelihood model printed below is one of the two mirror solutions, and it fits the data beautifully.\n", + "Nothing has failed.\n", + "\n", + "What has gone wrong is that the answer's labels are arbitrary. Read off \"the narrow component has a normalization\n", + "of about 20\" and you may be reading the wrong component, because the next run may put that solution in the other\n", + "slot. A degeneracy does not make the fit worse, it makes the *answer ambiguous*, and it costs the search effort\n", + "exploring a region it did not need to. The fit does not crash, it quietly costs more and tells us less than it\n", + "should.\n", + "\n", + "Be clear about what this short run does and does not show. It shows that the two mirrors exist, which we proved\n", + "exactly with the two identical log likelihoods, and that the search commits to one. It does not show a posterior\n", + "with two clean modes: a nested sampler with far more live points, run far longer, is designed to find and report\n", + "both peaks, and we have deliberately traded that away for a fit that runs in seconds." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(result_flip.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Assertions__\n", + "\n", + "The fix is to tell the model something we already know: `gaussian_0` is the narrow component and `gaussian_1` is\n", + "the broad one. If we forbid every model where that is not true, we delete one of the two mirror peaks and leave a\n", + "parameter space with a single solution.\n", + "\n", + "**PyAutoFit** expresses this with an \"assertion\", added to the model with `add_assertion`. An assertion is a\n", + "statement about the model's parameters that every accepted model must satisfy. Here we assert that the sigma of\n", + "`gaussian_0` is less than the sigma of `gaussian_1`, which makes `gaussian_0` the narrow one by definition." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model = af.Collection(gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian))\n", + "\n", + "for gaussian in [model.gaussian_0, model.gaussian_1]:\n", + " gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + " gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + " gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0)\n", + "\n", + "model.add_assertion(model.gaussian_0.sigma < model.gaussian_1.sigma)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What actually happens when the search proposes a model that violates the assertion?\n", + "\n", + "On the NumPy path, building the instance from the parameter vector raises an exception internally, which\n", + "**PyAutoFit** catches and converts into a special value called the \"resample figure of merit\". The search never sees\n", + "a likelihood for that model, it sees a number so bad it can never be selected.\n", + "\n", + "On the JAX path, introduced in tutorial 6 via `use_jax=True`, an exception cannot be raised at all, because the\n", + "likelihood is traced and compiled rather than executed line by line. **PyAutoFit** instead evaluates the assertion\n", + "as a traced boolean and applies it to the final figure of merit with a `where`, mapping a violating model to exactly\n", + "the same resample figure of merit. Different mechanism, same outcome, which is what lets a NumPy fit and a JAX fit\n", + "agree exactly.\n", + "\n", + "We can check the assertion ourselves with `assertions_satisfied_from_vector`, using the two mirror vectors from\n", + "before. One passes and one fails, which is the whole point." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Ordered vector satisfies the assertion: \")\n", + "print(model.assertions_satisfied_from_vector(vector_ordered))\n", + "print(\"Swapped vector satisfies the assertion: \")\n", + "print(model.assertions_satisfied_from_vector(vector_swapped))" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Two practical notes. An assertion becomes part of the model's unique identifier, so a model with an assertion\n", + "writes to a different output folder than the same model without one; they are different models, and results from\n", + "one should never be resumed as the other.\n", + "\n", + "The degeneracy can also be broken without an assertion, by giving the two components priors that cannot overlap.\n", + "Give `gaussian_0.sigma` a `UniformPrior` between 0.0 and 3.0 and `gaussian_1.sigma` one between 3.0 and 25.0, and\n", + "the mirror solution is not in parameter space at all. Use an assertion when you know the ordering but not the\n", + "values.\n", + "\n", + "Let's refit with the assertion in place." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\n", + " \"\"\"\n", + " The non-linear search has begun running.\n", + " This Jupyter notebook cell with progress once the search has completed - this could take a few minutes!\n", + " \"\"\"\n", + ")\n", + "\n", + "search = af.DynestyStatic(\n", + " sample=\"rwalk\",\n", + ")\n", + "\n", + "start = time.time()\n", + "\n", + "result_assert = search.fit(model=model, analysis=analysis)\n", + "\n", + "print(f\"Dynesty run time: {time.time() - start} seconds\")\n", + "print(\"The search has finished run - you may now continue the notebook.\")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The counts printed below are the crisp demonstration. Before the assertion, samples appeared on both sides of the\n", + "diagonal; with it in place the violating side is empty, and empty by construction rather than luck, because every\n", + "model proposed there was handed the resample figure of merit instead of a likelihood.\n", + "\n", + "The answer is now unambiguous: `gaussian_0` is the narrow component because we said so, and the maximum likelihood\n", + "model comes back in that order every run rather than on a coin toss. Half our parameter space has gone, and with it\n", + "half the work the search had to do.\n", + "\n", + "Removing a degeneracy is the single highest value thing you can do to a slow model-fit!" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "aplt.corner_cornerpy(samples=result_assert.samples)\n", + "\n", + "sigma_0_list = [parameters[2] for parameters in result_assert.samples.parameter_lists]\n", + "sigma_1_list = [parameters[5] for parameters in result_assert.samples.parameter_lists]\n", + "\n", + "plt.scatter(sigma_0_list, sigma_1_list, s=1, color=\"k\")\n", + "plt.title(\"Samples of the two sigmas with the assertion applied.\")\n", + "plt.xlabel(\"gaussian_0 sigma\")\n", + "plt.ylabel(\"gaussian_1 sigma\")\n", + "plt.show()\n", + "plt.clf()\n", + "\n", + "ordered_count = sum(\n", + " sigma_0 < sigma_1 for sigma_0, sigma_1 in zip(sigma_0_list, sigma_1_list)\n", + ")\n", + "\n", + "print(f\"Samples with gaussian_0 narrower than gaussian_1: {ordered_count}\")\n", + "print(f\"Samples that violate the assertion: {len(sigma_0_list) - ordered_count}\")\n", + "\n", + "print(result_assert.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Plateaus__\n", + "\n", + "The second detail is what happens when a parameter stops mattering.\n", + "\n", + "To create the problem we now load the single Gaussian dataset, `gaussian_x1`, which was simulated from one Gaussian\n", + "with a centre of 50.0, a normalization of 25.0 and a sigma of 10.0. It is the dataset we fitted in tutorials 2 and\n", + "3. We will then deliberately fit it with the two component model we have been using, which is one component more\n", + "than the data needs." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "dataset_x1_path = path.join(\"dataset\", \"example_1d\", \"gaussian_x1\")\n", + "\n", + "if not path.exists(dataset_x1_path):\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.run(\n", + " [sys.executable, \"scripts/simulators/simulators.py\"],\n", + " check=True,\n", + " )\n", + "\n", + "data_x1 = af.util.numpy_array_from_json(\n", + " file_path=path.join(dataset_x1_path, \"data.json\")\n", + ")\n", + "noise_map_x1 = af.util.numpy_array_from_json(\n", + " file_path=path.join(dataset_x1_path, \"noise_map.json\")\n", + ")\n", + "\n", + "analysis_x1 = Analysis(data=data_x1, noise_map=noise_map_x1)\n", + "\n", + "plt.errorbar(\n", + " xvalues,\n", + " data_x1,\n", + " yerr=noise_map_x1,\n", + " linestyle=\"\",\n", + " color=\"k\",\n", + " ecolor=\"k\",\n", + " elinewidth=1,\n", + " capsize=2,\n", + ")\n", + "plt.title(\"1D dataset containing a single Gaussian.\")\n", + "plt.xlabel(\"x values of profile\")\n", + "plt.ylabel(\"Profile Normalization\")\n", + "plt.show()\n", + "plt.clf()" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The data needs only one Gaussian, so the best thing the second component can do is get out of the way, which it\n", + "does by taking a normalization of zero and contributing nothing to the model data.\n", + "\n", + "Here is the consequence. Once `gaussian_1.normalization` is zero, its `centre` and `sigma` have no effect on the\n", + "model data at all. Every value gives the same model data, chi-squared and log likelihood. Instead of a peak in those\n", + "two dimensions, parameter space contains a perfectly flat region: a \"plateau\".\n", + "\n", + "Let's demonstrate it, evaluating the likelihood with `gaussian_1.normalization` fixed at zero and its `centre` and\n", + "`sigma` set to three wildly different pairs of values." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model_x1 = af.Collection(gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian))\n", + "\n", + "for gaussian in [model_x1.gaussian_0, model_x1.gaussian_1]:\n", + " gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + " gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + " gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0)\n", + "\n", + "for centre_1, sigma_1 in [(20.0, 2.0), (80.0, 15.0), (50.0, 0.5)]:\n", + " vector = [50.0, 25.0, 10.0, centre_1, 0.0, sigma_1]\n", + "\n", + " instance = model_x1.instance_from_vector(vector=vector)\n", + "\n", + " print(\n", + " f\"gaussian_1 centre = {centre_1}, sigma = {sigma_1}, log likelihood = \"\n", + " f\"{analysis_x1.log_likelihood_function(instance=instance)}\"\n", + " )" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Three completely different models, one identical log likelihood. That is a plateau, two dimensions wide.\n", + "\n", + "Every search in tutorial 3 struggles here, because nothing in the likelihood tells it which way to go. An MLE search\n", + "estimates the gradient, finds it is exactly zero and concludes it has converged. MCMC walkers wander at random,\n", + "since every proposal is equally good. A nested sampler's live points scatter uniformly across the flat region.\n", + "\n", + "Worse, the \"errors\" reported for the plateau parameters are not errors. If a parameter has no effect on the\n", + "likelihood its posterior is just its prior, so the error bar is the width of the prior you happened to choose. It\n", + "looks like a measurement and is nothing of the sort.\n", + "\n", + "There are three ways to deal with a plateau, in order of increasing honesty. The first is to stop the normalization\n", + "reaching zero: a `LogUniformPrior`, used in tutorial 4 for prior tuning, spreads its probability evenly across\n", + "orders of magnitude and has a strictly positive lower limit, so a normalization of exactly zero is not in parameter\n", + "space." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model_x1.gaussian_1.normalization = af.LogUniformPrior(\n", + " lower_limit=1e-2, upper_limit=1e2\n", + ")\n", + "\n", + "print(model_x1.gaussian_1.normalization)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The second is to remove the offending parameters altogether, by fixing them. As tutorial 1 showed, assigning a\n", + "float to a model parameter turns it into a constant rather than a free parameter, which we confirm by checking\n", + "`prior_count` before and after. If a parameter genuinely has no effect on the data, any value will do." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model_fixed = af.Collection(\n", + " gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian)\n", + ")\n", + "\n", + "print(f\"Number of free parameters before fixing sigma: {model_fixed.prior_count}\")\n", + "\n", + "model_fixed.gaussian_1.sigma = 5.0\n", + "\n", + "print(f\"Number of free parameters after fixing sigma: {model_fixed.prior_count}\")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The third is the honest answer, and the one I would use in a real analysis: reduce the model to what the data\n", + "supports, the \"reducing complexity\" strategy of tutorial 4. The data contains one Gaussian, so the model should\n", + "contain one Gaussian, and then there is no second normalization to go to zero and no plateau at all.\n", + "\n", + "The reason to know the other two is that you cannot always do this. Sometimes the extra component is physically\n", + "required even when this dataset cannot constrain it, and a sensible prior or a fixed parameter is how you stop it\n", + "poisoning the fit." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model_simple = af.Collection(gaussian=af.Model(Gaussian))\n", + "\n", + "print(f\"Number of free parameters in the reduced model: {model_simple.prior_count}\")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Comparing Searches__\n", + "\n", + "We now have two badly parameterized problems: the flip degeneracy on the two Gaussian data, and the plateau on the\n", + "single Gaussian data. We have already run nested sampling on the flip problem. Let's run MCMC on it too, then run\n", + "all three families on the plateau problem, and compare what comes back.\n", + "\n", + "We start with MCMC, using `Emcee` on the flip problem exactly as tutorial 3 did. The walkers begin scattered\n", + "through parameter space and climb towards whichever mirror peak is nearest." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model_emcee = af.Collection(\n", + " gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian)\n", + ")\n", + "\n", + "for gaussian in [model_emcee.gaussian_0, model_emcee.gaussian_1]:\n", + " gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + " gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + " gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0)\n", + "\n", + "search = af.Emcee(\n", + " nwalkers=20, # The number of walkers we'll use to sample parameter space.\n", + " nsteps=500, # The number of steps each walker takes.\n", + ")\n", + "\n", + "print(\n", + " \"\"\"\n", + " The non-linear search has begun running.\n", + " This Jupyter notebook cell with progress once the search has completed - this could take a few minutes!\n", + " \"\"\"\n", + ")\n", + "\n", + "start = time.time()\n", + "\n", + "result_emcee = search.fit(model=model_emcee, analysis=analysis)\n", + "\n", + "print(f\"Emcee run time: {time.time() - start} seconds\")\n", + "print(\"The search has finished run - you may now continue the notebook.\")\n", + "\n", + "print(result_emcee.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Compare that maximum likelihood model to the one the nested sampler found. With only 20 walkers taking 500 steps\n", + "they have not had long enough to climb either mirror properly, and they usually finish somewhere that is neither\n", + "mirror: the two normalizations and sigmas come back at values the simulator never used, sharing the flux out\n", + "between the components in whatever way the walkers happened to drift into.\n", + "\n", + "This is exactly the stochasticity of tutorial 4, and it deserves to be taken seriously rather than treated as a\n", + "nuisance. Run the cell above again and you will get a different answer, because the walkers start in different\n", + "random places. **That variability is itself the diagnostic.** A fit whose answer changes every run is telling you\n", + "the search has not converged on this parameter space, and the honest response is more steps, a better starting\n", + "point, or an easier parameter space.\n", + "\n", + "Now the plateau problem, with the same two searches. Nested sampling first, with more live points than we used\n", + "above so that it maps the flat region properly rather than skating over it.\n", + "\n", + "Note that the two component model has the flip degeneracy in it as well as the plateau, because either component\n", + "could be the one that vanishes. We therefore use the tool we just learned and assert that `gaussian_0` carries more\n", + "normalization than `gaussian_1`, which makes `gaussian_1` the vanishing component by definition and lets us talk\n", + "about its parameters without having to check which slot the search happened to use." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model_plateau_nest = af.Collection(\n", + " gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian)\n", + ")\n", + "\n", + "for gaussian in [model_plateau_nest.gaussian_0, model_plateau_nest.gaussian_1]:\n", + " gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + " gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + " gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0)\n", + "\n", + "model_plateau_nest.add_assertion(\n", + " model_plateau_nest.gaussian_0.normalization\n", + " > model_plateau_nest.gaussian_1.normalization\n", + ")\n", + "\n", + "search = af.DynestyStatic(\n", + " nlive=200, # More live points than before, so the flat region is properly sampled.\n", + " sample=\"rwalk\",\n", + ")\n", + "\n", + "print(\n", + " \"\"\"\n", + " The non-linear search has begun running.\n", + " This Jupyter notebook cell with progress once the search has completed - this could take a few minutes!\n", + " \"\"\"\n", + ")\n", + "\n", + "start = time.time()\n", + "\n", + "result_plateau_nest = search.fit(model=model_plateau_nest, analysis=analysis_x1)\n", + "\n", + "print(f\"Dynesty run time: {time.time() - start} seconds\")\n", + "print(\"The search has finished run - you may now continue the notebook.\")\n", + "\n", + "print(result_plateau_nest.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The result above is the plateau made visible in numbers, so it is worth reading carefully.\n", + "\n", + "`gaussian_0` has recovered the true Gaussian, with a centre near 50.0, a normalization near 25.0 and a sigma near\n", + "10.0. `gaussian_1`, the component our assertion made the smaller one, has been pushed down to a small remnant whose\n", + "normalization interval runs down towards zero. The data needed one Gaussian and the search gave it one.\n", + "\n", + "Now compare the parameter uncertainties of the two components. The cell below prints the one sigma interval of\n", + "every parameter, which as tutorial 5 showed comes from `values_at_sigma`." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "names = result_plateau_nest.samples.model.model_component_and_parameter_names\n", + "values = result_plateau_nest.samples.values_at_sigma(sigma=1.0, as_instance=False)\n", + "\n", + "for name, (lower, upper) in zip(names, values):\n", + " print(f\"{name}: {lower} -> {upper} (width {upper - lower})\")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Compare the two components line by line, and compare the widths rather than the values, because the values move\n", + "from run to run. `gaussian_0`, which recovered the real Gaussian, has a tight interval on its centre and a tighter\n", + "one still on its sigma. `gaussian_1`, which contributes almost nothing, has intervals on the same two parameters\n", + "that are many times wider, with its sigma spanning a large part of the 0.0 to 25.0 prior we gave it.\n", + "\n", + "That is the plateau statement made quantitative. The less a component contributes, the less its shape parameters\n", + "matter, so their posterior drifts back towards the prior and the \"error bar\" you would quote drifts towards the\n", + "prior width. It looks like a measurement and it is not one!\n", + "\n", + "Now MCMC on the same plateau problem." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model_plateau_mcmc = af.Collection(\n", + " gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian)\n", + ")\n", + "\n", + "for gaussian in [model_plateau_mcmc.gaussian_0, model_plateau_mcmc.gaussian_1]:\n", + " gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + " gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + " gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0)\n", + "\n", + "search = af.Emcee(\n", + " nwalkers=20,\n", + " nsteps=500,\n", + ")\n", + "\n", + "print(\n", + " \"\"\"\n", + " The non-linear search has begun running.\n", + " This Jupyter notebook cell with progress once the search has completed - this could take a few minutes!\n", + " \"\"\"\n", + ")\n", + "\n", + "start = time.time()\n", + "\n", + "result_plateau_mcmc = search.fit(model=model_plateau_mcmc, analysis=analysis_x1)\n", + "\n", + "print(f\"Emcee run time: {time.time() - start} seconds\")\n", + "print(\"The search has finished run - you may now continue the notebook.\")\n", + "\n", + "print(result_plateau_mcmc.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Finally the gradient search. As tutorial 6 explained, `MultiStartAdam` differentiates the likelihood with JAX, so\n", + "its `Analysis` must be created with `use_jax=True`, and it walks many independent \"lanes\" uphill from different\n", + "starting points." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model_plateau = af.Collection(\n", + " gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian)\n", + ")\n", + "\n", + "for gaussian in [model_plateau.gaussian_0, model_plateau.gaussian_1]:\n", + " gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + " gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + " gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0)\n", + "\n", + "analysis_x1_jax = Analysis(data=data_x1, noise_map=noise_map_x1, use_jax=True)\n", + "\n", + "search = af.MultiStartAdam(\n", + " n_starts=8, # The number of independent lanes launched through parameter space.\n", + " n_steps=150, # The number of gradient steps each lane takes.\n", + " learning_rate=0.5,\n", + " batch_size=None, # None evaluates every lane in one compiled call, as in tutorial 6.\n", + ")\n", + "\n", + "print(\n", + " \"\"\"\n", + " The non-linear search has begun running.\n", + " This Jupyter notebook cell with progress once the search has completed - this could take a few minutes!\n", + " \"\"\"\n", + ")\n", + "\n", + "start = time.time()\n", + "\n", + "result_adam = search.fit(model=model_plateau, analysis=analysis_x1_jax)\n", + "\n", + "print(f\"MultiStartAdam run time: {time.time() - start} seconds\")\n", + "print(\"The search has finished run - you may now continue the notebook.\")\n", + "\n", + "print(result_adam.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Put the results side by side. I want to separate two things carefully here: what these particular short runs\n", + "actually showed, and what we know about the mechanisms independently of them.\n", + "\n", + "**What the runs above showed.** On the flip problem, nested sampling committed to one mirror and fitted it\n", + "excellently, while MCMC, given only 20 walkers and 500 steps, typically finished at a model worse than either\n", + "mirror and gave a different answer each time it was run.\n", + "\n", + "On the plateau problem, nested sampling recovered the true Gaussian, pushed the spare component down towards zero\n", + "normalization, and reported intervals on that component's shape parameters many times wider than on the real one's.\n", + "MCMC also found roughly the right Gaussian, and left its spare component wandering, often finishing with its sigma\n", + "against the edge of the prior, which is what a walker with nothing to climb does. The gradient search converged quickly, and where\n", + "it converged depended on where its lanes started: some runs recover the true Gaussian, and some settle on a poor\n", + "local maximum with a broad component parked near the edge of its prior. Compare the result above with the true\n", + "values to see which you got.\n", + "\n", + "Notice that none of the four ever announced a problem. Every one ran to completion and returned a result with error\n", + "bars.\n", + "\n", + "**What we know from the mechanisms.** A plateau is a region of exactly zero gradient, and a zero gradient point is\n", + "a fixed point a gradient search cannot leave: a lane stepping onto one stops moving and its figure of merit stops\n", + "changing, which from the outside is indistinguishable from convergence. A local maximum is a zero gradient point\n", + "too, which is why the run above looks exactly as converged as a correct one would. Nested sampling has no such\n", + "trap, because its live points are replaced from the whole prior volume rather than moved uphill from where they\n", + "are. MCMC sits in between: a walker on a flat region accepts every proposal, so it wanders rather than freezing,\n", + "but it may wander for a very long time.\n", + "\n", + "None of this says which search is best, and that is not the point. If searches with completely different mechanisms\n", + "agree, the answer is probably a property of your data. If they disagree, or if one gives a different answer every\n", + "run, that is almost never a statement about which search is better. It is a statement about your parameter space,\n", + "and the degeneracies and flat regions you have accidentally put in it.\n", + "\n", + "Running more than one search tells you about your model, not just your searches!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Clipping__\n", + "\n", + "So far every model has been computable everywhere: any combination of values inside the priors gave a number.\n", + "\n", + "That is not always true. Consider a different model of our two Gaussian data, in which the components are not\n", + "independent. Suppose the narrow component is an instrumental effect blurred into the broad one, so the width we\n", + "want for the broad component is what is left after the narrow one is removed in quadrature:\n", + "\n", + "\\[ \\sigma_{\\rm halo} = \\sqrt{\\sigma_{1}^2 - \\sigma_{0}^2} \\]\n", + "\n", + "Where:\n", + "\n", + "- $\\sigma_{0}$: the sigma of the narrow component, `gaussian_0`.\n", + "- $\\sigma_{1}$: the sigma of the broad component, `gaussian_1`.\n", + "- $\\sigma_{\\rm halo}$: the width of the broad component after the narrow one is removed.\n", + "\n", + "In words: the broad component's true width is the broad width with the narrow width subtracted in quadrature.\n", + "\n", + "Now look at the priors. `gaussian_0.sigma` runs from 0.0 to 25.0 and so does `gaussian_1.sigma`, both perfectly\n", + "sensible ranges. But the *combination* $\\sigma_{1} < \\sigma_{0}$ asks for the square root of a negative number,\n", + "which is not a number at all. The individual priors are fine, the combination is unphysical." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "class DeconvolvedAnalysis(Analysis):\n", + " def model_data_from_instance(self, instance):\n", + " \"\"\"\n", + " Returns the summed model data of a narrow component plus a broad component whose width is the quadrature\n", + " difference of the two sigmas.\n", + "\n", + " This is unphysical, and undefined, whenever the sigma of `gaussian_1` is smaller than the sigma of\n", + " `gaussian_0`.\n", + " \"\"\"\n", + " xp = self._xp\n", + "\n", + " xvalues = xp.arange(self.data.shape[0])\n", + "\n", + " sigma_halo = xp.sqrt(\n", + " instance.gaussian_1.sigma**2.0 - instance.gaussian_0.sigma**2.0\n", + " )\n", + "\n", + " halo = Gaussian(\n", + " centre=instance.gaussian_1.centre,\n", + " normalization=instance.gaussian_1.normalization,\n", + " sigma=sigma_halo,\n", + " )\n", + "\n", + " return instance.gaussian_0.model_data_from(\n", + " xvalues=xvalues, xp=xp\n", + " ) + halo.model_data_from(xvalues=xvalues, xp=xp)\n" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let's evaluate this likelihood at a physical set of parameters and at an unphysical one, where the only difference\n", + "is that the two sigmas have been swapped so the \"narrow\" component is wider than the \"broad\" one." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "analysis_nan = DeconvolvedAnalysis(data=data, noise_map=noise_map)\n", + "\n", + "model_nan = af.Collection(gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian))\n", + "\n", + "for gaussian in [model_nan.gaussian_0, model_nan.gaussian_1]:\n", + " gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + " gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + " gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0)\n", + "\n", + "vector_physical = [50.0, 20.0, 1.0, 50.0, 40.0, 5.0]\n", + "vector_unphysical = [50.0, 20.0, 5.0, 50.0, 40.0, 1.0]\n", + "\n", + "print(\"Log likelihood of the physical model: \")\n", + "print(\n", + " analysis_nan.log_likelihood_function(\n", + " instance=model_nan.instance_from_vector(vector=vector_physical)\n", + " )\n", + ")\n", + "print(\"Log likelihood of the unphysical model: \")\n", + "print(\n", + " analysis_nan.log_likelihood_function(\n", + " instance=model_nan.instance_from_vector(vector=vector_unphysical)\n", + " )\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The second log likelihood is `nan`, short for \"not a number\": what floating point arithmetic produces when asked to\n", + "do something impossible. NumPy also prints a `RuntimeWarning: invalid value encountered in sqrt`, which is expected\n", + "here and not a bug. A `nan` is contagious, in that any sum or product involving one gives another `nan`.\n", + "\n", + "A search receiving a `nan` could not rank it against anything else, so **PyAutoFit** never lets one through. Before\n", + "the figure of merit is returned it is checked for `nan` and for infinity, and either is replaced by the \"resample\n", + "figure of merit\" we met in the assertions section: this model is unusable, draw another.\n", + "\n", + "The detail worth knowing is that the resample figure of merit is not the same number for every search. For the MLE\n", + "and MCMC searches it is `-inf`, negative infinity, the natural choice because it is the worst possible log\n", + "likelihood: an MLE search never steps towards it and an MCMC walker never accepts it.\n", + "\n", + "For the nested samplers and for SMC it is `-1e99` instead, a huge negative number that is nevertheless finite. Their\n", + "arithmetic with log weights and shell evidences has to stay finite, so a genuine `-inf` would poison the whole\n", + "calculation rather than reject one sample. You do not choose these values; each search sets its own internally, and\n", + "there is no user facing argument for them.\n", + "\n", + "There is one family of search for which rejection is not enough. As tutorial 6 showed, the gradient searches step in\n", + "*physical* parameter units, computing a gradient and moving along it. A large enough step carries a lane out of a\n", + "prior's range, where the log prior of a `UniformPrior` is `-inf`. An MCMC search rejects such a proposal and the\n", + "walker stays put; a nested sampler never leaves the unit cube. A gradient step has neither protection: nothing pulls\n", + "the lane back, because outside the box the log prior is a *constant* `-inf` and the derivative of a constant is\n", + "zero, so the lane keeps walking away.\n", + "\n", + "That is why the gradient searches take a `clipper` argument. A \"clipper\" projects each lane back inside the prior\n", + "box after every step, supplying the restoring force that rejection gives the other searches." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "clipper = af.ClipperPriorBox()\n", + "\n", + "print(f\"Clipper: {type(clipper).__name__}\")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__NaN Diagnostics__\n", + "\n", + "When you run a gradient search, **PyAutoFit** counts how often the likelihood and the gradient went non finite and\n", + "writes the counts to a file called `search.summary` in the output folder. To read that file we need the search to\n", + "write to disk, which as tutorial 5 showed means passing a `name` and a `path_prefix`.\n", + "\n", + "Let's fit our unphysical model with `MultiStartAdam`, using the clipper above, and then read the summary back." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "analysis_nan_jax = DeconvolvedAnalysis(data=data, noise_map=noise_map, use_jax=True)\n", + "\n", + "model_nan_fit = af.Collection(\n", + " gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian)\n", + ")\n", + "\n", + "for gaussian in [model_nan_fit.gaussian_0, model_nan_fit.gaussian_1]:\n", + " gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + " gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + " gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0)\n", + "\n", + "search = af.MultiStartAdam(\n", + " name=\"tutorial_7_the_details_nan\",\n", + " path_prefix=\"chapter_1_introduction\",\n", + " n_starts=8,\n", + " n_steps=150,\n", + " learning_rate=0.5,\n", + " batch_size=None, # As above.\n", + " clipper=clipper,\n", + ")\n", + "\n", + "print(\n", + " \"\"\"\n", + " The non-linear search has begun running.\n", + " Checkout the HowToFit/output/chapter_1_introduction/tutorial_7_the_details_nan\n", + " folder for live output of the results.\n", + " This Jupyter notebook cell with progress once the search has completed - this could take a few minutes!\n", + " \"\"\"\n", + ")\n", + "\n", + "start = time.time()\n", + "\n", + "result_nan = search.fit(model=model_nan_fit, analysis=analysis_nan_jax)\n", + "\n", + "print(f\"MultiStartAdam run time: {time.time() - start} seconds\")\n", + "print(\"The search has finished run - you may now continue the notebook.\")\n", + "\n", + "summary_path = path.join(str(search.paths.output_path), \"search.summary\")\n", + "\n", + "if path.exists(summary_path):\n", + " with open(summary_path) as summary_file:\n", + " print(summary_file.read())" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The block headed `Resampling Info` is the one we care about, and its two counters mean different things.\n", + "\n", + "`Value-NaN Lane-Steps` counts steps on which the likelihood itself was undefined, which happens whenever a lane\n", + "wanders into the region where `gaussian_1.sigma` is smaller than `gaussian_0.sigma`: the square root of a negative\n", + "number, a `nan` value, replaced by the resample figure of merit.\n", + "\n", + "`Gradient-NaN Lane-Steps` counts something subtler: steps on which the likelihood *value* was fine but its\n", + "*gradient* was not. Such a lane does not die and reports no error. The optimizer sees a non finite update, refuses\n", + "to apply it, and the lane stays exactly where it is, then does the same on the next step. A lane whose gradient is\n", + "`nan` is frozen, and a frozen lane is indistinguishable from a converged one in the figure of merit trace!\n", + "\n", + "`Resurrections` counts lanes restarted from a fresh point after dying, and the rate lines express the counters as a\n", + "fraction of the total lane-steps taken.\n", + "\n", + "The two counters are deliberately disjoint: a step is counted as a gradient-NaN only if its value was finite, so in\n", + "the run above, where every failure was an undefined square root, the gradient-NaN count is zero. Do not read that\n", + "as \"gradient NaNs cannot happen here\". How can a value be finite while its gradient is not? Here is the smallest\n", + "example, and it matters because the same pattern occurs constantly in real likelihood functions." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import jax\n", + "import jax.numpy as jnp\n", + "\n", + "unsafe = lambda x: jnp.where(x > 0.0, jnp.sqrt(x), 0.0)\n", + "\n", + "print(\"Unsafe function at x = -1.0:\")\n", + "print(f\"value = {unsafe(-1.0)}\")\n", + "print(f\"gradient = {jax.grad(unsafe)(-1.0)}\")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The value is `0.0`, exactly as intended, because the `where` selected the safe branch. The gradient is `nan`.\n", + "\n", + "Reverse mode automatic differentiation, which is how JAX computes gradients, differentiates *both* branches of a\n", + "`where` and multiplies the unselected one by zero. The derivative of `sqrt(x)` at `x = -1` is `nan`, and zero times\n", + "`nan` is `nan`, not zero. The mask protected the value and did nothing for the gradient.\n", + "\n", + "The fix is never to evaluate the offending operation at the invalid input, which takes a second `where` inside the\n", + "first. The inner `where` replaces the invalid input with a harmless one, so `sqrt` is only called on a positive\n", + "number, and the outer `where` still selects the right answer." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "safe = lambda x: jnp.where(x > 0.0, jnp.sqrt(jnp.where(x > 0.0, x, 1.0)), 0.0)\n", + "\n", + "print(\"Safe function at x = -1.0:\")\n", + "print(f\"value = {safe(-1.0)}\")\n", + "print(f\"gradient = {jax.grad(safe)(-1.0)}\")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Same value, and now a finite gradient.\n", + "\n", + "The lesson generalizes far beyond this function. A guard that checks the result of a calculation can only protect\n", + "the value, because by the time it runs the damage to the derivative is already recorded. Safety has to live where\n", + "the `nan` is created, not where it is detected.\n", + "\n", + "A good likelihood value does not mean a good gradient!\n", + "\n", + "__Unit Cube Vs Physical__\n", + "\n", + "The last detail is the most fundamental, and it changes how you think about every prior you have written.\n", + "\n", + "In tutorial 1 we mapped a vector of physical parameter values onto a model instance with `instance_from_vector`, and\n", + "in tutorial 3 we gave each parameter a prior. Those ideas are closer than they look, because a non-linear search\n", + "does not work in physical units at all.\n", + "\n", + "What a search explores is the \"unit cube\": a space where every parameter runs from 0.0 to 1.0, whatever it means and\n", + "whatever units it has, and the prior is the function converting a unit value into a physical one. **PyAutoFit**\n", + "exposes this mapping directly, so let's build a model with three deliberately different priors and ask what the\n", + "exact centre of the unit cube corresponds to." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model_cube = af.Model(Gaussian)\n", + "\n", + "model_cube.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + "model_cube.normalization = af.LogUniformPrior(lower_limit=1e-2, upper_limit=1e2)\n", + "model_cube.sigma = af.GaussianPrior(mean=10.0, sigma=5.0)\n", + "\n", + "print(model_cube.model_component_and_parameter_names)\n", + "\n", + "print(\"Physical vector at the centre of the unit cube:\")\n", + "print(model_cube.vector_from_unit_vector(unit_vector=[0.5, 0.5, 0.5]))\n", + "\n", + "instance_cube = model_cube.instance_from_unit_vector(unit_vector=[0.5, 0.5, 0.5])\n", + "\n", + "print(f\"Centre = {instance_cube.centre}\")\n", + "print(f\"Normalization = {instance_cube.normalization}\")\n", + "print(f\"Sigma = {instance_cube.sigma}\")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Look carefully at the second number. A unit value of 0.5 mapped `centre` to 50.0, which is what you would expect\n", + "from a `UniformPrior` between 0.0 and 100.0. But the same unit value mapped `normalization` to 1.0, not 50.005.\n", + "\n", + "That is because a `LogUniformPrior` between 0.01 and 100.0 puts the *geometric* midpoint at the centre of the cube,\n", + "and the geometric midpoint of 0.01 and 100.0 is 1.0. Let's see it directly, comparing the two priors a quarter of\n", + "the way through the cube as well." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\n", + " f\"UniformPrior at unit 0.25: {af.UniformPrior(lower_limit=0.0, upper_limit=100.0).value_for(0.25)}\"\n", + ")\n", + "print(\n", + " f\"UniformPrior at unit 0.50: {af.UniformPrior(lower_limit=0.0, upper_limit=100.0).value_for(0.5)}\"\n", + ")\n", + "print(\n", + " f\"LogUniformPrior at unit 0.25: {af.LogUniformPrior(lower_limit=1e-2, upper_limit=1e2).value_for(0.25)}\"\n", + ")\n", + "print(\n", + " f\"LogUniformPrior at unit 0.50: {af.LogUniformPrior(lower_limit=1e-2, upper_limit=1e2).value_for(0.5)}\"\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The uniform prior moves in equal steps of 25.0 across the cube. The log uniform prior moves in equal steps of one\n", + "order of magnitude, from 0.1 a quarter of the way through to 1.0 at halfway.\n", + "\n", + "This is the point of the section. The prior is not a filter applied to a search that would otherwise explore\n", + "physical space evenly, the prior *is* the geometry of the space the search explores. A log uniform prior makes the\n", + "search spend equal effort on each decade, which is what you want for a parameter that could be 0.1 or 100. A\n", + "uniform prior over the same range spends most of its effort above 10.0 and would essentially never propose a value\n", + "below 1.0.\n", + "\n", + "The searches use this differently. Nested samplers work in the unit cube directly, drawing their live points from\n", + "it, which is why they cannot take a starting point and never step outside a prior's range. MLE and MCMC searches\n", + "step in physical units instead, which is why they can walk out of a prior box, and why clipping matters for them\n", + "and not for nested sampling.\n", + "\n", + "Choosing a prior is not just a statement about what you believe. It is a decision about what the search's parameter\n", + "space looks like!\n", + "\n", + "__Summary__\n", + "\n", + "There are many details underneath a model-fit. We have looked at parameterization and mirror solutions, assertions,\n", + "plateaus, the resample figure of merit, `nan` values and their gradients, and the unit cube. There are more, and no\n", + "tutorial could cover them all.\n", + "\n", + "Most of the time, none of them matter. A sensible model, sensible priors and a sensible search give a sensible\n", + "answer, and you could go a whole career without thinking about a single thing in this tutorial. That is a property\n", + "of **PyAutoFit**: the defaults are chosen so the ordinary case works.\n", + "\n", + "When they do matter, attending to them buys three things. Inference runs faster, sometimes by a large factor,\n", + "because the search wastes no effort on redundant regions of parameter space. It converges on the right solution more\n", + "often, because there are fewer wrong places to get stuck. And it protects you from the worst case in model-fitting,\n", + "which is not a fit that crashes but a fit that returns the wrong answer and gives you no reason to doubt it.\n", + "\n", + "The tools in this tutorial are how you get a fit to complain out loud instead of failing quietly!\n", + "\n", + "Tutorial 8 moves on from a single fit to the scientific workflow: how to organise, compare and interpret the many\n", + "fits a real analysis is made of. There is also an optional tutorial on the Bayesian formalism underlying everything\n", + "we have done, which puts the priors, likelihoods and evidences used throughout this chapter on a formal footing." + ] + } + ], + "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" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file diff --git a/notebooks/chapter_1_introduction/tutorial_6_scientific_workflow.ipynb b/notebooks/chapter_1_introduction/tutorial_8_scientific_workflow.ipynb similarity index 96% rename from notebooks/chapter_1_introduction/tutorial_6_scientific_workflow.ipynb rename to notebooks/chapter_1_introduction/tutorial_8_scientific_workflow.ipynb index d916ec4..c24148c 100644 --- a/notebooks/chapter_1_introduction/tutorial_6_scientific_workflow.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_8_scientific_workflow.ipynb @@ -4,8 +4,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Tutorial 6: Scientific Workflow\n", - "==============================\n", + "Tutorial 8: Scientific Workflow\n", + "===============================\n", "\n", "You can now compose a model, fit it to data and interpret its results. A scientific study often repeats\n", "these steps for many datasets, competing models and different non-linear searches. The next challenge is\n", diff --git a/notebooks/chapter_1_introduction/tutorial_optional_bayesian_formalism.ipynb b/notebooks/chapter_1_introduction/tutorial_optional_bayesian_formalism.ipynb new file mode 100644 index 0000000..fcd6463 --- /dev/null +++ b/notebooks/chapter_1_introduction/tutorial_optional_bayesian_formalism.ipynb @@ -0,0 +1,786 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Tutorial Optional: Bayesian Formalism\n", + "=====================================\n", + "\n", + "Every tutorial in this chapter has been an exercise in Bayesian inference, and not one of them wrote down a single\n", + "equation of probability theory. That was deliberate. The **HowToFit** lectures are built on the conviction that you\n", + "can learn to fit models to data properly, and interpret the results correctly, without first sitting through a\n", + "course on Bayesian statistics.\n", + "\n", + "This optional tutorial writes those equations down anyway.\n", + "\n", + "Nothing in it will make your fits better. What it does is connect the phenomenological picture built up over\n", + "tutorials 1 to 7 -- guessing models, likelihood surfaces, walkers, live points, gradients -- to the handful of\n", + "symbols that papers and documentation use for exactly the same things. When a referee asks whether you quoted the\n", + "maximum likelihood model or the median of the marginalized posterior, this tutorial tells you they are talking\n", + "about quantities you have already computed.\n", + "\n", + "My suggestion is to read it once, run it once, and then forget most of it.\n", + "\n", + "__Contents__\n", + "\n", + "This tutorial is split into the following sections:\n", + "\n", + "- **Bayes Theorem**: The equation that every tutorial so far has been solving without writing it down.\n", + "- **Data**: Load the 1D Gaussian dataset that every equation in this tutorial is evaluated on.\n", + "- **The Model**: The parameters of tutorial 1 as the thing Bayes' theorem is about.\n", + "- **The Likelihood**: Why the chi-squared and noise normalization of tutorial 2 are the log of a Gaussian likelihood.\n", + "- **The Prior**: The priors of tutorial 3 as a probability distribution, and the unit cube as its inverse.\n", + "- **The Posterior**: The samples of tutorial 5 as draws from the posterior, and a numerical check that log prior plus log likelihood is the log posterior.\n", + "- **Maximum Likelihood Vs Maximum A Posteriori**: Two different \"best-fit\" answers and when they differ.\n", + "- **Marginalization**: The one-dimensional PDFs and errors of tutorial 5 as integrals over the other parameters.\n", + "- **The Evidence**: The Bayesian evidence of tutorial 5 as the normalization of Bayes' theorem, and why nested sampling computes it.\n", + "- **Gradients**: The gradient of tutorial 6 as the derivative of the log posterior.\n", + "- **Wrap Up**: Why HowToFit hides the maths, and why it helps to know it anyway.\n", + "\n", + "__Bayes Theorem__\n", + "\n", + "Here is the equation that every tutorial in this chapter has been solving without ever writing it down:\n", + "\n", + "\\[ P(\\theta \\mid D) = \\frac{P(D \\mid \\theta)\\,P(\\theta)}{P(D)} \\]\n", + "\n", + "Where:\n", + "\n", + "- \\( \\theta \\): the model parameters, for our 1D Gaussian the three numbers `centre`, `normalization` and `sigma`.\n", + "\n", + "- \\( D \\): the data, for us the 1D array of 100 values loaded from `data.json` together with its noise-map.\n", + "\n", + "- \\( P(\\theta \\mid D) \\): the \"posterior\", the probability of the parameters given the data, and the quantity we\n", + " actually want.\n", + "\n", + "- \\( P(D \\mid \\theta) \\): the \"likelihood\", the probability of the data given the parameters, computed by the\n", + " `log_likelihood_function` of tutorial 3 before we take its logarithm.\n", + "\n", + "- \\( P(\\theta) \\): the \"prior\", the probability we assign to parameter values before looking at the data, the\n", + " `UniformPrior` and `LogUniformPrior` objects of tutorial 3.\n", + "\n", + "- \\( P(D) \\): the \"evidence\", a single number which normalizes the right hand side, the `log_evidence` of tutorial 5.\n", + "\n", + "In plain words: the answer we want is the goodness-of-fit multiplied by our prior beliefs, divided by a normalizing\n", + "number. Every algorithm in this chapter is a strategy for evaluating the right hand side without ever computing the\n", + "integral hiding inside \\( P(D) \\).\n", + "\n", + "Each tutorial supplied exactly one piece. Tutorial 1 built \\( \\theta \\) and the forward model. Tutorial 2 built\n", + "\\( P(D \\mid \\theta) \\), calling it the log likelihood. Tutorial 3 built \\( P(\\theta) \\) and the searches which\n", + "explore the product of the two. Tutorial 4 showed what goes wrong when the posterior has more than one peak,\n", + "tutorial 5 read the answer back out, and tutorials 6 and 7 differentiated it and asked what the numbers mean.\n", + "\n", + "So when this tutorial says \"the posterior\", you have already computed one. We are only relabelling." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Google Colab Setup__\n", + "\n", + "This cell sets up the environment when the notebook is run on Google Colab: it installs the\n", + "required PyAuto packages, clones the workspace (configuration files and example datasets) and\n", + "points the configuration at it. If you are running the notebook elsewhere (e.g. locally via\n", + "your own installation) it does nothing, and you can run it safely.\n", + "\n", + "Colab tip: model-fits run much faster on a GPU \u2014 enable one via \"Runtime\" -> \"Change runtime\n", + "type\" -> \"Hardware accelerator\" before running the notebook." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "try:\n", + " import google.colab\n", + "except ImportError:\n", + " from autofit 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(\"howtofit\")" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from autofit import setup_notebook; setup_notebook()\n", + "\n", + "from os import path\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "import scipy.stats\n", + "\n", + "import autofit as af" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Data__\n", + "\n", + "We use the same `gaussian_x1` dataset that tutorials 2 and 3 fitted, so every equation below is evaluated on a fit\n", + "you have already seen." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "dataset_path = path.join(\"dataset\", \"example_1d\", \"gaussian_x1\")" + ], + "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 not path.exists(dataset_path):\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.run(\n", + " [sys.executable, \"scripts/simulators/simulators.py\"],\n", + " check=True,\n", + " )\n", + "\n", + "data = af.util.numpy_array_from_json(file_path=path.join(dataset_path, \"data.json\"))\n", + "noise_map = af.util.numpy_array_from_json(\n", + " file_path=path.join(dataset_path, \"noise_map.json\")\n", + ")\n", + "\n", + "xvalues = np.arange(data.shape[0])" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__The Model__\n", + "\n", + "The symbol \\( \\theta \\) is nothing more exotic than the list of numbers you passed to `instance_from_vector` in\n", + "tutorial 1. Bayes' theorem is a statement about a probability distribution over that list, and nothing else.\n", + "\n", + "We therefore begin as tutorial 1 did, by re-pasting the `Gaussian` class in full. Its constructor arguments are the\n", + "entries of \\( \\theta \\), and its `model_data_from` method is the forward model: the function which, given\n", + "\\( \\theta \\), predicts what the data should look like." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "class Gaussian:\n", + " def __init__(\n", + " self,\n", + " centre: float = 30.0, # <- **PyAutoFit** recognises these constructor arguments\n", + " normalization: float = 1.0, # <- are the Gaussian`s model parameters.\n", + " sigma: float = 5.0,\n", + " ):\n", + " \"\"\"\n", + " Represents a 1D Gaussian profile.\n", + "\n", + " This is a model-component of example models in the **HowToFit** lectures and is used to perform model-fitting\n", + " of example datasets.\n", + "\n", + " Parameters\n", + " ----------\n", + " centre\n", + " The x coordinate of the profile centre.\n", + " normalization\n", + " Overall normalization of the profile.\n", + " sigma\n", + " The sigma value controlling the size of the Gaussian.\n", + " \"\"\"\n", + " self.centre = centre\n", + " self.normalization = normalization\n", + " self.sigma = sigma\n", + "\n", + " def model_data_from(self, xvalues: np.ndarray) -> np.ndarray:\n", + " \"\"\"\n", + " Returns a 1D Gaussian on an input list of Cartesian x coordinates.\n", + "\n", + " The input xvalues are translated to a coordinate system centred on the Gaussian, via its `centre`.\n", + "\n", + " The output is referred to as the `model_data` to signify that it is a representation of the data from the\n", + " model.\n", + "\n", + " Parameters\n", + " ----------\n", + " xvalues\n", + " The x coordinates in the original reference frame of the data.\n", + "\n", + " Returns\n", + " -------\n", + " np.array\n", + " The Gaussian values at the input x coordinates.\n", + " \"\"\"\n", + " transformed_xvalues = np.subtract(xvalues, self.centre)\n", + " return np.multiply(\n", + " np.divide(self.normalization, self.sigma * np.sqrt(2.0 * np.pi)),\n", + " np.exp(-0.5 * np.square(np.divide(transformed_xvalues, self.sigma))),\n", + " )\n" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Composing the model gives the two pieces of book-keeping which make \\( \\theta \\) concrete. The `prior_count` is the\n", + "number of dimensions the posterior is a distribution over, and `paths` gives the order of the entries in the vector." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model = af.Model(Gaussian)\n", + "\n", + "print(\"Number of parameters in theta:\", model.prior_count)\n", + "print(\"Order of the parameters in theta:\", model.paths)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A specific \\( \\theta \\) becomes a model, and the model becomes predicted data, in the two lines below. This is the\n", + "forward modelling of tutorial 1, and it is what lets us ask \"how probable is the data, given these parameters?\"." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "instance = model.instance_from_vector(vector=[50.0, 25.0, 10.0])\n", + "\n", + "model_data = instance.model_data_from(xvalues=xvalues)\n", + "\n", + "plt.errorbar(\n", + " x=xvalues,\n", + " y=data,\n", + " yerr=noise_map,\n", + " linestyle=\"\",\n", + " color=\"k\",\n", + " ecolor=\"k\",\n", + " elinewidth=1,\n", + " capsize=2,\n", + ")\n", + "plt.plot(xvalues, model_data, color=\"r\")\n", + "plt.title(\"The data D, with the forward model prediction for one theta.\")\n", + "plt.xlabel(\"x values of profile\")\n", + "plt.ylabel(\"Profile normalization\")\n", + "plt.show()\n", + "plt.close()" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__The Likelihood__\n", + "\n", + "In tutorial 2 we built a chain of quantities -- residuals, a chi-squared and a noise normalization -- and combined\n", + "the last two into a log likelihood by multiplying their sum by -0.5. At the time I said the reason for the -0.5 was\n", + "not critical. Here it is.\n", + "\n", + "We assume each data point is its predicted value plus a random draw from a Gaussian of width equal to that point's\n", + "noise. The probability of the whole dataset is then a product of one Gaussian probability per data point:\n", + "\n", + "\\[ P(D \\mid \\theta) = \\prod_i \\frac{1}{\\sqrt{2\\pi\\sigma_i^2}} \\exp\\left(-\\frac{(d_i - m_i)^2}{2\\sigma_i^2}\\right) \\]\n", + "\n", + "Taking the logarithm turns that product into a sum:\n", + "\n", + "\\[ \\ln P(D \\mid \\theta) = -\\frac{1}{2} \\sum_i \\frac{(d_i - m_i)^2}{\\sigma_i^2} - \\frac{1}{2} \\sum_i \\ln(2\\pi\\sigma_i^2) \\]\n", + "\n", + "Where:\n", + "\n", + "- \\( d_i \\): the value of the data at point \\( i \\), the `data` array.\n", + "\n", + "- \\( m_i \\): the value of the model data at point \\( i \\), computed by `model_data_from` for this \\( \\theta \\).\n", + "\n", + "- \\( \\sigma_i \\): the noise at point \\( i \\), the `noise_map` array.\n", + "\n", + "Compare the second equation with tutorial 2 line by line. The first sum is the `chi_squared`, and the second is the\n", + "`noise_normalization`, the log of the product of the Gaussian prefactors. Both are multiplied by -0.5, which is\n", + "where the mysterious factor comes from: it is not a convention, it is the 2 in the denominator of the exponent of a\n", + "Gaussian. The noise normalization really is a constant, because it depends only on the noise-map and never on\n", + "\\( \\theta \\), so it shifts every log likelihood equally and can never change which model wins.\n", + "\n", + "Below we compute the log likelihood twice: by tutorial 2's chi-squared route, and by summing the log of a Gaussian\n", + "probability density at every data point using `scipy`. They are the same number." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "residual_map = data - model_data\n", + "chi_squared = np.sum((residual_map / noise_map) ** 2.0)\n", + "noise_normalization = np.sum(np.log(2 * np.pi * noise_map**2.0))\n", + "\n", + "log_likelihood = -0.5 * (chi_squared + noise_normalization)\n", + "\n", + "log_likelihood_via_pdf = np.sum(\n", + " scipy.stats.norm.logpdf(data, loc=model_data, scale=noise_map)\n", + ")\n", + "\n", + "print(\"Log likelihood via tutorial 2's chi-squared = \", log_likelihood)\n", + "print(\"Log likelihood via a sum of Gaussian PDFs = \", log_likelihood_via_pdf)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__The Prior__\n", + "\n", + "The priors of tutorial 3 were introduced as a way of telling the search where to look. Formally they are\n", + "\\( P(\\theta) \\), a probability distribution over the parameters written down before we look at the data. Because our\n", + "parameters are independent, the prior is a product of one distribution per parameter and its logarithm is a sum,\n", + "\\( \\ln P(\\theta) = \\sum_j \\ln P(\\theta_j) \\).\n", + "\n", + "The two priors on the default `Gaussian` model have simple forms. A `UniformPrior` is constant inside its limits and\n", + "zero outside them, so its log is a constant we may set to zero inside and negative infinity outside. A\n", + "`LogUniformPrior` is proportional to \\( 1 / \\theta_j \\), the statement \"every order of magnitude is equally likely\",\n", + "so its log falls off as \\( -\\ln \\theta_j \\).\n", + "\n", + "**PyAutoFit** hands you those numbers directly. Below we print the priors of the model, then evaluate the log prior\n", + "of each parameter inside the prior limits, and then for a `centre` of 150.0 which lies outside the `UniformPrior`\n", + "limits of 0.0 to 100.0." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(model.info)\n", + "\n", + "print(\"Log prior of each parameter, theta = [50.0, 25.0, 10.0]:\")\n", + "print(model.log_prior_list_from_vector(vector=[50.0, 25.0, 10.0]))\n", + "\n", + "print(\"Log prior of each parameter, theta = [150.0, 25.0, 10.0]:\")\n", + "print(model.log_prior_list_from_vector(vector=[150.0, 25.0, 10.0]))" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The first entry of the second list is `-inf`, an infinitely improbable model. This is the formal version of tutorial\n", + "3's statement that priors define the valid parameter space: a model outside the priors is not penalised, it is\n", + "excluded. The middle entry is not zero, because the `LogUniformPrior` on `normalization` prefers smaller values and\n", + "\\( -\\ln(25) \\) is about -3.2.\n", + "\n", + "Priors enter a fit a second way, and it is how nested sampling works. Every prior can be inverted: instead of asking\n", + "\"how probable is this value?\", we ask \"which value sits at this fraction of the distribution?\". That inverse is the\n", + "inverse cumulative distribution function, and in **PyAutoFit** it is the `value_for` method, which maps a number\n", + "between 0 and 1 -- the \"unit cube\" -- onto a physical parameter value. Feeding in 0.5 asks each prior for its\n", + "median, and the lines below show why a unit value is not the same thing as a parameter value." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "uniform_prior = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\n", + "log_uniform_prior = af.LogUniformPrior(lower_limit=1e-2, upper_limit=1e2)\n", + "gaussian_prior = af.GaussianPrior(mean=10.0, sigma=5.0)\n", + "\n", + "print(\"UniformPrior(0.0, 100.0).value_for(0.5) = \", uniform_prior.value_for(0.5))\n", + "print(\n", + " \"LogUniformPrior(0.01, 100.0).value_for(0.5) = \", log_uniform_prior.value_for(0.5)\n", + ")\n", + "print(\n", + " \"GaussianPrior(mean=10, sigma=5).value_for(0.5) = \", gaussian_prior.value_for(0.5)\n", + ")\n", + "\n", + "print(\"The whole model, unit cube [0.5, 0.5, 0.5] mapped to physical values:\")\n", + "print(model.vector_from_unit_vector(unit_vector=[0.5, 0.5, 0.5]))" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This is the key to a sentence in tutorial 3 which may have seemed arbitrary: nested sampling \"draws live points from\n", + "the priors\". A search which picks unit values uniformly at random between 0 and 1 and passes them through\n", + "`value_for` is drawing samples from the prior distribution itself. It is also why a nested sampling search cannot be\n", + "given a starting point: its first step is defined to be a draw from \\( P(\\theta) \\).\n", + "\n", + "__The Posterior__\n", + "\n", + "We now have both pieces of the numerator of Bayes' theorem, so we can fit the model and look at the left hand side.\n", + "The `Analysis` class below is the one from tutorial 3, whose `log_likelihood_function` returns exactly the equation\n", + "verified above, and we fit it with the nested sampling search of tutorial 3." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "class Analysis(af.Analysis):\n", + " def __init__(self, data: np.ndarray, noise_map: np.ndarray):\n", + " \"\"\"\n", + " The `Analysis` class acts as an interface between the data and model in **PyAutoFit**, exactly as it did in\n", + " tutorial 3.\n", + "\n", + " Parameters\n", + " ----------\n", + " data\n", + " A 1D numpy array containing the data (e.g. a noisy 1D signal) fitted in the workspace examples.\n", + " noise_map\n", + " A 1D numpy array containing the noise values of the data.\n", + " \"\"\"\n", + " super().__init__()\n", + "\n", + " self.data = data\n", + " self.noise_map = noise_map\n", + "\n", + " def log_likelihood_function(self, instance) -> float:\n", + " \"\"\"\n", + " Returns the log likelihood of a fit of a 1D Gaussian to the dataset, which is the log of a product of\n", + " Gaussian probabilities, one per data point, as derived in the `The Likelihood` section above.\n", + " \"\"\"\n", + " xvalues = np.arange(self.data.shape[0])\n", + "\n", + " model_data = instance.model_data_from(xvalues=xvalues)\n", + " residual_map = self.data - model_data\n", + " chi_squared_map = (residual_map / self.noise_map) ** 2.0\n", + " chi_squared = np.sum(chi_squared_map)\n", + " noise_normalization = np.sum(np.log(2 * np.pi * self.noise_map**2.0))\n", + "\n", + " return -0.5 * (chi_squared + noise_normalization)\n", + "\n", + "\n", + "analysis = Analysis(data=data, noise_map=noise_map)\n", + "\n", + "search = af.DynestyStatic(\n", + " sample=\"rwalk\", # This makes dynesty run faster, dont worry about what it means for now!\n", + ")\n", + "\n", + "print(\n", + " \"\"\"\n", + " The non-linear search has begun running.\n", + " This Jupyter notebook cell with progress once the search has completed - this could take a few minutes!\n", + " \"\"\"\n", + ")\n", + "\n", + "model = af.Model(Gaussian)\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": [ + "The `Samples` object of tutorial 5 is the posterior. Each entry of `parameter_lists` is a \\( \\theta \\) the search\n", + "accepted, and each entry of `weight_list` says how much that sample counts when the posterior is summed up. Together\n", + "they approximate \\( P(\\theta \\mid D) \\): a cloud of points, denser where the posterior is higher.\n", + "\n", + "Tutorial 5 also told you, without justification, that the log posterior is the log likelihood plus the log prior.\n", + "That is Bayes' theorem logged, with the evidence dropped because it is the same number for every sample:\n", + "\n", + "\\[ \\ln P(\\theta \\mid D) = \\ln P(D \\mid \\theta) + \\ln P(\\theta) - \\ln P(D) \\]\n", + "\n", + "Below we check the first few samples, printing the log likelihood, log prior, log posterior, and the difference\n", + "between the log posterior and the sum of the first two." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "samples = result.samples\n", + "\n", + "total_printed = min(5, len(samples.log_likelihood_list))\n", + "\n", + "print(\"Sample : log likelihood : log prior : log posterior : difference\")\n", + "\n", + "for sample_index in range(total_printed):\n", + " log_likelihood = samples.log_likelihood_list[sample_index]\n", + " log_prior = samples.log_prior_list[sample_index]\n", + " log_posterior = samples.log_posterior_list[sample_index]\n", + "\n", + " print(\n", + " sample_index,\n", + " log_likelihood,\n", + " log_prior,\n", + " log_posterior,\n", + " log_posterior - (log_likelihood + log_prior),\n", + " )" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The final column is zero. There is no approximation in that identity, it is the definition of the log posterior, and\n", + "it means every number tutorial 5 printed was already a Bayesian quantity. Note also how much larger the log\n", + "likelihoods are than the log priors: for this fit the data is far more informative than our prior beliefs.\n", + "\n", + "__Maximum Likelihood Vs Maximum A Posteriori__\n", + "\n", + "There are two \"best-fit\" models hiding in a set of samples, and tutorial 5 printed both without saying they could\n", + "disagree:\n", + "\n", + "- The \"maximum likelihood\" model, `samples.max_log_likelihood()`, is the \\( \\theta \\) fitting the data best,\n", + " ignoring the priors entirely.\n", + "\n", + "- The \"maximum a posteriori\" model, usually shortened to MAP, `samples.max_log_posterior()`, is the \\( \\theta \\)\n", + " which maximizes likelihood times prior.\n", + "\n", + "If every prior is uniform the log prior is the same constant inside the limits, so the two are the same model. They\n", + "separate only when a prior varies appreciably across the region the data allows." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Maximum likelihood theta = \", samples.max_log_likelihood(as_instance=False))\n", + "print(\"Maximum a posteriori theta = \", samples.max_log_posterior(as_instance=False))" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For this fit they agree, or very nearly, because the log-uniform prior on `normalization` is almost flat over the\n", + "tiny range of normalizations the data permits. Had we instead placed a tight Gaussian prior on `centre`, say a mean\n", + "of 49.0 with a sigma of 0.05, the log prior would fall away steeply across the region the data allows and the MAP\n", + "model would be pulled towards 49.0, away from what the data alone prefers.\n", + "\n", + "Neither answer is wrong, they answer different questions, and a paper quoting one while calling it the other is\n", + "making a real mistake. It is also why most results are quoted as neither, but as the median of the marginalized\n", + "posterior.\n", + "\n", + "__Marginalization__\n", + "\n", + "Tutorial 5 quoted a value and an error for each parameter individually, and plotted their 1D histograms via\n", + "`aplt.corner_cornerpy`. That requires an operation with a formal name, \"marginalization\", which means integrating\n", + "the posterior over the parameters you are not currently interested in:\n", + "\n", + "\\[ P(\\theta_1 \\mid D) = \\int P(\\theta \\mid D) \\, d\\theta_2 \\, d\\theta_3 \\ldots \\]\n", + "\n", + "Where:\n", + "\n", + "- \\( \\theta_1 \\): the parameter we want a one-dimensional answer for, for example `centre`.\n", + "\n", + "- \\( \\theta_2, \\theta_3, \\ldots \\): every other parameter of the model, integrated away.\n", + "\n", + "That integral looks intimidating, and done analytically it would be. This is the greatest practical advantage of\n", + "having samples: marginalizing them means ignoring the columns you do not care about and histogramming the one you\n", + "do, weighted by `weight_list`. The integral becomes a counting exercise, and the cell below marginalizes over\n", + "`normalization` and `sigma` by never mentioning them." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "centre_list = [parameters[0] for parameters in samples.parameter_lists]\n", + "\n", + "plt.hist(centre_list, bins=30, weights=samples.weight_list, color=\"k\")\n", + "plt.title(\"Marginalized 1D posterior of the Gaussian's centre.\")\n", + "plt.xlabel(\"centre of the Gaussian\")\n", + "plt.ylabel(\"Posterior probability\")\n", + "plt.show()\n", + "plt.close()" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Every summary statistic of tutorial 5 is read off that curve. The `median_pdf` value is the point with half the\n", + "weight either side of it, and the values at a given sigma are the points enclosing the corresponding fraction of it,\n", + "68 per cent at one sigma." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Median of the marginalized posterior:\")\n", + "print(samples.median_pdf(as_instance=False))\n", + "\n", + "print(\"Values at 1.0 sigma confidence (lower, upper) for each parameter:\")\n", + "print(samples.values_at_sigma(sigma=1.0, as_instance=False))" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__The Evidence__\n", + "\n", + "The one term of Bayes' theorem we have ignored is the denominator, \\( P(D) \\), the evidence. It is the integral of\n", + "the numerator over the whole of parameter space:\n", + "\n", + "\\[ P(D) = \\int P(D \\mid \\theta) \\, P(\\theta) \\, d\\theta \\]\n", + "\n", + "Where:\n", + "\n", + "- The integral runs over every value of every parameter the priors allow.\n", + "\n", + "Two facts about this integral explain a lot of what you have seen. First, it does not depend on \\( \\theta \\), which\n", + "is why MCMC never needs it: a walker deciding whether to move compares posteriors as a ratio and the evidence\n", + "cancels. Second, it is genuinely hard, an integral over a many-dimensional space in which almost all of the volume\n", + "contributes almost nothing.\n", + "\n", + "Nested sampling gets it almost for free, and this is the real reason the algorithm is built the way it is. Tutorial\n", + "3 described it as replacing the lowest-likelihood live point over and over, and each replacement shrinks the prior\n", + "volume still under consideration by a known factor, so summing likelihood times shrinking volume as it goes is the\n", + "integral above. The parameter estimates are the by-product, the evidence is what the method actually computes, and\n", + "because it penalises models which spread their prior probability over regions the data rejects, comparing the\n", + "evidence of two models is the Bayesian way to ask whether extra parameters were worth adding." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "log_evidence = samples.log_evidence\n", + "\n", + "if log_evidence is not None:\n", + " print(\"Log evidence of this model = \", log_evidence)\n", + "else:\n", + " print(\"This search does not compute a Bayesian evidence, so log_evidence is None.\")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Gradients__\n", + "\n", + "Tutorial 6 introduced the gradient: the direction in which the log likelihood increases fastest, computed exactly by\n", + "automatic differentiation. In this notation, what the gradient searches climb is the derivative of the log\n", + "posterior:\n", + "\n", + "\\[ \\nabla_\\theta \\ln P(\\theta \\mid D) = \\nabla_\\theta \\ln P(D \\mid \\theta) + \\nabla_\\theta \\ln P(\\theta) \\]\n", + "\n", + "Where:\n", + "\n", + "- \\( \\nabla_\\theta \\): the vector of derivatives with respect to each parameter in turn.\n", + "\n", + "The evidence has vanished, and its disappearance is the point. Because \\( \\ln P(D) \\) does not depend on\n", + "\\( \\theta \\), differentiating it gives zero: the hardest term in Bayes' theorem is invisible to any method which\n", + "only ever looks at slopes.\n", + "\n", + "This is the formal reason gradient methods scale so well. Hamiltonian Monte Carlo and its self-tuning variant NUTS,\n", + "which tutorial 6 introduced, use this gradient to propose moves following the contours of the posterior rather than\n", + "stumbling across them at random. In many dimensions, knowing which way is uphill is worth an enormous number of the\n", + "blind guesses tutorial 4 showed we could not afford to make.\n", + "\n", + "There is no code here, because the numbers were computed in tutorial 6. All that is new is the name of the quantity\n", + "being differentiated.\n", + "\n", + "__Wrap Up__\n", + "\n", + "The **HowToFit** lectures teach model-fitting without formal statistics on purpose. Most scientists who fit models\n", + "to data do not need the equations to do it well: they need to know what a log likelihood measures, why priors\n", + "matter, which search suits their problem and how to tell a good fit from a bad one. Every one of those lessons was\n", + "taught in this chapter without an integral in sight.\n", + "\n", + "Knowing the formalism afterwards is still worth an hour of your time. It tells you that the maximum likelihood model\n", + "and the median of the marginalized posterior answer different questions, and what the log evidence in `result.info`\n", + "is an integral of. And it lets you read a methods section, where these quantities go by their symbols rather than\n", + "their attribute names.\n", + "\n", + "So, with your own problem in mind:\n", + "\n", + "- Which of the two \"best-fit\" answers above is the one your field quotes, and is it the one you have been quoting?\n", + "\n", + "- How informative are your priors compared with your data, and would your results change if someone else chose them?\n", + "\n", + "- Is there a question in your science which is really a model comparison, and therefore really about the evidence?\n", + "\n", + "If you are unsure, that is fine, and it is no obstacle to fitting models. Go back to tutorial 5, run a fit and look\n", + "at the numbers again. They will mean a little more than they did before." + ] + } + ], + "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" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file diff --git a/scripts/README.md b/scripts/README.md index e8ed038..4d4d138 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -2,7 +2,7 @@ The `scripts` folder contains **HowToFit** lectures, which teach a new user how # Folders -- `chapter_1_introduction`: Introduction lectures describing how to compose and fit models in **PyAutoFit**, ending with a prose-only introduction to scientific workflows. +- `chapter_1_introduction`: Introduction lectures describing how to compose and fit models in **PyAutoFit**, use gradients to fit them more efficiently and handle the details that make a fit succeed or fail, ending with a prose-only introduction to scientific workflows and an optional tutorial on the Bayesian formalism. - `chapter_3_graphical_models`: How to compose and fit graphical models which fit many datasets simultaneously, including hierarchical models and Expectation Propagation. - `simulators`: Simulator scripts that generate the tutorial 1D datasets at runtime. @@ -55,6 +55,8 @@ able to: 4. Fit a model to data using a non-linear search. 5. Compose and fit more complex models using **PyAutoFit**'s model composition API. 6. Analyse the results of a model-fit, including parameter estimates and errors. +7. Use gradients of the log likelihood, computed with JAX automatic differentiation, to fit models with gradient based searches. +8. Recognise and fix the details that make a fit fail: degenerate parameterizations, plateaus, clipping and NaNs, and the unit cube. # Overview of Chapter 3 (Advanced) diff --git a/scripts/chapter_1_introduction/README.md b/scripts/chapter_1_introduction/README.md index fa87227..bb1c995 100644 --- a/scripts/chapter_1_introduction/README.md +++ b/scripts/chapter_1_introduction/README.md @@ -17,4 +17,10 @@ The chapter contains the following tutorials: - [Tutorial 5: Results and Samples](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.8.1/notebooks/chapter_1_introduction/tutorial_5_results_and_samples.ipynb) — Interpreting model-fit results and using the samples for scientific analysis. -- [Tutorial 6: Scientific Workflow](../../notebooks/chapter_1_introduction/tutorial_6_scientific_workflow.ipynb) — A prose-only introduction to organizing and comparing many fits, with links to the full guide and workspace example. +- [Tutorial 6: Gradients](../../notebooks/chapter_1_introduction/tutorial_6_gradients.ipynb) — How gradients tell a search which way is up, JAX autodiff, and how gradients change MLE, MCMC and nested sampling. + +- [Tutorial 7: The Details](../../notebooks/chapter_1_introduction/tutorial_7_the_details.ipynb) — Parameterization, plateaus, assertions, clipping, NaN diagnostics and the unit cube — the details that decide whether a fit converges. + +- [Tutorial 8: Scientific Workflow](../../notebooks/chapter_1_introduction/tutorial_8_scientific_workflow.ipynb) — A prose-only introduction to organizing and comparing many fits, with links to the full guide and workspace example. + +- [Tutorial Optional: Bayesian Formalism](../../notebooks/chapter_1_introduction/tutorial_optional_bayesian_formalism.ipynb) — How everything in chapter 1 maps onto Bayes' theorem. diff --git a/scripts/chapter_1_introduction/start_here.py b/scripts/chapter_1_introduction/start_here.py index 7e4fda7..4fe6fbb 100644 --- a/scripts/chapter_1_introduction/start_here.py +++ b/scripts/chapter_1_introduction/start_here.py @@ -21,8 +21,9 @@ The HowToFit lectures cover an introductory chapter and an advanced chapter: -**Chapter 1: Introduction**: How to fit a model to data, perform statistical inference, and interpret the results -for scientific analysis, ending with an introduction to scientific workflows. +**Chapter 1: Introduction**: How to fit a model to data, perform statistical inference, interpret the results +for scientific analysis and use gradients to fit models more efficiently, ending with an introduction to +scientific workflows. **Chapter 3: Graphical Models**: Simultaneous model fitting of large datasets, scaling up to models with tens of thousands of parameters. @@ -45,9 +46,17 @@ `tutorial_5_results_and_samples.py`: Interpreting model-fit results and using the samples for scientific analysis. -`tutorial_6_scientific_workflow.py`: A short, prose-only introduction to organizing and comparing many model fits, +`tutorial_6_gradients.py`: How gradients tell a search which way is up, JAX autodiff, and how gradients change +MLE, MCMC and nested sampling. + +`tutorial_7_the_details.py`: Parameterization, plateaus, assertions, clipping, NaN diagnostics and the unit cube, +the details that decide whether a fit converges. + +`tutorial_8_scientific_workflow.py`: A short, prose-only introduction to organizing and comparing many model fits, with links to the scientific workflow guide and workspace example. +`tutorial_optional_bayesian_formalism.py`: How everything in chapter 1 maps onto Bayes' theorem. + An applied astronomy-focused example (previously tutorial 8) now lives in `autofit_workspace_developer/scripts/howtofit/chapter_1_introduction/tutorial_8_astronomy_example.py`, alongside the larger `autofit_workspace_developer/projects/cosmology/` example. These depend on astronomy-specific datasets diff --git a/scripts/chapter_1_introduction/tutorial_6_gradients.py b/scripts/chapter_1_introduction/tutorial_6_gradients.py new file mode 100644 index 0000000..f6c7bcd --- /dev/null +++ b/scripts/chapter_1_introduction/tutorial_6_gradients.py @@ -0,0 +1,919 @@ +""" +Tutorial 6: Gradients +===================== + +In tutorial 3, describing how a maximum likelihood estimator works, we said it "evaluates the likelihood at nearby +points to estimate the gradient, determining the direction in which to move up in parameter space". That sentence +slipped by quickly, but it hides one of the most important ideas in model-fitting: the search does not have to be +blind, because the likelihood surface has a slope, and the slope tells us which way is up. + +In tutorial 5 we saw the other half of the story: errors, computed by marginalizing over the Probability Density +Function of the samples. Errors came from samples, and samples are expensive. Here we make the gradient explicit, +hand it to three types of non-linear search, and end by computing errors without drawing a single sample. + +__Overview__ + +In this tutorial, we will introduce gradients and use them to fit a 1D Gaussian profile to noisy data. Specifically, +we will: + +- Introduce the "gradient" of the log likelihood and plot it on a slice through parameter space. + +- Compute a gradient by "finite differencing", and see why the answer depends on the step size. + +- Use JAX to differentiate the `log_likelihood_function` exactly, via "automatic differentiation". + +- Compare searches which use gradients with those which do not. + +- Estimate errors from the second derivatives of the log likelihood. + +__Contents__ + +This tutorial is split into the following sections: + +- **Data**: Load and plot the 1D Gaussian dataset fitted throughout the chapter. +- **Model**: The `Gaussian` model component, now written so it can run on NumPy or JAX. +- **Analysis**: The `Analysis` class with a log likelihood function that can be differentiated. +- **Gradients**: Extending the parameter-space picture of tutorial 3 with the idea that a search can know which way "up" is at every point. +- **Finite Differencing**: Computing a gradient numerically by nudging each parameter and re-evaluating the likelihood. +- **JAX and Autodiff**: Why analytic gradients are impractical, and how JAX differentiates the likelihood function under the hood. +- **Maximum Likelihood Estimation (MLE)**: Comparing a finite-difference optimizer (`LBFGS`) with a multi-start autodiff optimizer (`MultiStartAdam`). +- **Markov Chain Monte Carlo (MCMC)**: Comparing walkers that ignore gradients (`Emcee`) with Hamiltonian sampling that follows them (`BlackJAXNUTS`). +- **Nested Sampling**: Why nested sampling does not use gradients, and how JAX still speeds it up (`Nautilus`). +- **Errors From Curvature**: Using second derivatives at the maximum likelihood solution to estimate parameter errors and comparing them with the errors from samples in tutorial 5. +- **Wrap Up**: Concluding the tutorial with a recap of how gradients change each search. +""" + +# from autofit import setup_notebook; setup_notebook() + +from os import path +import matplotlib.pyplot as plt +import numpy as np + +import autofit as af +import autofit.plot as aplt + +""" +__Data__ + +Load and plot the dataset from the `HowToFit/dataset` folder. +""" +dataset_path = path.join("dataset", "example_1d", "gaussian_x1") + +""" +__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 not path.exists(dataset_path): + import subprocess + import sys + + subprocess.run( + [sys.executable, "scripts/simulators/simulators.py"], + check=True, + ) + +data = af.util.numpy_array_from_json(file_path=path.join(dataset_path, "data.json")) +noise_map = af.util.numpy_array_from_json( + file_path=path.join(dataset_path, "noise_map.json") +) + +xvalues = np.arange(data.shape[0]) + +plt.errorbar( + xvalues, + data, + yerr=noise_map, + linestyle="", + color="k", + ecolor="k", + elinewidth=1, + capsize=2, +) +plt.title("1D Gaussian dataset.") +plt.xlabel("x values of profile") +plt.ylabel("Profile Normalization") +plt.show() +plt.clf() + +""" +__Model__ + +This is the same dataset we fitted in tutorials 2 and 3, whose true parameters are `centre=50.0`, +`normalization=25.0` and `sigma=10.0`. We lean on those values here, because a gradient is always a gradient *at a +point*, and the truth is the most interesting point to stand at. + +We re-paste the `Gaussian` class in full, as the chapter always does. There is exactly one change from tutorials 1 +to 5: `model_data_from` takes an extra argument `xp`, which defaults to `np`, and every operation inside it is +written as `xp.subtract`, `xp.multiply`, `xp.divide`, `xp.sqrt`, `xp.exp` and `xp.square`. The `xp` argument asks +"which array library should I compute with?", and later we pass it a library which gives us gradients for free. +""" + + +class Gaussian: + def __init__( + self, + centre: float = 30.0, # <- **PyAutoFit** recognises these constructor arguments + normalization: float = 1.0, # <- are the Gaussian`s model parameters. + sigma: float = 5.0, + ): + """ + Represents a 1D Gaussian profile. + + This is a model-component of example models in the **HowToFit** lectures and is used to perform model-fitting + of example datasets. + + Parameters + ---------- + centre + The x coordinate of the profile centre. + normalization + Overall normalization of the profile. + sigma + The sigma value controlling the size of the Gaussian. + """ + self.centre = centre + self.normalization = normalization + self.sigma = sigma + + def model_data_from(self, xvalues: np.ndarray, xp=np) -> np.ndarray: + """ + Returns a 1D Gaussian on an input list of Cartesian x coordinates. + + The input xvalues are translated to a coordinate system centred on the Gaussian, via its `centre`. + + The output is referred to as the `model_data` to signify that it is a representation of the data from the + model. + + Parameters + ---------- + xvalues + The x coordinates in the original reference frame of the data. + xp + The array library the calculation is performed with, which is NumPy by default and JAX when the + model data is being differentiated. + + Returns + ------- + np.array + The Gaussian values at the input x coordinates. + """ + transformed_xvalues = xp.subtract(xvalues, self.centre) + return xp.multiply( + xp.divide(self.normalization, self.sigma * xp.sqrt(2.0 * np.pi)), + xp.exp(-0.5 * xp.square(xp.divide(transformed_xvalues, self.sigma))), + ) + + +""" +We compose the model exactly as in tutorial 3, with uniform priors. They are wider than tutorial 3's, where +`normalization` and `sigma` ran from 0.0 to 10.0, so the true values sit inside parameter space rather than on its +edge. + +We also print `model.model_component_and_parameter_names`, the order of the parameters when the model is expressed +as a plain vector. This matters throughout, because gradients are vectors too and their entries share that order. +""" +model = af.Model(Gaussian) + +model.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) +model.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=50.0) +model.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0) + +print("Order of the parameters in a model vector:") +print(model.model_component_and_parameter_names) + +""" +__Analysis__ + +The `Analysis` class plays the same role it did in tutorial 3, receiving the data and defining the +`log_likelihood_function`. There are two small changes, and they are the reason this tutorial exists. + +First, `__init__` takes a `use_jax` input which it passes to `super().__init__(use_jax=use_jax)`, the switch saying +which array library the analysis computes with: NumPy when `use_jax=False`, the default, and JAX when `use_jax=True`. + +Second, the `log_likelihood_function` uses `self._xp` rather than `np`. `self._xp` is the library that switch +selected, passed into the `Gaussian` via its `xp` argument so the whole calculation uses one library. Note we write +`self._xp.sum(...)` and not the builtin `sum(...)`, which iterates the array one element at a time. The environment +variable `PYAUTO_DISABLE_JAX=1` forces every analysis back to NumPy. +""" + + +class Analysis(af.Analysis): + def __init__(self, data: np.ndarray, noise_map: np.ndarray, use_jax: bool = False): + """ + The `Analysis` class acts as an interface between the data and model in **PyAutoFit**. + + Its `log_likelihood_function` defines how the model is fitted to the data and it is called many times by + the non-linear search fitting algorithm. + + Parameters + ---------- + data + A 1D numpy array containing the data (e.g. a noisy 1D signal) fitted in the workspace examples. + noise_map + A 1D numpy array containing the noise values of the data, used for computing the goodness of fit + metric, the log likelihood. + use_jax + If `True` the log likelihood is computed with JAX, meaning it can be differentiated, and if `False` + it is computed with NumPy. + """ + super().__init__(use_jax=use_jax) + + self.data = data + self.noise_map = noise_map + + def log_likelihood_function(self, instance) -> float: + """ + Returns the log likelihood of a fit of a 1D Gaussian to the dataset. + + The calculation is identical to the one performed in tutorial 3, except every operation is performed with + `self._xp`, the array library chosen by the `use_jax` input, instead of NumPy. + """ + xp = self._xp + + xvalues = xp.arange(self.data.shape[0]) + + model_data = instance.model_data_from(xvalues=xvalues, xp=xp) + residual_map = self.data - model_data + chi_squared_map = (residual_map / self.noise_map) ** 2.0 + chi_squared = xp.sum(chi_squared_map) + noise_normalization = xp.sum(xp.log(2 * np.pi * self.noise_map**2.0)) + log_likelihood = -0.5 * (chi_squared + noise_normalization) + + return log_likelihood + + +""" +We create two analysis objects from the same data, one computing with NumPy and one with JAX. They compute the same +number. We use the NumPy one for the next two sections, and the JAX one when we start differentiating. +""" +analysis = Analysis(data=data, noise_map=noise_map) +analysis_jax = Analysis(data=data, noise_map=noise_map, use_jax=True) + +instance = model.instance_from_vector(vector=[50.0, 25.0, 10.0]) + +print("Log likelihood of the true model, computed with NumPy:") +print(analysis.log_likelihood_function(instance=instance)) + +r""" +__Gradients__ + +In tutorial 3 we pictured model-fitting as an exploration of a "parameter space": a surface, one axis per free +parameter, whose height is the log likelihood. Our job was to find its peak, and the searches we used explored it +essentially blind, evaluating points and remembering which came back high. + +But a surface has more structure than that. At any point there is a slope: walk a tiny distance in the `centre` +direction and the log likelihood changes by some amount, walk the same distance in `sigma` and it changes by a +different amount. One such number per parameter gives the "gradient", a vector pointing in the direction the log +likelihood increases fastest, whose length says how steeply. + +The gradient of a function \( f \) with respect to parameters \( x, y, z \) is written: + +\[ \nabla f = \left( \frac{\partial f}{\partial x}, \frac{\partial f}{\partial y}, \frac{\partial f}{\partial z} \right) \] + +Where: + +- \( \nabla f \): the gradient, a vector with one entry per parameter. +- \( \partial f / \partial x \): the "partial derivative" of \( f \) with respect to \( x \), how much \( f \) + changes when \( x \) changes and everything else is held fixed. + +The gradient is a list of slopes, one per parameter, measured at the same point. A search which knows it does not +have to guess which way to move, it can simply walk uphill! + +Below we fix `normalization` and `sigma` at their true values and vary only `centre`, a 1D "slice" through the three +dimensional parameter space. +""" +centre_list = np.linspace(40.0, 60.0, 100) + +log_likelihood_list = [] + +for centre in centre_list: + instance = model.instance_from_vector(vector=[centre, 25.0, 10.0]) + log_likelihood_list.append(analysis.log_likelihood_function(instance=instance)) + +plt.plot(centre_list, log_likelihood_list, color="k") +plt.title("Log likelihood as a function of the Gaussian centre.") +plt.xlabel("centre") +plt.ylabel("Log Likelihood") +plt.show() +plt.close() + +""" +The slice is a smooth hill peaking almost exactly at the true `centre` of 50.0, falling away steeply because an +offset Gaussian produces enormous residuals. + +Now the important part. Pick a point on that hill, say `centre=44.0`, and ask "if I step a little to the right, does +the log likelihood go up or down, and by how much?". The answer is the slope of the curve there, drawn below as the +straight line touching the curve at that point, the "tangent line". +""" +centre_point = 44.0 +step = 0.01 + +instance_up = model.instance_from_vector(vector=[centre_point + step, 25.0, 10.0]) +instance_down = model.instance_from_vector(vector=[centre_point - step, 25.0, 10.0]) + +slope = ( + analysis.log_likelihood_function(instance=instance_up) + - analysis.log_likelihood_function(instance=instance_down) +) / (2.0 * step) + +instance_point = model.instance_from_vector(vector=[centre_point, 25.0, 10.0]) +log_likelihood_point = analysis.log_likelihood_function(instance=instance_point) + +print(f"Slope of the log likelihood at centre = {centre_point}: {slope}") + +tangent_centre_list = np.linspace(centre_point - 3.0, centre_point + 3.0, 10) +tangent_list = log_likelihood_point + slope * (tangent_centre_list - centre_point) + +plt.plot(centre_list, log_likelihood_list, color="k") +plt.plot(tangent_centre_list, tangent_list, color="r") +plt.scatter(centre_point, log_likelihood_point, color="r") +plt.title("The tangent line shows which way is up at a point.") +plt.xlabel("centre") +plt.ylabel("Log Likelihood") +plt.show() +plt.close() + +""" +The red line is the gradient made visible. It slopes upwards to the right and its value is positive, which together +say that increasing `centre` from 44.0 increases the log likelihood. A search standing here does not need to try +both directions to learn that, and the size of the number tells it the surface is steep enough for a decent step. + +The same holds for every parameter. Below we slice in `sigma` instead, giving a hill of a different shape and +therefore different slopes. +""" +sigma_list = np.linspace(5.0, 15.0, 100) + +log_likelihood_list = [] + +for sigma in sigma_list: + instance = model.instance_from_vector(vector=[50.0, 25.0, sigma]) + log_likelihood_list.append(analysis.log_likelihood_function(instance=instance)) + +plt.plot(sigma_list, log_likelihood_list, color="k") +plt.title("Log likelihood as a function of the Gaussian sigma.") +plt.xlabel("sigma") +plt.ylabel("Log Likelihood") +plt.show() +plt.close() + +r""" +Our model has three parameters, so its gradient has three entries, one per slice of the kind we just drew, ordered +as the parameter names we printed earlier: + +\[ \left( \frac{\partial \log L}{\partial centre}, \frac{\partial \log L}{\partial normalization}, \frac{\partial \log L}{\partial \sigma} \right) \] + +The five-Gaussian model of tutorial 4 has a gradient with 15 entries; a lens model in astronomy might have 50. It +always has as many entries as the model has free parameters, and always belongs to one specific point. Move to a +new point and you get a new gradient! + +__Finite Differencing__ + +So how do we compute a gradient? The most direct way is the one we just used for the tangent line: nudge a parameter +by a small amount \( h \), evaluate the log likelihood, nudge it the other way, evaluate again, and take the +difference. This is "finite differencing", in the "central difference" form: + +\[ \frac{\partial f}{\partial x} \approx \frac{f(x + h) - f(x - h)}{2h} \] + +Where: + +- \( h \): the step size, a small number chosen by us. +- \( f(x + h) \): the log likelihood with the parameter increased by \( h \), everything else held fixed. +- \( f(x - h) \): the log likelihood with the parameter decreased by \( h \). + +In words: measure how much the function changed over a small interval and divide by the width of that interval. +Below we write this out for all three parameters, returning a list of three slopes: a gradient. +""" + + +def log_likelihood_from_vector_numpy(vector): + """ + Returns the log likelihood of a model defined by an input vector of parameter values, computed with NumPy. + """ + instance = model.instance_from_vector(vector=list(vector)) + + return analysis.log_likelihood_function(instance=instance) + + +def gradient_via_finite_difference_from(vector, h=1.0e-3): + """ + Returns the gradient of the log likelihood at an input vector of parameter values, computed via central finite + differences with a step size `h`. + """ + gradient = [] + + for index in range(len(vector)): + vector_up = list(vector) + vector_up[index] += h + + vector_down = list(vector) + vector_down[index] -= h + + log_likelihood_up = log_likelihood_from_vector_numpy(vector=vector_up) + log_likelihood_down = log_likelihood_from_vector_numpy(vector=vector_down) + + gradient.append((log_likelihood_up - log_likelihood_down) / (2.0 * h)) + + return gradient + + +""" +We evaluate the gradient at a point some way from the true solution, `centre=44.0`, `normalization=20.0` +and `sigma=8.0`, roughly where a search might find itself part way through a fit. +""" +vector = [44.0, 20.0, 8.0] + +gradient = gradient_via_finite_difference_from(vector=vector) + +print("Gradient of the log likelihood at [44.0, 20.0, 8.0]:\n") +print(f"d(log likelihood) / d(centre) = {gradient[0]}") +print(f"d(log likelihood) / d(normalization) = {gradient[1]}") +print(f"d(log likelihood) / d(sigma) = {gradient[2]}") + +r""" +The signs tell a search to increase `centre`, decrease `normalization` and increase `sigma`. Compared to the true +values of 50.0, 25.0 and 10.0 that is sensible in two of the three parameters: the gradient is a local instruction, +under no obligation to point straight at the peak. + +There is a catch. We had to choose \( h \), and the answer depends on that choice. Below we compute the gradient +with respect to `centre` for step sizes spanning ten orders of magnitude. +""" +print("Step size h d(log likelihood) / d(centre)\n") + +for h in [10.0, 1.0, 0.1, 1.0e-3, 1.0e-6, 1.0e-9]: + gradient = gradient_via_finite_difference_from(vector=vector, h=h) + + print(f"{h:<18.0e} {gradient[0]}") + +r""" +The table shows the two failure modes of finite differencing, one at each end. + +When \( h \) is too large, the two evaluations are so far apart that the line between them is not the slope at our +point at all, it is the average slope over a wide interval. The answer is "biased". + +When \( h \) is too small, the two log likelihoods subtracted are almost identical numbers. A computer stores them +to about sixteen significant figures, so subtracting them keeps mostly round-off noise, which dividing by a tiny +number then amplifies. The answer becomes erratic. + +Somewhere in the middle is a sweet spot, visible as the region where the answer stops changing, but its location +depends on the units of the parameter, the scale of the data and the model, so it must be found by trial and error +for every new problem. That is not a comfortable position to be in! + +There is a second cost. Each parameter needs two evaluations, so a gradient for a model with \( N \) parameters +costs \( 2N \) evaluations, which for a 50-parameter model whose likelihood takes a second is over a minute of +computation to work out which way to take one step. + +This is exactly what the `LBFGS` search of tutorial 3 was doing, silently, on your behalf. It "evaluates the +likelihood at nearby points to estimate the gradient", and now we know what that means: finite differencing, with a +step size it chose for us. + +__JAX and Autodiff__ + +If finite differencing is unreliable and expensive, why not write the derivative down? For our 1D Gaussian we could. +But no interesting log likelihood is a short equation. A realistic one is a long chain of operations: in astronomy, +ray tracing light through a gravitational lens, convolving with the telescope's point spread function, solving a +large linear system to reconstruct a source, and only then comparing to data. Differentiating that by hand means +applying the chain rule hundreds of times and maintaining the result every time the model changes. It is +impractical, and error prone in a way which is hard to detect, because a subtly wrong gradient still points roughly +uphill and still produces a plausible looking fit. + +"Automatic differentiation", or "autodiff", solves this. Every calculation is built from a handful of elementary +operations whose derivatives we know, so a library which records those operations as they run can apply the chain +rule to that record and produce the exact derivative of whatever was computed. + +This is what JAX does, and it is why our `Gaussian` was written in terms of `xp` and our `Analysis` in terms +of `self._xp`. When `use_jax=True`, `xp` is `jax.numpy`, whose operations record themselves as they execute, and the +derivative that comes out is exact and costs a small fixed multiple of one likelihood evaluation, however many +parameters the model has. + +Below we build a function mapping a vector of parameters to a log likelihood and ask JAX to differentiate it. That +is the whole API: `jax.grad(f)` returns a function which, called at a point, returns the gradient of `f` there. +""" +import jax +import jax.numpy as jnp + + +def log_likelihood_from_vector(vector): + """ + Returns the log likelihood of a model defined by an input vector of parameter values, computed with JAX. + """ + instance = model.instance_from_vector(vector=vector, xp=jnp) + + return analysis_jax.log_likelihood_function(instance=instance) + + +gradient_jax = jax.grad(log_likelihood_from_vector)(jnp.array(vector)) + +gradient_finite_difference = gradient_via_finite_difference_from(vector=vector) + +print("Gradient at [44.0, 20.0, 8.0] via automatic differentiation:") +print(gradient_jax) + +print("\nGradient at [44.0, 20.0, 8.0] via finite differencing:") +print(gradient_finite_difference) + +r""" +The two gradients agree to several decimal places, the sanity check that matters: autodiff computes the same +quantity we computed by hand, exactly and in one pass rather than approximately and in six. Where they disagree it +is the finite-difference answer that is wrong, because it carries the error we chose when we picked \( h \). + +JAX has a second trick. `jax.jit` compiles a function into optimised machine code the first time it is called and +reuses that code on every subsequent call, so for a search calling the likelihood thousands of times a one-off +compilation cost is an excellent trade. Below we time a hundred compiled calls against a hundred uncompiled ones. +""" +import time + +log_likelihood_jit = jax.jit(log_likelihood_from_vector) + +start = time.time() +log_likelihood_jit(jnp.array(vector)) +print(f"Time of the first (compiling) call: {time.time() - start} seconds") + +start = time.time() +for i in range(100): + log_likelihood_jit(jnp.array(vector)) +print(f"Time of 100 compiled calls: {time.time() - start} seconds") + +start = time.time() +for i in range(100): + log_likelihood_from_vector(jnp.array(vector)) +print(f"Time of 100 uncompiled calls: {time.time() - start} seconds") + +r""" +__Maximum Likelihood Estimation (MLE)__ + +We now have gradients. Let us give them to the three families of search we met in tutorial 3. + +We start with `LBFGS`, passing it the NumPy analysis, because `LBFGS` cannot use JAX gradients: it estimates the +gradient itself by finite differencing, exactly as we did by hand, so every iteration costs \( 2N + 1 \) +evaluations. It also starts from a single point, the centre of the priors. In tutorial 3 that was enough to trap it +in a local maximum; with the wider priors here it does better, but a single walker walking uphill can still only +find the peak it happens to be standing on. +""" +search = af.LBFGS() + +print( + """ + The non-linear search has begun running. + This Jupyter notebook cell with progress once the search has completed - this could take a few minutes! + """ +) + +start = time.time() + +result = search.fit(model=model, analysis=analysis) + +print("The search has finished run - you may now continue the notebook.") +print(f"LBFGS run time: {time.time() - start} seconds") + +print(result.info) + +""" +Now the gradient-aware alternative, `MultiStartAdam`. Two words in that name describe what it does differently. + +"Multi start" means it starts not from one point but from many, scattered across the priors. Each start is a "lane" +walking uphill independently, so a lane which walks into a local maximum loses to the lanes which found something +better, addressing the failure mode that trapped `LBFGS` in tutorial 3. + +"Adam" is the algorithm each lane steps with, a gradient method used to train neural networks, which follows the +exact autodiff gradient and adapts its step size per parameter. Because the gradients come from JAX, every lane is +advanced together in one compiled call using `vmap`, so twelve lanes cost far less than twelve times one lane. + +This search is given a `name` and `path_prefix`, so its results are written to the `output` folder as tutorial 5 +did, because there is a file in there we are about to read. +""" +search = af.MultiStartAdam( + name="tutorial_6_gradients_adam", + path_prefix="chapter_1_introduction", + n_starts=12, # The number of independent lanes which walk uphill from different starting points. + n_steps=200, # The maximum number of gradient steps each lane takes. + learning_rate=0.5, # How far each lane moves per step, in units of the adapted gradient. + batch_size=None, # None evaluates every lane in one compiled call; pass an integer to cap memory on large models. +) + +print( + """ + The non-linear search has begun running. + Checkout the HowToFit/output/chapter_1_introduction/tutorial_6_gradients_adam + folder for live output of the results. + This Jupyter notebook cell with progress once the search has completed - this could take a few minutes! + """ +) + +start = time.time() + +result = search.fit(model=model, analysis=analysis_jax) + +print("The search has finished run - you may now continue the notebook.") +print(f"MultiStartAdam run time: {time.time() - start} seconds") + +print(result.info) + +""" +Let us plot the maximum likelihood fit, which should look familiar from tutorial 3. +""" +model_data = result.max_log_likelihood_instance.model_data_from(xvalues=xvalues) + +plt.errorbar( + x=xvalues, + y=data, + yerr=noise_map, + linestyle="", + color="k", + ecolor="k", + elinewidth=1, + capsize=2, +) +plt.plot(xvalues, model_data, color="r") +plt.title("MultiStartAdam model fit to 1D Gaussian dataset.") +plt.xlabel("x values of profile") +plt.ylabel("Profile normalization") +plt.show() +plt.close() + +""" +Because this search wrote its results to hard disk, its output folder contains a file called `search.summary`: how +long the search took, how long one log likelihood evaluation took and, for gradient searches, diagnostics on how +often things went wrong. We read it back below. +""" +search_summary_path = path.join(str(search.paths.output_path), "search.summary") + +if path.exists(search_summary_path): + with open(search_summary_path) as f: + print(f.read()) + +""" +The block at the bottom, headed `Resampling Info`, contains two entries only a gradient search can report: + +- `Value-NaN Lane-Steps`: the number of times a lane stepped somewhere the log likelihood could not be computed at + all, most often because it stepped outside the priors. + +- `Gradient-NaN Lane-Steps`: the number of times the log likelihood *was* computable but its gradient was not. This + is the sneakier of the two, because such a lane does not crash or die, it simply stops moving while continuing to + look perfectly healthy. + +Both counters are usually small and harmless, but they are the vocabulary you need to diagnose a gradient fit that +has gone quietly wrong. Tutorial 7 explains where they come from and what to do about them. + +__Markov Chain Monte Carlo (MCMC)__ + +In tutorial 3 we used `Emcee`, whose walkers propose a step, compute the likelihood there and accept or reject the +move by comparing it to where they are. Notice what is missing: the walkers never ask which way is up. That is a +strength, because `Emcee` works on any likelihood you can evaluate, and a weakness, because in many dimensions a +random step is overwhelmingly likely to point somewhere worse, so most proposals are rejected. +""" +search = af.Emcee( + nwalkers=20, # The number of walkers we'll use to sample parameter space. + nsteps=500, # The number of steps each walker takes. +) + +print( + """ + The non-linear search has begun running. + This Jupyter notebook cell with progress once the search has completed - this could take a few minutes! + """ +) + +start = time.time() + +result = search.fit(model=model, analysis=analysis) + +print("The search has finished run - you may now continue the notebook.") +print(f"Emcee run time: {time.time() - start} seconds") + +print(result.info) + +""" +Now the gradient-aware alternative, `BlackJAXNUTS`, which is Hamiltonian Monte Carlo. The physical picture behind it +is genuinely helpful. + +Imagine the likelihood surface turned upside down, so its peak becomes a valley, and place a ball on the resulting +landscape. Give it a random flick and let it roll: it accelerates down slopes, coasts up the other side and travels +a long way while staying in regions the landscape favours. That trajectory is computed from the gradient at each +moment, which is what autodiff hands us for free. Where the ball stops becomes the next sample, and because it +travelled a long, informed distance rather than a small random hop, consecutive samples are far less similar. + +"NUTS" stands for the No U-Turn Sampler, which solves the awkward choice here: how long to let the ball roll. Roll +too briefly and you wasted the gradient; roll too long and the ball curves back on itself. NUTS stops the trajectory +when it starts doubling back. Being a gradient method, it needs the JAX analysis. +""" +search = af.BlackJAXNUTS( + num_warmup=200, # Steps used to tune the sampler, which are then discarded. + num_samples=300, # Steps kept as samples of the posterior. +) + +print( + """ + The non-linear search has begun running. + This Jupyter notebook cell with progress once the search has completed - this could take a few minutes! + """ +) + +start = time.time() + +result = search.fit(model=model, analysis=analysis_jax) + +print("The search has finished run - you may now continue the notebook.") +print(f"BlackJAXNUTS run time: {time.time() - start} seconds") + +print(result.info) + +""" +Hamiltonian sampling comes with its own diagnostics, stored in the `samples_info` dictionary. Three are worth +knowing: + +- `n_divergent`: the number of trajectories which "diverged", meaning the ball flew off to infinity instead of + following the landscape. A handful is tolerable; many means the steps are too large and the samples cannot be + trusted. + +- `ess_min`: the "effective sample size" of the worst constrained parameter. Consecutive samples are correlated, so + 300 samples are worth fewer than 300 independent draws, and this says how many they are worth. + +- `mean_acceptance`: the fraction of proposed trajectories accepted, which for NUTS should sit high, around the 0.8 + the warm up phase tunes towards. A low value means the sampler is struggling. +""" +samples = result.samples + +print("Diagnostics of the Hamiltonian Monte Carlo fit:\n") +print(f"Number of divergent trajectories = {samples.samples_info.get('n_divergent')}") +print(f"Minimum effective sample size = {samples.samples_info.get('ess_min')}") +print( + f"Mean acceptance rate = {samples.samples_info.get('mean_acceptance')}" +) + +""" +Because NUTS maps out the posterior, we can plot the Probability Density Functions of its samples with `corner.py`, +wrapped via the `aplt.corner_cornerpy` function, exactly as we did for `Emcee` in tutorial 5. +""" +aplt.corner_cornerpy(samples=result.samples) + +""" +__Nested Sampling__ + +Finally, nested sampling, the interesting case, because gradients do not help it at all. + +Recall from tutorial 3 how it works: a set of "live points" is drawn from the priors, the lowest likelihood one is +discarded, and a replacement is drawn from the priors subject to having a higher likelihood. Repeat, and the live +points contract onto the peak. There is no walker in that description and therefore nothing to steer. The algorithm +never asks "which way is up from here", it asks "give me any point better than this one". + +JAX still helps, for a different reason. `Nautilus` proposes points in batches, and with a JAX analysis +**PyAutoFit** evaluates a whole batch in one compiled call rather than looping in Python, which is the +`use_jax_vmap=True` input, on by default. Gradients change *how a search explores*; JAX compilation changes *how +fast the likelihood is evaluated*, and nested sampling benefits only from the second. +""" +search = af.Nautilus( + n_live=150, # The number of live points used to explore parameter space. + n_eff=200, # The effective sample size the search runs until it reaches. +) + +print( + """ + The non-linear search has begun running. + This Jupyter notebook cell with progress once the search has completed - this could take a few minutes! + """ +) + +start = time.time() + +result = search.fit(model=model, analysis=analysis_jax) + +print("The search has finished run - you may now continue the notebook.") +print(f"Nautilus run time: {time.time() - start} seconds") + +print(result.info) + +r""" +__Errors From Curvature__ + +In tutorial 5 we computed errors from the samples, by marginalizing over each parameter's 1D Probability Density +Function. That assumes nothing about the posterior's shape, but it requires the samples, which are thousands of +likelihood evaluations of work. + +Gradients offer a shortcut. The first derivative gives the slope; the second gives the "curvature", how quickly the +slope itself changes. At the peak the slope is zero, so the curvature is all there is, and it says how sharply the +likelihood falls away as we step off the peak. A sharply curved peak means a small error, a gently curved one a +large error. The error is the curvature, read backwards. + +For several parameters the second derivatives form a matrix called the "Hessian", which `jax.hessian` computes by +the same autodiff machinery as `jax.grad`. The errors follow from: + +\[ C = -H^{-1}, \qquad \sigma_{i} = \sqrt{C_{ii}} \] + +Where: + +- \( H \): the Hessian, the matrix of second derivatives of the log likelihood at the peak. +- \( C \): the covariance matrix, the negative inverse of the Hessian. +- \( \sigma_{i} \): the 1 sigma error on parameter \( i \), the square root of the \( i \)th diagonal entry + of \( C \). + +In words: invert the curvature, flip its sign, and the square roots of its diagonal are the errors. We evaluate this +at the maximum likelihood vector found by `Nautilus`. +""" +samples = result.samples + +max_log_likelihood_vector = samples.max_log_likelihood(as_instance=False) + +hessian = jax.hessian(log_likelihood_from_vector)( + jnp.array(max_log_likelihood_vector, dtype=float) +) + +covariance = -jnp.linalg.inv(hessian) + +errors_from_curvature = jnp.sqrt(jnp.diag(covariance)) + +print("Errors from the curvature of the likelihood (Laplace approximation):\n") +print(f"centre = {errors_from_curvature[0]}") +print(f"normalization = {errors_from_curvature[1]}") +print(f"sigma = {errors_from_curvature[2]}") + +""" +Now the comparison. Below we print the errors the `Nautilus` samples give, with the `errors_at_upper_sigma` and +`errors_at_lower_sigma` methods of tutorial 5. Tutorial 5 used `sigma=3.0`, because a result quoted in a paper wants +a conservative interval; we use `sigma=1.0`, because that is what the curvature calculation produces. +""" +errors_at_upper_sigma = samples.errors_at_upper_sigma(sigma=1.0, as_instance=False) +errors_at_lower_sigma = samples.errors_at_lower_sigma(sigma=1.0, as_instance=False) + +print("Errors from the samples (upper, at 1.0 sigma confidence):") +print(errors_at_upper_sigma) + +print("\nErrors from the samples (lower, at 1.0 sigma confidence):") +print(errors_at_lower_sigma) + +""" +The two sets of numbers agree closely, and that is not a coincidence, it is the "Laplace approximation" working: +near its peak a well behaved likelihood looks like a Gaussian, whose width the curvature sets. If the posterior +really is Gaussian, the curvature knows everything the samples know. + +The catch is in the words "if" and "near". The curvature is measured at a single point, so it describes only the +peak it was measured on. If the posterior has a second peak the Hessian has no idea; if it is skewed, cut off by a +prior edge, or banana shaped because two parameters are degenerate, a symmetric Gaussian centred on the peak +misdescribes it, and the errors are wrong in ways the numbers do not reveal. Sampling assumes none of that. + +One last check is visual rather than numerical. Instead of summarising the posterior at all, we can take a handful +of the models it contains and plot each over the data. Below we use the final five samples the search accepted, +which for nested sampling are its highest likelihood ones, turning each into an instance with +`sample.instance_for_model` as tutorial 5 did. If the draws all trace the data closely, and their spread is +comparable to the error bars, the fit is telling a consistent story. This is a "posterior predictive check", and it +catches what no single number can. +""" +plt.errorbar( + x=xvalues, + y=data, + yerr=noise_map, + linestyle="", + color="k", + ecolor="k", + elinewidth=1, + capsize=2, +) + +for sample in samples.sample_list[-5:]: + instance = sample.instance_for_model(model=samples.model) + + plt.plot(xvalues, instance.model_data_from(xvalues=xvalues), "--") + +plt.title("Five models from the posterior, plotted over the data.") +plt.xlabel("x values of profile") +plt.ylabel("Profile normalization") +plt.show() +plt.close() + +r""" +__Wrap Up__ + +This tutorial took the one sentence tutorial 3 used to describe how an MLE search moves and unpacked it: + +1. **Gradients**: the gradient of the log likelihood is a vector with one entry per free parameter, evaluated at a +point, pointing in the direction the likelihood increases fastest. + +2. **Finite differencing versus autodiff**: a gradient can be estimated by nudging each parameter and re-evaluating, +but this costs \( 2N \) evaluations and forces a step size which is biased if too large and noisy if too small. +Autodiff applies the chain rule to the operations the likelihood performs, giving the exact gradient for a small fixed +multiple of the cost of one evaluation, whatever the number of parameters. + +3. **MLE**: `LBFGS` finite differences its own gradient from a single starting point, which is expensive and +fragile. `MultiStartAdam` follows exact gradients from many starting points at once, evaluated together in one +compiled call, making it far harder to trap in a local maximum. + +4. **MCMC**: `Emcee` proposes random steps and accepts or rejects them, never asking which way is up. +`BlackJAXNUTS` rolls a ball across the landscape using the gradient to shape its trajectory, producing far less +correlated samples for the same number of steps. + +5. **Nested sampling**: `Nautilus` replaces low likelihood live points with higher likelihood ones drawn from the +priors, a procedure with no direction of travel for a gradient to inform. JAX speeds it up by evaluating batches of +points in one compiled call, but the algorithm is unchanged. + +6. **Curvature errors**: the second derivatives at the peak give a covariance matrix and hence 1 sigma errors on +every parameter, essentially for free. They agree with the errors from samples whenever the peak is single and +Gaussian shaped, and quietly mislead when it is not. + +Gradients are therefore not a different way of fitting models, they are extra information about the same likelihood +surface we have explored since tutorial 3, and each family of search makes its own use of it, or none at all. + +Whether a gradient fit succeeds depends on details we have skated over: what happens when a search steps outside its +priors, when two parameters are degenerate, or when the likelihood is defined somewhere its gradient is not. +Tutorial 7 looks at the details that decide whether these searches succeed. +""" diff --git a/scripts/chapter_1_introduction/tutorial_7_the_details.py b/scripts/chapter_1_introduction/tutorial_7_the_details.py new file mode 100644 index 0000000..544d92d --- /dev/null +++ b/scripts/chapter_1_introduction/tutorial_7_the_details.py @@ -0,0 +1,1142 @@ +""" +Tutorial 7: The Details +======================= + +In tutorial 6 we opened up the non-linear search and looked at how it moves. We saw that some searches only ever ask +the likelihood function "what is the value here?", whilst gradient based searches also ask "and which way is uphill?", +and that **PyAutoFit** can answer the second question exactly by using JAX to differentiate the likelihood function. + +This tutorial is about everything else: the details sitting underneath every model-fit. How your model is +parameterized, what happens when two parameter combinations describe the same data, what a search does when a +parameter stops mattering, and what parameter space looks like from the search's point of view. + +I want to be upfront. Most of the time none of this matters, and a sensible model fitted with a sensible search +gives a sensible answer. The reason to learn these details is that when they do matter they are hard to spot, +because the failure mode is not an error message but a wrong answer that looks completely reasonable. + +__Overview__ + +In this tutorial, we will look at the details that make a model-fit succeed or fail, specifically: + +- Composing a model whose components can swap roles, producing mirror solutions, and removing them with an + "assertion". + +- Creating a "plateau", a flat region of parameter space where a parameter has no effect, and removing it. + +- Running the same problem with three searches, and using the disagreement between them as a diagnostic. + +- Making the likelihood return `NaN` on purpose, and reading the `NaN` diagnostics a gradient search writes out. + +- Looking at parameter space the way a search does, through the "unit cube" defined by the priors. + +__Contents__ + +This tutorial is split into the following sections: + +- **Data**: Load the two-Gaussian dataset used to study degenerate parameterizations. +- **Model**: The JAX-capable `Gaussian` model component from tutorial 6. +- **Analysis**: The `Analysis` class, fitting a `Collection` of profiles on NumPy or JAX. +- **Parameterization**: How two model components that can swap roles produce mirror solutions, and why that hurts a search. +- **Assertions**: Removing mirror solutions with `add_assertion` and what happens to a sample that violates one. +- **Plateaus**: How a parameter whose effect vanishes (a normalization of zero) creates a flat region of parameter space, and how to remove it. +- **Comparing Searches**: Running the same problems with MCMC, nested sampling and gradient descent to see how each is affected, and why comparing searches is a diagnostic in itself. +- **Clipping**: Parameter combinations that are unphysical even when every individual prior is sensible, the NaN likelihoods they produce, and the resample figure of merit each search substitutes. +- **NaN Diagnostics**: Reading the value-NaN and gradient-NaN counters in `search.summary`, and why a finite likelihood does not guarantee a finite gradient. +- **Unit Cube Vs Physical**: How a search actually sees parameter space through the priors, and why that changes how it explores. +- **Summary**: When these details matter, and what attending to them buys you. +""" + +# from autofit import setup_notebook; setup_notebook() + +from os import path +import time +import numpy as np +import matplotlib.pyplot as plt + +import autofit as af +import autofit.plot as aplt + +""" +__Data__ + +Load and plot the dataset from the `HowToFit/dataset` folder. + +We use the `gaussian_x2` dataset, simulated from two Gaussians sharing a centre of 50.0. The first has a +normalization of 20.0 and a sigma of 1.0, a narrow spike; the second a normalization of 40.0 and a sigma of 5.0, a +broader bump underneath. The two are summed and noise added, as in tutorials 2 and 4. Two identical model components +fitted to two component data is the simplest example of the parameterization problem we study first. +""" +dataset_path = path.join("dataset", "example_1d", "gaussian_x2") + +""" +__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 not path.exists(dataset_path): + import subprocess + import sys + + subprocess.run( + [sys.executable, "scripts/simulators/simulators.py"], + check=True, + ) + +data = af.util.numpy_array_from_json(file_path=path.join(dataset_path, "data.json")) +noise_map = af.util.numpy_array_from_json( + file_path=path.join(dataset_path, "noise_map.json") +) + +xvalues = np.arange(data.shape[0]) + +plt.errorbar( + xvalues, + data, + yerr=noise_map, + linestyle="", + color="k", + ecolor="k", + elinewidth=1, + capsize=2, +) +plt.title("1D dataset containing two blended Gaussians.") +plt.xlabel("x values of profile") +plt.ylabel("Profile Normalization") +plt.show() +plt.clf() + +""" +__Model__ + +The narrow spike sits on top of the broader bump, but only just. The two components are blended, and by eye it is +hard to say where one ends and the other begins. That blending is what makes the parameter space interesting. + +We now re-define the `Gaussian` class, using the version introduced in tutorial 6, which is identical to the class +used since tutorial 1 except that `model_data_from` takes an extra argument `xp` and is written in `xp.` functions. +As tutorial 6 showed, `xp` is whichever array library the fit is running with: `numpy` by default, `jax.numpy` when +the `Analysis` has been told to use JAX. +""" + + +class Gaussian: + def __init__( + self, + centre: float = 30.0, # <- **PyAutoFit** recognises these constructor arguments + normalization: float = 1.0, # <- are the Gaussian`s model parameters. + sigma: float = 5.0, + ): + """ + Represents a 1D Gaussian profile. + + This is a model-component of example models in the **HowToFit** lectures and is used to perform model-fitting + of example datasets. + + Parameters + ---------- + centre + The x coordinate of the profile centre. + normalization + Overall normalization of the profile. + sigma + The sigma value controlling the size of the Gaussian. + """ + self.centre = centre + self.normalization = normalization + self.sigma = sigma + + def model_data_from(self, xvalues: np.ndarray, xp=np) -> np.ndarray: + """ + Returns a 1D Gaussian on an input list of Cartesian x coordinates. + + The input xvalues are translated to a coordinate system centred on the Gaussian, via its `centre`. + + The output is referred to as the `model_data` to signify that it is a representation of the data from the + model. + + Parameters + ---------- + xvalues + The x coordinates in the original reference frame of the data. + xp + The array library the calculation is performed with, `numpy` by default and `jax.numpy` when the fit + is being performed with JAX. + + Returns + ------- + np.array + The Gaussian values at the input x coordinates. + """ + transformed_xvalues = xp.subtract(xvalues, self.centre) + return xp.multiply( + xp.divide(self.normalization, self.sigma * xp.sqrt(2.0 * np.pi)), + xp.exp(-0.5 * xp.square(xp.divide(transformed_xvalues, self.sigma))), + ) + + +""" +__Analysis__ + +The `Analysis` class below is the tutorial 4 version, which sums the model data of every profile in the instance, +combined with the tutorial 6 version, which accepts `use_jax` and passes it to `af.Analysis` via `super().__init__`. + +Two details matter. The first is `self._xp`, an attribute created for us by `af.Analysis` which is `numpy` when +`use_jax=False` and `jax.numpy` when `use_jax=True`. Every array operation in the likelihood goes through it, which +is why we write `self._xp.sum` rather than the built-in `sum`. The second is `model_data_from_instance`: the +`instance` is an iterable `Collection`, so we sum the model data of every profile it contains without knowing how +many there are. + +We create the `Analysis` at the end of the cell below, leaving `use_jax` at its default of `False` until we need +gradients. +""" + + +class Analysis(af.Analysis): + def __init__(self, data: np.ndarray, noise_map: np.ndarray, use_jax: bool = False): + """ + The `Analysis` class acts as an interface between the data and model in **PyAutoFit**. + + Parameters + ---------- + data + A 1D numpy array containing the data (e.g. a noisy 1D signal) fitted in the workspace examples. + noise_map + A 1D numpy array containing the noise values of the data, used for computing the goodness of fit + metric, the log likelihood. + use_jax + If `True` the log likelihood function is computed with `jax.numpy`, making it differentiable and + therefore usable by the gradient based searches introduced in tutorial 6. + """ + super().__init__(use_jax=use_jax) + + self.data = data + self.noise_map = noise_map + + def model_data_from_instance(self, instance): + """ + Returns the summed model data of every profile in an instance. + + The `instance` is a `Collection`, which is iterable, so a list comprehension over it returns the model data + of every profile it contains. + """ + xvalues = self._xp.arange(self.data.shape[0]) + + return sum( + [ + profile.model_data_from(xvalues=xvalues, xp=self._xp) + for profile in instance + ] + ) + + def log_likelihood_function(self, instance) -> float: + """ + Returns the log likelihood of a fit of a collection of 1D profiles to the dataset. + + Every array operation uses `self._xp`, which is `numpy` for an ordinary fit and `jax.numpy` for a fit which + uses JAX. The log likelihood is therefore differentiable whenever `use_jax=True` was passed to `__init__`. + """ + model_data = self.model_data_from_instance(instance=instance) + + residual_map = self.data - model_data + chi_squared_map = (residual_map / self.noise_map) ** 2.0 + chi_squared = self._xp.sum(chi_squared_map) + noise_normalization = self._xp.sum( + self._xp.log(2 * np.pi * self.noise_map**2.0) + ) + log_likelihood = -0.5 * (chi_squared + noise_normalization) + + return log_likelihood + + +analysis = Analysis(data=data, noise_map=noise_map) + +""" +__Parameterization__ + +"Parameterization" means the specific choice of parameters we use to describe our model. It is easy to think of a +model as a fixed thing, but it is not: the same physical model can be written down in many different ways, and the +choice we make changes the shape of parameter space that the search has to explore. + +Our dataset contains two Gaussians, so the obvious model is a `Collection` of two `Gaussian` components, with +identical priors on both. This is the model composition API from tutorial 1, and it is the same six free parameter +model that tutorial 2 fitted by hand. +""" +model = af.Collection(gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian)) + +for gaussian in [model.gaussian_0, model.gaussian_1]: + gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0) + +print(model.info) + +""" +There is a problem hiding in that model. The two components are interchangeable: nothing says `gaussian_0` is the +narrow one and `gaussian_1` the broad one. Swap all six values over and we get exactly the same summed model data, +because addition does not care about the order of its arguments, which means the same residuals, the same +chi-squared and the same log likelihood. + +Let's confirm it, using the parameter ordering of the model vector which, as tutorial 1 showed, is given by +`model.model_component_and_parameter_names`. +""" +print(model.model_component_and_parameter_names) + +vector_ordered = [50.0, 20.0, 1.0, 50.0, 40.0, 5.0] +vector_swapped = [50.0, 40.0, 5.0, 50.0, 20.0, 1.0] + +instance_ordered = model.instance_from_vector(vector=vector_ordered) +instance_swapped = model.instance_from_vector(vector=vector_swapped) + +print("Log likelihood of the ordered model: ") +print(analysis.log_likelihood_function(instance=instance_ordered)) +print("Log likelihood of the swapped model: ") +print(analysis.log_likelihood_function(instance=instance_swapped)) + +""" +The two log likelihoods are identical to the last decimal place. They are not merely similar, they are the same +number, because the two vectors produce the same model data. + +This is a "degeneracy", and this one is a "label switching" degeneracy: the labels `gaussian_0` and `gaussian_1` are +arbitrary, so every solution has a mirror image partner elsewhere. Our six dimensional parameter space does not +contain one peak, it contains two identical peaks related by a reflection. + +Why does this hurt? Recall the searches of tutorial 3. Every search has to decide which of the two peaks to spend +its effort on, and nothing in the data prefers one over the other. A search that commits to one peak gives an +answer whose component labels are a coin toss; a search that splits its effort between both returns a posterior +that is a smeared average of two solutions rather than an estimate of either, whose "errors" are not errors at all +but a measure of the distance between the mirrors. Either way we have paid for a second copy of the answer. + +Let's fit with `DynestyStatic`, the nested sampling search from tutorial 3. +""" +search = af.DynestyStatic( + sample="rwalk", # This makes dynesty run faster, dont worry about what it means for now! +) + +print( + """ + The non-linear search has begun running. + This Jupyter notebook cell with progress once the search has completed - this could take a few minutes! + """ +) + +start = time.time() + +result_flip = search.fit(model=model, analysis=analysis) + +print(f"Dynesty run time: {time.time() - start} seconds") +print("The search has finished run - you may now continue the notebook.") + +""" +The corner plot below shows the Probability Density Functions (PDF's) of the result, via the `corner.py` wrapper +`aplt.corner_cornerpy` we met in tutorial 5. The run is short, so there may be too few samples for `corner.py` to +draw contours; the scatter plot afterwards makes the point without them, putting every sample's `gaussian_0.sigma` +against its `gaussian_1.sigma`. + +Its diagonal is the line where the two sigmas are equal, and the two mirror solutions sit on opposite sides of it. +What you will almost certainly see is the great majority of samples piled on one side, with a thin scatter of early +exploration samples on the other: the search committed to one mirror. Which one is a coin toss, and I got each of +them on different runs while writing this tutorial. +""" +aplt.corner_cornerpy(samples=result_flip.samples) + +sigma_0_list = [parameters[2] for parameters in result_flip.samples.parameter_lists] +sigma_1_list = [parameters[5] for parameters in result_flip.samples.parameter_lists] + +plt.scatter(sigma_0_list, sigma_1_list, s=1, color="k") +plt.title("Samples of the two sigmas, split by the two mirror solutions.") +plt.xlabel("gaussian_0 sigma") +plt.ylabel("gaussian_1 sigma") +plt.show() +plt.clf() + +ordered_count = sum( + sigma_0 < sigma_1 for sigma_0, sigma_1 in zip(sigma_0_list, sigma_1_list) +) + +print(f"Samples with gaussian_0 narrower than gaussian_1: {ordered_count}") +print( + f"Samples with gaussian_0 broader than gaussian_1: {len(sigma_0_list) - ordered_count}" +) + +""" +The maximum log likelihood model printed below is one of the two mirror solutions, and it fits the data beautifully. +Nothing has failed. + +What has gone wrong is that the answer's labels are arbitrary. Read off "the narrow component has a normalization +of about 20" and you may be reading the wrong component, because the next run may put that solution in the other +slot. A degeneracy does not make the fit worse, it makes the *answer ambiguous*, and it costs the search effort +exploring a region it did not need to. The fit does not crash, it quietly costs more and tells us less than it +should. + +Be clear about what this short run does and does not show. It shows that the two mirrors exist, which we proved +exactly with the two identical log likelihoods, and that the search commits to one. It does not show a posterior +with two clean modes: a nested sampler with far more live points, run far longer, is designed to find and report +both peaks, and we have deliberately traded that away for a fit that runs in seconds. +""" +print(result_flip.info) + +""" +__Assertions__ + +The fix is to tell the model something we already know: `gaussian_0` is the narrow component and `gaussian_1` is +the broad one. If we forbid every model where that is not true, we delete one of the two mirror peaks and leave a +parameter space with a single solution. + +**PyAutoFit** expresses this with an "assertion", added to the model with `add_assertion`. An assertion is a +statement about the model's parameters that every accepted model must satisfy. Here we assert that the sigma of +`gaussian_0` is less than the sigma of `gaussian_1`, which makes `gaussian_0` the narrow one by definition. +""" +model = af.Collection(gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian)) + +for gaussian in [model.gaussian_0, model.gaussian_1]: + gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0) + +model.add_assertion(model.gaussian_0.sigma < model.gaussian_1.sigma) + +""" +What actually happens when the search proposes a model that violates the assertion? + +On the NumPy path, building the instance from the parameter vector raises an exception internally, which +**PyAutoFit** catches and converts into a special value called the "resample figure of merit". The search never sees +a likelihood for that model, it sees a number so bad it can never be selected. + +On the JAX path, introduced in tutorial 6 via `use_jax=True`, an exception cannot be raised at all, because the +likelihood is traced and compiled rather than executed line by line. **PyAutoFit** instead evaluates the assertion +as a traced boolean and applies it to the final figure of merit with a `where`, mapping a violating model to exactly +the same resample figure of merit. Different mechanism, same outcome, which is what lets a NumPy fit and a JAX fit +agree exactly. + +We can check the assertion ourselves with `assertions_satisfied_from_vector`, using the two mirror vectors from +before. One passes and one fails, which is the whole point. +""" +print("Ordered vector satisfies the assertion: ") +print(model.assertions_satisfied_from_vector(vector_ordered)) +print("Swapped vector satisfies the assertion: ") +print(model.assertions_satisfied_from_vector(vector_swapped)) + +""" +Two practical notes. An assertion becomes part of the model's unique identifier, so a model with an assertion +writes to a different output folder than the same model without one; they are different models, and results from +one should never be resumed as the other. + +The degeneracy can also be broken without an assertion, by giving the two components priors that cannot overlap. +Give `gaussian_0.sigma` a `UniformPrior` between 0.0 and 3.0 and `gaussian_1.sigma` one between 3.0 and 25.0, and +the mirror solution is not in parameter space at all. Use an assertion when you know the ordering but not the +values. + +Let's refit with the assertion in place. +""" +print( + """ + The non-linear search has begun running. + This Jupyter notebook cell with progress once the search has completed - this could take a few minutes! + """ +) + +search = af.DynestyStatic( + sample="rwalk", +) + +start = time.time() + +result_assert = search.fit(model=model, analysis=analysis) + +print(f"Dynesty run time: {time.time() - start} seconds") +print("The search has finished run - you may now continue the notebook.") + +""" +The counts printed below are the crisp demonstration. Before the assertion, samples appeared on both sides of the +diagonal; with it in place the violating side is empty, and empty by construction rather than luck, because every +model proposed there was handed the resample figure of merit instead of a likelihood. + +The answer is now unambiguous: `gaussian_0` is the narrow component because we said so, and the maximum likelihood +model comes back in that order every run rather than on a coin toss. Half our parameter space has gone, and with it +half the work the search had to do. + +Removing a degeneracy is the single highest value thing you can do to a slow model-fit! +""" +aplt.corner_cornerpy(samples=result_assert.samples) + +sigma_0_list = [parameters[2] for parameters in result_assert.samples.parameter_lists] +sigma_1_list = [parameters[5] for parameters in result_assert.samples.parameter_lists] + +plt.scatter(sigma_0_list, sigma_1_list, s=1, color="k") +plt.title("Samples of the two sigmas with the assertion applied.") +plt.xlabel("gaussian_0 sigma") +plt.ylabel("gaussian_1 sigma") +plt.show() +plt.clf() + +ordered_count = sum( + sigma_0 < sigma_1 for sigma_0, sigma_1 in zip(sigma_0_list, sigma_1_list) +) + +print(f"Samples with gaussian_0 narrower than gaussian_1: {ordered_count}") +print(f"Samples that violate the assertion: {len(sigma_0_list) - ordered_count}") + +print(result_assert.info) + +""" +__Plateaus__ + +The second detail is what happens when a parameter stops mattering. + +To create the problem we now load the single Gaussian dataset, `gaussian_x1`, which was simulated from one Gaussian +with a centre of 50.0, a normalization of 25.0 and a sigma of 10.0. It is the dataset we fitted in tutorials 2 and +3. We will then deliberately fit it with the two component model we have been using, which is one component more +than the data needs. +""" +dataset_x1_path = path.join("dataset", "example_1d", "gaussian_x1") + +if not path.exists(dataset_x1_path): + import subprocess + import sys + + subprocess.run( + [sys.executable, "scripts/simulators/simulators.py"], + check=True, + ) + +data_x1 = af.util.numpy_array_from_json( + file_path=path.join(dataset_x1_path, "data.json") +) +noise_map_x1 = af.util.numpy_array_from_json( + file_path=path.join(dataset_x1_path, "noise_map.json") +) + +analysis_x1 = Analysis(data=data_x1, noise_map=noise_map_x1) + +plt.errorbar( + xvalues, + data_x1, + yerr=noise_map_x1, + linestyle="", + color="k", + ecolor="k", + elinewidth=1, + capsize=2, +) +plt.title("1D dataset containing a single Gaussian.") +plt.xlabel("x values of profile") +plt.ylabel("Profile Normalization") +plt.show() +plt.clf() + +""" +The data needs only one Gaussian, so the best thing the second component can do is get out of the way, which it +does by taking a normalization of zero and contributing nothing to the model data. + +Here is the consequence. Once `gaussian_1.normalization` is zero, its `centre` and `sigma` have no effect on the +model data at all. Every value gives the same model data, chi-squared and log likelihood. Instead of a peak in those +two dimensions, parameter space contains a perfectly flat region: a "plateau". + +Let's demonstrate it, evaluating the likelihood with `gaussian_1.normalization` fixed at zero and its `centre` and +`sigma` set to three wildly different pairs of values. +""" +model_x1 = af.Collection(gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian)) + +for gaussian in [model_x1.gaussian_0, model_x1.gaussian_1]: + gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0) + +for centre_1, sigma_1 in [(20.0, 2.0), (80.0, 15.0), (50.0, 0.5)]: + vector = [50.0, 25.0, 10.0, centre_1, 0.0, sigma_1] + + instance = model_x1.instance_from_vector(vector=vector) + + print( + f"gaussian_1 centre = {centre_1}, sigma = {sigma_1}, log likelihood = " + f"{analysis_x1.log_likelihood_function(instance=instance)}" + ) + +""" +Three completely different models, one identical log likelihood. That is a plateau, two dimensions wide. + +Every search in tutorial 3 struggles here, because nothing in the likelihood tells it which way to go. An MLE search +estimates the gradient, finds it is exactly zero and concludes it has converged. MCMC walkers wander at random, +since every proposal is equally good. A nested sampler's live points scatter uniformly across the flat region. + +Worse, the "errors" reported for the plateau parameters are not errors. If a parameter has no effect on the +likelihood its posterior is just its prior, so the error bar is the width of the prior you happened to choose. It +looks like a measurement and is nothing of the sort. + +There are three ways to deal with a plateau, in order of increasing honesty. The first is to stop the normalization +reaching zero: a `LogUniformPrior`, used in tutorial 4 for prior tuning, spreads its probability evenly across +orders of magnitude and has a strictly positive lower limit, so a normalization of exactly zero is not in parameter +space. +""" +model_x1.gaussian_1.normalization = af.LogUniformPrior( + lower_limit=1e-2, upper_limit=1e2 +) + +print(model_x1.gaussian_1.normalization) + +""" +The second is to remove the offending parameters altogether, by fixing them. As tutorial 1 showed, assigning a +float to a model parameter turns it into a constant rather than a free parameter, which we confirm by checking +`prior_count` before and after. If a parameter genuinely has no effect on the data, any value will do. +""" +model_fixed = af.Collection( + gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian) +) + +print(f"Number of free parameters before fixing sigma: {model_fixed.prior_count}") + +model_fixed.gaussian_1.sigma = 5.0 + +print(f"Number of free parameters after fixing sigma: {model_fixed.prior_count}") + +""" +The third is the honest answer, and the one I would use in a real analysis: reduce the model to what the data +supports, the "reducing complexity" strategy of tutorial 4. The data contains one Gaussian, so the model should +contain one Gaussian, and then there is no second normalization to go to zero and no plateau at all. + +The reason to know the other two is that you cannot always do this. Sometimes the extra component is physically +required even when this dataset cannot constrain it, and a sensible prior or a fixed parameter is how you stop it +poisoning the fit. +""" +model_simple = af.Collection(gaussian=af.Model(Gaussian)) + +print(f"Number of free parameters in the reduced model: {model_simple.prior_count}") + +""" +__Comparing Searches__ + +We now have two badly parameterized problems: the flip degeneracy on the two Gaussian data, and the plateau on the +single Gaussian data. We have already run nested sampling on the flip problem. Let's run MCMC on it too, then run +all three families on the plateau problem, and compare what comes back. + +We start with MCMC, using `Emcee` on the flip problem exactly as tutorial 3 did. The walkers begin scattered +through parameter space and climb towards whichever mirror peak is nearest. +""" +model_emcee = af.Collection( + gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian) +) + +for gaussian in [model_emcee.gaussian_0, model_emcee.gaussian_1]: + gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0) + +search = af.Emcee( + nwalkers=20, # The number of walkers we'll use to sample parameter space. + nsteps=500, # The number of steps each walker takes. +) + +print( + """ + The non-linear search has begun running. + This Jupyter notebook cell with progress once the search has completed - this could take a few minutes! + """ +) + +start = time.time() + +result_emcee = search.fit(model=model_emcee, analysis=analysis) + +print(f"Emcee run time: {time.time() - start} seconds") +print("The search has finished run - you may now continue the notebook.") + +print(result_emcee.info) + +""" +Compare that maximum likelihood model to the one the nested sampler found. With only 20 walkers taking 500 steps +they have not had long enough to climb either mirror properly, and they usually finish somewhere that is neither +mirror: the two normalizations and sigmas come back at values the simulator never used, sharing the flux out +between the components in whatever way the walkers happened to drift into. + +This is exactly the stochasticity of tutorial 4, and it deserves to be taken seriously rather than treated as a +nuisance. Run the cell above again and you will get a different answer, because the walkers start in different +random places. **That variability is itself the diagnostic.** A fit whose answer changes every run is telling you +the search has not converged on this parameter space, and the honest response is more steps, a better starting +point, or an easier parameter space. + +Now the plateau problem, with the same two searches. Nested sampling first, with more live points than we used +above so that it maps the flat region properly rather than skating over it. + +Note that the two component model has the flip degeneracy in it as well as the plateau, because either component +could be the one that vanishes. We therefore use the tool we just learned and assert that `gaussian_0` carries more +normalization than `gaussian_1`, which makes `gaussian_1` the vanishing component by definition and lets us talk +about its parameters without having to check which slot the search happened to use. +""" +model_plateau_nest = af.Collection( + gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian) +) + +for gaussian in [model_plateau_nest.gaussian_0, model_plateau_nest.gaussian_1]: + gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0) + +model_plateau_nest.add_assertion( + model_plateau_nest.gaussian_0.normalization + > model_plateau_nest.gaussian_1.normalization +) + +search = af.DynestyStatic( + nlive=200, # More live points than before, so the flat region is properly sampled. + sample="rwalk", +) + +print( + """ + The non-linear search has begun running. + This Jupyter notebook cell with progress once the search has completed - this could take a few minutes! + """ +) + +start = time.time() + +result_plateau_nest = search.fit(model=model_plateau_nest, analysis=analysis_x1) + +print(f"Dynesty run time: {time.time() - start} seconds") +print("The search has finished run - you may now continue the notebook.") + +print(result_plateau_nest.info) + +""" +The result above is the plateau made visible in numbers, so it is worth reading carefully. + +`gaussian_0` has recovered the true Gaussian, with a centre near 50.0, a normalization near 25.0 and a sigma near +10.0. `gaussian_1`, the component our assertion made the smaller one, has been pushed down to a small remnant whose +normalization interval runs down towards zero. The data needed one Gaussian and the search gave it one. + +Now compare the parameter uncertainties of the two components. The cell below prints the one sigma interval of +every parameter, which as tutorial 5 showed comes from `values_at_sigma`. +""" +names = result_plateau_nest.samples.model.model_component_and_parameter_names +values = result_plateau_nest.samples.values_at_sigma(sigma=1.0, as_instance=False) + +for name, (lower, upper) in zip(names, values): + print(f"{name}: {lower} -> {upper} (width {upper - lower})") + +""" +Compare the two components line by line, and compare the widths rather than the values, because the values move +from run to run. `gaussian_0`, which recovered the real Gaussian, has a tight interval on its centre and a tighter +one still on its sigma. `gaussian_1`, which contributes almost nothing, has intervals on the same two parameters +that are many times wider, with its sigma spanning a large part of the 0.0 to 25.0 prior we gave it. + +That is the plateau statement made quantitative. The less a component contributes, the less its shape parameters +matter, so their posterior drifts back towards the prior and the "error bar" you would quote drifts towards the +prior width. It looks like a measurement and it is not one! + +Now MCMC on the same plateau problem. +""" +model_plateau_mcmc = af.Collection( + gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian) +) + +for gaussian in [model_plateau_mcmc.gaussian_0, model_plateau_mcmc.gaussian_1]: + gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0) + +search = af.Emcee( + nwalkers=20, + nsteps=500, +) + +print( + """ + The non-linear search has begun running. + This Jupyter notebook cell with progress once the search has completed - this could take a few minutes! + """ +) + +start = time.time() + +result_plateau_mcmc = search.fit(model=model_plateau_mcmc, analysis=analysis_x1) + +print(f"Emcee run time: {time.time() - start} seconds") +print("The search has finished run - you may now continue the notebook.") + +print(result_plateau_mcmc.info) + +""" +Finally the gradient search. As tutorial 6 explained, `MultiStartAdam` differentiates the likelihood with JAX, so +its `Analysis` must be created with `use_jax=True`, and it walks many independent "lanes" uphill from different +starting points. +""" +model_plateau = af.Collection( + gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian) +) + +for gaussian in [model_plateau.gaussian_0, model_plateau.gaussian_1]: + gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0) + +analysis_x1_jax = Analysis(data=data_x1, noise_map=noise_map_x1, use_jax=True) + +search = af.MultiStartAdam( + n_starts=8, # The number of independent lanes launched through parameter space. + n_steps=150, # The number of gradient steps each lane takes. + learning_rate=0.5, + batch_size=None, # None evaluates every lane in one compiled call, as in tutorial 6. +) + +print( + """ + The non-linear search has begun running. + This Jupyter notebook cell with progress once the search has completed - this could take a few minutes! + """ +) + +start = time.time() + +result_adam = search.fit(model=model_plateau, analysis=analysis_x1_jax) + +print(f"MultiStartAdam run time: {time.time() - start} seconds") +print("The search has finished run - you may now continue the notebook.") + +print(result_adam.info) + +""" +Put the results side by side. I want to separate two things carefully here: what these particular short runs +actually showed, and what we know about the mechanisms independently of them. + +**What the runs above showed.** On the flip problem, nested sampling committed to one mirror and fitted it +excellently, while MCMC, given only 20 walkers and 500 steps, typically finished at a model worse than either +mirror and gave a different answer each time it was run. + +On the plateau problem, nested sampling recovered the true Gaussian, pushed the spare component down towards zero +normalization, and reported intervals on that component's shape parameters many times wider than on the real one's. +MCMC also found roughly the right Gaussian, and left its spare component wandering, often finishing with its sigma +against the edge of the prior, which is what a walker with nothing to climb does. The gradient search converged quickly, and where +it converged depended on where its lanes started: some runs recover the true Gaussian, and some settle on a poor +local maximum with a broad component parked near the edge of its prior. Compare the result above with the true +values to see which you got. + +Notice that none of the four ever announced a problem. Every one ran to completion and returned a result with error +bars. + +**What we know from the mechanisms.** A plateau is a region of exactly zero gradient, and a zero gradient point is +a fixed point a gradient search cannot leave: a lane stepping onto one stops moving and its figure of merit stops +changing, which from the outside is indistinguishable from convergence. A local maximum is a zero gradient point +too, which is why the run above looks exactly as converged as a correct one would. Nested sampling has no such +trap, because its live points are replaced from the whole prior volume rather than moved uphill from where they +are. MCMC sits in between: a walker on a flat region accepts every proposal, so it wanders rather than freezing, +but it may wander for a very long time. + +None of this says which search is best, and that is not the point. If searches with completely different mechanisms +agree, the answer is probably a property of your data. If they disagree, or if one gives a different answer every +run, that is almost never a statement about which search is better. It is a statement about your parameter space, +and the degeneracies and flat regions you have accidentally put in it. + +Running more than one search tells you about your model, not just your searches! +""" + +r""" +__Clipping__ + +So far every model has been computable everywhere: any combination of values inside the priors gave a number. + +That is not always true. Consider a different model of our two Gaussian data, in which the components are not +independent. Suppose the narrow component is an instrumental effect blurred into the broad one, so the width we +want for the broad component is what is left after the narrow one is removed in quadrature: + +\[ \sigma_{\rm halo} = \sqrt{\sigma_{1}^2 - \sigma_{0}^2} \] + +Where: + +- $\sigma_{0}$: the sigma of the narrow component, `gaussian_0`. +- $\sigma_{1}$: the sigma of the broad component, `gaussian_1`. +- $\sigma_{\rm halo}$: the width of the broad component after the narrow one is removed. + +In words: the broad component's true width is the broad width with the narrow width subtracted in quadrature. + +Now look at the priors. `gaussian_0.sigma` runs from 0.0 to 25.0 and so does `gaussian_1.sigma`, both perfectly +sensible ranges. But the *combination* $\sigma_{1} < \sigma_{0}$ asks for the square root of a negative number, +which is not a number at all. The individual priors are fine, the combination is unphysical. +""" + + +class DeconvolvedAnalysis(Analysis): + def model_data_from_instance(self, instance): + """ + Returns the summed model data of a narrow component plus a broad component whose width is the quadrature + difference of the two sigmas. + + This is unphysical, and undefined, whenever the sigma of `gaussian_1` is smaller than the sigma of + `gaussian_0`. + """ + xp = self._xp + + xvalues = xp.arange(self.data.shape[0]) + + sigma_halo = xp.sqrt( + instance.gaussian_1.sigma**2.0 - instance.gaussian_0.sigma**2.0 + ) + + halo = Gaussian( + centre=instance.gaussian_1.centre, + normalization=instance.gaussian_1.normalization, + sigma=sigma_halo, + ) + + return instance.gaussian_0.model_data_from( + xvalues=xvalues, xp=xp + ) + halo.model_data_from(xvalues=xvalues, xp=xp) + + +""" +Let's evaluate this likelihood at a physical set of parameters and at an unphysical one, where the only difference +is that the two sigmas have been swapped so the "narrow" component is wider than the "broad" one. +""" +analysis_nan = DeconvolvedAnalysis(data=data, noise_map=noise_map) + +model_nan = af.Collection(gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian)) + +for gaussian in [model_nan.gaussian_0, model_nan.gaussian_1]: + gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0) + +vector_physical = [50.0, 20.0, 1.0, 50.0, 40.0, 5.0] +vector_unphysical = [50.0, 20.0, 5.0, 50.0, 40.0, 1.0] + +print("Log likelihood of the physical model: ") +print( + analysis_nan.log_likelihood_function( + instance=model_nan.instance_from_vector(vector=vector_physical) + ) +) +print("Log likelihood of the unphysical model: ") +print( + analysis_nan.log_likelihood_function( + instance=model_nan.instance_from_vector(vector=vector_unphysical) + ) +) + +""" +The second log likelihood is `nan`, short for "not a number": what floating point arithmetic produces when asked to +do something impossible. NumPy also prints a `RuntimeWarning: invalid value encountered in sqrt`, which is expected +here and not a bug. A `nan` is contagious, in that any sum or product involving one gives another `nan`. + +A search receiving a `nan` could not rank it against anything else, so **PyAutoFit** never lets one through. Before +the figure of merit is returned it is checked for `nan` and for infinity, and either is replaced by the "resample +figure of merit" we met in the assertions section: this model is unusable, draw another. + +The detail worth knowing is that the resample figure of merit is not the same number for every search. For the MLE +and MCMC searches it is `-inf`, negative infinity, the natural choice because it is the worst possible log +likelihood: an MLE search never steps towards it and an MCMC walker never accepts it. + +For the nested samplers and for SMC it is `-1e99` instead, a huge negative number that is nevertheless finite. Their +arithmetic with log weights and shell evidences has to stay finite, so a genuine `-inf` would poison the whole +calculation rather than reject one sample. You do not choose these values; each search sets its own internally, and +there is no user facing argument for them. + +There is one family of search for which rejection is not enough. As tutorial 6 showed, the gradient searches step in +*physical* parameter units, computing a gradient and moving along it. A large enough step carries a lane out of a +prior's range, where the log prior of a `UniformPrior` is `-inf`. An MCMC search rejects such a proposal and the +walker stays put; a nested sampler never leaves the unit cube. A gradient step has neither protection: nothing pulls +the lane back, because outside the box the log prior is a *constant* `-inf` and the derivative of a constant is +zero, so the lane keeps walking away. + +That is why the gradient searches take a `clipper` argument. A "clipper" projects each lane back inside the prior +box after every step, supplying the restoring force that rejection gives the other searches. +""" +clipper = af.ClipperPriorBox() + +print(f"Clipper: {type(clipper).__name__}") + +""" +__NaN Diagnostics__ + +When you run a gradient search, **PyAutoFit** counts how often the likelihood and the gradient went non finite and +writes the counts to a file called `search.summary` in the output folder. To read that file we need the search to +write to disk, which as tutorial 5 showed means passing a `name` and a `path_prefix`. + +Let's fit our unphysical model with `MultiStartAdam`, using the clipper above, and then read the summary back. +""" +analysis_nan_jax = DeconvolvedAnalysis(data=data, noise_map=noise_map, use_jax=True) + +model_nan_fit = af.Collection( + gaussian_0=af.Model(Gaussian), gaussian_1=af.Model(Gaussian) +) + +for gaussian in [model_nan_fit.gaussian_0, model_nan_fit.gaussian_1]: + gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=25.0) + +search = af.MultiStartAdam( + name="tutorial_7_the_details_nan", + path_prefix="chapter_1_introduction", + n_starts=8, + n_steps=150, + learning_rate=0.5, + batch_size=None, # As above. + clipper=clipper, +) + +print( + """ + The non-linear search has begun running. + Checkout the HowToFit/output/chapter_1_introduction/tutorial_7_the_details_nan + folder for live output of the results. + This Jupyter notebook cell with progress once the search has completed - this could take a few minutes! + """ +) + +start = time.time() + +result_nan = search.fit(model=model_nan_fit, analysis=analysis_nan_jax) + +print(f"MultiStartAdam run time: {time.time() - start} seconds") +print("The search has finished run - you may now continue the notebook.") + +summary_path = path.join(str(search.paths.output_path), "search.summary") + +if path.exists(summary_path): + with open(summary_path) as summary_file: + print(summary_file.read()) + +""" +The block headed `Resampling Info` is the one we care about, and its two counters mean different things. + +`Value-NaN Lane-Steps` counts steps on which the likelihood itself was undefined, which happens whenever a lane +wanders into the region where `gaussian_1.sigma` is smaller than `gaussian_0.sigma`: the square root of a negative +number, a `nan` value, replaced by the resample figure of merit. + +`Gradient-NaN Lane-Steps` counts something subtler: steps on which the likelihood *value* was fine but its +*gradient* was not. Such a lane does not die and reports no error. The optimizer sees a non finite update, refuses +to apply it, and the lane stays exactly where it is, then does the same on the next step. A lane whose gradient is +`nan` is frozen, and a frozen lane is indistinguishable from a converged one in the figure of merit trace! + +`Resurrections` counts lanes restarted from a fresh point after dying, and the rate lines express the counters as a +fraction of the total lane-steps taken. + +The two counters are deliberately disjoint: a step is counted as a gradient-NaN only if its value was finite, so in +the run above, where every failure was an undefined square root, the gradient-NaN count is zero. Do not read that +as "gradient NaNs cannot happen here". How can a value be finite while its gradient is not? Here is the smallest +example, and it matters because the same pattern occurs constantly in real likelihood functions. +""" +import jax +import jax.numpy as jnp + +unsafe = lambda x: jnp.where(x > 0.0, jnp.sqrt(x), 0.0) + +print("Unsafe function at x = -1.0:") +print(f"value = {unsafe(-1.0)}") +print(f"gradient = {jax.grad(unsafe)(-1.0)}") + +""" +The value is `0.0`, exactly as intended, because the `where` selected the safe branch. The gradient is `nan`. + +Reverse mode automatic differentiation, which is how JAX computes gradients, differentiates *both* branches of a +`where` and multiplies the unselected one by zero. The derivative of `sqrt(x)` at `x = -1` is `nan`, and zero times +`nan` is `nan`, not zero. The mask protected the value and did nothing for the gradient. + +The fix is never to evaluate the offending operation at the invalid input, which takes a second `where` inside the +first. The inner `where` replaces the invalid input with a harmless one, so `sqrt` is only called on a positive +number, and the outer `where` still selects the right answer. +""" +safe = lambda x: jnp.where(x > 0.0, jnp.sqrt(jnp.where(x > 0.0, x, 1.0)), 0.0) + +print("Safe function at x = -1.0:") +print(f"value = {safe(-1.0)}") +print(f"gradient = {jax.grad(safe)(-1.0)}") + +""" +Same value, and now a finite gradient. + +The lesson generalizes far beyond this function. A guard that checks the result of a calculation can only protect +the value, because by the time it runs the damage to the derivative is already recorded. Safety has to live where +the `nan` is created, not where it is detected. + +A good likelihood value does not mean a good gradient! + +__Unit Cube Vs Physical__ + +The last detail is the most fundamental, and it changes how you think about every prior you have written. + +In tutorial 1 we mapped a vector of physical parameter values onto a model instance with `instance_from_vector`, and +in tutorial 3 we gave each parameter a prior. Those ideas are closer than they look, because a non-linear search +does not work in physical units at all. + +What a search explores is the "unit cube": a space where every parameter runs from 0.0 to 1.0, whatever it means and +whatever units it has, and the prior is the function converting a unit value into a physical one. **PyAutoFit** +exposes this mapping directly, so let's build a model with three deliberately different priors and ask what the +exact centre of the unit cube corresponds to. +""" +model_cube = af.Model(Gaussian) + +model_cube.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) +model_cube.normalization = af.LogUniformPrior(lower_limit=1e-2, upper_limit=1e2) +model_cube.sigma = af.GaussianPrior(mean=10.0, sigma=5.0) + +print(model_cube.model_component_and_parameter_names) + +print("Physical vector at the centre of the unit cube:") +print(model_cube.vector_from_unit_vector(unit_vector=[0.5, 0.5, 0.5])) + +instance_cube = model_cube.instance_from_unit_vector(unit_vector=[0.5, 0.5, 0.5]) + +print(f"Centre = {instance_cube.centre}") +print(f"Normalization = {instance_cube.normalization}") +print(f"Sigma = {instance_cube.sigma}") + +""" +Look carefully at the second number. A unit value of 0.5 mapped `centre` to 50.0, which is what you would expect +from a `UniformPrior` between 0.0 and 100.0. But the same unit value mapped `normalization` to 1.0, not 50.005. + +That is because a `LogUniformPrior` between 0.01 and 100.0 puts the *geometric* midpoint at the centre of the cube, +and the geometric midpoint of 0.01 and 100.0 is 1.0. Let's see it directly, comparing the two priors a quarter of +the way through the cube as well. +""" +print( + f"UniformPrior at unit 0.25: {af.UniformPrior(lower_limit=0.0, upper_limit=100.0).value_for(0.25)}" +) +print( + f"UniformPrior at unit 0.50: {af.UniformPrior(lower_limit=0.0, upper_limit=100.0).value_for(0.5)}" +) +print( + f"LogUniformPrior at unit 0.25: {af.LogUniformPrior(lower_limit=1e-2, upper_limit=1e2).value_for(0.25)}" +) +print( + f"LogUniformPrior at unit 0.50: {af.LogUniformPrior(lower_limit=1e-2, upper_limit=1e2).value_for(0.5)}" +) + +""" +The uniform prior moves in equal steps of 25.0 across the cube. The log uniform prior moves in equal steps of one +order of magnitude, from 0.1 a quarter of the way through to 1.0 at halfway. + +This is the point of the section. The prior is not a filter applied to a search that would otherwise explore +physical space evenly, the prior *is* the geometry of the space the search explores. A log uniform prior makes the +search spend equal effort on each decade, which is what you want for a parameter that could be 0.1 or 100. A +uniform prior over the same range spends most of its effort above 10.0 and would essentially never propose a value +below 1.0. + +The searches use this differently. Nested samplers work in the unit cube directly, drawing their live points from +it, which is why they cannot take a starting point and never step outside a prior's range. MLE and MCMC searches +step in physical units instead, which is why they can walk out of a prior box, and why clipping matters for them +and not for nested sampling. + +Choosing a prior is not just a statement about what you believe. It is a decision about what the search's parameter +space looks like! + +__Summary__ + +There are many details underneath a model-fit. We have looked at parameterization and mirror solutions, assertions, +plateaus, the resample figure of merit, `nan` values and their gradients, and the unit cube. There are more, and no +tutorial could cover them all. + +Most of the time, none of them matter. A sensible model, sensible priors and a sensible search give a sensible +answer, and you could go a whole career without thinking about a single thing in this tutorial. That is a property +of **PyAutoFit**: the defaults are chosen so the ordinary case works. + +When they do matter, attending to them buys three things. Inference runs faster, sometimes by a large factor, +because the search wastes no effort on redundant regions of parameter space. It converges on the right solution more +often, because there are fewer wrong places to get stuck. And it protects you from the worst case in model-fitting, +which is not a fit that crashes but a fit that returns the wrong answer and gives you no reason to doubt it. + +The tools in this tutorial are how you get a fit to complain out loud instead of failing quietly! + +Tutorial 8 moves on from a single fit to the scientific workflow: how to organise, compare and interpret the many +fits a real analysis is made of. There is also an optional tutorial on the Bayesian formalism underlying everything +we have done, which puts the priors, likelihoods and evidences used throughout this chapter on a formal footing. +""" diff --git a/scripts/chapter_1_introduction/tutorial_6_scientific_workflow.py b/scripts/chapter_1_introduction/tutorial_8_scientific_workflow.py similarity index 96% rename from scripts/chapter_1_introduction/tutorial_6_scientific_workflow.py rename to scripts/chapter_1_introduction/tutorial_8_scientific_workflow.py index 4621e5c..06984e8 100644 --- a/scripts/chapter_1_introduction/tutorial_6_scientific_workflow.py +++ b/scripts/chapter_1_introduction/tutorial_8_scientific_workflow.py @@ -1,6 +1,6 @@ """ -Tutorial 6: Scientific Workflow -============================== +Tutorial 8: Scientific Workflow +=============================== You can now compose a model, fit it to data and interpret its results. A scientific study often repeats these steps for many datasets, competing models and different non-linear searches. The next challenge is diff --git a/scripts/chapter_1_introduction/tutorial_optional_bayesian_formalism.py b/scripts/chapter_1_introduction/tutorial_optional_bayesian_formalism.py new file mode 100644 index 0000000..41a96e7 --- /dev/null +++ b/scripts/chapter_1_introduction/tutorial_optional_bayesian_formalism.py @@ -0,0 +1,554 @@ +r""" +Tutorial Optional: Bayesian Formalism +===================================== + +Every tutorial in this chapter has been an exercise in Bayesian inference, and not one of them wrote down a single +equation of probability theory. That was deliberate. The **HowToFit** lectures are built on the conviction that you +can learn to fit models to data properly, and interpret the results correctly, without first sitting through a +course on Bayesian statistics. + +This optional tutorial writes those equations down anyway. + +Nothing in it will make your fits better. What it does is connect the phenomenological picture built up over +tutorials 1 to 7 -- guessing models, likelihood surfaces, walkers, live points, gradients -- to the handful of +symbols that papers and documentation use for exactly the same things. When a referee asks whether you quoted the +maximum likelihood model or the median of the marginalized posterior, this tutorial tells you they are talking +about quantities you have already computed. + +My suggestion is to read it once, run it once, and then forget most of it. + +__Contents__ + +This tutorial is split into the following sections: + +- **Bayes Theorem**: The equation that every tutorial so far has been solving without writing it down. +- **Data**: Load the 1D Gaussian dataset that every equation in this tutorial is evaluated on. +- **The Model**: The parameters of tutorial 1 as the thing Bayes' theorem is about. +- **The Likelihood**: Why the chi-squared and noise normalization of tutorial 2 are the log of a Gaussian likelihood. +- **The Prior**: The priors of tutorial 3 as a probability distribution, and the unit cube as its inverse. +- **The Posterior**: The samples of tutorial 5 as draws from the posterior, and a numerical check that log prior plus log likelihood is the log posterior. +- **Maximum Likelihood Vs Maximum A Posteriori**: Two different "best-fit" answers and when they differ. +- **Marginalization**: The one-dimensional PDFs and errors of tutorial 5 as integrals over the other parameters. +- **The Evidence**: The Bayesian evidence of tutorial 5 as the normalization of Bayes' theorem, and why nested sampling computes it. +- **Gradients**: The gradient of tutorial 6 as the derivative of the log posterior. +- **Wrap Up**: Why HowToFit hides the maths, and why it helps to know it anyway. + +__Bayes Theorem__ + +Here is the equation that every tutorial in this chapter has been solving without ever writing it down: + +\[ P(\theta \mid D) = \frac{P(D \mid \theta)\,P(\theta)}{P(D)} \] + +Where: + +- \( \theta \): the model parameters, for our 1D Gaussian the three numbers `centre`, `normalization` and `sigma`. + +- \( D \): the data, for us the 1D array of 100 values loaded from `data.json` together with its noise-map. + +- \( P(\theta \mid D) \): the "posterior", the probability of the parameters given the data, and the quantity we + actually want. + +- \( P(D \mid \theta) \): the "likelihood", the probability of the data given the parameters, computed by the + `log_likelihood_function` of tutorial 3 before we take its logarithm. + +- \( P(\theta) \): the "prior", the probability we assign to parameter values before looking at the data, the + `UniformPrior` and `LogUniformPrior` objects of tutorial 3. + +- \( P(D) \): the "evidence", a single number which normalizes the right hand side, the `log_evidence` of tutorial 5. + +In plain words: the answer we want is the goodness-of-fit multiplied by our prior beliefs, divided by a normalizing +number. Every algorithm in this chapter is a strategy for evaluating the right hand side without ever computing the +integral hiding inside \( P(D) \). + +Each tutorial supplied exactly one piece. Tutorial 1 built \( \theta \) and the forward model. Tutorial 2 built +\( P(D \mid \theta) \), calling it the log likelihood. Tutorial 3 built \( P(\theta) \) and the searches which +explore the product of the two. Tutorial 4 showed what goes wrong when the posterior has more than one peak, +tutorial 5 read the answer back out, and tutorials 6 and 7 differentiated it and asked what the numbers mean. + +So when this tutorial says "the posterior", you have already computed one. We are only relabelling. +""" + +# from autofit import setup_notebook; setup_notebook() + +from os import path +import matplotlib.pyplot as plt +import numpy as np +import scipy.stats + +import autofit as af + +""" +__Data__ + +We use the same `gaussian_x1` dataset that tutorials 2 and 3 fitted, so every equation below is evaluated on a fit +you have already seen. +""" +dataset_path = path.join("dataset", "example_1d", "gaussian_x1") + +""" +__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 not path.exists(dataset_path): + import subprocess + import sys + + subprocess.run( + [sys.executable, "scripts/simulators/simulators.py"], + check=True, + ) + +data = af.util.numpy_array_from_json(file_path=path.join(dataset_path, "data.json")) +noise_map = af.util.numpy_array_from_json( + file_path=path.join(dataset_path, "noise_map.json") +) + +xvalues = np.arange(data.shape[0]) + +r""" +__The Model__ + +The symbol \( \theta \) is nothing more exotic than the list of numbers you passed to `instance_from_vector` in +tutorial 1. Bayes' theorem is a statement about a probability distribution over that list, and nothing else. + +We therefore begin as tutorial 1 did, by re-pasting the `Gaussian` class in full. Its constructor arguments are the +entries of \( \theta \), and its `model_data_from` method is the forward model: the function which, given +\( \theta \), predicts what the data should look like. +""" + + +class Gaussian: + def __init__( + self, + centre: float = 30.0, # <- **PyAutoFit** recognises these constructor arguments + normalization: float = 1.0, # <- are the Gaussian`s model parameters. + sigma: float = 5.0, + ): + """ + Represents a 1D Gaussian profile. + + This is a model-component of example models in the **HowToFit** lectures and is used to perform model-fitting + of example datasets. + + Parameters + ---------- + centre + The x coordinate of the profile centre. + normalization + Overall normalization of the profile. + sigma + The sigma value controlling the size of the Gaussian. + """ + self.centre = centre + self.normalization = normalization + self.sigma = sigma + + def model_data_from(self, xvalues: np.ndarray) -> np.ndarray: + """ + Returns a 1D Gaussian on an input list of Cartesian x coordinates. + + The input xvalues are translated to a coordinate system centred on the Gaussian, via its `centre`. + + The output is referred to as the `model_data` to signify that it is a representation of the data from the + model. + + Parameters + ---------- + xvalues + The x coordinates in the original reference frame of the data. + + Returns + ------- + np.array + The Gaussian values at the input x coordinates. + """ + transformed_xvalues = np.subtract(xvalues, self.centre) + return np.multiply( + np.divide(self.normalization, self.sigma * np.sqrt(2.0 * np.pi)), + np.exp(-0.5 * np.square(np.divide(transformed_xvalues, self.sigma))), + ) + + +r""" +Composing the model gives the two pieces of book-keeping which make \( \theta \) concrete. The `prior_count` is the +number of dimensions the posterior is a distribution over, and `paths` gives the order of the entries in the vector. +""" +model = af.Model(Gaussian) + +print("Number of parameters in theta:", model.prior_count) +print("Order of the parameters in theta:", model.paths) + +r""" +A specific \( \theta \) becomes a model, and the model becomes predicted data, in the two lines below. This is the +forward modelling of tutorial 1, and it is what lets us ask "how probable is the data, given these parameters?". +""" +instance = model.instance_from_vector(vector=[50.0, 25.0, 10.0]) + +model_data = instance.model_data_from(xvalues=xvalues) + +plt.errorbar( + x=xvalues, + y=data, + yerr=noise_map, + linestyle="", + color="k", + ecolor="k", + elinewidth=1, + capsize=2, +) +plt.plot(xvalues, model_data, color="r") +plt.title("The data D, with the forward model prediction for one theta.") +plt.xlabel("x values of profile") +plt.ylabel("Profile normalization") +plt.show() +plt.close() + +r""" +__The Likelihood__ + +In tutorial 2 we built a chain of quantities -- residuals, a chi-squared and a noise normalization -- and combined +the last two into a log likelihood by multiplying their sum by -0.5. At the time I said the reason for the -0.5 was +not critical. Here it is. + +We assume each data point is its predicted value plus a random draw from a Gaussian of width equal to that point's +noise. The probability of the whole dataset is then a product of one Gaussian probability per data point: + +\[ P(D \mid \theta) = \prod_i \frac{1}{\sqrt{2\pi\sigma_i^2}} \exp\left(-\frac{(d_i - m_i)^2}{2\sigma_i^2}\right) \] + +Taking the logarithm turns that product into a sum: + +\[ \ln P(D \mid \theta) = -\frac{1}{2} \sum_i \frac{(d_i - m_i)^2}{\sigma_i^2} - \frac{1}{2} \sum_i \ln(2\pi\sigma_i^2) \] + +Where: + +- \( d_i \): the value of the data at point \( i \), the `data` array. + +- \( m_i \): the value of the model data at point \( i \), computed by `model_data_from` for this \( \theta \). + +- \( \sigma_i \): the noise at point \( i \), the `noise_map` array. + +Compare the second equation with tutorial 2 line by line. The first sum is the `chi_squared`, and the second is the +`noise_normalization`, the log of the product of the Gaussian prefactors. Both are multiplied by -0.5, which is +where the mysterious factor comes from: it is not a convention, it is the 2 in the denominator of the exponent of a +Gaussian. The noise normalization really is a constant, because it depends only on the noise-map and never on +\( \theta \), so it shifts every log likelihood equally and can never change which model wins. + +Below we compute the log likelihood twice: by tutorial 2's chi-squared route, and by summing the log of a Gaussian +probability density at every data point using `scipy`. They are the same number. +""" +residual_map = data - model_data +chi_squared = np.sum((residual_map / noise_map) ** 2.0) +noise_normalization = np.sum(np.log(2 * np.pi * noise_map**2.0)) + +log_likelihood = -0.5 * (chi_squared + noise_normalization) + +log_likelihood_via_pdf = np.sum( + scipy.stats.norm.logpdf(data, loc=model_data, scale=noise_map) +) + +print("Log likelihood via tutorial 2's chi-squared = ", log_likelihood) +print("Log likelihood via a sum of Gaussian PDFs = ", log_likelihood_via_pdf) + +r""" +__The Prior__ + +The priors of tutorial 3 were introduced as a way of telling the search where to look. Formally they are +\( P(\theta) \), a probability distribution over the parameters written down before we look at the data. Because our +parameters are independent, the prior is a product of one distribution per parameter and its logarithm is a sum, +\( \ln P(\theta) = \sum_j \ln P(\theta_j) \). + +The two priors on the default `Gaussian` model have simple forms. A `UniformPrior` is constant inside its limits and +zero outside them, so its log is a constant we may set to zero inside and negative infinity outside. A +`LogUniformPrior` is proportional to \( 1 / \theta_j \), the statement "every order of magnitude is equally likely", +so its log falls off as \( -\ln \theta_j \). + +**PyAutoFit** hands you those numbers directly. Below we print the priors of the model, then evaluate the log prior +of each parameter inside the prior limits, and then for a `centre` of 150.0 which lies outside the `UniformPrior` +limits of 0.0 to 100.0. +""" +print(model.info) + +print("Log prior of each parameter, theta = [50.0, 25.0, 10.0]:") +print(model.log_prior_list_from_vector(vector=[50.0, 25.0, 10.0])) + +print("Log prior of each parameter, theta = [150.0, 25.0, 10.0]:") +print(model.log_prior_list_from_vector(vector=[150.0, 25.0, 10.0])) + +r""" +The first entry of the second list is `-inf`, an infinitely improbable model. This is the formal version of tutorial +3's statement that priors define the valid parameter space: a model outside the priors is not penalised, it is +excluded. The middle entry is not zero, because the `LogUniformPrior` on `normalization` prefers smaller values and +\( -\ln(25) \) is about -3.2. + +Priors enter a fit a second way, and it is how nested sampling works. Every prior can be inverted: instead of asking +"how probable is this value?", we ask "which value sits at this fraction of the distribution?". That inverse is the +inverse cumulative distribution function, and in **PyAutoFit** it is the `value_for` method, which maps a number +between 0 and 1 -- the "unit cube" -- onto a physical parameter value. Feeding in 0.5 asks each prior for its +median, and the lines below show why a unit value is not the same thing as a parameter value. +""" +uniform_prior = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) +log_uniform_prior = af.LogUniformPrior(lower_limit=1e-2, upper_limit=1e2) +gaussian_prior = af.GaussianPrior(mean=10.0, sigma=5.0) + +print("UniformPrior(0.0, 100.0).value_for(0.5) = ", uniform_prior.value_for(0.5)) +print( + "LogUniformPrior(0.01, 100.0).value_for(0.5) = ", log_uniform_prior.value_for(0.5) +) +print( + "GaussianPrior(mean=10, sigma=5).value_for(0.5) = ", gaussian_prior.value_for(0.5) +) + +print("The whole model, unit cube [0.5, 0.5, 0.5] mapped to physical values:") +print(model.vector_from_unit_vector(unit_vector=[0.5, 0.5, 0.5])) + +r""" +This is the key to a sentence in tutorial 3 which may have seemed arbitrary: nested sampling "draws live points from +the priors". A search which picks unit values uniformly at random between 0 and 1 and passes them through +`value_for` is drawing samples from the prior distribution itself. It is also why a nested sampling search cannot be +given a starting point: its first step is defined to be a draw from \( P(\theta) \). + +__The Posterior__ + +We now have both pieces of the numerator of Bayes' theorem, so we can fit the model and look at the left hand side. +The `Analysis` class below is the one from tutorial 3, whose `log_likelihood_function` returns exactly the equation +verified above, and we fit it with the nested sampling search of tutorial 3. +""" + + +class Analysis(af.Analysis): + def __init__(self, data: np.ndarray, noise_map: np.ndarray): + """ + The `Analysis` class acts as an interface between the data and model in **PyAutoFit**, exactly as it did in + tutorial 3. + + Parameters + ---------- + data + A 1D numpy array containing the data (e.g. a noisy 1D signal) fitted in the workspace examples. + noise_map + A 1D numpy array containing the noise values of the data. + """ + super().__init__() + + self.data = data + self.noise_map = noise_map + + def log_likelihood_function(self, instance) -> float: + """ + Returns the log likelihood of a fit of a 1D Gaussian to the dataset, which is the log of a product of + Gaussian probabilities, one per data point, as derived in the `The Likelihood` section above. + """ + xvalues = np.arange(self.data.shape[0]) + + model_data = instance.model_data_from(xvalues=xvalues) + residual_map = self.data - model_data + chi_squared_map = (residual_map / self.noise_map) ** 2.0 + chi_squared = np.sum(chi_squared_map) + noise_normalization = np.sum(np.log(2 * np.pi * self.noise_map**2.0)) + + return -0.5 * (chi_squared + noise_normalization) + + +analysis = Analysis(data=data, noise_map=noise_map) + +search = af.DynestyStatic( + sample="rwalk", # This makes dynesty run faster, dont worry about what it means for now! +) + +print( + """ + The non-linear search has begun running. + This Jupyter notebook cell with progress once the search has completed - this could take a few minutes! + """ +) + +model = af.Model(Gaussian) + +result = search.fit(model=model, analysis=analysis) + +print("The search has finished run - you may now continue the notebook.") + +r""" +The `Samples` object of tutorial 5 is the posterior. Each entry of `parameter_lists` is a \( \theta \) the search +accepted, and each entry of `weight_list` says how much that sample counts when the posterior is summed up. Together +they approximate \( P(\theta \mid D) \): a cloud of points, denser where the posterior is higher. + +Tutorial 5 also told you, without justification, that the log posterior is the log likelihood plus the log prior. +That is Bayes' theorem logged, with the evidence dropped because it is the same number for every sample: + +\[ \ln P(\theta \mid D) = \ln P(D \mid \theta) + \ln P(\theta) - \ln P(D) \] + +Below we check the first few samples, printing the log likelihood, log prior, log posterior, and the difference +between the log posterior and the sum of the first two. +""" +samples = result.samples + +total_printed = min(5, len(samples.log_likelihood_list)) + +print("Sample : log likelihood : log prior : log posterior : difference") + +for sample_index in range(total_printed): + log_likelihood = samples.log_likelihood_list[sample_index] + log_prior = samples.log_prior_list[sample_index] + log_posterior = samples.log_posterior_list[sample_index] + + print( + sample_index, + log_likelihood, + log_prior, + log_posterior, + log_posterior - (log_likelihood + log_prior), + ) + +r""" +The final column is zero. There is no approximation in that identity, it is the definition of the log posterior, and +it means every number tutorial 5 printed was already a Bayesian quantity. Note also how much larger the log +likelihoods are than the log priors: for this fit the data is far more informative than our prior beliefs. + +__Maximum Likelihood Vs Maximum A Posteriori__ + +There are two "best-fit" models hiding in a set of samples, and tutorial 5 printed both without saying they could +disagree: + +- The "maximum likelihood" model, `samples.max_log_likelihood()`, is the \( \theta \) fitting the data best, + ignoring the priors entirely. + +- The "maximum a posteriori" model, usually shortened to MAP, `samples.max_log_posterior()`, is the \( \theta \) + which maximizes likelihood times prior. + +If every prior is uniform the log prior is the same constant inside the limits, so the two are the same model. They +separate only when a prior varies appreciably across the region the data allows. +""" +print("Maximum likelihood theta = ", samples.max_log_likelihood(as_instance=False)) +print("Maximum a posteriori theta = ", samples.max_log_posterior(as_instance=False)) + +r""" +For this fit they agree, or very nearly, because the log-uniform prior on `normalization` is almost flat over the +tiny range of normalizations the data permits. Had we instead placed a tight Gaussian prior on `centre`, say a mean +of 49.0 with a sigma of 0.05, the log prior would fall away steeply across the region the data allows and the MAP +model would be pulled towards 49.0, away from what the data alone prefers. + +Neither answer is wrong, they answer different questions, and a paper quoting one while calling it the other is +making a real mistake. It is also why most results are quoted as neither, but as the median of the marginalized +posterior. + +__Marginalization__ + +Tutorial 5 quoted a value and an error for each parameter individually, and plotted their 1D histograms via +`aplt.corner_cornerpy`. That requires an operation with a formal name, "marginalization", which means integrating +the posterior over the parameters you are not currently interested in: + +\[ P(\theta_1 \mid D) = \int P(\theta \mid D) \, d\theta_2 \, d\theta_3 \ldots \] + +Where: + +- \( \theta_1 \): the parameter we want a one-dimensional answer for, for example `centre`. + +- \( \theta_2, \theta_3, \ldots \): every other parameter of the model, integrated away. + +That integral looks intimidating, and done analytically it would be. This is the greatest practical advantage of +having samples: marginalizing them means ignoring the columns you do not care about and histogramming the one you +do, weighted by `weight_list`. The integral becomes a counting exercise, and the cell below marginalizes over +`normalization` and `sigma` by never mentioning them. +""" +centre_list = [parameters[0] for parameters in samples.parameter_lists] + +plt.hist(centre_list, bins=30, weights=samples.weight_list, color="k") +plt.title("Marginalized 1D posterior of the Gaussian's centre.") +plt.xlabel("centre of the Gaussian") +plt.ylabel("Posterior probability") +plt.show() +plt.close() + +""" +Every summary statistic of tutorial 5 is read off that curve. The `median_pdf` value is the point with half the +weight either side of it, and the values at a given sigma are the points enclosing the corresponding fraction of it, +68 per cent at one sigma. +""" +print("Median of the marginalized posterior:") +print(samples.median_pdf(as_instance=False)) + +print("Values at 1.0 sigma confidence (lower, upper) for each parameter:") +print(samples.values_at_sigma(sigma=1.0, as_instance=False)) + +r""" +__The Evidence__ + +The one term of Bayes' theorem we have ignored is the denominator, \( P(D) \), the evidence. It is the integral of +the numerator over the whole of parameter space: + +\[ P(D) = \int P(D \mid \theta) \, P(\theta) \, d\theta \] + +Where: + +- The integral runs over every value of every parameter the priors allow. + +Two facts about this integral explain a lot of what you have seen. First, it does not depend on \( \theta \), which +is why MCMC never needs it: a walker deciding whether to move compares posteriors as a ratio and the evidence +cancels. Second, it is genuinely hard, an integral over a many-dimensional space in which almost all of the volume +contributes almost nothing. + +Nested sampling gets it almost for free, and this is the real reason the algorithm is built the way it is. Tutorial +3 described it as replacing the lowest-likelihood live point over and over, and each replacement shrinks the prior +volume still under consideration by a known factor, so summing likelihood times shrinking volume as it goes is the +integral above. The parameter estimates are the by-product, the evidence is what the method actually computes, and +because it penalises models which spread their prior probability over regions the data rejects, comparing the +evidence of two models is the Bayesian way to ask whether extra parameters were worth adding. +""" +log_evidence = samples.log_evidence + +if log_evidence is not None: + print("Log evidence of this model = ", log_evidence) +else: + print("This search does not compute a Bayesian evidence, so log_evidence is None.") + +r""" +__Gradients__ + +Tutorial 6 introduced the gradient: the direction in which the log likelihood increases fastest, computed exactly by +automatic differentiation. In this notation, what the gradient searches climb is the derivative of the log +posterior: + +\[ \nabla_\theta \ln P(\theta \mid D) = \nabla_\theta \ln P(D \mid \theta) + \nabla_\theta \ln P(\theta) \] + +Where: + +- \( \nabla_\theta \): the vector of derivatives with respect to each parameter in turn. + +The evidence has vanished, and its disappearance is the point. Because \( \ln P(D) \) does not depend on +\( \theta \), differentiating it gives zero: the hardest term in Bayes' theorem is invisible to any method which +only ever looks at slopes. + +This is the formal reason gradient methods scale so well. Hamiltonian Monte Carlo and its self-tuning variant NUTS, +which tutorial 6 introduced, use this gradient to propose moves following the contours of the posterior rather than +stumbling across them at random. In many dimensions, knowing which way is uphill is worth an enormous number of the +blind guesses tutorial 4 showed we could not afford to make. + +There is no code here, because the numbers were computed in tutorial 6. All that is new is the name of the quantity +being differentiated. + +__Wrap Up__ + +The **HowToFit** lectures teach model-fitting without formal statistics on purpose. Most scientists who fit models +to data do not need the equations to do it well: they need to know what a log likelihood measures, why priors +matter, which search suits their problem and how to tell a good fit from a bad one. Every one of those lessons was +taught in this chapter without an integral in sight. + +Knowing the formalism afterwards is still worth an hour of your time. It tells you that the maximum likelihood model +and the median of the marginalized posterior answer different questions, and what the log evidence in `result.info` +is an integral of. And it lets you read a methods section, where these quantities go by their symbols rather than +their attribute names. + +So, with your own problem in mind: + +- Which of the two "best-fit" answers above is the one your field quotes, and is it the one you have been quoting? + +- How informative are your priors compared with your data, and would your results change if someone else chose them? + +- Is there a question in your science which is really a model comparison, and therefore really about the evidence? + +If you are unsure, that is fine, and it is no obstacle to fitting models. Go back to tutorial 5, run a fit and look +at the numbers again. They will mean a little more than they did before. +""" diff --git a/workspace_index.json b/workspace_index.json index fc3c726..afe17d6 100644 --- a/workspace_index.json +++ b/workspace_index.json @@ -8,7 +8,10 @@ "tutorial_3_non_linear_search.py", "tutorial_4_why_modeling_is_hard.py", "tutorial_5_results_and_samples.py", - "tutorial_6_scientific_workflow.py" + "tutorial_6_gradients.py", + "tutorial_7_the_details.py", + "tutorial_8_scientific_workflow.py", + "tutorial_optional_bayesian_formalism.py" ], "notebook": "notebooks/chapter_1_introduction/start_here.ipynb", "path": "scripts/chapter_1_introduction/start_here.py", @@ -139,15 +142,79 @@ "summary": "In this tutorial, we'll cover all of the output that comes from a non-linear search's `Result` object.", "title": "Tutorial 5: Results And Samples" }, + { + "contents": [ + "Data", + "Model", + "Analysis", + "Gradients", + "Finite Differencing", + "JAX and Autodiff", + "Maximum Likelihood Estimation (MLE)", + "Markov Chain Monte Carlo (MCMC)", + "Nested Sampling", + "Errors From Curvature", + "Wrap Up" + ], + "cross_refs": [ + "corner.py" + ], + "notebook": "notebooks/chapter_1_introduction/tutorial_6_gradients.ipynb", + "path": "scripts/chapter_1_introduction/tutorial_6_gradients.py", + "summary": "In tutorial 3, describing how a maximum likelihood estimator works, we said it \"evaluates the likelihood at nearby points to estimate the gradient, determining the direction in which to move up in parameter space\". That sentence slipped by quickly, but it hides one of the most important ideas in model-fitting: the search does not have to be blind, because the likelihood surface has a slope, and the slope tells us which way is up.", + "title": "Tutorial 6: Gradients" + }, + { + "contents": [ + "Data", + "Model", + "Analysis", + "Parameterization", + "Assertions", + "Plateaus", + "Comparing Searches", + "Clipping", + "NaN Diagnostics", + "Unit Cube Vs Physical", + "Summary" + ], + "cross_refs": [ + "corner.py" + ], + "notebook": "notebooks/chapter_1_introduction/tutorial_7_the_details.ipynb", + "path": "scripts/chapter_1_introduction/tutorial_7_the_details.py", + "summary": "In tutorial 6 we opened up the non-linear search and looked at how it moves. We saw that some searches only ever ask the likelihood function \"what is the value here?\", whilst gradient based searches also ask \"and which way is uphill?\", and that **PyAutoFit** can answer the second question exactly by using JAX to differentiate the likelihood function.", + "title": "Tutorial 7: The Details" + }, { "contents": [], "cross_refs": [ "//github.com/PyAutoLabs/autofit_workspace/blob/main/scripts/overview/overview_2_scientific_workflow.py" ], - "notebook": "notebooks/chapter_1_introduction/tutorial_6_scientific_workflow.ipynb", - "path": "scripts/chapter_1_introduction/tutorial_6_scientific_workflow.py", + "notebook": "notebooks/chapter_1_introduction/tutorial_8_scientific_workflow.ipynb", + "path": "scripts/chapter_1_introduction/tutorial_8_scientific_workflow.py", "summary": "You can now compose a model, fit it to data and interpret its results. A scientific study often repeats these steps for many datasets, competing models and different non-linear searches. The next challenge is keeping those fits organized so that you can understand and compare them.", - "title": "Tutorial 6: Scientific Workflow" + "title": "Tutorial 8: Scientific Workflow" + }, + { + "contents": [ + "Bayes Theorem", + "Data", + "The Model", + "The Likelihood", + "The Prior", + "The Posterior", + "Maximum Likelihood Vs Maximum A Posteriori", + "Marginalization", + "The Evidence", + "Gradients", + "Wrap Up" + ], + "cross_refs": [], + "notebook": "notebooks/chapter_1_introduction/tutorial_optional_bayesian_formalism.ipynb", + "path": "scripts/chapter_1_introduction/tutorial_optional_bayesian_formalism.py", + "summary": "Every tutorial in this chapter has been an exercise in Bayesian inference, and not one of them wrote down a single equation of probability theory. That was deliberate. The **HowToFit** lectures are built on the conviction that you can learn to fit models to data properly, and interpret the results correctly, without first sitting through a course on Bayesian statistics.", + "title": "Tutorial Optional: Bayesian Formalism" }, { "contents": [