diff --git a/autofit/non_linear/fitness.py b/autofit/non_linear/fitness.py index 524619e96..2c4d2ed5c 100644 --- a/autofit/non_linear/fitness.py +++ b/autofit/non_linear/fitness.py @@ -675,7 +675,11 @@ def manage_quick_update(self, parameters, log_likelihood): from IPython.display import clear_output - clear_output(wait=True) + # Clearing a notebook cell removes the display_id target used by + # LiveDisplay.update_display, leaving later image updates invisible. + # Keep that target alive for both synchronous and background renders. + if not self.live_visual_update: + clear_output(wait=True) start_time = time.time() @@ -997,4 +1001,4 @@ def check_log_likelihood(self, fitness): Old Log Likelihood = {log_likelihood_old} New Log Likelihood = {log_likelihood_new} """ - ) \ No newline at end of file + ) diff --git a/docs/overview/scientific_workflow.md b/docs/overview/scientific_workflow.md index 7bc451898..2c7f3589f 100644 --- a/docs/overview/scientific_workflow.md +++ b/docs/overview/scientific_workflow.md @@ -2,607 +2,337 @@ # Scientific Workflow -A scientific workflow comprises the tasks you perform to conduct a scientific study. This includes fitting models to -datasets, interpreting the results, and gaining insights into your scientific problem. - -Different problems require different scientific workflows, depending on factors such as model complexity, dataset size, -and computational run times. For example, some problems involve fitting a single dataset with many models to gain -scientific insights, while others involve fitting thousands of datasets with a single model for large-scale studies. - -The **PyAutoFit** API is flexible, customizable, and extensible, enabling users to develop scientific workflows -tailored to their specific problems. - -This overview covers the key features of **PyAutoFit** that support the development of effective scientific workflows: - -- **On The Fly**: Display results immediately (e.g., in Jupyter notebooks) to provide instant feedback for adapting your workflow. -- **Hard Disk Output**: Output results to hard disk with high customization, allowing quick and detailed inspection of fits to many datasets. -- **Visualization**: Generate model-specific visualizations to create custom plots that streamline result inspection. -- **Loading Results**: Load results from the hard disk to inspect and interpret the outcomes of a model fit. -- **Result Customization**: Customize the returned results to simplify scientific interpretation. -- **Model Composition**: Extensible model composition makes it easy to fit many models with different parameterizations and assumptions. -- **Searches**: Support for various non-linear searches (e.g., nested sampling, MCMC), including gradient based fitting using JAX, to find the right method for your problem. -- **Configs**: Configuration files that set default model, fitting, and visualization behaviors, streamlining model fitting. -- **Database**: Store results in a relational SQLite3 database, enabling efficient management of large modeling results. -- **Scaling Up**: Guidance on scaling up your scientific workflow from small to large datasets. - -## On The Fly - -:::{note} -The on-the-fly feature described below is not implemented yet, we are working on it currently. -The best way to get on-the-fly output is to output to hard-disk, which is described in the next section. -This feature is fully implemented and provides on-the-fly output of results to hard-disk. -::: - -When a model fit is running, information about the fit is displayed at user-specified intervals. - -The frequency of this on-the-fly output is controlled by a search's `iterations_per_full_update` parameter, which -specifies how often this information is output. The example code below outputs on-the-fly information every 1000 iterations: - -```python -search = af.DynestyStatic( - iterations_per_full_update=1000 -) -``` - -In a Jupyter notebook, the default behavior is for this information to appear in the cell being run and to include: - -- Text displaying the maximum likelihood model inferred so far and related information. -- A visual showing how the search has sampled parameter space so far, providing intuition on how the search is performing. - -Here is an image of how this looks: - -!\[Example On-the-Fly Output\](path/to/image.png) - -The most valuable on-the-fly output is often specific to the model and dataset you are fitting. For instance, it -might be a `matplotlib` subplot showing the maximum likelihood model's fit to the dataset, complete with residuals -and other diagnostic information. - -The on-the-fly output can be fully customized by extending the `on_the_fly_output` method of the `Analysis` -class being used to fit the model. - -The example below shows how this is done for the simple case of fitting a 1D Gaussian profile: - -```python -class Analysis(af.Analysis): - def __init__(self, data: np.ndarray, noise_map: np.ndarray): - """ - Example Analysis class illustrating how to customize the on-the-fly output of a model-fit. - """ - super().__init__() - - self.data = data - self.noise_map = noise_map - - def on_the_fly_output(self, instance): - """ - During a model-fit, the `on_the_fly_output` method is called throughout the non-linear search. - - The `instance` passed into the method is maximum log likelihood solution obtained by the model-fit so far and it can be - used to provide on-the-fly output showing how the model-fit is going. - """ - xvalues = np.arange(analysis.data.shape[0]) - - model_data = instance.model_data_from(xvalues=xvalues) - - """ - The visualizer now outputs images of the best-fit results to hard-disk (checkout `visualizer.py`). - """ - import matplotlib.pyplot as plt - - plt.errorbar( - x=xvalues, - y=self.data, - yerr=self.noise_map, - color="k", - ecolor="k", - elinewidth=1, - capsize=2, - ) - plt.plot(xvalues, model_data, color="r") - plt.title("Maximum Likelihood Fit") - plt.xlabel("x value of profile") - plt.ylabel("Profile Normalization") - plt.show() # By using `plt.show()` the plot will be displayed in the Jupyter notebook. -``` - -Here's how the visuals appear in a Jupyter Notebook: - -!\[Example On-the-Fly Output\](path/to/image.png) - -In the early stages of setting up a scientific workflow, on-the-fly output is invaluable. It provides immediate -feedback on how your model fitting is performing, which is often crucial at the beginning of a project when things -might not be going well. It also encourages you to prioritize visualizing your fit and diagnosing whether the process -is working correctly. - -We highly recommend users starting a new model-fitting problem begin by setting up on-the-fly output! - ## Hard Disk Output -By default, a non-linear search does not save its results to the hard disk; the results can only be inspected in a Jupyter Notebook or Python script via the returned `result`. - -However, you can enable the output of non-linear search results to the hard disk by specifying the `name` and/or `path_prefix` attributes. These attributes determine how files are named and where results are saved on your hard disk. - -Benefits of saving results to the hard disk include: - -- More efficient inspection of results for multiple datasets compared to using a Jupyter Notebook. -- Results are saved on-the-fly, allowing you to check the progress of a fit midway. -- Additional information about a fit, such as visualizations, can be saved (see below). -- Unfinished runs can be resumed from where they left off if they are terminated. -- On high-performance supercomputers, results often need to be saved in this manner. - -Here's how to enable the output of results to the hard disk: - -```python -search = af.Emcee( - path_prefix=path.join("folder_0", "folder_1"), - name="my_search_name" -) -``` - -The screenshot below shows the output folder where all output is enabled: - -```{image} https://raw.githubusercontent.com/PyAutoLabs/PyAutoFit/main/docs/overview/image/output_example.png -:alt: Alternative text -:width: 400 +> Describe the contents of the output folder from our completed inference, +> explaining what each file and subfolder tells me. Add a domain-specific +> results summary in `science_summary.json`. + +After fitting a model, you need to inspect the result, understand how it was +obtained and decide what to try next. A scientific workflow connects these +steps across your study: perhaps many models for one dataset, or the same +models fitted to thousands of datasets. + +This guide continues the [Natural Language Inference](natural_language.md) +example. Every task can be requested through +[autofit_assistant](https://github.com/PyAutoLabs/autofit_assistant) in natural +language. We use a simple 1D Gaussian profile, but you supply the scientific +meaning of the models, data and derived quantities for your own project. +The [workspace example](https://github.com/PyAutoLabs/autofit_workspace/blob/main/scripts/overview/overview_2_scientific_workflow.py) +contains the corresponding runnable Python. + +Saving results to hard disk makes it possible to: + +- Inspect many fits without keeping their original notebook sessions open. +- Check intermediate results and images while inference is running. +- Revisit the model, priors, search settings and samples behind a conclusion. +- Resume an interrupted search when its saved search state supports resuming. +- Collect results from runs performed on another machine or a computing cluster. + +If your previous fit did not save output, first ask: + +> Configure this analysis to save its results under `output/scientific_workflow`, +> with readable labels for the dataset, model and search. Run the fit and show +> me its output location. + +PyAutoFit enables directory output when a search is given a name or path +prefix. Within the chosen location, an identifier derived from the model and +search configuration distinguishes runs. It is not a random folder name or a +substitute for labelling datasets: retain a dataset tag and record which data +were fitted. Reusing an existing run's identity can reload or resume it. + +At the top level of a run, `model.info` describes the model and its priors, +`model.results` summarizes parameter estimates, and `search.summary` records +search information such as runtime. The `image/` folder holds visualizations, +and `search_internal/` can hold the search's own state. The `files/` folder +contains structured information that both you and the assistant can read: + +| File | What it records | +| --- | --- | +| `model.json` | Named model components, parameters, priors and their relationships. | +| `search.json` | The search type and its saved configuration. | +| `samples_summary.json` | A compact summary of the inferred solution and available uncertainty estimates. | +| `samples.csv` | Sampled parameter values, log likelihoods, log priors and weights. | +| `samples_info.json` | Metadata needed to interpret and reload the samples. | +| `info.json` | Additional metadata supplied for the fit, such as dataset and model labels; present when supplied. | +| `covariance.csv` | A parameter covariance matrix, when available and enabled. | +| `science_summary.json` | The custom scientific summary requested above; added by your analysis. | + +The exact files depend on the search, output settings and how far the run has +progressed. They are not all JSON, and an incomplete run may not yet have a +final summary. + +For example, this excerpt from the workspace example's `model.json` records +the prior on the Gaussian's centre; the other parameters are omitted here: + +```json +{ + "type": "model", + "class_path": "autofit.example.model.Gaussian", + "arguments": { + "centre": { + "type": "Uniform", + "id": 3, + "lower_limit": 0.0, + "upper_limit": 100.0 + } + } +} ``` -Let's break down the output folder generated by **PyAutoFit**: +You can see what the parameter is called, which model it belongs to and what +values were allowed. This matters when two fits give different answers: +their saved models let you check whether the assumptions also changed. -- **Unique Identifier**: Results are saved in a folder named with a unique identifier composed of random characters. This identifier is automatically generated based on the specific model fit. For scientific workflows involving numerous model fits, this ensures that each fit is uniquely identified without requiring manual updates to output paths. -- **Info Files**: These files contain valuable information about the fit. For instance, `model.info` provides the complete model composition used in the fit, while `search.summary` details how long the search has been running and other relevant search-specific information. -- **Files Folder**: Within the output folder, the `files` directory contains detailed information saved as `.json` files. For example, `model.json` stores the model configuration used in the fit. This enables researchers to revisit the results later and review how the fit was performed. +For the Gaussian example, the custom summary can record the full width at +half maximum and residual statistics at the maximum-likelihood solution, +together with units and the dataset label. These are derived diagnostics; +posterior uncertainties require evaluating the derived quantity over the +samples. Ask for quantities that answer questions in your own science: -**PyAutoFit** offers extensive tools for customizing hard-disk output. This includes using configuration files to control what information is saved, which helps manage disk space utilization. Additionally, specific `.json` files tailored to different models can be utilized for more detailed output. +> Include the full width at half maximum and the residual root mean square +> in the saved summary. State their units and which fitted solution they +> describe, so I can compare them across datasets later. -For many scientific workflows, having detailed output for each fit is crucial for thorough inspection and accurate -interpretation of results. However, in scenarios where the volume of output data might overwhelm users or impede -scientific study, this feature can be easily disabled by omitting the `name` or `path prefix` when initiating the search. +Structured output is the foundation of a scientific workflow. Each fit +retains a readable record of its assumptions and results, so adding more +datasets does not mean losing track of what was fitted or how to interpret it. ## Visualization -When search hard-disk output is enabled in **PyAutoFit**, the visualization of model fits can also be saved directly -to disk. This capability is crucial for many scientific workflows as it allows for quick and effective assessment of -fit quality. - -To accomplish this, you can customize the `Visualizer` object of an `Analysis` class with a custom `Visualizer` class. -This custom class is responsible for generating and saving visual representations of the model fits. By leveraging -this approach, scientists can efficiently visualize and analyze the outcomes of model fitting processes. - -```python -class Visualizer(af.Visualizer): - - @staticmethod - def visualize_before_fit( - analysis, - paths: af.DirectoryPaths, - model: af.AbstractPriorModel - ): - """ - Before a model-fit, the `visualize_before_fit` method is called to perform visualization. - - The function receives as input an instance of the `Analysis` class which is being used to perform the fit, - which is used to perform the visualization (e.g. it contains the data and noise map which are plotted). - - This can output visualization of quantities which do not change during the model-fit, for example the - data and noise-map. - - The `paths` object contains the path to the folder where the visualization should be output, which is determined - by the non-linear search `name` and other inputs. - """ - - import matplotlib.pyplot as plt - - xvalues = np.arange(self.data.shape[0]) - - plt.errorbar( - x=xvalues, - y=analysis.data, - yerr=analysis.noise_map, - color="k", - ecolor="k", - elinewidth=1, - capsize=2, - ) - plt.title("Maximum Likelihood Fit") - plt.xlabel("x value of profile") - plt.ylabel("Profile Normalization") - plt.savefig(path.join(paths.image_path, f"data.png")) - plt.clf() - - @staticmethod - def visualize( - analysis, - paths: af.DirectoryPaths, - instance, - during_analysis - ): - """ - During a model-fit, the `visualize` method is called throughout the non-linear search. - - The function receives as input an instance of the `Analysis` class which is being used to perform the fit, - which is used to perform the visualization (e.g. it generates the model data which is plotted). - - The `instance` passed into the visualize method is maximum log likelihood solution obtained by the model-fit - so far and it can be used to provide on-the-fly images showing how the model-fit is going. - - The `paths` object contains the path to the folder where the visualization should be output, which is determined - by the non-linear search `name` and other inputs. - """ - xvalues = np.arange(analysis.data.shape[0]) - - model_data = instance.model_data_from(xvalues=xvalues) - residual_map = analysis.data - model_data - - """ - The visualizer now outputs images of the best-fit results to hard-disk (checkout `visualizer.py`). - """ - import matplotlib.pyplot as plt - - plt.errorbar( - x=xvalues, - y=analysis.data, - yerr=analysis.noise_map, - color="k", - ecolor="k", - elinewidth=1, - capsize=2, - ) - plt.plot(xvalues, model_data, color="r") - plt.title("Maximum Likelihood Fit") - plt.xlabel("x value of profile") - plt.ylabel("Profile Normalization") - plt.savefig(path.join(paths.image_path, f"model_fit.png")) - plt.clf() - - plt.errorbar( - x=xvalues, - y=residual_map, - yerr=analysis.noise_map, - color="k", - ecolor="k", - elinewidth=1, - capsize=2, - ) - plt.title("Residuals of Maximum Likelihood Fit") - plt.xlabel("x value of profile") - plt.ylabel("Residual") - plt.savefig(path.join(paths.image_path, f"model_fit.png")) - plt.clf() -``` - -The `Analysis` class is defined following the same API as before, but now with its `Visualizer` class attribute -overwritten with the `Visualizer` class above. - -```python -class Analysis(af.Analysis): +> Before inference, save a plot of the data with its uncertainties, so I can +> check the dataset that will be fitted. - """ - This over-write means the `Visualizer` class is used for visualization throughout the model-fit. +> During inference, update separate plots of the best-fitting profile over +> the data and its residuals. Keep the data plot alongside them and save the +> final versions when inference finishes. - This `VisualizerExample` object is in the `autofit.example.visualize` module and is used to customize the - plots output during the model-fit. +You can specify visualization before fitting separately from visualization +during fitting. The first shows quantities that do not change, such as the +measurements and noise map. The second uses the best solution found so far, +so you can follow the model as the search explores parameter space. - It has been extended with visualize methods that output visuals specific to the fitting of `1D` data. - """ - Visualizer = Visualizer +In the workspace example these images are `data.png`, `model_fit.png` and +`residuals.png`. Separate filenames preserve both the fit and its residuals. +For convenient inspection, ask for a combined view too: - def __init__(self, data, noise_map): - """ - An Analysis class which illustrates visualization. - """ - super().__init__() +> Also save a two-panel figure with the model fit above its residuals, using +> the same horizontal scale. Use this figure for live updates as well. - self.data = data - self.noise_map = noise_map +This produces `fit.png`, the shared figure used by the live display in the +next section. In your own workflow, choose plots that reveal scientifically +meaningful shortcomings: a good-looking best fit can still leave systematic +structure in the residuals. Search-specific posterior plots provide another +view of how well parameters are constrained. - def log_likelihood_function(self, instance): - """ - The `log_likelihood_function` is identical to the example above - """ - xvalues = np.arange(self.data.shape[0]) - - model_data = instance.model_data_from(xvalues=xvalues) - residual_map = self.data - model_data - chi_squared_map = (residual_map / self.noise_map) ** 2.0 - chi_squared = 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 -``` +## On The Fly -Visualization of the results of the non-linear search, for example the "Probability Density -Function", are also automatically output during the model-fit on the fly. +> While inference runs, refresh the combined model-fit and residual figure +> in my notebook and report the best parameters found so far. Start with an +> update every 500 likelihood evaluations, and explain what the updates +> suggest about the search's progress. + +Live output connects the visualization you have just chosen to the running +inference. In a notebook, the fit figure updates in place. When running a +Python script on a desktop, live visual updates can instead use a separate +viewer. The saved images remain available for inspection on disk. + +Quick updates show the best solution encountered so far without waiting for +a full update of the search's samples and posterior products. Their cadence +is measured in likelihood evaluations; full search updates have their own +cadence. The workspace example explicitly enables quick updates and live +visualization, and uses the same plotting routine for the live figure and +the saved fit image. + +> Keep the live updates frequent while I develop the analysis. If plotting +> becomes expensive, reduce their frequency while retaining periodic saved +> output. For a cluster run, save the images without opening a viewer. + +This feedback helps build intuition about inference: is the model finding +the signal, do the residuals retain structure, and is the search making +progress? A slowly changing image may motivate checking priors, the +likelihood or the search settings. A stable best-fit image alone does not +establish convergence or show that the posterior has been fully explored. ## Loading Results -In your scientific workflow, you'll likely conduct numerous model fits, each generating outputs stored in individual -folders on your hard disk. +> Reload the saved fits under `output/scientific_workflow` without rerunning +> inference. Make a table of the Gaussian widths and their 68% credible +> intervals, labelled by dataset, model and search, and include each run's +> output path. -To efficiently work with these results in Python scripts or Jupyter notebooks, **PyAutoFit** provides -the `aggregator` API. This tool simplifies the process of loading results from hard disk into Python variables. -By pointing the aggregator at the folder containing your results, it automatically loads all relevant information -from each model fit. +PyAutoFit's aggregator loads results from a collection of output folders. +The assistant can inspect saved models and samples, calculate summaries and +return to particular runs. Results are loaded lazily, so processing a large +collection does not require holding every sample from every fit in memory +at once. -This capability streamlines the workflow by enabling easy manipulation and inspection of model-fit results directly -within your Python environment. It's particularly useful for managing and analyzing large-scale studies where -handling multiple model fits and their associated outputs is essential. +> Open the fit with the widest uncertainty on sigma. Show its posterior and +> saved residual plot, and explain what might account for the uncertainty. -```python -from autofit.aggregator.aggregator import Aggregator - -agg = Aggregator.from_directory( - directory=path.join("result_folder"), -) -``` - -The `values` method is used to specify the information that is loaded from the hard-disk, for example the -`samples` of the model-fit. - -The for loop below iterates over all results in the folder passed to the aggregator above. - -```python -for samples in agg.values("samples"): - print(samples.parameter_lists[0]) -``` - -Result loading uses Python generators to ensure that memory use is minimized, meaning that even when loading -thousands of results from hard-disk the memory use of your machine is not exceeded. - -The [result cookbook](https://pyautofit.readthedocs.io/en/latest/cookbooks/model.html) gives a full run-through of -the tools that allow results to be loaded and inspected. +This turns a table entry into an inspectable scientific result. Retain the +original data and analysis code as well as the saved outputs if you want to +compute new model predictions or plots later. See the +[result cookbook](../cookbooks/result.md) for more ways to inspect a result. ## Result Customization -The `Result` object is returned by a non-linear search after running the following code: +> Make the best-fitting profile, residuals and full width at half maximum +> directly accessible from the result. Use those same quantities in the +> scientific summary saved for each fit. -```python -result = search.fit(model=model, analysis=analysis) -``` +A useful result should expose the quantities you need to interpret your +science. For this example, that means the fitted 1D profile and its width; +another project might require an integrated signal or a derived physical +quantity. The workspace example shows how to extend a result while keeping +access to the model, samples and analysis. -An effective scientific workflow ensures that this object contains all information a user needs to quickly inspect -the quality of a model-fit and undertake scientific interpretation. +> Calculate the posterior median and 68% credible interval of the full width +> at half maximum from the saved samples. Distinguish this uncertainty from +> the width evaluated at the maximum-likelihood solution. -The result can be can be customized to include additional information about the model-fit that is specific to your -model-fitting problem. - -For example, for fitting 1D profiles, the `Result` could include the maximum log likelihood model 1D data: - -```python -print(result.max_log_likelihood_model_data_1d) -``` - -To do this we use the custom result API, where we first define a custom `Result` class which includes the -property `max_log_likelihood_model_data_1d`: - -```python -class ResultExample(af.Result): - - @property - def max_log_likelihood_model_data_1d(self) -> np.ndarray: - """ - Returns the maximum log likelihood model's 1D model data. - - This is an example of how we can pass the `Analysis` class a custom `Result` object and extend this result - object with new properties that are specific to the model-fit we are performing. - """ - xvalues = np.arange(self.analysis.data.shape[0]) - - return self.instance.model_data_from(xvalues=xvalues) -``` - -The custom result has access to the analysis class, meaning that we can use any of its methods or properties to -compute custom result properties. - -To make it so that the `ResultExample` object above is returned by the search we overwrite the `Result` class attribute -of the `Analysis` and define a `make_result` object describing what we want it to contain: - -```python -class Analysis(af.Analysis): - - """ - This overwrite means the `ResultExample` class is returned after the model-fit. - """ - Result = ResultExample - - def __init__(self, data, noise_map): - """ - An Analysis class which illustrates custom results. - """ - super().__init__() - - self.data = data - self.noise_map = noise_map - - def log_likelihood_function(self, instance): - """ - The `log_likelihood_function` is identical to the example above - """ - xvalues = np.arange(self.data.shape[0]) - - model_data = instance.model_data_from(xvalues=xvalues) - residual_map = self.data - model_data - chi_squared_map = (residual_map / self.noise_map) ** 2.0 - chi_squared = 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 - - def make_result( - self, - samples_summary: af.SamplesSummary, - paths: af.AbstractPaths, - samples: Optional[af.SamplesPDF] = None, - search_internal: Optional[object] = None, - analysis: Optional[object] = None, - ) -> Result: - """ - Returns the `Result` of the non-linear search after it is completed. - - The result type is defined as a class variable in the `Analysis` class (see top of code under the python code - `class Analysis(af.Analysis)`. - - The result can be manually overwritten by a user to return a user-defined result object, which can be extended - with additional methods and attribute specific to the model-fit. - - This example class does example this, whereby the analysis result has been overwritten with the `ResultExample` - class, which contains a property `max_log_likelihood_model_data_1d` that returns the model data of the - best-fit model. This API means you can customize your result object to include whatever attributes you want - and therefore make a result object specific to your model-fit and model-fitting problem. - - The `Result` object you return can be customized to include: - - - The samples summary, which contains the maximum log likelihood instance and median PDF model. - - - The paths of the search, which are used for loading the samples and search internal below when a search - is resumed. - - - The samples of the non-linear search (e.g. MCMC chains) also stored in `samples.csv`. - - - The non-linear search used for the fit in its internal representation, which is used for resuming a search - and making bespoke visualization using the search's internal results. - - - The analysis used to fit the model (default disabled to save memory, but option may be useful for certain - projects). - - Parameters - ---------- - samples_summary - The summary of the samples of the non-linear search, which include the maximum log likelihood instance and - median PDF model. - paths - An object describing the paths for saving data (e.g. hard-disk directories or entries in sqlite database). - samples - The samples of the non-linear search, for example the chains of an MCMC run. - search_internal - The internal representation of the non-linear search used to perform the model-fit. - analysis - The analysis used to fit the model. - - Returns - ------- - Result - The result of the non-linear search, which is defined as a class variable in the `Analysis` class. - """ - return self.Result( - samples_summary=samples_summary, - paths=paths, - samples=samples, - search_internal=search_internal, - analysis=self - ) -``` - -Result customization has full support for **latent variables**, which are parameters that are not sampled by the non-linear -search but are computed from the sampled parameters. - -They are often integral to assessing and interpreting the results of a model-fit, as they present information -on the model in a different way to the sampled parameters. - -The [result cookbook](https://pyautofit.readthedocs.io/en/latest/cookbooks/result.html) gives a full run-through of -all the different ways the result can be customized. +Derived quantities, also called latent variables, need not be sampled +parameters themselves. Computing them from posterior samples lets you +propagate parameter uncertainty into quantities that matter for your study. +The [result cookbook](../cookbooks/result.md) develops these customizations. ## Model Composition -In many scientific workflows, there's often a need to construct and fit a variety of different models. This -could range from making minor adjustments to a model's parameters to handling complex models with thousands of parameters and multiple components. - -For simpler scenarios, adjustments might include: - -- **Parameter Assignment**: Setting specific values for certain parameters or linking parameters together so they share the same value. -- **Parameter Assertions**: Imposing constraints on model parameters, such as requiring one parameter to be greater than another. -- **Model Arithmetic**: Defining relationships between parameters using arithmetic operations, such as defining a linear relationship like `y = mx + c`, where `m` and `c` are model parameters. +> Fit this dataset with a Gaussian whose width is free, then with its width +> fixed to an independently measured value of 10 in the same coordinate +> units. Show the priors and save each model under a readable label. -In more intricate cases, models might involve numerous parameters and complex compositions of multiple model components. +Model composition is introduced in [Natural Language Inference](natural_language.md) +and developed in the [model cookbook](../cookbooks/model.md). Here, its role +is to make competing scientific assumptions explicit and comparable: one +component or two, a fixed parameter or a free one, shared parameters or +independent ones. -**PyAutoFit** offers a sophisticated model composition API designed to handle these complexities. It provides -tools for constructing elaborate models using lists of Python classes, NumPy arrays and hierarchical structures of Python classes. +> Compare the saved free-width and fixed-width fits to this same dataset. +> Show residuals, parameter constraints and Bayesian evidence where +> available. Explain how the priors affect the comparison, and link to the +> saved model definitions. -For a detailed exploration of these capabilities, you can refer to -the [model cookbook](https://pyautofit.readthedocs.io/en/latest/cookbooks/model.html), which provides comprehensive -guidance on using the model composition API. This resource covers everything from basic parameter assignments to -constructing complex models with hierarchical structures. +The workflow must make many models feasible to interpret as well as feasible +to fit. Named components, consistent diagnostics and saved assumptions let +you work out what changed and whether the additional complexity is useful. +Keep model comparisons within the same dataset and likelihood convention; +evidence values from different datasets are not a ranking of model quality. ## Searches -Different model-fitting problems often require different approaches to fitting the model effectively. +> Fit the same model with Nautilus and Dynesty, keeping the data, likelihood +> and priors fixed. Compare runtime, likelihood evaluations, parameter +> constraints and the searches' available convergence diagnostics. -The choice of the most suitable search method depends on several factors: +Model dimension, parameter correlations and likelihood cost all affect +which search works well. Trying more than one method early helps establish +whether results are reliable and how expensive the wider study will be. +Give each search its own saved location so both outcomes remain available. -- **Model Dimensions**: How many parameters constitute the model and its non-linear parameter space? -- **Model Complexity**: Different models exhibit varying degrees of parameter degeneracy, which necessitates different non-linear search techniques. -- **Run Times**: How efficiently can the likelihood function be evaluated and the model-fit performed? -- **Gradients**: If your likelihood function is differentiable, leveraging JAX and using a search that exploits gradient information can be advantageous. +> Compare these posterior constraints with an Emcee run, and the best-fit +> values with an optimizer. Report Bayesian evidence only for searches +> that estimate it, and flag runs whose sampling is insufficient. -**PyAutoFit** provides support for a wide range of non-linear searches, ensuring that users can select the method -best suited to their specific problem. - -During the initial stages of setting up your scientific workflow, it's beneficial to experiment with different -searches. This process helps identify which methods reliably infer maximum likelihood fits to the data and assess -their efficiency in terms of computational time. - -For a comprehensive exploration of available search methods and customization options, refer to -the [search cookbook](https://pyautofit.readthedocs.io/en/latest/cookbooks/search.html). This resource covers -detailed guides on all non-linear searches supported by PyAutoFit and provides insights into how to tailor them to your needs. - -:::{note} -There are currently no documentation guiding reads on what search might be appropriate for their problem and how to -profile and experiment with different methods. Writing such documentation is on the to do list and will appear -in the future. However, you can make progress now simply using visuals output by PyAutoFit and the search.summary\` file. -::: +Agreement in best-fit parameters does not imply agreement in posterior +uncertainties. Similarly, a fast unfinished run is not evidence that an +algorithm is more efficient. If your likelihood supports differentiation, +gradient-based searches offer further possibilities. See the +[search cookbook](../cookbooks/search.md) for the available interfaces. ## Configs -As you refine your scientific workflow, you'll often find yourself repeatedly setting up models with identical priors -and using the same non-linear search configurations. This repetition can result in lengthy Python scripts with -redundant inputs. - -To streamline this process, configuration files can be utilized to define default values. This approach eliminates -the need to specify identical prior inputs and search settings in every script, leading to more concise and -readable Python code. Moreover, it reduces the cognitive load associated with performing model-fitting tasks. +> Put the shared priors and search settings for this study into configuration +> files. Show the defaults and any per-fit overrides, and preserve the +> effective model and search settings with each saved result. -For a comprehensive guide on setting up and utilizing configuration files effectively, refer -to the [configs cookbook](https://pyautofit.readthedocs.io/en/latest/cookbooks/configs.html). This resource provides -detailed instructions on configuring and optimizing your PyAutoFit workflow through the use of configuration files. +As the study grows, consistent defaults reduce repeated setup and make +intentional differences easier to see. Configuration files can also control +output and update frequency. A later configuration change should not erase +your record of the settings used for a previous inference. The +[configs cookbook](../cookbooks/configs.md) explains how to organize them. ## Database -By default, model-fitting results are written to folders on hard-disk, which is straightforward for navigating and -manual inspection. However, this approach becomes impractical for large datasets or extensive scientific workflows, -where manually checking each result can be time-consuming. +> Collect the saved runs into a SQLite database. Select the completed +> free-width Gaussian fits and make a table of their widths and uncertainties, +> retaining dataset, model and search labels. -To address this challenge, all results can be stored in an sqlite3 relational database. This enables loading results -directly into Jupyter notebooks or Python scripts for inspection, analysis, and interpretation. The database -supports advanced querying capabilities, allowing users to retrieve specific model-fits based on criteria such -as the fitted model or dataset. +Folders remain useful for direct inspection. A database adds a way to query +a large collection by model, metadata or result properties, then load only +the results needed for a comparison. You can build it from existing output +folders, so the first exploratory fits can become part of the larger study. -For a comprehensive guide on using the database functionality within PyAutoFit, refer to -the `database cookbook `. This resource -provides detailed instructions on leveraging the database to manage and analyze model-fitting results efficiently. +> Find runs with missing summaries or unusually large residuals. Show the +> relevant output paths and explain which need further inspection. -## Scaling Up - -Regardless of your final scientific objective, it's crucial to consider scalability in your scientific workflow and -ensure it remains flexible to accommodate varying scales of complexity. +The [multiple datasets cookbook](../cookbooks/multiple_datasets.md) describes +collecting and querying results at this scale. -Initially, scientific studies often begin with a small number of datasets (e.g., tens of datasets). During this phase, -researchers iteratively refine their models and gain insights through trial and error. This involves fitting numerous -models to datasets and manually inspecting results to evaluate model performance. A flexible workflow is essential -here, allowing rapid iteration and outputting results in a format that facilitates quick inspection and interpretation. +## Scaling Up -As the study progresses, researchers may scale up to larger datasets (e.g., thousands of datasets). Manual inspection -of individual results becomes impractical, necessitating a more automated approach to model fitting and interpretation. -Additionally, analyses may transition to high-performance computing environments, requiring output formats suitable for these setups. +> Set up a study of five datasets, fitting each with free-width and fixed-width +> Gaussian models using Nautilus and Dynesty. Organize the output by dataset, model +> and search, and retain the same scientific summaries and diagnostic plots +> for every run. + +The following is an **illustrative directory layout**, not a claim that this +page has performed twenty fits. Each search folder contains its run's +identifier directory; one run is expanded to show what you can inspect. + +```text +output/scientific_workflow/ +├── dataset_01/ +│ ├── gaussian_free_width/ +│ │ ├── nautilus// +│ │ │ ├── model.info +│ │ │ ├── model.results +│ │ │ ├── search.summary +│ │ │ ├── files/ +│ │ │ │ ├── model.json +│ │ │ │ ├── search.json +│ │ │ │ ├── samples.csv +│ │ │ │ ├── samples_info.json +│ │ │ │ ├── samples_summary.json +│ │ │ │ ├── info.json +│ │ │ │ └── science_summary.json +│ │ │ └── image/ +│ │ │ ├── data.png +│ │ │ ├── model_fit.png +│ │ │ ├── residuals.png +│ │ │ └── fit.png +│ │ └── dynesty// +│ └── gaussian_fixed_width/ +│ ├── nautilus// +│ └── dynesty// +├── dataset_02/ +│ ├── gaussian_free_width/ (nautilus and dynesty runs) +│ └── gaussian_fixed_width/ (nautilus and dynesty runs) +├── dataset_03/ +│ ├── gaussian_free_width/ (nautilus and dynesty runs) +│ └── gaussian_fixed_width/ (nautilus and dynesty runs) +├── dataset_04/ +│ ├── gaussian_free_width/ (nautilus and dynesty runs) +│ └── gaussian_fixed_width/ (nautilus and dynesty runs) +└── dataset_05/ + ├── gaussian_free_width/ (nautilus and dynesty runs) + └── gaussian_fixed_width/ (nautilus and dynesty runs) +``` -**PyAutoFit** is designed to enable the development of effective scientific workflows for both small and large datasets. +You can browse a particular run on disk, open its plots and read its model. +Or you can ask about the collection: -## Wrap Up +> Inspect all five datasets and compare the models and searches fitted to +> each. Summarize parameter constraints, fit quality and runtime, compare +> Bayesian evidence where available, and link each assessment to its saved +> output. Flag incomplete runs and results that need closer inspection. -This overview has provided a comprehensive guide to the key features of **PyAutoFit** that support the development of -effective scientific workflows. By leveraging these tools, researchers can tailor their workflows to specific problems, -streamline model fitting, and gain valuable insights into their scientific studies. +This is the purpose of a scientific workflow: as the number of experiments +grows, you can still trace a conclusion to its data, assumptions and results. +The same organization supports early experimentation with a handful of fits +and later studies where manual inspection of every run is impractical. -The final aspect of core functionality, described in the next overview, is the wide variety of statistical -inference methods available in **PyAutoFit**. These methods include graphical models, hierarchical models, -Bayesian model comparison and many more. +Continue with [Statistical Methods](statistical_methods.md) for hierarchical +models, search chaining and other ways to extend your inference. To see how +the workflow above is implemented, open the +[runnable workspace overview](https://github.com/PyAutoLabs/autofit_workspace/blob/main/scripts/overview/overview_2_scientific_workflow.py). diff --git a/test_autofit/non_linear/test_quick_update_invalid_instance.py b/test_autofit/non_linear/test_quick_update_invalid_instance.py index 533f218ad..09011a618 100644 --- a/test_autofit/non_linear/test_quick_update_invalid_instance.py +++ b/test_autofit/non_linear/test_quick_update_invalid_instance.py @@ -134,6 +134,23 @@ def test__a_valid_max_lh_instance_still_renders_the_visual(caplog): assert len(fitness.paths.results) == 1 +@pytest.mark.parametrize("live_visual_update", [False, True]) +def test__quick_updates_preserve_the_live_notebook_display(monkeypatch, live_visual_update): + cleared = [] + monkeypatch.setattr("IPython.display.clear_output", lambda **kwargs: cleared.append(kwargs)) + fitness = _fitness(RecordingAnalysis()) + fitness.live_visual_update = live_visual_update + + for likelihood in [-10.0, -9.0]: + fitness.manage_quick_update( + parameters=[50.0, 25.0, 10.0], log_likelihood=likelihood + ) + + # Text-only updates can clear their old output. Live updates must retain + # the image's display_id target across subsequent likelihood evaluations. + assert len(cleared) == (0 if live_visual_update else 2) + + def test__a_visual_that_raises_is_swallowed_like_the_background_worker_does(caplog): # The background quick-update worker already swallows `Exception` around the # render (`BackgroundQuickUpdate._process_pending`). The synchronous path