diff --git a/AGENTS.md b/AGENTS.md index 6906b6c..ce4f142 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,7 +9,7 @@ interpret probabilistic models from first principles. It is the teaching compani - `scripts/` — Runnable Python tutorial scripts: - `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 + - `chapter_advanced/` — 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) - `config/` — PyAutoFit configuration YAML diff --git a/README.md b/README.md index feac30f..f05aab9 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,8 @@ # HowToFit +[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/start_here.ipynb) + +[Start Here on Colab](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/start_here.ipynb) | [Installation Guide](https://pyautofit.readthedocs.io/en/latest/installation/overview.html) | [PyAutoFit readthedocs](https://pyautofit.readthedocs.io/en/latest/index.html) | [Browse Chapter 1 With Images](markdown/README.md) | @@ -23,27 +26,39 @@ they are concise, API-focused, and assume the concepts taught in **HowToFit** as - `chapter_1_introduction` — Models, likelihoods, non-linear searches, why modeling is hard, and how to interpret the results of a fit, ending with a short guide to building a scientific workflow. -- `chapter_3_graphical_models` — Fitting many datasets simultaneously with graphical models, +- `chapter_advanced` — Fitting many datasets simultaneously with graphical models, hierarchical models, and Expectation Propagation. -Each chapter is organised into numbered tutorial files: `chapter__/tutorial__.py` -(Python script) or the matching `.ipynb` in `notebooks/`. Tutorials build on each other within a -chapter and assume you have completed the earlier ones. +Each chapter is a folder of numbered tutorial files — `tutorial__.py` (Python script) or the +matching `.ipynb` in `notebooks/`. Tutorials build on each other within a chapter and assume you have +completed the earlier ones. ## Getting Started -You can run the tutorials on your own machine by following the +### Run in Google Colab (nothing to install) + +Every tutorial opens in Google Colab in one click. There is nothing to install and no local Python +environment to set up — **PyAutoFit** installs itself in the notebook's first cell. + +- **[Start here](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/start_here.ipynb)** — a one-page overview of the whole series. +- **[Chapter 1, Tutorial 1: Models](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_1_introduction/tutorial_1_models.ipynb)** — the first tutorial. +- Every tutorial, chapter by chapter: **[chapter 1](scripts/chapter_1_introduction/README.md)** | + **[the advanced chapter](scripts/chapter_advanced/README.md)** + +Model-fits run considerably faster on a GPU. In Colab, enable one via *Runtime* → *Change runtime type* +→ *Hardware accelerator* before running a notebook. + +### Run on your own machine + +Follow the [PyAutoFit installation guide](https://pyautofit.readthedocs.io/en/latest/installation/overview.html), -then cloning this repository: +then clone this repository: ```bash git clone https://github.com/PyAutoLabs/HowToFit.git cd HowToFit ``` -Alternatively, every tutorial can be opened directly in Google Colab via the links in each chapter's -`README.md`. - The tutorials are distributed as both Jupyter notebooks (`notebooks/`) and Python scripts (`scripts/`). We recommend the notebooks for reading — figures render inline, and you can step through small code blocks interactively. Use the Python scripts for actual **PyAutoFit** use. diff --git a/llms-full.txt b/llms-full.txt index 6f3fd71..343517f 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -28,21 +28,21 @@ AUTO-GENERATED by PyAutoHands — do not edit by hand; regenerate with generate. - [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 +## chapter_advanced -- [Tutorial 1: Individual Models](scripts/chapter_3_graphical_models/tutorial_1_individual_models.py): In many examples, we fit one model to one dataset. For many problems, we may have a large dataset and are not interested in how well the model fits each individual dataset. Instead, we want to know how the model fits the full dataset, so that we can determine "global" trends of how the model fits the data. +- [Tutorial 1: Individual Models](scripts/chapter_advanced/tutorial_1_individual_models.py): In many examples, we fit one model to one dataset. For many problems, we may have a large dataset and are not interested in how well the model fits each individual dataset. Instead, we want to know how the model fits the full dataset, so that we can determine "global" trends of how the model fits the data. - Contents: Real World Example, Example Source Code (`af.ex`), Model, Data, Model Fits (one-by-one), Results, Estimating the Centre, Posterior Multiplication, Wrap Up -- [Tutorial 2: Graphical Models](scripts/chapter_3_graphical_models/tutorial_2_graphical_model.py): We have fitted a dataset containing 5 noisy 1D Gaussian which had a shared `centre` value. We estimated the `centre` by fitting each dataset individually and combining the value of the `centre` inferred by each fit into an overall estimate, using a weighted average. +- [Tutorial 2: Graphical Models](scripts/chapter_advanced/tutorial_2_graphical_model.py): We have fitted a dataset containing 5 noisy 1D Gaussian which had a shared `centre` value. We estimated the `centre` by fitting each dataset individually and combining the value of the `centre` inferred by each fit into an overall estimate, using a weighted average. - Contents: Example Source Code (`af.ex`), Dataset, Analysis, Model, Analysis Factors, Factor Graph, Search, Result, Wrap Up -- [Tutorial 3: Graphical Benefits](scripts/chapter_3_graphical_models/tutorial_3_graphical_benefits.py): In the previous tutorials, we fitted a dataset containing 5 noisy 1D Gaussian which had a shared `centre` value and compared different approaches to estimate the shared `centre`. This included a simple approach fitting each dataset one-by-one and estimating the centre via a weighted average or posterior multiplication and a more complicated approach using a graphical model. +- [Tutorial 3: Graphical Benefits](scripts/chapter_advanced/tutorial_3_graphical_benefits.py): In the previous tutorials, we fitted a dataset containing 5 noisy 1D Gaussian which had a shared `centre` value and compared different approaches to estimate the shared `centre`. This included a simple approach fitting each dataset one-by-one and estimating the centre via a weighted average or posterior multiplication and a more complicated approach using a graphical model. - Contents: The Model, Example Source Code (`af.ex`), Dataset, Analysis, Model (one-by-one), Model Fits (one-by-one), Centre Estimates (Weighted Average), Discussion, Model (Graphical), Analysis Factors, Factor Graph, Search, Result, Discussion, Posterior Multiplication, Wrap Up -- [Tutorial 4: Hierarchical](scripts/chapter_3_graphical_models/tutorial_4_hierachical_models.py): In the previous tutorial, we fitted a graphical model with the aim of determining an estimate of shared parameters, the `centre`'s of a dataset of 1D Gaussians. We did this by fitting all datasets simultaneously. When there are shared parameters in a model, this is a powerful and effective tool, but things may not always be so simple. +- [Tutorial 4: Hierarchical](scripts/chapter_advanced/tutorial_4_hierachical_models.py): In the previous tutorial, we fitted a graphical model with the aim of determining an estimate of shared parameters, the `centre`'s of a dataset of 1D Gaussians. We did this by fitting all datasets simultaneously. When there are shared parameters in a model, this is a powerful and effective tool, but things may not always be so simple. - Contents: Example Source Code (`af.ex`), Dataset, Analysis, Model Individual Factors, Analysis Factors, Model, Factor Graph, Search, Result, Comparison to One-by-One Fits, Benefits of Graphical Model, Wrap Up -- [Tutorial 5: Expectation Propagation](scripts/chapter_3_graphical_models/tutorial_5_expectation_propagation.py): In the previous tutorials, we fitted graphical models to dataset comprising many noisy 1D Gaussians. These had a shared and global value of their `centre`, or assumed their centres were hierarchically drawn from a parent Gaussian distribution. This provides the basis of composing and fitting complex graphical models to large datasets. +- [Tutorial 5: Expectation Propagation](scripts/chapter_advanced/tutorial_5_expectation_propagation.py): In the previous tutorials, we fitted graphical models to dataset comprising many noisy 1D Gaussians. These had a shared and global value of their `centre`, or assumed their centres were hierarchically drawn from a parent Gaussian distribution. This provides the basis of composing and fitting complex graphical models to large datasets. - Contents: Example Source Code (`af.ex`), Dataset, Analysis, Model, Analysis Factors, Factor Graph, Expectation Propagation, Cyclic Fitting, Result, Output, Results -- [Tutorial Optional: Hierarchical Expectation Propagation (EP)](scripts/chapter_3_graphical_models/tutorial_optional_hierarchical_ep.py): This optional tutorial gives an example of fitting a hierarchical model using EP. +- [Tutorial Optional: Hierarchical Expectation Propagation (EP)](scripts/chapter_advanced/tutorial_optional_hierarchical_ep.py): This optional tutorial gives an example of fitting a hierarchical model using EP. - Contents: Example Source Code (`af.ex`), Dataset, Analysis, Model Individual Factors, Analysis Factors, Model, Factor Graph, Model Fit -- [Tutorial Optional: Hierarchical Individual](scripts/chapter_3_graphical_models/tutorial_optional_hierarchical_individual.py): In tutorial 4, we fit a hierarchical model using a graphical model, whereby all datasets are fitted simultaneously and the hierarchical parameters are fitted for simultaneously with the model parameters of each 1D Gaussian in each dataset. +- [Tutorial Optional: Hierarchical Individual](scripts/chapter_advanced/tutorial_optional_hierarchical_individual.py): In tutorial 4, we fit a hierarchical model using a graphical model, whereby all datasets are fitted simultaneously and the hierarchical parameters are fitted for simultaneously with the model parameters of each 1D Gaussian in each dataset. - Contents: Example Source Code (`af.ex`), Dataset, Analysis, Model, Model Fits (one-by-one), Results, Overall Gaussian Parent Distribution, Model, Analysis + Search ## simulators diff --git a/llms.txt b/llms.txt index 6f3ce32..12bd2ca 100644 --- a/llms.txt +++ b/llms.txt @@ -28,7 +28,7 @@ analysis?" below). ## The learning path (chapters in order) - **Chapter 1 — Introduction** → [scripts/chapter_1_introduction/](scripts/chapter_1_introduction/): The foundations of model-fitting — defining models, fitting data (residuals / chi-squared / likelihood), the non-linear search, why modeling is hard, and reading results & samples. -- **Chapter 3 — Graphical Models** → [scripts/chapter_3_graphical_models/](scripts/chapter_3_graphical_models/): Fitting one model across a large dataset — individual fits vs graphical models, shared parameters, hierarchical models, and Expectation Propagation for scaling to many datasets. +- **Advanced Chapter — Graphical Models** → [scripts/chapter_advanced/](scripts/chapter_advanced/): Fitting one model across a large dataset — individual fits vs graphical models, shared parameters, hierarchical models, and Expectation Propagation for scaling to many datasets. ## I want to understand… @@ -40,8 +40,8 @@ analysis?" below). - **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). +- **I have many datasets with a shared parameter — what's the right tool?** → [scripts/chapter_advanced/tutorial_2_graphical_model.py](scripts/chapter_advanced/tutorial_2_graphical_model.py): Factor graphs and graphical models vs one-by-one fits. +- **What is a hierarchical model / Expectation Propagation?** → [scripts/chapter_advanced/tutorial_4_hierachical_models.py](scripts/chapter_advanced/tutorial_4_hierachical_models.py) then [tutorial_5_expectation_propagation.py](scripts/chapter_advanced/tutorial_5_expectation_propagation.py). ## Ready for real analysis? diff --git a/markdown/chapter_1_introduction/start_here.md b/markdown/chapter_1_introduction/start_here.md index 996868b..93db1eb 100644 --- a/markdown/chapter_1_introduction/start_here.md +++ b/markdown/chapter_1_introduction/start_here.md @@ -27,7 +27,7 @@ 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 3: Graphical Models**: Simultaneous model fitting of large datasets, scaling up to models with tens of +**Advanced Chapter: Graphical Models**: Simultaneous model fitting of large datasets, scaling up to models with tens of thousands of parameters. After each chapter, it is advised that you apply what you've learned to your own model-fitting analysis based on diff --git a/markdown/chapter_1_introduction/tutorial_8_scientific_workflow.md b/markdown/chapter_1_introduction/tutorial_8_scientific_workflow.md index a632046..de33467 100644 --- a/markdown/chapter_1_introduction/tutorial_8_scientific_workflow.md +++ b/markdown/chapter_1_introduction/tutorial_8_scientific_workflow.md @@ -27,4 +27,4 @@ For the corresponding Python implementation, follow the __Wrap Up__ -Apply the workflow to your own data before returning to chapter 3 for graphical and hierarchical models. +Apply the workflow to your own data before returning to the advanced chapter for graphical and hierarchical models. diff --git a/notebooks/README.md b/notebooks/README.md index 4d4d138..fb43dd7 100644 --- a/notebooks/README.md +++ b/notebooks/README.md @@ -3,7 +3,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**, 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. +- `chapter_advanced`: 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. # Jupyter Notebooks @@ -20,7 +20,7 @@ This makes them an ideal way for us to present the **HowToFit** lecture series. `notebooks/` and are auto-generated from the Python scripts in `scripts/` — **edit the Python scripts, not the notebooks.** -For actual **PyAutoFit** use we recommend the Python scripts. Chapter 3 onwards assumes that transition. +For actual **PyAutoFit** use we recommend the Python scripts. The advanced chapter assumes that transition. # Code Style and Formatting @@ -33,14 +33,14 @@ is auto-formatted with `black` — see . # How to Approach HowToFit -**HowToFit** consists of the introductory chapter 1 and advanced chapter 3. Chapter 1 will take a couple of -hours to work through. The concepts in chapter 3 are challenging, and familiarity with **PyAutoFit** and +**HowToFit** consists of the introductory chapter 1 and the advanced chapter. Chapter 1 will take a couple of +hours to work through. The concepts in the advanced chapter are challenging, and familiarity with **PyAutoFit** and model fitting is desirable before tackling them. We recommend that you complete chapter 1 and then apply what you've learnt to a model-fitting problem you are interested in, building on the scripts found in the [autofit_workspace](https://github.com/PyAutoLabs/autofit_workspace) repository. Once you're confident -with your use of **PyAutoFit**, return for chapter 3. +with your use of **PyAutoFit**, return for the advanced chapter. # Overview of Chapter 1 (Beginner) @@ -58,11 +58,11 @@ able to: 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) +# Overview of the Advanced Chapter **Fitting Graphical Models to Large Datasets** -Chapter 3 covers how to compose and fit graphical models to extremely large datasets. You'll learn: +The advanced chapter covers how to compose and fit graphical models to extremely large datasets. You'll learn: 1. Why fitting a model to many datasets one-by-one is suboptimal. 2. How to fit a graphical model to all datasets simultaneously and why this improves the model results. diff --git a/notebooks/chapter_1_introduction/README.md b/notebooks/chapter_1_introduction/README.md index aee9248..9c9dc33 100644 --- a/notebooks/chapter_1_introduction/README.md +++ b/notebooks/chapter_1_introduction/README.md @@ -17,10 +17,10 @@ The chapter contains the following tutorials: - [Tutorial 5: Results and Samples](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_1_introduction/tutorial_5_results_and_samples.ipynb) — Interpreting model-fit results and using the samples for scientific analysis. -- [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 6: Gradients](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/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 7: The Details](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/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 8: Scientific Workflow](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/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. +- [Tutorial Optional: Bayesian Formalism](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/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 5d253b0..a4af1c9 100644 --- a/notebooks/chapter_1_introduction/start_here.ipynb +++ b/notebooks/chapter_1_introduction/start_here.ipynb @@ -30,7 +30,7 @@ "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", + "**Advanced Chapter: Graphical Models**: Simultaneous model fitting of large datasets, scaling up to models with tens of\n", "thousands of parameters.\n", "\n", "After each chapter, it is advised that you apply what you've learned to your own model-fitting analysis based on\n", diff --git a/notebooks/chapter_1_introduction/tutorial_1_models.ipynb b/notebooks/chapter_1_introduction/tutorial_1_models.ipynb index d63e5c4..334d5e5 100644 --- a/notebooks/chapter_1_introduction/tutorial_1_models.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_1_models.ipynb @@ -347,7 +347,7 @@ "\n", "Right now both views fit on one screen and the figure may look like a redundant restatement of the `info`. Draw it\n", "anyway, because the two views scale very differently. By the end of this chapter our models have five components, in\n", - "chapter 3 they span five datasets at once, and at that point the `info` runs to hundreds of lines whilst the map\n", + "the advanced chapter they span five datasets at once, and at that point the `info` runs to hundreds of lines whilst the map\n", "still fits in a glance." ] }, diff --git a/notebooks/chapter_1_introduction/tutorial_8_scientific_workflow.ipynb b/notebooks/chapter_1_introduction/tutorial_8_scientific_workflow.ipynb index c24148c..549dfb0 100644 --- a/notebooks/chapter_1_introduction/tutorial_8_scientific_workflow.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_8_scientific_workflow.ipynb @@ -29,7 +29,7 @@ "\n", "__Wrap Up__\n", "\n", - "Apply the workflow to your own data before returning to chapter 3 for graphical and hierarchical models." + "Apply the workflow to your own data before returning to the advanced chapter for graphical and hierarchical models." ] } ], diff --git a/notebooks/chapter_3_graphical_models/README.md b/notebooks/chapter_3_graphical_models/README.md deleted file mode 100644 index c30478c..0000000 --- a/notebooks/chapter_3_graphical_models/README.md +++ /dev/null @@ -1,19 +0,0 @@ -In this chapter, we take you through how to compose and fit graphical models in **PyAutoFit**. Graphical models -simultaneously fit many datasets with a model that has 'local' parameters specific to each individual dataset -and 'global' parameters that fit for global trends across the whole dataset. - -**Colab** links to every tutorial are included. - -# Files - -The chapter contains the following tutorials: - -- [Tutorial 1: Individual Models](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_3_graphical_models/tutorial_1_individual_models.ipynb) — Inferring global parameters from a dataset by fitting the model to each individual dataset one-by-one. - -- [Tutorial 2: Graphical Model](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_3_graphical_models/tutorial_2_graphical_model.ipynb) — Fitting the dataset with a graphical model that fits all datasets simultaneously to infer the global parameters. - -- [Tutorial 3: Graphical Benefits](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_3_graphical_models/tutorial_3_graphical_benefits.ipynb) — Illustrating the benefits of graphical modeling over fitting individual datasets one-by-one. - -- [Tutorial 4: Hierarchical Models](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_3_graphical_models/tutorial_4_hierachical_models.ipynb) — Fitting hierarchical models using the graphical modeling framework. - -- [Tutorial 5: Expectation Propagation](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_3_graphical_models/tutorial_5_expectation_propagation.ipynb) — Scaling graphical models up to fit extremely large datasets using Expectation Propagation (EP). diff --git a/notebooks/chapter_advanced/README.md b/notebooks/chapter_advanced/README.md new file mode 100644 index 0000000..38b6e82 --- /dev/null +++ b/notebooks/chapter_advanced/README.md @@ -0,0 +1,23 @@ +In this chapter, we take you through how to compose and fit graphical models in **PyAutoFit**. Graphical models +simultaneously fit many datasets with a model that has 'local' parameters specific to each individual dataset +and 'global' parameters that fit for global trends across the whole dataset. + +**Colab** links to every tutorial are included. + +# Files + +The chapter contains the following tutorials: + +- [Tutorial 1: Individual Models](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_advanced/tutorial_1_individual_models.ipynb) — Inferring global parameters from a dataset by fitting the model to each individual dataset one-by-one. + +- [Tutorial 2: Graphical Model](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_advanced/tutorial_2_graphical_model.ipynb) — Fitting the dataset with a graphical model that fits all datasets simultaneously to infer the global parameters. + +- [Tutorial 3: Graphical Benefits](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_advanced/tutorial_3_graphical_benefits.ipynb) — Illustrating the benefits of graphical modeling over fitting individual datasets one-by-one. + +- [Tutorial 4: Hierarchical Models](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_advanced/tutorial_4_hierachical_models.ipynb) — Fitting hierarchical models using the graphical modeling framework. + +- [Tutorial 5: Expectation Propagation](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_advanced/tutorial_5_expectation_propagation.ipynb) — Scaling graphical models up to fit extremely large datasets using Expectation Propagation (EP). + +- [Tutorial Optional: Hierarchical Expectation Propagation](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_advanced/tutorial_optional_hierarchical_ep.ipynb) — Fitting a hierarchical model with Expectation Propagation, scaling the hierarchical approach to large datasets. + +- [Tutorial Optional: Hierarchical Individual](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_advanced/tutorial_optional_hierarchical_individual.ipynb) — Estimating a hierarchical model's parent distribution from one-by-one fits, and why the graphical approach improves on it. diff --git a/notebooks/chapter_3_graphical_models/tutorial_1_individual_models.ipynb b/notebooks/chapter_advanced/tutorial_1_individual_models.ipynb similarity index 98% rename from notebooks/chapter_3_graphical_models/tutorial_1_individual_models.ipynb rename to notebooks/chapter_advanced/tutorial_1_individual_models.ipynb index 8639f1e..5bf28d6 100644 --- a/notebooks/chapter_3_graphical_models/tutorial_1_individual_models.ipynb +++ b/notebooks/chapter_advanced/tutorial_1_individual_models.ipynb @@ -281,7 +281,7 @@ " dynesty = af.DynestyStatic(\n", " name=\"global_model\",\n", " path_prefix=path.join(\n", - " \"chapter_3_graphical_models\", \"tutorial_1_individual_models\"\n", + " \"chapter_advanced\", \"tutorial_1_individual_models\"\n", " ),\n", " unique_tag=dataset_name,\n", " nlive=200,\n", @@ -292,7 +292,7 @@ "\n", " print(\n", " f\"The non-linear search has begun running, checkout \\n\"\n", - " f\"HowToFit/output/chapter_3_graphical_models/tutorial_1_individual_models/{dataset_name} for live \\n\"\n", + " f\"HowToFit/output/chapter_advanced/tutorial_1_individual_models/{dataset_name} for live \\n\"\n", " f\"output of the results. This Jupyter notebook cell with progress once search has completed, this could take a \\n\"\n", " f\"few minutes!\"\n", " )\n", diff --git a/notebooks/chapter_3_graphical_models/tutorial_2_graphical_model.ipynb b/notebooks/chapter_advanced/tutorial_2_graphical_model.ipynb similarity index 99% rename from notebooks/chapter_3_graphical_models/tutorial_2_graphical_model.ipynb rename to notebooks/chapter_advanced/tutorial_2_graphical_model.ipynb index 18e2c65..0bc39a3 100644 --- a/notebooks/chapter_3_graphical_models/tutorial_2_graphical_model.ipynb +++ b/notebooks/chapter_advanced/tutorial_2_graphical_model.ipynb @@ -409,7 +409,7 @@ "metadata": {}, "source": [ "search = af.DynestyStatic(\n", - " path_prefix=path.join(\"chapter_3_graphical_models\"),\n", + " path_prefix=path.join(\"chapter_advanced\"),\n", " name=\"tutorial_2_graphical_model\",\n", " nlive=200,\n", " dlogz=1e-4,\n", diff --git a/notebooks/chapter_3_graphical_models/tutorial_3_graphical_benefits.ipynb b/notebooks/chapter_advanced/tutorial_3_graphical_benefits.ipynb similarity index 99% rename from notebooks/chapter_3_graphical_models/tutorial_3_graphical_benefits.ipynb rename to notebooks/chapter_advanced/tutorial_3_graphical_benefits.ipynb index ee54e77..6265db0 100644 --- a/notebooks/chapter_3_graphical_models/tutorial_3_graphical_benefits.ipynb +++ b/notebooks/chapter_advanced/tutorial_3_graphical_benefits.ipynb @@ -287,7 +287,7 @@ " search = af.DynestyStatic(\n", " name=f\"individual_fit_{i}\",\n", " path_prefix=path.join(\n", - " \"chapter_3_graphical_models\", \"tutorial_3_graphical_benefits\"\n", + " \"chapter_advanced\", \"tutorial_3_graphical_benefits\"\n", " ),\n", " nlive=200,\n", " dlogz=1e-4,\n", @@ -297,7 +297,7 @@ "\n", " print(\n", " f\"The non-linear search has begun running, checkout \\n\"\n", - " f\"HowToFit/output/chapter_3_graphical_models/tutorial_3_graphical_benefits/{dataset_name} for live \\n\"\n", + " f\"HowToFit/output/chapter_advanced/tutorial_3_graphical_benefits/{dataset_name} for live \\n\"\n", " f\"output of the results. This Jupyter notebook cell with progress once search has completed, this could take a \\n\"\n", " f\"few minutes!\"\n", " )\n", @@ -589,7 +589,7 @@ "metadata": {}, "source": [ "search = af.DynestyStatic(\n", - " path_prefix=path.join(\"chapter_3_graphical_models\"),\n", + " path_prefix=path.join(\"chapter_advanced\"),\n", " name=\"tutorial_3_graphical_benefits\",\n", " sample=\"rwalk\",\n", ")\n", diff --git a/notebooks/chapter_3_graphical_models/tutorial_4_hierachical_models.ipynb b/notebooks/chapter_advanced/tutorial_4_hierachical_models.ipynb similarity index 99% rename from notebooks/chapter_3_graphical_models/tutorial_4_hierachical_models.ipynb rename to notebooks/chapter_advanced/tutorial_4_hierachical_models.ipynb index 7472d0a..c61afc6 100644 --- a/notebooks/chapter_3_graphical_models/tutorial_4_hierachical_models.ipynb +++ b/notebooks/chapter_advanced/tutorial_4_hierachical_models.ipynb @@ -417,7 +417,7 @@ "metadata": {}, "source": [ "search = af.DynestyStatic(\n", - " path_prefix=path.join(\"chapter_3_graphical_models\"),\n", + " path_prefix=path.join(\"chapter_advanced\"),\n", " name=\"tutorial_4_hierarchical\",\n", " sample=\"rwalk\",\n", ")\n", diff --git a/notebooks/chapter_3_graphical_models/tutorial_5_expectation_propagation.ipynb b/notebooks/chapter_advanced/tutorial_5_expectation_propagation.ipynb similarity index 99% rename from notebooks/chapter_3_graphical_models/tutorial_5_expectation_propagation.ipynb rename to notebooks/chapter_advanced/tutorial_5_expectation_propagation.ipynb index 764bf47..fd4224f 100644 --- a/notebooks/chapter_3_graphical_models/tutorial_5_expectation_propagation.ipynb +++ b/notebooks/chapter_advanced/tutorial_5_expectation_propagation.ipynb @@ -280,7 +280,7 @@ "metadata": {}, "source": [ "paths = af.DirectoryPaths(\n", - " name=path.join(\"chapter_3_graphical_models\", \"tutorial_5_expectation_propagation\")\n", + " name=path.join(\"chapter_advanced\", \"tutorial_5_expectation_propagation\")\n", ")\n", "\n", "search = af.DynestyStatic(paths=paths, nlive=100, sample=\"rwalk\")\n", @@ -533,7 +533,7 @@ "__Output__\n", "\n", "The results of the factor graph, using the EP framework and message passing, are contained in the folder \n", - "`output/chapter_3_graphical_models/tutorial_5_expectation_propagation`. \n", + "`output/chapter_advanced/tutorial_5_expectation_propagation`. \n", "\n", "The following folders and files are worth of note:\n", "\n", diff --git a/notebooks/chapter_3_graphical_models/tutorial_optional_hierarchical_ep.ipynb b/notebooks/chapter_advanced/tutorial_optional_hierarchical_ep.ipynb similarity index 99% rename from notebooks/chapter_3_graphical_models/tutorial_optional_hierarchical_ep.ipynb rename to notebooks/chapter_advanced/tutorial_optional_hierarchical_ep.ipynb index c6de18c..d030ea3 100644 --- a/notebooks/chapter_3_graphical_models/tutorial_optional_hierarchical_ep.ipynb +++ b/notebooks/chapter_advanced/tutorial_optional_hierarchical_ep.ipynb @@ -376,7 +376,7 @@ "# laplace,\n", "# paths=af.DirectoryPaths(\n", "# name=path.join(\n", - "# \"chapter_3_graphical_models\", \"tutorial_4_hierarchical\"\n", + "# \"chapter_advanced\", \"tutorial_4_hierarchical\"\n", "# )\n", "# ),\n", "# ep_history=af.EPHistory(kl_tol=1.0),\n", @@ -396,7 +396,7 @@ "`factor_graph.optimise` call above is commented out because a full EP fit is computationally expensive; uncomment it\n", "to run the fit yourself.\n", "\n", - "For the concepts behind hierarchical models and EP, see the main chapter 3 tutorials\n", + "For the concepts behind hierarchical models and EP, see the main advanced chapter tutorials\n", "(`tutorial_4_hierarchical_model` and `tutorial_5_expectation_propagation`)." ] } diff --git a/notebooks/chapter_3_graphical_models/tutorial_optional_hierarchical_individual.ipynb b/notebooks/chapter_advanced/tutorial_optional_hierarchical_individual.ipynb similarity index 100% rename from notebooks/chapter_3_graphical_models/tutorial_optional_hierarchical_individual.ipynb rename to notebooks/chapter_advanced/tutorial_optional_hierarchical_individual.ipynb diff --git a/notebooks/simulators/simulators.ipynb b/notebooks/simulators/simulators.ipynb index f9930b5..8fa48f3 100644 --- a/notebooks/simulators/simulators.ipynb +++ b/notebooks/simulators/simulators.ipynb @@ -484,10 +484,10 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "__Sample Datasets (Chapter 3)__\n", + "__Sample Datasets (Advanced Chapter)__\n", "\n", "Chain-run the sample simulator so every tutorial's `simulators.py` subprocess\n", - "call also produces the `dataset_*/` sample folders used by chapter 3.\n", + "call also produces the `dataset_*/` sample folders used by the advanced chapter.\n", "\n", "The path is relative to the repository root, which every execution context sets as the working\n", "directory: scripts are run from the root, the notebook kernel is pinned there, and Colab chdirs\n", diff --git a/scripts/README.md b/scripts/README.md index 4d4d138..fb43dd7 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -3,7 +3,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**, 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. +- `chapter_advanced`: 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. # Jupyter Notebooks @@ -20,7 +20,7 @@ This makes them an ideal way for us to present the **HowToFit** lecture series. `notebooks/` and are auto-generated from the Python scripts in `scripts/` — **edit the Python scripts, not the notebooks.** -For actual **PyAutoFit** use we recommend the Python scripts. Chapter 3 onwards assumes that transition. +For actual **PyAutoFit** use we recommend the Python scripts. The advanced chapter assumes that transition. # Code Style and Formatting @@ -33,14 +33,14 @@ is auto-formatted with `black` — see . # How to Approach HowToFit -**HowToFit** consists of the introductory chapter 1 and advanced chapter 3. Chapter 1 will take a couple of -hours to work through. The concepts in chapter 3 are challenging, and familiarity with **PyAutoFit** and +**HowToFit** consists of the introductory chapter 1 and the advanced chapter. Chapter 1 will take a couple of +hours to work through. The concepts in the advanced chapter are challenging, and familiarity with **PyAutoFit** and model fitting is desirable before tackling them. We recommend that you complete chapter 1 and then apply what you've learnt to a model-fitting problem you are interested in, building on the scripts found in the [autofit_workspace](https://github.com/PyAutoLabs/autofit_workspace) repository. Once you're confident -with your use of **PyAutoFit**, return for chapter 3. +with your use of **PyAutoFit**, return for the advanced chapter. # Overview of Chapter 1 (Beginner) @@ -58,11 +58,11 @@ able to: 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) +# Overview of the Advanced Chapter **Fitting Graphical Models to Large Datasets** -Chapter 3 covers how to compose and fit graphical models to extremely large datasets. You'll learn: +The advanced chapter covers how to compose and fit graphical models to extremely large datasets. You'll learn: 1. Why fitting a model to many datasets one-by-one is suboptimal. 2. How to fit a graphical model to all datasets simultaneously and why this improves the model results. diff --git a/scripts/chapter_1_introduction/README.md b/scripts/chapter_1_introduction/README.md index aee9248..9c9dc33 100644 --- a/scripts/chapter_1_introduction/README.md +++ b/scripts/chapter_1_introduction/README.md @@ -17,10 +17,10 @@ The chapter contains the following tutorials: - [Tutorial 5: Results and Samples](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_1_introduction/tutorial_5_results_and_samples.ipynb) — Interpreting model-fit results and using the samples for scientific analysis. -- [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 6: Gradients](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/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 7: The Details](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/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 8: Scientific Workflow](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/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. +- [Tutorial Optional: Bayesian Formalism](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/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 4fe6fbb..d7f6dba 100644 --- a/scripts/chapter_1_introduction/start_here.py +++ b/scripts/chapter_1_introduction/start_here.py @@ -25,7 +25,7 @@ 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 +**Advanced Chapter: Graphical Models**: Simultaneous model fitting of large datasets, scaling up to models with tens of thousands of parameters. After each chapter, it is advised that you apply what you've learned to your own model-fitting analysis based on diff --git a/scripts/chapter_1_introduction/tutorial_1_models.py b/scripts/chapter_1_introduction/tutorial_1_models.py index 1f9e292..541ec02 100644 --- a/scripts/chapter_1_introduction/tutorial_1_models.py +++ b/scripts/chapter_1_introduction/tutorial_1_models.py @@ -1,595 +1,595 @@ -""" -Tutorial 1: Models -================== - -At the heart of model-fitting is the model: a set of equations, numerical processes, and assumptions describing a -physical system of interest. The goal of model-fitting is to better understand this physical system and develop -predictive models that describe it more accurately. - -In astronomy, a model might describe the distribution of stars within a galaxy. In biology, it might represent the -interaction of proteins within a cell. In finance, it could describe the evolution of stock prices in a market. -Regardless of the field, the model acts as a mathematical description of the physical system, aiming to enhance -understanding and enable new predictions. - -Whatever your model, its equations are defined by "free parameters." Changing these parameters alters the -behavior and predictions of the model. - -Once the model is defined and parameter values are chosen, the model creates "model data"—a realization of how the -physical system appears given those parameters. This process, often referred to as "forward modeling," describes the -physical system from its starting point and predicts the data we observe. - -By varying the model parameters, we can generate numerous model datasets. The ultimate goal of model-fitting, which -you will learn by the end of this chapter, is to determine the model parameters and corresponding dataset that best -fit the observed data. - -__Astronomy Example__ - -For instance, in astronomy, we might model the distribution of stars, including: - -- A parameter describing the brightness of the stars. - -- Multiple parameters defining their distribution. - -- Several parameters describing their colors. - -If our model pertains to the distribution of stars within a galaxy, the forward model will produce an image of what -that galaxy looks like when observed with a telescope. This forward model might account for physical effects such as -the blurring of light due to diffraction in the telescope optics. - -By altering the parameters describing the stars, we can generate many different model images via this forward model. - -At the end of this chapter, we will use a real-world astronomy example to illustrate everything you have learned, -including fitting a real galaxy observed with the Hubble Space Telescope. - -__Overview__ - -In tutorial 1, we will cover the basics of defining a model, specifically: - -- Defining a simple model described by a few simple equations. - -- Showing that this model is characterized by three or more free parameters. - -- Using the model, with different sets of parameters, to generate model data. - -__Contents__ - -This tutorial is split into the following sections: - -- **Paths**: Setting up the working directory path so the tutorial runs correctly on your computer. -- **Model Parameterization**: An example of how a model is parameterized and is made up of free parameters. -- **Model Composition**: Composing a model using PyAutoFit's model composition API. -- **Model Creation**: Creating an instance of the model using PyAutoFit's `Model` python object. -- **Model Mapping**: Mapping an input vector of parameters to the model to create an instance of the model. -- **Complex Models**: Composing a more complex model with multiple model components and more free parameters. -- **Tuple Parameters**: Defining a model component with tuple parameters. -- **Extensibility**: Discussing how PyAutoFit's model composition API is scalable and extensible. -- **Wrap Up**: Concluding the tutorial and considering how to apply the concepts to your own scientific problem. - -This tutorial introduces the PyAutoFit API for model composition, which forms the foundation of all model-fitting -performed by PyAutoFit. -""" - -# from autofit import setup_notebook; setup_notebook() - -import numpy as np -import matplotlib.pyplot as plt - -import autofit as af - -r""" -__Paths__ - -PyAutoFit assumes the current working directory is /path/to/HowToFit/ on your hard-disk (or in Colab). -This setup allows PyAutoFit to: - -- Load configuration settings from config files in the HowToFit/config folder. - -- Load example data from the HowToFit/dataset folder. - -- Output the results of model fits to your hard disk in the autofit/output folder. - -If you don't have a HowToFit clone, you can download it here: - - https://github.com/PyAutoLabs/autofit_workspace - -__Model Parameterization__ - -A model is a set of equations, numerical processes, and assumptions that describe a physical system and dataset. - -In this example, our model is one or more 1-dimensional Gaussians, defined by the following equation: - -\begin{equation*} -g(x, I, \sigma) = \frac{N}{\sigma\sqrt{2\pi}} \exp{(-0.5 (x / \sigma)^2)} -\end{equation*} - -Where: - -- `x`: The x-axis coordinate where the Gaussian is evaluated. - -- `N`: The overall normalization of the Gaussian. - - -- `\sigma`: The size of the Gaussian (Full Width Half Maximum, $\mathrm{FWHM}$, is $2{\sqrt{2\ln 2}}\;\sigma$). - -While a 1D Gaussian might seem like a rudimentary model, it has many real-world applications in signal processing. -For example, 1D Gaussians are fitted to datasets to measure the size of an observed signal. Thus, this model has -practical real-world applications. - -We now have a model, expressed as a simple 1D Gaussian. The model has three parameters, $(x, N, \sigma)$. Using -different combinations of these parameters creates different realizations of the model, which we illustrate below. - -__Model Composition__ - -We now define the 1D Gaussian as a "model component" in PyAutoFit. We use the term "model component" because the model -can be extended to include multiple components, each related to different equations and numerical processes. - -We first illustrate a model composed of a single model component, the 1D Gaussian. We then show a model made of -multiple model components. - -To define a "model component" in PyAutoFit, we simply write it as a Python class using the format shown below: -""" - - -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))), - ) - - -""" -The format of this Python class defines how PyAutoFit composes the Gaussian as a model component, where: - -- The name of the class is the name of the model component, in this case, "Gaussian". - -- The input arguments of the constructor (the `__init__` method) are the parameters of the model, in the example -above `centre`, `normalization`, and `sigma`. - -- The default values and typing of the input arguments define whether a parameter is a single-valued float or a -multi-valued tuple. For the `Gaussian` class above, no input parameters are tuples, but later examples use tuples. - -- It includes functions associated with that model component, specifically the model_data function. When we create -instances of a `Gaussian` below, this function is used to generate a 1D representation of it as a NumPy array. - -__Model Creation__ - -The `Gaussian` class above is a standard Python class. It does not yet act as a model component that can be used -for model fitting with PyAutoFit. - -To transform the Gaussian class into a model component that can be used for model fitting with PyAutoFit, we use -the `af.Model` object. This tells PyAutoFit to treat the input Python class as a model component. -""" -model = af.Model(Gaussian) -print("Model `Gaussian` object: \n") -print(model) - -""" -In PyAutoFit, a Model object encapsulates a model component that can be used for model fitting. It provides several -attributes that describe the model component, such as the `total_free_parameters` attribute, which indicates the -number of free parameters in the model: -""" -print(model.total_free_parameters) - -""" -In PyAutoFit, you can retrieve comprehensive information about a model by accessing its `info` attribute. - -When you print the model info, it displays detailed information about each parameter in the model, including its name, -type, and associated prior distribution. Priors define the expected range or distribution of values for each -parameter during the model fitting process. If you're unfamiliar with priors, they are covered in tutorial 3 of -this chapter, which explains their role in model fitting. - -[The `info` below may not display optimally on your computer screen, for example the whitespace between parameter -names on the left and parameter priors on the right may lead them to appear across multiple lines. This is a -common issue in Jupyter notebooks. - -The`info_whitespace_length` parameter in the file `config/general.yaml` in the "output" section can be changed to -increase or decrease the amount of whitespace (The Jupyter notebook kernel will need to be reset for this change to -appear in a notebook).] -""" -print(model.info) - -""" -The same model can also be drawn, via `af.ModelPlotter`. - -The figure and the `info` are two views of the same object, and it is worth being precise about the division of -labour between them. The figure is the **map**: it shows the structure of the model, meaning which component owns -which parameter and, in the models we build later, which parameters are fixed, shared between components, related to -one another by an expression or constrained by an assertion. The `info` is the **legend**: it lists the priors and -values themselves, the numbers that the map has no room for. - -For this first model the map is about as simple as a map gets. There is a single card, titled `model` and `Gaussian` -after the class it was composed from, holding one pill per parameter: `centre`, `normalization` and `sigma`. The -footer counts them for you, `3 unique sampled scalars`, which is the same number the `total_free_parameters` -attribute printed above. Read the card as the answer to "what is this model made of?", and the `info` above it as the -answer to "and what values may each of those parts take?". - -Right now both views fit on one screen and the figure may look like a redundant restatement of the `info`. Draw it -anyway, because the two views scale very differently. By the end of this chapter our models have five components, in -chapter 3 they span five datasets at once, and at that point the `info` runs to hundreds of lines whilst the map -still fits in a glance. -""" -af.ModelPlotter(model).figure() - -""" -__Model Mapping__ - -In PyAutoFit, instances of model components created via the af.Model object can be instantiated by mapping an input -vector of parameters to the Python class that the model object represents. The order of parameters in the model is -crucial for correctly defining the input vector. - -To determine the order of parameters in the model, PyAutoFit provides the paths attribute of the model object. -This attribute contains information about the parameter paths within the model. - -Here's how you can access the paths attribute to understand the order of parameters in the model: -""" -print(model.paths) - -""" -To create an instance of the Gaussian model component using PyAutoFit, following the order of parameters defined by -the paths attribute (`centre`, `normalization`, and `sigma`), you can initialize the instance as follows: -""" -instance = model.instance_from_vector(vector=[30.0, 2.0, 3.0]) - -""" -This is an instance of the `Gaussian` class. -""" -print("Model Instance: \n") -print(instance) - -""" -It has the parameters of the `Gaussian` with the values input above. -""" -print("Instance Parameters \n") -print("x = ", instance.centre) -print("normalization = ", instance.normalization) -print("sigma = ", instance.sigma) - -""" -We can use all class functions, such as the `model_data_from` function, to generate an instance of the -1D `Gaussian` and visualize it through plotting. - -The code below generates the 1D Gaussian model data, which requires an input list of x values where the Gaussian is -evaluated. The output is a NumPy array of the Gaussian's y values at the input x coordinates. - -Although simple, the code below is essentially the process of forward modeling, where we use the model to generate -the data we would observe in an experiment for a given set of parameters. -""" -xvalues = np.arange(0.0, 100.0, 1.0) - -model_data = instance.model_data_from(xvalues=xvalues) - -plt.plot(xvalues, model_data, color="r") -plt.title("1D Gaussian Model Data.") -plt.xlabel("x values of profile") -plt.ylabel("Gaussian Value") -plt.show() -plt.clf() - -r""" -__Complex Models__ - -The code above may seem like a lot of steps just to create an instance of the `Gaussian` class. Couldn't we have -simply done this instead? - -```python -instance = Gaussian(centre=30.0, normalization=2.0, sigma=3.0) -``` - -Yes, we could have. - -However, the model composition API used above is designed to simplify the process of composing complex models that -consist of multiple components with many free parameters. It provides a scalable approach for defining and -manipulating models. - -To demonstrate this capability, let's conclude the tutorial by composing a model composed of a Gaussian -component and another 1D profile, an `Exponential`, defined by the equation: - -\begin{equation*} -g(x, I, \lambda) = N \lambda \exp{- \lambda x } -\end{equation*} - -where: - -- `x`: Represents the x-axis coordinate where the Exponential profile is evaluated. - -- `N`: Describes the overall normalization of the Exponential profile. - -- $\lambda$: Represents the rate of decay of the exponential. - -We'll start by defining the `Exponential` profile using a format similar to the Gaussian definition above. -""" - - -class Exponential: - def __init__( - self, - centre: float = 30.0, # <- **PyAutoFit** recognises these constructor arguments - normalization: float = 1.0, # <- are the Exponential`s model parameters. - rate: float = 0.01, - ): - """ - Represents a 1D Exponential profile. - - This is a model-component of example models in the **HowToFit** lectures and is used to fit example datasets - via a non-linear search. - - Parameters - ---------- - centre - The x coordinate of the profile centre. - normalization - Overall normalization of the profile. - ratw - The decay rate controlling has fast the Exponential declines. - """ - self.centre = centre - self.normalization = normalization - self.rate = rate - - def model_data_from(self, xvalues: 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 `Exponential`, 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. - """ - transformed_xvalues = np.subtract(xvalues, self.centre) - return self.normalization * np.multiply( - self.rate, np.exp(-1.0 * self.rate * abs(transformed_xvalues)) - ) - - -""" -We can construct a model comprising one `Gaussian` object and one `Exponential` object using the `af.Collection` object: -""" -model = af.Collection(gaussian=af.Model(Gaussian), exponential=af.Model(Exponential)) - -""" -You can retrieve all the information about the model created via the `af.Collection` by printing its `info` attribute -in one go: -""" -print(model.info) - -""" -Drawing the model shows what a `Collection` does to the map. There are now two cards side by side, -`gaussian` and `exponential`, each titled with the class it was composed from and each owning its own pills, and the -footer counts `6 unique sampled scalars` across the pair. Components sit beside one another, and nothing yet joins -them: the two `centre` parameters are separate parameters that happen to share a name. -""" -af.ModelPlotter(model).figure() - -""" -When `Gaussian` and `Exponential` are added to a `Collection`, they are automatically assigned as `Model` objects. - -Therefore, there's no need to use the `af.Model` method when passing classes to a `Collection`, which makes the Python -code more concise and readable. -""" -model = af.Collection(gaussian=Gaussian, exponential=Exponential) - -""" -The `model.info` is identical to the previous example. -""" -print(model.info) - -""" -The figure is identical to the previous one too, and that is the point worth taking from this example. The two ways -of writing the composition look different on the page, but they build the same structure, and structure is all the -map draws. Whenever you change how a model is written, draw it: if the map does not move then nothing about the model -moved either, and any difference between the two fits has to be hiding in the legend rather than in the model. -""" -af.ModelPlotter(model).figure() - -""" -A `Collection` functions analogously to a `Model`, but it includes multiple model components. - -This can be observed by examining its `paths` attribute, which displays paths to all 6 free parameters across both model components. - -The paths contain entries such as `.gaussian.` and `.exponential.`, corresponding to the names we provided when -defining the `af.Collection` earlier. Modifying the names of the model components supplied to the `Collection` -would adjust the paths accordingly. -""" -print(model.paths) - -""" -A model instance can again be created by mapping an input `vector`, which now has 6 entries. -""" -instance = model.instance_from_vector(vector=[0.1, 0.2, 0.3, 0.4, 0.5, 0.01]) - -""" -This `instance` contains each of the model components we defined above. - -The argument names input into the `Collection` define the attribute names of the `instance`: -""" -print("Instance Parameters \n") -print("x (Gaussian) = ", instance.gaussian.centre) -print("normalization (Gaussian) = ", instance.gaussian.normalization) -print("sigma (Gaussian) = ", instance.gaussian.sigma) -print("x (Exponential) = ", instance.exponential.centre) -print("normalization (Exponential) = ", instance.exponential.normalization) -print("sigma (Exponential) = ", instance.exponential.rate) - -""" -In the context of the model's equations, it is simply the sum of the equations defining the `Gaussian` -and `Exponential` components. - -To generate the `model_data`, we sum the `model_data` of each individual model component, as demonstrated and -visualized below. -""" -xvalues = np.arange(0.0, 100.0, 1.0) - -model_data_0 = instance.gaussian.model_data_from(xvalues=xvalues) -model_data_1 = instance.exponential.model_data_from(xvalues=xvalues) - -model_data = model_data_0 + model_data_1 - -plt.plot(xvalues, model_data, color="r") -plt.plot(xvalues, model_data_0, "b", "--") -plt.plot(xvalues, model_data_1, "k", "--") -plt.title("1D Gaussian + Exponential Model Data.") -plt.xlabel("x values of profile") -plt.ylabel("Value") -plt.show() -plt.clf() - -""" -__Tuple Parameters__ - -The `Gaussian` and `Exponential` model components above only has parameters that are single-valued floats. - -Parameters can also be tuples, which is useful for defining model components where certain parameters are naturally -grouped together. - -For example, we can define a 2D Gaussian with a center that has two coordinates and therefore free parameters, (x, y), -using a tuple. -""" -from typing import Tuple - - -class Gaussian2D: - def __init__( - self, - centre: Tuple[float, float] = (0.0, 0.0), - normalization: float = 0.1, - sigma: float = 1.0, - ): - self.centre = centre - self.normalization = normalization - self.sigma = sigma - - -""" -The model's `total_free_parameters` attribute now includes 4 free parameters, as the tuple `centre` parameter accounts -for 2 free parameters. -""" -model = af.Model(Gaussian2D) - -print("Total Free Parameters:", model.total_free_parameters) - -""" -This information is again displayed in the `info` attribute: -""" -print("\nInfo:") -print(model.info) - -""" -The map shows how a tuple is handled. `centre` is still drawn as one pill, because it is one input argument of the -`Gaussian2D` class, but it now carries a `2D` badge marking it as a tuple, and the footer counts `4 unique sampled -scalars` rather than 3. The `paths` printed below unpack that badge into the two entries, one per coordinate, which -the input vector must supply. -""" -af.ModelPlotter(model).figure() - -""" -The `paths` attribute provides information on the order of parameters in the model, illustrating how the -`centre` tuple is split into two parameters. -""" -print("\nPaths:") -print(model.paths) - -""" -This ordering is used to create an instance of the `Gaussian2D` model component: -""" -instance = model.instance_from_vector(vector=[40.0, 60.0, 2.0, 3.0]) - -print("\nInstance Parameters:") -print("centre (x) = ", instance.centre[0]) -print("centre (y) = ", instance.centre[1]) -print("normalization = ", instance.normalization) -print("sigma = ", instance.sigma) - -""" -__Extensibility__ - -It should now be clear why we use `Model` and `Collection` objects to construct our model. - -These objects facilitate the straightforward extension of our models to include multiple components and parameters. -For instance, we can add more `Gaussian` and `Exponential` components to the `Collection`, or define new Python -classes to represent entirely new model components with additional parameters. - -These objects serve numerous other essential purposes that we will explore in subsequent tutorials. - -**PyAutoFit** offers a comprehensive API for building models, which includes models constructed using NumPy arrays, -hierarchies of Python classes, and graphical models where parameters are interconnected. These advanced modeling -techniques are gradually introduced throughout the HowToFit lectures. - -For a detailed understanding of PyAutoFit's model composition API and a quick reference guide on how to construct -models, you may want to take a quick look at the model cookbook in the PyAutoFit documentation. It provides an -extensive overview and can serve as a helpful resource as you progress: - -[PyAutoFit Model Cookbook](https://pyautofit.readthedocs.io/en/latest/cookbooks/model.html) - -Don't worry if it seems a bit overwhelming at this stage; the concepts will become clearer as you continue exploring -and working with PyAutoFit. - -__Wrap Up__ - -In this tutorial, we've learned how to define and compose a model that can generate model data. - -Now, think about your specific field of study and the problem you want to address through model-fitting. Consider -the following questions: - -- What type of model would best describe your data? - -- Which Python class, following the format introduced here, would you need to compose this model? - -- What are the free parameters of your model that need to be determined through fitting? - -If you decide to incorporate a new model component into your autofit_workspace tailored to your specific model-fitting -task, refer to the following script: - -autofit_workspace/scripts/overview/new_model_component/new_model_component.py - -This script provides guidance on setting up the PyAutoFit configuration files associated with your custom model. -""" +""" +Tutorial 1: Models +================== + +At the heart of model-fitting is the model: a set of equations, numerical processes, and assumptions describing a +physical system of interest. The goal of model-fitting is to better understand this physical system and develop +predictive models that describe it more accurately. + +In astronomy, a model might describe the distribution of stars within a galaxy. In biology, it might represent the +interaction of proteins within a cell. In finance, it could describe the evolution of stock prices in a market. +Regardless of the field, the model acts as a mathematical description of the physical system, aiming to enhance +understanding and enable new predictions. + +Whatever your model, its equations are defined by "free parameters." Changing these parameters alters the +behavior and predictions of the model. + +Once the model is defined and parameter values are chosen, the model creates "model data"—a realization of how the +physical system appears given those parameters. This process, often referred to as "forward modeling," describes the +physical system from its starting point and predicts the data we observe. + +By varying the model parameters, we can generate numerous model datasets. The ultimate goal of model-fitting, which +you will learn by the end of this chapter, is to determine the model parameters and corresponding dataset that best +fit the observed data. + +__Astronomy Example__ + +For instance, in astronomy, we might model the distribution of stars, including: + +- A parameter describing the brightness of the stars. + +- Multiple parameters defining their distribution. + +- Several parameters describing their colors. + +If our model pertains to the distribution of stars within a galaxy, the forward model will produce an image of what +that galaxy looks like when observed with a telescope. This forward model might account for physical effects such as +the blurring of light due to diffraction in the telescope optics. + +By altering the parameters describing the stars, we can generate many different model images via this forward model. + +At the end of this chapter, we will use a real-world astronomy example to illustrate everything you have learned, +including fitting a real galaxy observed with the Hubble Space Telescope. + +__Overview__ + +In tutorial 1, we will cover the basics of defining a model, specifically: + +- Defining a simple model described by a few simple equations. + +- Showing that this model is characterized by three or more free parameters. + +- Using the model, with different sets of parameters, to generate model data. + +__Contents__ + +This tutorial is split into the following sections: + +- **Paths**: Setting up the working directory path so the tutorial runs correctly on your computer. +- **Model Parameterization**: An example of how a model is parameterized and is made up of free parameters. +- **Model Composition**: Composing a model using PyAutoFit's model composition API. +- **Model Creation**: Creating an instance of the model using PyAutoFit's `Model` python object. +- **Model Mapping**: Mapping an input vector of parameters to the model to create an instance of the model. +- **Complex Models**: Composing a more complex model with multiple model components and more free parameters. +- **Tuple Parameters**: Defining a model component with tuple parameters. +- **Extensibility**: Discussing how PyAutoFit's model composition API is scalable and extensible. +- **Wrap Up**: Concluding the tutorial and considering how to apply the concepts to your own scientific problem. + +This tutorial introduces the PyAutoFit API for model composition, which forms the foundation of all model-fitting +performed by PyAutoFit. +""" + +# from autofit import setup_notebook; setup_notebook() + +import numpy as np +import matplotlib.pyplot as plt + +import autofit as af + +r""" +__Paths__ + +PyAutoFit assumes the current working directory is /path/to/HowToFit/ on your hard-disk (or in Colab). +This setup allows PyAutoFit to: + +- Load configuration settings from config files in the HowToFit/config folder. + +- Load example data from the HowToFit/dataset folder. + +- Output the results of model fits to your hard disk in the autofit/output folder. + +If you don't have a HowToFit clone, you can download it here: + + https://github.com/PyAutoLabs/autofit_workspace + +__Model Parameterization__ + +A model is a set of equations, numerical processes, and assumptions that describe a physical system and dataset. + +In this example, our model is one or more 1-dimensional Gaussians, defined by the following equation: + +\begin{equation*} +g(x, I, \sigma) = \frac{N}{\sigma\sqrt{2\pi}} \exp{(-0.5 (x / \sigma)^2)} +\end{equation*} + +Where: + +- `x`: The x-axis coordinate where the Gaussian is evaluated. + +- `N`: The overall normalization of the Gaussian. + + +- `\sigma`: The size of the Gaussian (Full Width Half Maximum, $\mathrm{FWHM}$, is $2{\sqrt{2\ln 2}}\;\sigma$). + +While a 1D Gaussian might seem like a rudimentary model, it has many real-world applications in signal processing. +For example, 1D Gaussians are fitted to datasets to measure the size of an observed signal. Thus, this model has +practical real-world applications. + +We now have a model, expressed as a simple 1D Gaussian. The model has three parameters, $(x, N, \sigma)$. Using +different combinations of these parameters creates different realizations of the model, which we illustrate below. + +__Model Composition__ + +We now define the 1D Gaussian as a "model component" in PyAutoFit. We use the term "model component" because the model +can be extended to include multiple components, each related to different equations and numerical processes. + +We first illustrate a model composed of a single model component, the 1D Gaussian. We then show a model made of +multiple model components. + +To define a "model component" in PyAutoFit, we simply write it as a Python class using the format shown below: +""" + + +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))), + ) + + +""" +The format of this Python class defines how PyAutoFit composes the Gaussian as a model component, where: + +- The name of the class is the name of the model component, in this case, "Gaussian". + +- The input arguments of the constructor (the `__init__` method) are the parameters of the model, in the example +above `centre`, `normalization`, and `sigma`. + +- The default values and typing of the input arguments define whether a parameter is a single-valued float or a +multi-valued tuple. For the `Gaussian` class above, no input parameters are tuples, but later examples use tuples. + +- It includes functions associated with that model component, specifically the model_data function. When we create +instances of a `Gaussian` below, this function is used to generate a 1D representation of it as a NumPy array. + +__Model Creation__ + +The `Gaussian` class above is a standard Python class. It does not yet act as a model component that can be used +for model fitting with PyAutoFit. + +To transform the Gaussian class into a model component that can be used for model fitting with PyAutoFit, we use +the `af.Model` object. This tells PyAutoFit to treat the input Python class as a model component. +""" +model = af.Model(Gaussian) +print("Model `Gaussian` object: \n") +print(model) + +""" +In PyAutoFit, a Model object encapsulates a model component that can be used for model fitting. It provides several +attributes that describe the model component, such as the `total_free_parameters` attribute, which indicates the +number of free parameters in the model: +""" +print(model.total_free_parameters) + +""" +In PyAutoFit, you can retrieve comprehensive information about a model by accessing its `info` attribute. + +When you print the model info, it displays detailed information about each parameter in the model, including its name, +type, and associated prior distribution. Priors define the expected range or distribution of values for each +parameter during the model fitting process. If you're unfamiliar with priors, they are covered in tutorial 3 of +this chapter, which explains their role in model fitting. + +[The `info` below may not display optimally on your computer screen, for example the whitespace between parameter +names on the left and parameter priors on the right may lead them to appear across multiple lines. This is a +common issue in Jupyter notebooks. + +The`info_whitespace_length` parameter in the file `config/general.yaml` in the "output" section can be changed to +increase or decrease the amount of whitespace (The Jupyter notebook kernel will need to be reset for this change to +appear in a notebook).] +""" +print(model.info) + +""" +The same model can also be drawn, via `af.ModelPlotter`. + +The figure and the `info` are two views of the same object, and it is worth being precise about the division of +labour between them. The figure is the **map**: it shows the structure of the model, meaning which component owns +which parameter and, in the models we build later, which parameters are fixed, shared between components, related to +one another by an expression or constrained by an assertion. The `info` is the **legend**: it lists the priors and +values themselves, the numbers that the map has no room for. + +For this first model the map is about as simple as a map gets. There is a single card, titled `model` and `Gaussian` +after the class it was composed from, holding one pill per parameter: `centre`, `normalization` and `sigma`. The +footer counts them for you, `3 unique sampled scalars`, which is the same number the `total_free_parameters` +attribute printed above. Read the card as the answer to "what is this model made of?", and the `info` above it as the +answer to "and what values may each of those parts take?". + +Right now both views fit on one screen and the figure may look like a redundant restatement of the `info`. Draw it +anyway, because the two views scale very differently. By the end of this chapter our models have five components, in +the advanced chapter they span five datasets at once, and at that point the `info` runs to hundreds of lines whilst the map +still fits in a glance. +""" +af.ModelPlotter(model).figure() + +""" +__Model Mapping__ + +In PyAutoFit, instances of model components created via the af.Model object can be instantiated by mapping an input +vector of parameters to the Python class that the model object represents. The order of parameters in the model is +crucial for correctly defining the input vector. + +To determine the order of parameters in the model, PyAutoFit provides the paths attribute of the model object. +This attribute contains information about the parameter paths within the model. + +Here's how you can access the paths attribute to understand the order of parameters in the model: +""" +print(model.paths) + +""" +To create an instance of the Gaussian model component using PyAutoFit, following the order of parameters defined by +the paths attribute (`centre`, `normalization`, and `sigma`), you can initialize the instance as follows: +""" +instance = model.instance_from_vector(vector=[30.0, 2.0, 3.0]) + +""" +This is an instance of the `Gaussian` class. +""" +print("Model Instance: \n") +print(instance) + +""" +It has the parameters of the `Gaussian` with the values input above. +""" +print("Instance Parameters \n") +print("x = ", instance.centre) +print("normalization = ", instance.normalization) +print("sigma = ", instance.sigma) + +""" +We can use all class functions, such as the `model_data_from` function, to generate an instance of the +1D `Gaussian` and visualize it through plotting. + +The code below generates the 1D Gaussian model data, which requires an input list of x values where the Gaussian is +evaluated. The output is a NumPy array of the Gaussian's y values at the input x coordinates. + +Although simple, the code below is essentially the process of forward modeling, where we use the model to generate +the data we would observe in an experiment for a given set of parameters. +""" +xvalues = np.arange(0.0, 100.0, 1.0) + +model_data = instance.model_data_from(xvalues=xvalues) + +plt.plot(xvalues, model_data, color="r") +plt.title("1D Gaussian Model Data.") +plt.xlabel("x values of profile") +plt.ylabel("Gaussian Value") +plt.show() +plt.clf() + +r""" +__Complex Models__ + +The code above may seem like a lot of steps just to create an instance of the `Gaussian` class. Couldn't we have +simply done this instead? + +```python +instance = Gaussian(centre=30.0, normalization=2.0, sigma=3.0) +``` + +Yes, we could have. + +However, the model composition API used above is designed to simplify the process of composing complex models that +consist of multiple components with many free parameters. It provides a scalable approach for defining and +manipulating models. + +To demonstrate this capability, let's conclude the tutorial by composing a model composed of a Gaussian +component and another 1D profile, an `Exponential`, defined by the equation: + +\begin{equation*} +g(x, I, \lambda) = N \lambda \exp{- \lambda x } +\end{equation*} + +where: + +- `x`: Represents the x-axis coordinate where the Exponential profile is evaluated. + +- `N`: Describes the overall normalization of the Exponential profile. + +- $\lambda$: Represents the rate of decay of the exponential. + +We'll start by defining the `Exponential` profile using a format similar to the Gaussian definition above. +""" + + +class Exponential: + def __init__( + self, + centre: float = 30.0, # <- **PyAutoFit** recognises these constructor arguments + normalization: float = 1.0, # <- are the Exponential`s model parameters. + rate: float = 0.01, + ): + """ + Represents a 1D Exponential profile. + + This is a model-component of example models in the **HowToFit** lectures and is used to fit example datasets + via a non-linear search. + + Parameters + ---------- + centre + The x coordinate of the profile centre. + normalization + Overall normalization of the profile. + ratw + The decay rate controlling has fast the Exponential declines. + """ + self.centre = centre + self.normalization = normalization + self.rate = rate + + def model_data_from(self, xvalues: 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 `Exponential`, 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. + """ + transformed_xvalues = np.subtract(xvalues, self.centre) + return self.normalization * np.multiply( + self.rate, np.exp(-1.0 * self.rate * abs(transformed_xvalues)) + ) + + +""" +We can construct a model comprising one `Gaussian` object and one `Exponential` object using the `af.Collection` object: +""" +model = af.Collection(gaussian=af.Model(Gaussian), exponential=af.Model(Exponential)) + +""" +You can retrieve all the information about the model created via the `af.Collection` by printing its `info` attribute +in one go: +""" +print(model.info) + +""" +Drawing the model shows what a `Collection` does to the map. There are now two cards side by side, +`gaussian` and `exponential`, each titled with the class it was composed from and each owning its own pills, and the +footer counts `6 unique sampled scalars` across the pair. Components sit beside one another, and nothing yet joins +them: the two `centre` parameters are separate parameters that happen to share a name. +""" +af.ModelPlotter(model).figure() + +""" +When `Gaussian` and `Exponential` are added to a `Collection`, they are automatically assigned as `Model` objects. + +Therefore, there's no need to use the `af.Model` method when passing classes to a `Collection`, which makes the Python +code more concise and readable. +""" +model = af.Collection(gaussian=Gaussian, exponential=Exponential) + +""" +The `model.info` is identical to the previous example. +""" +print(model.info) + +""" +The figure is identical to the previous one too, and that is the point worth taking from this example. The two ways +of writing the composition look different on the page, but they build the same structure, and structure is all the +map draws. Whenever you change how a model is written, draw it: if the map does not move then nothing about the model +moved either, and any difference between the two fits has to be hiding in the legend rather than in the model. +""" +af.ModelPlotter(model).figure() + +""" +A `Collection` functions analogously to a `Model`, but it includes multiple model components. + +This can be observed by examining its `paths` attribute, which displays paths to all 6 free parameters across both model components. + +The paths contain entries such as `.gaussian.` and `.exponential.`, corresponding to the names we provided when +defining the `af.Collection` earlier. Modifying the names of the model components supplied to the `Collection` +would adjust the paths accordingly. +""" +print(model.paths) + +""" +A model instance can again be created by mapping an input `vector`, which now has 6 entries. +""" +instance = model.instance_from_vector(vector=[0.1, 0.2, 0.3, 0.4, 0.5, 0.01]) + +""" +This `instance` contains each of the model components we defined above. + +The argument names input into the `Collection` define the attribute names of the `instance`: +""" +print("Instance Parameters \n") +print("x (Gaussian) = ", instance.gaussian.centre) +print("normalization (Gaussian) = ", instance.gaussian.normalization) +print("sigma (Gaussian) = ", instance.gaussian.sigma) +print("x (Exponential) = ", instance.exponential.centre) +print("normalization (Exponential) = ", instance.exponential.normalization) +print("sigma (Exponential) = ", instance.exponential.rate) + +""" +In the context of the model's equations, it is simply the sum of the equations defining the `Gaussian` +and `Exponential` components. + +To generate the `model_data`, we sum the `model_data` of each individual model component, as demonstrated and +visualized below. +""" +xvalues = np.arange(0.0, 100.0, 1.0) + +model_data_0 = instance.gaussian.model_data_from(xvalues=xvalues) +model_data_1 = instance.exponential.model_data_from(xvalues=xvalues) + +model_data = model_data_0 + model_data_1 + +plt.plot(xvalues, model_data, color="r") +plt.plot(xvalues, model_data_0, "b", "--") +plt.plot(xvalues, model_data_1, "k", "--") +plt.title("1D Gaussian + Exponential Model Data.") +plt.xlabel("x values of profile") +plt.ylabel("Value") +plt.show() +plt.clf() + +""" +__Tuple Parameters__ + +The `Gaussian` and `Exponential` model components above only has parameters that are single-valued floats. + +Parameters can also be tuples, which is useful for defining model components where certain parameters are naturally +grouped together. + +For example, we can define a 2D Gaussian with a center that has two coordinates and therefore free parameters, (x, y), +using a tuple. +""" +from typing import Tuple + + +class Gaussian2D: + def __init__( + self, + centre: Tuple[float, float] = (0.0, 0.0), + normalization: float = 0.1, + sigma: float = 1.0, + ): + self.centre = centre + self.normalization = normalization + self.sigma = sigma + + +""" +The model's `total_free_parameters` attribute now includes 4 free parameters, as the tuple `centre` parameter accounts +for 2 free parameters. +""" +model = af.Model(Gaussian2D) + +print("Total Free Parameters:", model.total_free_parameters) + +""" +This information is again displayed in the `info` attribute: +""" +print("\nInfo:") +print(model.info) + +""" +The map shows how a tuple is handled. `centre` is still drawn as one pill, because it is one input argument of the +`Gaussian2D` class, but it now carries a `2D` badge marking it as a tuple, and the footer counts `4 unique sampled +scalars` rather than 3. The `paths` printed below unpack that badge into the two entries, one per coordinate, which +the input vector must supply. +""" +af.ModelPlotter(model).figure() + +""" +The `paths` attribute provides information on the order of parameters in the model, illustrating how the +`centre` tuple is split into two parameters. +""" +print("\nPaths:") +print(model.paths) + +""" +This ordering is used to create an instance of the `Gaussian2D` model component: +""" +instance = model.instance_from_vector(vector=[40.0, 60.0, 2.0, 3.0]) + +print("\nInstance Parameters:") +print("centre (x) = ", instance.centre[0]) +print("centre (y) = ", instance.centre[1]) +print("normalization = ", instance.normalization) +print("sigma = ", instance.sigma) + +""" +__Extensibility__ + +It should now be clear why we use `Model` and `Collection` objects to construct our model. + +These objects facilitate the straightforward extension of our models to include multiple components and parameters. +For instance, we can add more `Gaussian` and `Exponential` components to the `Collection`, or define new Python +classes to represent entirely new model components with additional parameters. + +These objects serve numerous other essential purposes that we will explore in subsequent tutorials. + +**PyAutoFit** offers a comprehensive API for building models, which includes models constructed using NumPy arrays, +hierarchies of Python classes, and graphical models where parameters are interconnected. These advanced modeling +techniques are gradually introduced throughout the HowToFit lectures. + +For a detailed understanding of PyAutoFit's model composition API and a quick reference guide on how to construct +models, you may want to take a quick look at the model cookbook in the PyAutoFit documentation. It provides an +extensive overview and can serve as a helpful resource as you progress: + +[PyAutoFit Model Cookbook](https://pyautofit.readthedocs.io/en/latest/cookbooks/model.html) + +Don't worry if it seems a bit overwhelming at this stage; the concepts will become clearer as you continue exploring +and working with PyAutoFit. + +__Wrap Up__ + +In this tutorial, we've learned how to define and compose a model that can generate model data. + +Now, think about your specific field of study and the problem you want to address through model-fitting. Consider +the following questions: + +- What type of model would best describe your data? + +- Which Python class, following the format introduced here, would you need to compose this model? + +- What are the free parameters of your model that need to be determined through fitting? + +If you decide to incorporate a new model component into your autofit_workspace tailored to your specific model-fitting +task, refer to the following script: + +autofit_workspace/scripts/overview/new_model_component/new_model_component.py + +This script provides guidance on setting up the PyAutoFit configuration files associated with your custom model. +""" diff --git a/scripts/chapter_1_introduction/tutorial_8_scientific_workflow.py b/scripts/chapter_1_introduction/tutorial_8_scientific_workflow.py index 06984e8..55106cb 100644 --- a/scripts/chapter_1_introduction/tutorial_8_scientific_workflow.py +++ b/scripts/chapter_1_introduction/tutorial_8_scientific_workflow.py @@ -24,5 +24,5 @@ __Wrap Up__ -Apply the workflow to your own data before returning to chapter 3 for graphical and hierarchical models. +Apply the workflow to your own data before returning to the advanced chapter for graphical and hierarchical models. """ diff --git a/scripts/chapter_3_graphical_models/README.md b/scripts/chapter_3_graphical_models/README.md deleted file mode 100644 index c30478c..0000000 --- a/scripts/chapter_3_graphical_models/README.md +++ /dev/null @@ -1,19 +0,0 @@ -In this chapter, we take you through how to compose and fit graphical models in **PyAutoFit**. Graphical models -simultaneously fit many datasets with a model that has 'local' parameters specific to each individual dataset -and 'global' parameters that fit for global trends across the whole dataset. - -**Colab** links to every tutorial are included. - -# Files - -The chapter contains the following tutorials: - -- [Tutorial 1: Individual Models](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_3_graphical_models/tutorial_1_individual_models.ipynb) — Inferring global parameters from a dataset by fitting the model to each individual dataset one-by-one. - -- [Tutorial 2: Graphical Model](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_3_graphical_models/tutorial_2_graphical_model.ipynb) — Fitting the dataset with a graphical model that fits all datasets simultaneously to infer the global parameters. - -- [Tutorial 3: Graphical Benefits](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_3_graphical_models/tutorial_3_graphical_benefits.ipynb) — Illustrating the benefits of graphical modeling over fitting individual datasets one-by-one. - -- [Tutorial 4: Hierarchical Models](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_3_graphical_models/tutorial_4_hierachical_models.ipynb) — Fitting hierarchical models using the graphical modeling framework. - -- [Tutorial 5: Expectation Propagation](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_3_graphical_models/tutorial_5_expectation_propagation.ipynb) — Scaling graphical models up to fit extremely large datasets using Expectation Propagation (EP). diff --git a/scripts/chapter_advanced/README.md b/scripts/chapter_advanced/README.md new file mode 100644 index 0000000..38b6e82 --- /dev/null +++ b/scripts/chapter_advanced/README.md @@ -0,0 +1,23 @@ +In this chapter, we take you through how to compose and fit graphical models in **PyAutoFit**. Graphical models +simultaneously fit many datasets with a model that has 'local' parameters specific to each individual dataset +and 'global' parameters that fit for global trends across the whole dataset. + +**Colab** links to every tutorial are included. + +# Files + +The chapter contains the following tutorials: + +- [Tutorial 1: Individual Models](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_advanced/tutorial_1_individual_models.ipynb) — Inferring global parameters from a dataset by fitting the model to each individual dataset one-by-one. + +- [Tutorial 2: Graphical Model](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_advanced/tutorial_2_graphical_model.ipynb) — Fitting the dataset with a graphical model that fits all datasets simultaneously to infer the global parameters. + +- [Tutorial 3: Graphical Benefits](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_advanced/tutorial_3_graphical_benefits.ipynb) — Illustrating the benefits of graphical modeling over fitting individual datasets one-by-one. + +- [Tutorial 4: Hierarchical Models](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_advanced/tutorial_4_hierachical_models.ipynb) — Fitting hierarchical models using the graphical modeling framework. + +- [Tutorial 5: Expectation Propagation](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_advanced/tutorial_5_expectation_propagation.ipynb) — Scaling graphical models up to fit extremely large datasets using Expectation Propagation (EP). + +- [Tutorial Optional: Hierarchical Expectation Propagation](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_advanced/tutorial_optional_hierarchical_ep.ipynb) — Fitting a hierarchical model with Expectation Propagation, scaling the hierarchical approach to large datasets. + +- [Tutorial Optional: Hierarchical Individual](https://colab.research.google.com/github/PyAutoLabs/HowToFit/blob/2026.9.14.1/notebooks/chapter_advanced/tutorial_optional_hierarchical_individual.ipynb) — Estimating a hierarchical model's parent distribution from one-by-one fits, and why the graphical approach improves on it. diff --git a/scripts/chapter_3_graphical_models/__init__.py b/scripts/chapter_advanced/__init__.py similarity index 100% rename from scripts/chapter_3_graphical_models/__init__.py rename to scripts/chapter_advanced/__init__.py diff --git a/scripts/chapter_3_graphical_models/tutorial_1_individual_models.py b/scripts/chapter_advanced/tutorial_1_individual_models.py similarity index 98% rename from scripts/chapter_3_graphical_models/tutorial_1_individual_models.py rename to scripts/chapter_advanced/tutorial_1_individual_models.py index c146255..c2f0128 100644 --- a/scripts/chapter_3_graphical_models/tutorial_1_individual_models.py +++ b/scripts/chapter_advanced/tutorial_1_individual_models.py @@ -178,7 +178,7 @@ dynesty = af.DynestyStatic( name="global_model", path_prefix=path.join( - "chapter_3_graphical_models", "tutorial_1_individual_models" + "chapter_advanced", "tutorial_1_individual_models" ), unique_tag=dataset_name, nlive=200, @@ -189,7 +189,7 @@ print( f"The non-linear search has begun running, checkout \n" - f"HowToFit/output/chapter_3_graphical_models/tutorial_1_individual_models/{dataset_name} for live \n" + f"HowToFit/output/chapter_advanced/tutorial_1_individual_models/{dataset_name} for live \n" f"output of the results. This Jupyter notebook cell with progress once search has completed, this could take a \n" f"few minutes!" ) diff --git a/scripts/chapter_3_graphical_models/tutorial_2_graphical_model.py b/scripts/chapter_advanced/tutorial_2_graphical_model.py similarity index 99% rename from scripts/chapter_3_graphical_models/tutorial_2_graphical_model.py rename to scripts/chapter_advanced/tutorial_2_graphical_model.py index ea080b1..0a7a102 100644 --- a/scripts/chapter_3_graphical_models/tutorial_2_graphical_model.py +++ b/scripts/chapter_advanced/tutorial_2_graphical_model.py @@ -240,7 +240,7 @@ We can now create a non-linear search and use it to the fit the factor graph, using its `global_prior_model` property. """ search = af.DynestyStatic( - path_prefix=path.join("chapter_3_graphical_models"), + path_prefix=path.join("chapter_advanced"), name="tutorial_2_graphical_model", nlive=200, dlogz=1e-4, diff --git a/scripts/chapter_3_graphical_models/tutorial_3_graphical_benefits.py b/scripts/chapter_advanced/tutorial_3_graphical_benefits.py similarity index 98% rename from scripts/chapter_3_graphical_models/tutorial_3_graphical_benefits.py rename to scripts/chapter_advanced/tutorial_3_graphical_benefits.py index 6e58d57..bab98f8 100644 --- a/scripts/chapter_3_graphical_models/tutorial_3_graphical_benefits.py +++ b/scripts/chapter_advanced/tutorial_3_graphical_benefits.py @@ -173,7 +173,7 @@ search = af.DynestyStatic( name=f"individual_fit_{i}", path_prefix=path.join( - "chapter_3_graphical_models", "tutorial_3_graphical_benefits" + "chapter_advanced", "tutorial_3_graphical_benefits" ), nlive=200, dlogz=1e-4, @@ -183,7 +183,7 @@ print( f"The non-linear search has begun running, checkout \n" - f"HowToFit/output/chapter_3_graphical_models/tutorial_3_graphical_benefits/{dataset_name} for live \n" + f"HowToFit/output/chapter_advanced/tutorial_3_graphical_benefits/{dataset_name} for live \n" f"output of the results. This Jupyter notebook cell with progress once search has completed, this could take a \n" f"few minutes!" ) @@ -376,7 +376,7 @@ property. """ search = af.DynestyStatic( - path_prefix=path.join("chapter_3_graphical_models"), + path_prefix=path.join("chapter_advanced"), name="tutorial_3_graphical_benefits", sample="rwalk", ) diff --git a/scripts/chapter_3_graphical_models/tutorial_4_hierachical_models.py b/scripts/chapter_advanced/tutorial_4_hierachical_models.py similarity index 99% rename from scripts/chapter_3_graphical_models/tutorial_4_hierachical_models.py rename to scripts/chapter_advanced/tutorial_4_hierachical_models.py index 2d34118..b10a865 100644 --- a/scripts/chapter_3_graphical_models/tutorial_4_hierachical_models.py +++ b/scripts/chapter_advanced/tutorial_4_hierachical_models.py @@ -238,7 +238,7 @@ its `global_prior_model` property. """ search = af.DynestyStatic( - path_prefix=path.join("chapter_3_graphical_models"), + path_prefix=path.join("chapter_advanced"), name="tutorial_4_hierarchical", sample="rwalk", ) diff --git a/scripts/chapter_3_graphical_models/tutorial_5_expectation_propagation.py b/scripts/chapter_advanced/tutorial_5_expectation_propagation.py similarity index 99% rename from scripts/chapter_3_graphical_models/tutorial_5_expectation_propagation.py rename to scripts/chapter_advanced/tutorial_5_expectation_propagation.py index 270a258..0eac482 100644 --- a/scripts/chapter_3_graphical_models/tutorial_5_expectation_propagation.py +++ b/scripts/chapter_advanced/tutorial_5_expectation_propagation.py @@ -166,7 +166,7 @@ to name the folders containing the results in the output directory. """ paths = af.DirectoryPaths( - name=path.join("chapter_3_graphical_models", "tutorial_5_expectation_propagation") + name=path.join("chapter_advanced", "tutorial_5_expectation_propagation") ) search = af.DynestyStatic(paths=paths, nlive=100, sample="rwalk") @@ -347,7 +347,7 @@ def log_likelihood_function(self, instance, xp=np): __Output__ The results of the factor graph, using the EP framework and message passing, are contained in the folder -`output/chapter_3_graphical_models/tutorial_5_expectation_propagation`. +`output/chapter_advanced/tutorial_5_expectation_propagation`. The following folders and files are worth of note: diff --git a/scripts/chapter_3_graphical_models/tutorial_optional_hierarchical_ep.py b/scripts/chapter_advanced/tutorial_optional_hierarchical_ep.py similarity index 98% rename from scripts/chapter_3_graphical_models/tutorial_optional_hierarchical_ep.py rename to scripts/chapter_advanced/tutorial_optional_hierarchical_ep.py index 19fde22..d6b5766 100644 --- a/scripts/chapter_3_graphical_models/tutorial_optional_hierarchical_ep.py +++ b/scripts/chapter_advanced/tutorial_optional_hierarchical_ep.py @@ -222,7 +222,7 @@ # laplace, # paths=af.DirectoryPaths( # name=path.join( -# "chapter_3_graphical_models", "tutorial_4_hierarchical" +# "chapter_advanced", "tutorial_4_hierarchical" # ) # ), # ep_history=af.EPHistory(kl_tol=1.0), @@ -236,6 +236,6 @@ `factor_graph.optimise` call above is commented out because a full EP fit is computationally expensive; uncomment it to run the fit yourself. -For the concepts behind hierarchical models and EP, see the main chapter 3 tutorials +For the concepts behind hierarchical models and EP, see the main advanced chapter tutorials (`tutorial_4_hierarchical_model` and `tutorial_5_expectation_propagation`). """ diff --git a/scripts/chapter_3_graphical_models/tutorial_optional_hierarchical_individual.py b/scripts/chapter_advanced/tutorial_optional_hierarchical_individual.py similarity index 100% rename from scripts/chapter_3_graphical_models/tutorial_optional_hierarchical_individual.py rename to scripts/chapter_advanced/tutorial_optional_hierarchical_individual.py diff --git a/scripts/simulators/simulators.py b/scripts/simulators/simulators.py index ee3d269..1d52ca4 100644 --- a/scripts/simulators/simulators.py +++ b/scripts/simulators/simulators.py @@ -234,10 +234,10 @@ ) """ -__Sample Datasets (Chapter 3)__ +__Sample Datasets (Advanced Chapter)__ Chain-run the sample simulator so every tutorial's `simulators.py` subprocess -call also produces the `dataset_*/` sample folders used by chapter 3. +call also produces the `dataset_*/` sample folders used by the advanced chapter. The path is relative to the repository root, which every execution context sets as the working directory: scripts are run from the root, the notebook kernel is pinned there, and Colab chdirs diff --git a/start_here.ipynb b/start_here.ipynb index 803921d..0bd24bb 100644 --- a/start_here.ipynb +++ b/start_here.ipynb @@ -21,7 +21,7 @@ "- Chapter 1: Introduction \u2014 what a model is, how we fit data, how non-linear searches work,\n", " why model fitting is hard, and how to inspect the results. The final tutorial introduces\n", " scientific workflows and links to the full guide and workspace example.\n", - "- Chapter 3: Graphical models \u2014 fitting many datasets simultaneously with graphical models,\n", + "- Advanced chapter: Graphical models \u2014 fitting many datasets simultaneously with graphical models,\n", " hierarchical models, and Expectation Propagation.\n", "\n", "Each chapter is organised into numbered tutorial files: `chapter__/tutorial__.py`\n", @@ -36,7 +36,7 @@ " continue through the rest of chapter 1.\n", "2. At this point you can start applying **PyAutoFit** to your own data using scripts in the\n", " separate `autofit_workspace` repository \u2014 you know enough to be productive.\n", - "3. Come back for `chapter_3_graphical_models` when you need to fit many datasets simultaneously\n", + "3. Come back for `chapter_advanced` when you need to fit many datasets simultaneously\n", " or build hierarchical inference pipelines.\n", "\n", "__Notebooks vs Scripts__\n", diff --git a/start_here.py b/start_here.py index 6a1594e..c11e4fa 100644 --- a/start_here.py +++ b/start_here.py @@ -16,7 +16,7 @@ - Chapter 1: Introduction — what a model is, how we fit data, how non-linear searches work, why model fitting is hard, and how to inspect the results. The final tutorial introduces scientific workflows and links to the full guide and workspace example. -- Chapter 3: Graphical models — fitting many datasets simultaneously with graphical models, +- Advanced chapter: Graphical models — fitting many datasets simultaneously with graphical models, hierarchical models, and Expectation Propagation. Each chapter is organised into numbered tutorial files: `chapter__/tutorial__.py` @@ -31,7 +31,7 @@ continue through the rest of chapter 1. 2. At this point you can start applying **PyAutoFit** to your own data using scripts in the separate `autofit_workspace` repository — you know enough to be productive. -3. Come back for `chapter_3_graphical_models` when you need to fit many datasets simultaneously +3. Come back for `chapter_advanced` when you need to fit many datasets simultaneously or build hierarchical inference pipelines. __Notebooks vs Scripts__ diff --git a/workspace_index.json b/workspace_index.json index afe17d6..77e2ebe 100644 --- a/workspace_index.json +++ b/workspace_index.json @@ -229,8 +229,8 @@ "Wrap Up" ], "cross_refs": [], - "notebook": "notebooks/chapter_3_graphical_models/tutorial_1_individual_models.ipynb", - "path": "scripts/chapter_3_graphical_models/tutorial_1_individual_models.py", + "notebook": "notebooks/chapter_advanced/tutorial_1_individual_models.ipynb", + "path": "scripts/chapter_advanced/tutorial_1_individual_models.py", "summary": "In many examples, we fit one model to one dataset. For many problems, we may have a large dataset and are not interested in how well the model fits each individual dataset. Instead, we want to know how the model fits the full dataset, so that we can determine \"global\" trends of how the model fits the data.", "title": "Tutorial 1: Individual Models" }, @@ -247,8 +247,8 @@ "Wrap Up" ], "cross_refs": [], - "notebook": "notebooks/chapter_3_graphical_models/tutorial_2_graphical_model.ipynb", - "path": "scripts/chapter_3_graphical_models/tutorial_2_graphical_model.py", + "notebook": "notebooks/chapter_advanced/tutorial_2_graphical_model.ipynb", + "path": "scripts/chapter_advanced/tutorial_2_graphical_model.py", "summary": "We have fitted a dataset containing 5 noisy 1D Gaussian which had a shared `centre` value. We estimated the `centre` by fitting each dataset individually and combining the value of the `centre` inferred by each fit into an overall estimate, using a weighted average.", "title": "Tutorial 2: Graphical Models" }, @@ -272,8 +272,8 @@ "Wrap Up" ], "cross_refs": [], - "notebook": "notebooks/chapter_3_graphical_models/tutorial_3_graphical_benefits.ipynb", - "path": "scripts/chapter_3_graphical_models/tutorial_3_graphical_benefits.py", + "notebook": "notebooks/chapter_advanced/tutorial_3_graphical_benefits.ipynb", + "path": "scripts/chapter_advanced/tutorial_3_graphical_benefits.py", "summary": "In the previous tutorials, we fitted a dataset containing 5 noisy 1D Gaussian which had a shared `centre` value and compared different approaches to estimate the shared `centre`. This included a simple approach fitting each dataset one-by-one and estimating the centre via a weighted average or posterior multiplication and a more complicated approach using a graphical model.", "title": "Tutorial 3: Graphical Benefits" }, @@ -295,8 +295,8 @@ "cross_refs": [ "tutorial_optional_hierarchical_individual.py" ], - "notebook": "notebooks/chapter_3_graphical_models/tutorial_4_hierachical_models.ipynb", - "path": "scripts/chapter_3_graphical_models/tutorial_4_hierachical_models.py", + "notebook": "notebooks/chapter_advanced/tutorial_4_hierachical_models.ipynb", + "path": "scripts/chapter_advanced/tutorial_4_hierachical_models.py", "summary": "In the previous tutorial, we fitted a graphical model with the aim of determining an estimate of shared parameters, the `centre`'s of a dataset of 1D Gaussians. We did this by fitting all datasets simultaneously. When there are shared parameters in a model, this is a powerful and effective tool, but things may not always be so simple.", "title": "Tutorial 4: Hierarchical" }, @@ -315,8 +315,8 @@ "Results" ], "cross_refs": [], - "notebook": "notebooks/chapter_3_graphical_models/tutorial_5_expectation_propagation.ipynb", - "path": "scripts/chapter_3_graphical_models/tutorial_5_expectation_propagation.py", + "notebook": "notebooks/chapter_advanced/tutorial_5_expectation_propagation.ipynb", + "path": "scripts/chapter_advanced/tutorial_5_expectation_propagation.py", "summary": "In the previous tutorials, we fitted graphical models to dataset comprising many noisy 1D Gaussians. These had a shared and global value of their `centre`, or assumed their centres were hierarchically drawn from a parent Gaussian distribution. This provides the basis of composing and fitting complex graphical models to large datasets.", "title": "Tutorial 5: Expectation Propagation" }, @@ -332,8 +332,8 @@ "Model Fit" ], "cross_refs": [], - "notebook": "notebooks/chapter_3_graphical_models/tutorial_optional_hierarchical_ep.ipynb", - "path": "scripts/chapter_3_graphical_models/tutorial_optional_hierarchical_ep.py", + "notebook": "notebooks/chapter_advanced/tutorial_optional_hierarchical_ep.ipynb", + "path": "scripts/chapter_advanced/tutorial_optional_hierarchical_ep.py", "summary": "This optional tutorial gives an example of fitting a hierarchical model using EP.", "title": "Tutorial Optional: Hierarchical Expectation Propagation (EP)" }, @@ -350,8 +350,8 @@ "Analysis + Search" ], "cross_refs": [], - "notebook": "notebooks/chapter_3_graphical_models/tutorial_optional_hierarchical_individual.ipynb", - "path": "scripts/chapter_3_graphical_models/tutorial_optional_hierarchical_individual.py", + "notebook": "notebooks/chapter_advanced/tutorial_optional_hierarchical_individual.ipynb", + "path": "scripts/chapter_advanced/tutorial_optional_hierarchical_individual.py", "summary": "In tutorial 4, we fit a hierarchical model using a graphical model, whereby all datasets are fitted simultaneously and the hierarchical parameters are fitted for simultaneously with the model parameters of each 1D Gaussian in each dataset.", "title": "Tutorial Optional: Hierarchical Individual" },