diff --git a/docs/api/analysis.rst b/docs/api/analysis.rst index 765552668..6be6f53ae 100644 --- a/docs/api/analysis.rst +++ b/docs/api/analysis.rst @@ -8,7 +8,7 @@ It acts as an interface between the data, model and the non-linear search. **Examples / Tutorials:** -- `readthedocs: example using Analysis object `_. +- `readthedocs: example using Analysis object `_. - `autofit_workspace: simple tutorial `_ - `autofit_workspace: complex tutorial `_ - `HowToFit: tutorial lectures (detailed step-by-step examples) `_ diff --git a/docs/api/model.rst b/docs/api/model.rst index a599cf8d4..36cf81725 100644 --- a/docs/api/model.rst +++ b/docs/api/model.rst @@ -10,7 +10,7 @@ It is recommended the `model API cookbooks `_. -- `readthedocs: example using Model object `_. +- `readthedocs: example using Model object `_. - `readthedocs: example using Collection object `_. - `autofit_workspace: simple tutorial `_ - `autofit_workspace: complex tutorial `_ diff --git a/docs/api/priors.rst b/docs/api/priors.rst index 4c86af576..34d4ca7a0 100644 --- a/docs/api/priors.rst +++ b/docs/api/priors.rst @@ -8,7 +8,7 @@ The priors of parameters of every component of a mdoel, which is fitted to data, - `Model API Cookbooks (recommended) `_. -- `readthedocs: example using Model object `_. +- `readthedocs: example using Model object `_. - `readthedocs: example using Collection object `_. - `autofit_workspace: simple tutorial `_ - `autofit_workspace: complex tutorial `_ diff --git a/docs/index.md b/docs/index.md index 520e552ca..d6d985a36 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,12 +1,15 @@ # PyAutoFit -**PyAutoFit** is a Python based probabilistic programming language for model fitting and Bayesian inference -of large datasets. +**PyAutoFit** is a Python package for scientific model fitting and Bayesian inference. Bring your own model +classes, data and likelihood code; **PyAutoFit** provides priors, inference algorithms and tools for interpreting +and organising the results. It is domain agnostic: inference can sit around your existing scientific software. -The basic **PyAutoFit** API allows us a user to quickly compose a probabilistic model and fit it to data via a -log likelihood function, using a range of non-linear search algorithms (e.g. MCMC, nested sampling). +We recommend getting started with [autofit_assistant](https://github.com/PyAutoLabs/autofit_assistant), which lets +you **perform scientific inference using natural language**. Describe the model you want to fit, ask the assistant +to run the analysis, and explore the results through follow-up requests — +see [Inference with Natural Language](https://pyautofit.readthedocs.io/en/latest/overview/natural_language.html). -Users can then set up **PyAutoFit** scientific workflow, which enables streamlined modeling of small +Users can then set up a **PyAutoFit** scientific workflow, which enables streamlined modeling of small datasets with tools to scale up to large datasets. **PyAutoFit** supports advanced statistical methods, most @@ -16,6 +19,7 @@ notably [a big data framework for Bayesian hierarchical analysis](https://pyauto The following links are useful for new starters: +- [The autofit_assistant repository](https://github.com/PyAutoLabs/autofit_assistant), which lets you perform inference in natural language via a coding agent — the recommended starting point. - [The PyAutoFit readthedocs](https://pyautofit.readthedocs.io/en/latest), which includes an [installation guide](https://pyautofit.readthedocs.io/en/latest/installation/overview.html) and an overview of **PyAutoFit**'s core features. - [The introduction Jupyter Notebook on Colab](https://colab.research.google.com/github/PyAutoLabs/autofit_workspace/blob/2026.9.8.1/notebooks/overview/overview_1_the_basics.ipynb), where you can try **PyAutoFit** in a web browser (without installation). - [The autofit_workspace GitHub repository](https://github.com/PyAutoLabs/autofit_workspace), which includes example scripts demonstrating **PyAutoFit**'s features. @@ -38,108 +42,39 @@ content pitched at undergraduate level and above. The lectures are available in the [standalone HowToFit repository](https://github.com/PyAutoLabs/HowToFit). -## API Overview +## Overview -To illustrate the **PyAutoFit** API, we use an illustrative toy model of fitting a one-dimensional Gaussian to -noisy 1D data. Here's the `data` (black) and the model (red) we'll fit: +To illustrate **PyAutoFit** we use a toy model of fitting a one-dimensional Gaussian to noisy 1D data. Here's +the `data` (black) and the model (red) we'll fit: ```{image} https://raw.githubusercontent.com/PyAutoLabs/PyAutoFit/main/files/toy_model_fit.png :width: 400 ``` -We define our model, a 1D Gaussian by writing a Python class using the format below: +There are two ways to read the rest of these docs: -```python -class Gaussian: +- [Inference with Natural Language](https://pyautofit.readthedocs.io/en/latest/overview/natural_language.html) + walks through this fit as a conversation with an assistant — composing the model, defining the likelihood, + choosing a search, running the fit and inspecting the results, all described in words rather than written by + hand. **This is the recommended starting point.** +- [The Python API](https://pyautofit.readthedocs.io/en/latest/overview/python_api.html) walks through the same + fit in code, showing the `Model`, `Analysis`, search and `Result` objects the assistant writes for you, and + which you can read, run and extend yourself. - def __init__( - self, - centre=0.0, # <- PyAutoFit recognises these - normalization=0.1, # <- constructor arguments are - sigma=0.01, # <- the Gaussian's parameters. - ): - self.centre = centre - self.normalization = normalization - self.sigma = sigma - - """ - An instance of the Gaussian class will be available during model fitting. - - This method will be used to fit the model to data and compute a likelihood. - """ - - def model_data_from(self, xvalues): - - transformed_xvalues = xvalues - self.centre - - return (self.normalization / (self.sigma * (2.0 * np.pi) ** 0.5)) * \ - np.exp(-0.5 * (transformed_xvalues / self.sigma) ** 2.0) -``` - -**PyAutoFit** recognises that this Gaussian may be treated as a model component whose parameters can be fitted for via -a non-linear search like [emcee](https://github.com/dfm/emcee). - -To fit this Gaussian to the `data` we create an Analysis object, which gives **PyAutoFit** the `data` and a -`log_likelihood_function` describing how to fit the `data` with the model: - -```python -class Analysis(af.Analysis): - - def __init__(self, data, noise_map): - - self.data = data - self.noise_map = noise_map - - def log_likelihood_function(self, instance): - - """ - The 'instance' that comes into this method is an instance of the Gaussian class - above, with the parameters set to values chosen by the non-linear search. - """ - - print("Gaussian Instance:") - print("Centre = ", instance.centre) - print("normalization = ", instance.normalization) - print("Sigma = ", instance.sigma) - - """ - We fit the ``data`` with the Gaussian instance, using its - "model_data_from" function to create the model data. - """ - - xvalues = np.arange(self.data.shape[0]) - - model_data = instance.model_data_from(xvalues=xvalues) - residual_map = self.data - model_data - chi_squared_map = (residual_map / self.noise_map) ** 2.0 - log_likelihood = -0.5 * sum(chi_squared_map) - - return log_likelihood -``` - -We can now fit our model to the `data` using a non-linear search: - -```python -model = af.Model(Gaussian) - -analysis = Analysis(data=data, noise_map=noise_map) - -emcee = af.Emcee(nwalkers=50, nsteps=2000) - -result = emcee.fit(model=model, analysis=analysis) -``` - -The `result` contains information on the model-fit, for example the parameter samples, maximum log likelihood -model and marginalized probability density functions. +Between them sit the [Scientific Workflow](https://pyautofit.readthedocs.io/en/latest/overview/scientific_workflow.html), +which makes inference scalable to large datasets, and the +[Statistical Methods](https://pyautofit.readthedocs.io/en/latest/overview/statistical_methods.html) overview, +covering hierarchical models, search chaining and Bayesian model comparison. ```{toctree} :caption: 'Overview:' :hidden: true :maxdepth: 1 -overview/the_basics +overview/natural_language overview/scientific_workflow overview/statistical_methods +overview/python_api ``` ```{toctree} diff --git a/docs/overview/backup.md b/docs/overview/backup.md deleted file mode 100644 index 548c63fff..000000000 --- a/docs/overview/backup.md +++ /dev/null @@ -1,377 +0,0 @@ -# Extending Models - -The model composition API is designed to make composing complex models, consisting of multiple components with many -free parameters, straightforward and scalable. - -To illustrate this, we will extend our model to include a second component, representing a symmetric 1D Exponential -profile, and fit it to data generated with both profiles. - -Lets begin by loading and plotting this data. - -```python -dataset_path = path.join("dataset", "example_1d", "gaussian_x1__exponential_x1") -data = af.util.numpy_array_from_json(file_path=path.join(dataset_path, "data.json")) -noise_map = af.util.numpy_array_from_json( - file_path=path.join(dataset_path, "noise_map.json") -) -xvalues = range(data.shape[0]) -plt.errorbar( - x=xvalues, y=data, yerr=noise_map, color="k", ecolor="k", elinewidth=1, capsize=2 -) -plt.show() -plt.close() -``` - -The data appear as follows: - -```{image} https://raw.githubusercontent.com/PyAutoLabs/PyAutoFit/main/docs/images/data_2.png -:alt: Alternative text -:width: 600 -``` - -We define a Python class for the `Exponential` model component, exactly as we did for the `Gaussian` above. - -```python -class Exponential: - def __init__( - self, - centre=30.0, # <- **PyAutoFit** recognises these constructor arguments - normalization=1.0, # <- are the Exponentials``s model parameters. - rate=0.01, - ): - """ - Represents a symmetric 1D Exponential profile. - - 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 the symmetric 1D Exponential 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 easily compose a model consisting of 1 `Gaussian` object and 1 `Exponential` object using the `af.Collection` -object: - -```python -model = af.Collection(gaussian=af.Model(Gaussian), exponential=af.Model(Exponential)) -``` - -A `Collection` behaves analogous to a `Model`, but it contains a multiple model components. - -We can see this by printing its `paths` attribute, where paths to all 6 free parameters via both model components -are shown. - -The paths have the entries `.gaussian.` and `.exponential.`, which correspond to the names we input into -the `af.Collection` above. - -```python -print(model.paths) -``` - -The output is as follows: - -```bash -[ - ('gaussian', 'centre'), - ('gaussian', 'normalization'), - ('gaussian', 'sigma'), - ('exponential', 'centre'), - ('exponential', 'normalization'), - ('exponential', 'rate') -] -``` - -We can use the paths to customize the priors of each parameter. - -```python -model.gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) -model.gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=1e2) -model.gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=30.0) -model.exponential.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) -model.exponential.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=1e2) -model.exponential.rate = af.UniformPrior(lower_limit=0.0, upper_limit=10.0) -``` - -All of the information about the model created via the collection can be printed at once using its `info` attribute: - -```python -print(model.info) -``` - -The output appears as follows: - -```bash -Total Free Parameters = 6 -model Collection (N=6) - gaussian Gaussian (N=3) - exponential Exponential (N=3) - - gaussian - centre UniformPrior [13], lower_limit = 0.0, upper_limit = 100.0 - normalization UniformPrior [14], lower_limit = 0.0, upper_limit = 100.0 - sigma UniformPrior [15], lower_limit = 0.0, upper_limit = 30.0 - exponential - centre UniformPrior [16], lower_limit = 0.0, upper_limit = 100.0 - normalization UniformPrior [17], lower_limit = 0.0, upper_limit = 100.0 - rate UniformPrior [18], lower_limit = 0.0, upper_limit = 10.0 -``` - -A model instance can again be created by mapping an input `vector`, which now has 6 entries. - -```python -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`: - -```python -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) -``` - -The output appear as follows: - -```bash - -``` - -The `Analysis` class above assumed the `instance` contained only a single model-component. - -We update its `log_likelihood_function` to use both model components in the `instance` to fit the data. - -```python -class Analysis(af.Analysis): - def __init__(self, data: np.ndarray, noise_map: np.ndarray): - """ - The `Analysis` class acts as an interface between the data and - model in **PyAutoFit**. - - Its `log_likelihood_function` defines how the model is fitted to - the data and it is called many times by the non-linear search - fitting algorithm. - - In this example the `Analysis` `__init__` constructor only - contains the `data` and `noise-map`, but it can be easily - extended to include other quantities. - - Parameters - ---------- - data - A 1D numpy array containing the data (e.g. a noisy 1D signal) - fitted in the workspace examples. - noise_map - A 1D numpy array containing the noise values of the data, - used for computing the goodness of fit metric, the log likelihood. - """ - - super().__init__() - - self.data = data - self.noise_map = noise_map - - def log_likelihood_function(self, instance) -> float: - """ - Returns the log likelihood of a fit of a 1D Gaussian to the dataset. - - The data is fitted using an `instance` of multiple 1D profiles - (e.g. a `Gaussian`, `Exponential`) where - their `model_data_from` methods are called and summed - in order to create a model data representation that is fitted to the data. - """ - - """ - The `instance` that comes into this method is an instance of the - `Gaussian` and `Exponential` models above, which were created - via `af.Collection()`. - - It contains instances of every class we instantiated it with, where - each instance is named following the names given to the Collection, - which in this example is a `Gaussian` (with name `gaussian) and - Exponential (with name `exponential`). - - The parameter values are again chosen by the non-linear search, - based on where it thinks the high likelihood regions of parameter - space are. The lines of Python code are commented out below to - prevent excessive print statements. - - - # print("Gaussian Instance:") - # print("Centre = ", instance.gaussian.centre) - # print("Normalization = ", instance.gaussian.normalization) - # print("Sigma = ", instance.gaussian.sigma) - - # print("Exponential Instance:") - # print("Centre = ", instance.exponential.centre) - # print("Normalization = ", instance.exponential.normalization) - # print("Rate = ", instance.exponential.rate) - """ - """ - Get the range of x-values the data is defined on, to evaluate - the model of the Gaussian. - """ - xvalues = np.arange(self.data.shape[0]) - - """ - Internally, the `instance` variable is a list of all model - omponents pass to the `Collection` above. - - we can therefore iterate over them and use their - `model_data_from` methods to create the - summed overall model data. - """ - model_data = sum( - [ - profile_1d.model_data_from(xvalues=xvalues) - for profile_1d in instance - ] - ) - - """ - Fit the model gaussian line data to the observed data, computing the residuals, chi-squared and log likelihood. - """ - residual_map = self.data - model_data - chi_squared_map = (residual_map / self.noise_map) ** 2.0 - chi_squared = sum(chi_squared_map) - noise_normalization = np.sum(np.log(2 * np.pi * noise_map**2.0)) - log_likelihood = -0.5 * (chi_squared + noise_normalization) - - return log_likelihood -``` - -We can now fit this model to the data using the same API we did before. - -```python -analysis = Analysis(data=data, noise_map=noise_map) - -search = af.DynestyStatic( - nlive=100, - number_of_cores=1, -) - -result = search.fit(model=model, analysis=analysis) -``` - -The `info` attribute shows the result in a readable format, showing that all 6 free parameters were fitted for. - -```python -print(result.info) -``` - -The output appears as follows: - -```bash -Bayesian Evidence 144.86032973 -Maximum Log Likelihood 181.14287034 -Maximum Log Posterior 181.14287034 - -model Collection (N=6) - gaussian Gaussian (N=3) - exponential Exponential (N=3) - -Maximum Log Likelihood Model: - -gaussian - centre 50.223 - normalization 26.108 - sigma 9.710 -exponential - centre 50.057 - normalization 39.948 - rate 0.048 - - -Summary (3.0 sigma limits): - -gaussian - centre 50.27 (49.63, 50.88) - normalization 26.22 (21.37, 32.41) - sigma 9.75 (9.25, 10.27) -exponential - centre 50.04 (49.60, 50.50) - normalization 40.06 (37.60, 42.38) - rate 0.05 (0.04, 0.05) - - -Summary (1.0 sigma limits): - -gaussian - centre 50.27 (50.08, 50.49) - normalization 26.22 (24.33, 28.39) - sigma 9.75 (9.60, 9.90) -exponential - centre 50.04 (49.90, 50.18) - normalization 40.06 (39.20, 40.88) - rate 0.05 (0.05, 0.05) -``` - -We can again use the max log likelihood instance to visualize the model data of the best fit model compared to the -data. - -```python -instance = result.max_log_likelihood_instance - -model_gaussian = instance.gaussian.model_data_from( - xvalues=np.arange(data.shape[0]) -) -model_exponential = instance.exponential.model_data_from( - xvalues=np.arange(data.shape[0]) -) -model_data = model_gaussian + model_exponential - -plt.errorbar( - x=xvalues, y=data, yerr=noise_map, color="k", ecolor="k", elinewidth=1, capsize=2 -) -plt.plot(range(data.shape[0]), model_data, color="r") -plt.plot(range(data.shape[0]), model_gaussian, "--") -plt.plot(range(data.shape[0]), model_exponential, "--") -plt.title("Dynesty model fit to 1D Gaussian + Exponential dataset.") -plt.xlabel("x values of profile") -plt.ylabel("Profile normalization") -plt.show() -plt.close() -``` - -The plot appears as follows: - -```{image} https://raw.githubusercontent.com/PyAutoLabs/PyAutoFit/main/docs/images/toy_model_fit.png -:alt: Alternative text -:width: 600 -``` diff --git a/docs/overview/natural_language.md b/docs/overview/natural_language.md new file mode 100644 index 000000000..4910d14b9 --- /dev/null +++ b/docs/overview/natural_language.md @@ -0,0 +1,286 @@ +# Inference with Natural Language + +> **Access requirements** +> +> The assistant runs through a coding agent such as Claude Code or OpenAI +> Codex. Sustained use normally needs a paid subscription or API billing; +> limited free access may be available. See the [assistant setup guide](https://github.com/PyAutoLabs/autofit_assistant#getting-started) +> for current options. PyAutoFit itself is open source. + +**PyAutoFit is a Python package for scientific model fitting and Bayesian +inference.** Bring your own model classes, data and likelihood code; +PyAutoFit provides priors, inference algorithms and tools for interpreting +and organising the results. It is domain agnostic: inference can sit around +your existing scientific software. + +We recommend getting started with [autofit_assistant](https://github.com/PyAutoLabs/autofit_assistant), which lets you +**perform scientific inference using natural language**. Describe the model +you want to fit, ask the assistant to run the analysis, and explore the +results through follow-up requests. PyAutoFit's named models, separate +likelihood, interchangeable searches and structured results make this +workflow well suited to AI agents. The examples below show why. + +An LLM can help write a fitting script. An agent with access to your project +can also run it, inspect the outputs and extend the analysis. You guide the +science; the assistant leaves the work as Python scripts you can inspect, +rerun and share. + +To begin instantly, follow the [assistant setup guide](https://github.com/PyAutoLabs/autofit_assistant#getting-started) and ask: + +> Fit the bundled dataset in dataset/gaussian_x1/ with a 1D Gaussian. +> Explain the model, priors, likelihood, search and results as we go. + +**Every step on this page can be requested in natural language—you do not +need to write Python to follow it.** The workflow is: +**model → priors → likelihood → search → results → scientific workflow**. + +If you do want to see how **PyAutoFit** works under the hood, [The Python API](https://pyautofit.readthedocs.io/en/latest/overview/python_api.html) explains PyAutoFit's +inner workings and Python API, including the model, Analysis, search and Result objects that the assistant +uses behind the scenes. + +## Contents + +- **Compose the Model**: Describe model components and assign priors to named parameters. +- **Define the Likelihood**: Specify how the model is compared with your data, or supply existing likelihood code. +- **Searches**: Choose between nested sampling, MCMC and optimisation. +- **Model Fit and Results**: Run a fit, inspect parameter estimates and uncertainties, and plot the fitted model. +- **Saving and Loading**: Save results and images during fitting, then reload completed runs for further analysis. +- **Scientific Workflows**: Compose more complex models, compare inference algorithms and investigate saved results. + +## Example + +We will fit a 1D Gaussian profile to noisy data and infer its centre, +normalization and width. The data points and their uncertainties are shown +below: + +![Noisy one-dimensional Gaussian data with error bars](https://raw.githubusercontent.com/PyAutoLabs/PyAutoFit/main/docs/images/data.png) + +For the assistant's bundled dataset, the profile is: + +$$ +g(x) = N \exp\left[-\frac{1}{2}\left(\frac{x-c}{\sigma}\right)^2\right] +$$ + +Here, $x$ is the coordinate, $c$ is the centre, $N$ is the normalization +(the peak amplitude in this example), and $\sigma$ is the width. Our task +is to infer $c$, $N$ and $\sigma$ from the data, together with their +uncertainties. + +## Compose the model + +> Create a 1D Gaussian model with free centre, normalization and sigma. +> Use uniform priors from 0 to 100 for centre, 0 to 100 for normalization, +> and 0.1 to 30 for sigma. Show me the model and its priors. + +This specifies a model with three free parameters: + +```bash +Total Free Parameters = 3 + +model Gaussian (N=3) + +centre UniformPrior [1], lower_limit = 0.0, upper_limit = 100.0 +normalization LogUniformPrior [2], lower_limit = 1e-06, upper_limit = 1000000.0 +sigma UniformPrior [3], lower_limit = 0.0, upper_limit = 25.0 +``` + +Models are highly customizable: you can ask to fix a parameter, +link parameters between components, or assert a constraint. For your own +science, simply ask the assistant to compose your model for you. + +**AI First Design: Internally, **PyAutoFit** composes the model with a name +(`Gaussian`), named parameters (`centre`, `normalization`, `sigma`) and +an expressive naming convention (e.g. `model.gaussian.sigma`) which ensure +the AI can easily map natural language descriptions of the model to changes in its +internal representation.** + +## Define the likelihood + +> Load the 1D Gaussian data and noise map, define a likelihood function which uses +> independent Gaussian errors to compare the model with the data and for a random +> set of parameters calculate the likelihood. Produce an image comparing the fit +> to the data + +The assistant sets up the likelihood function: which in this case evaluates the +Gaussian at each data point and compares the predictions with the measurements, +accounting for their uncertainties. As requested, you get an image comparing +the model and data. + +[Find 1D example of a random model to the data, maybe from HowToFit]? + +For your own project, you can instead ask: + +> Use my existing likelihood code for this analysis [point to code]. Connect +> it to PyAutoFit and check that it returns the same likelihood values at +> the same parameter values. + +**AI First Design: PyAutoFit gives the agent a small, testable integration task: connect +named model parameters to your existing likelihood and check that its numerical outputs are unchanged. +Your validated science code then becomes available to PyAutoFit's searches and result-analysis tools, +without the agent having to reimplement it.** + +You can also give the assistant papers and descriptions of your data, +parameters and assumptions. This supplies the scientific context so you can +use domain-specific natural language while keeping it separate from the inference code. + +## Choose a search + +> Show me the available searches. For this first fit, use Dynesty nested +> sampling with 100 live points to estimate the posterior and evidence. + +PyAutoFit supports several types of inference algorithm: + +- **Nested sampling:** Dynesty and Nautilus, for posterior inference and + Bayesian evidence estimation. +- **MCMC:** Emcee and Zeus, for posterior sampling. +- **Optimisation:** algorithms such as L-BFGS, for finding a best-fitting + solution. + +The assistant configures the requested search. You can ask it to explain +the settings or help choose an algorithm for your likelihood and scientific +goal. + +**AI First Design: All **PyAutoFit** searches share a common interface, +so the agent can switch between them while retaining the model and likelihood, +making it easy to compare inference across different searches.** + +## Fit and inspect the result + +> Run the model fit. Show the parameter estimates and uncertainties, and plot +> the maximum-likelihood Gaussian over the data. + +The assistant runs the search and presents a summary of the inferred +centre, normalization and width, together with their uncertainties and +a plot of the fitted profile. You can then explore the result: + +> Plot the posterior distributions. How well is sigma constrained, and +> is it correlated with normalization? + +**AI First Design: Results preserve the model's named +parameters (e.g. `result.instance.gaussian.sigma`), so the agent can connect +the scientific quantities you specify via language to the numerical results.** + +## Save and revisit the analysis + +> Save the run to disk, with fit and residual images updated during +> sampling. Afterwards, reload the saved samples and inspect the fit +> without rerunning it. + +Ask to save results and visualization for before starting the fit and the +assistant will ensure all results and output to hard-disk in a way **designed for efficient human inspection**. + +Saved runs retain the model, search settings and sample information, alongside the domain and model specific +visualization you request. At scale, results can also be collected into a database and queried by dataset metadata, +search, model or result properties. For example: + +> Find the completed Gaussian fits and make a table of the inferred widths +> and their uncertainties, labelled by dataset and search algorithm. + +**AI First Design: Structured, persistent outputs give +the agent a history of experiments it can reload, query and compare as +your analysis grows.** + +## Extend the workflow + +The same building blocks support more involved requests: + +**Fit three Gaussians** + +> Extend the model to three Gaussians and sum their profiles in the +> likelihood. Assert that their centres are in ascending order, show me +> the priors, perform inference with Dynesty again and compare the Bayesian +> evidence with the single-Gaussian fit. + +The assistant builds a model with three named components and reports +the Bayesian evidence comparison under the stated priors. + +**Compare inference algorithms** + +> Fit the same model using Emcee, Dynesty and an optimiser for maximum +> likelihood estimation. Keep the likelihood and parameter bounds fixed, +> and use the same priors for both samplers. Compare runtime, likelihood +> evaluations and best-fit values. For the samplers, also assess convergence +> and agreement of posterior constraints. + +This produces a comparison for your likelihood and computing environment, +making it easy to work out which inference method is fastest and which +ones successfully find the best-fit reliably. + +**Investigate a saved result** + +> Load the saved Gaussian fit. Report the median and 68% credible interval +> for sigma, plot its correlation with normalization, and inspect the +> residuals for structure the model may have missed. + +The assistant uses saved samples and the original data to reinspect an +already completed fit. + +## Scientific Context + +PyAutoFit is domain agnostic: **you bring the scientific context**. The assistant ships with a statistics wiki +covering Bayesian inference, priors, searches and model comparison. Its **literature wiki** at `wiki/literature/` +is yours to populate with the papers that define your field and analysis. + +Adding papers lets the assistant connect your natural language scientific descriptions to its inference: what +parameters mean, which assumptions are conventional, how previous studies approached the problem, and what might +complicate the interpretation of a result. + +To add a paper, simply ask: + +> Ingest this paper into the literature wiki: [arXiv ID, link or local PDF]. +> Summarise its model, likelihood, priors and main conclusions, and explain +> how it relates to the analysis we are developing. + +The wiki builds a lasting reference for your project, so scientific context is available alongside your code and +results. As you add relevant papers, the assistant can draw on them to frame decisions, cite prior work and identify +caveats worth investigating. + +## What Next? + +I now recommend you install the [autofit_assistant](https://github.com/PyAutoLabs/autofit_assistant), have it perform inference on a +topic within your scientific domain and experiment with what it can do. + +If you find you start doing larger more complex modeling tasks, you may quickly find you have more +results than you can manage and inspect. At this point, you should setup a **PyAutoFit** [Scientific Workflow](https://pyautofit.readthedocs.io/en/latest/overview/scientific_workflow.html), +with this page describing advanced tools that make inference scalable and the inspection of results fitting to +large datasets feasible. + +**PyAutoFit** also supports many advanced [Statistical Methods](https://pyautofit.readthedocs.io/en/latest/overview/statistical_methods.html) +not mentioned here. This includes hierarchical models to large dataset, building inference pipelines combining different searches by +chaining them together, and Bayesian model comparison. You can ask the assistant to describe each feature and then perform inference using the +same natural-language approach. + +## HowToFit + +For users less familiar with Bayesian inference and scientific analysis you may wish to read through +the **HowToFits** lectures. These teach you the basic principles of Bayesian inference, with the +content pitched at undergraduate level and above. + +The lectures are available in the [standalone HowToFit repository](https://github.com/PyAutoLabs/HowToFit). + +If you're new to statistical inference and are not totally sure what concepts like a model, likelihood or +sampling are, you can use **teacher mode** to have the assistant explain concepts in more detail. Simply +start a prompt with "Teacher mode." and ask questions: + +``` +Teacher mode. + +I'm new to PyAutoFit and want to learn the basic workflow end-to-end. Fit the +bundled 1D Gaussian dataset in dataset/gaussian_x1/ and recover its input +parameters. + +Explain what each step is doing and why as we go: composing the model, choosing +the priors, picking the non-linear search, and how to read the posterior. So I +come away understanding the workflow, not just the commands. +``` + +## The Python API + +Checking [The Python API](https://pyautofit.readthedocs.io/en/latest/overview/python_api.html) to see the actual underlying +**PyAutoFit** Python API which implements the inference performed through natural language above. + +The [autofit_workspace](https://github.com/PyAutoLabs/autofit_workspace) provides human readable, runnable examples +for everything **PyAutoFit**. These examples are the basis on which the [autofit_assistant](https://github.com/PyAutoLabs/autofit_assistant) is +trained, and what allows it to do complex inference tasks through natural language. +For you as a scientist, reading through these guides can help build understanding +of how inference actually works. diff --git a/docs/overview/the_basics.md b/docs/overview/python_api.md similarity index 97% rename from docs/overview/the_basics.md rename to docs/overview/python_api.md index aa74a27fc..c265ca576 100644 --- a/docs/overview/the_basics.md +++ b/docs/overview/python_api.md @@ -1,11 +1,13 @@ -(the-basics)= +(python-api)= -# The Basics +# The Python API -**PyAutoFit** is a Python based probabilistic programming language for model fitting and Bayesian inference -of large datasets. +This page is the under-the-hood companion to [Inference with Natural Language](https://pyautofit.readthedocs.io/en/latest/overview/natural_language.html): +it walks through the **PyAutoFit** Python API that an assistant writes for you, so you can read, run and +extend that code yourself. -The basic **PyAutoFit** API allows us a user to quickly compose a probabilistic model and fit it to data via a +**PyAutoFit** is a Python based probabilistic programming language for model fitting and Bayesian inference +of large datasets. The API lets a user quickly compose a probabilistic model and fit it to data via a log likelihood function, using a range of non-linear search algorithms (e.g. MCMC, nested sampling). This overview gives a run through of: @@ -633,7 +635,8 @@ a non-linear search, and interpret the results. The **PyAutoFit** API introduced here is highly extensible and customizable, making it adaptable to a wide range of model-fitting problems. -The next overview will delve into setting up a scientific workflow with **PyAutoFit**, utilizing its API to +The [Scientific Workflow](https://pyautofit.readthedocs.io/en/latest/overview/scientific_workflow.html) overview +delves into setting up a scientific workflow with **PyAutoFit**, utilizing this API to optimize model-fitting efficiency and scalability for large datasets. This approach ensures that detailed scientific interpretation of the results remains feasible and insightful. diff --git a/docs/sphinx_warning_baseline.txt b/docs/sphinx_warning_baseline.txt index e85087aff..64bb6b746 100644 --- a/docs/sphinx_warning_baseline.txt +++ b/docs/sphinx_warning_baseline.txt @@ -1 +1 @@ -31 +30