From 46a1efd062078207d7744111ec93e840ba8b90f2 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Mon, 2 Nov 2026 11:05:23 +0000 Subject: [PATCH] docs: results library feature guide (declare, index, check, enrich) Refs PyAutoLabs/PyAutoFit#1752 Co-Authored-By: Claude Opus 5.5 --- llms-full.txt | 2 + notebooks/features/README.md | 1 + notebooks/features/results_library.ipynb | 291 +++++++++++++++++++++++ scripts/features/README.md | 1 + scripts/features/results_library.py | 147 ++++++++++++ workspace_index.json | 15 ++ 6 files changed, 457 insertions(+) create mode 100644 notebooks/features/results_library.ipynb create mode 100644 scripts/features/results_library.py diff --git a/llms-full.txt b/llms-full.txt index 9079140d..98878f8c 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -40,6 +40,8 @@ AUTO-GENERATED by PyAutoHands — do not edit by hand; regenerate with generate. - Contents: Example Source Code (`af.ex`), Dataset, Fit, Interpolation, Serialization, Database - [Feature: Model Comparison](scripts/features/model_comparison.py): Common questions when fitting a model to data are: what model should I use? How many parameters should the model have? Is the model too complex or too simple? - Contents: Metrics, Example Source Code (`af.ex`), Data, Model x1 Gaussian, Model x2 Gaussian, Model x3 Gaussian, Wrap Up +- [Feature: Results Library](scripts/features/results_library.py): When you fit many datasets — hundreds of objects on a cluster, say — the hard question at the end is not "what are the results?" but "which results are *missing*?". A fit that crashed, ran out of time, or completed without a product you need leaves no error behind: it is simply not there, and a catalogue built from the output quietly loses it. + - Contents: Fits, Index, Declare, Check, Enrich, Command Line - [Feature: Search Chaining](scripts/features/search_chaining.py): To perform a model-fit, we typically compose one model and fit it to our data using one non-linear search. - Contents: Example Source Code (`af.ex`), Data, Analysis, Model, Search 1, Result 1, Search 2, Model, Result 2, Search 3, Prior Passing, EXAMPLE, Prerequisites, Overview, Model-Fit, Instance & Model, Component Specification, Take Attributes, As Model - [Feature: Search Grid Search](scripts/features/search_grid_search.py): A classic method to perform model-fitting is a grid search, where the parameters of a model are divided on to a grid of values and the likelihood of each set of parameters on this grid is sampled. For low dimensionality problems this simple approach can be sufficient to locate high likelihood solutions, however it scales poorly to higher dimensional problems. diff --git a/notebooks/features/README.md b/notebooks/features/README.md index acdd86fa..0e1c023f 100644 --- a/notebooks/features/README.md +++ b/notebooks/features/README.md @@ -6,6 +6,7 @@ The `features` folder contains example scripts for using advanced **PyAutoFit** - `shared_analysis_state.py`: Share per-evaluation model state across the factors of a graphical model so identical work is computed once, not once per factor. - `interpolate.py`: Fit datasets which smoothly vary as a function of a continuous parameter (e.g. time) and interpolate between them. - `model_comparison.py`: Perform Bayesian model comparison between different models to determine which the data favours. +- `results_library.py`: Declare the results a set of fits should produce, list every one that is missing (and why), and add new products to finished results. - `search_chaining.py`: Chaining together multiple non-linear searches to automate the fitting of a complex model. - `search_grid_search.py`: Perform a massively parallel grid search of non-linear searches. - `sensitivity_mapping.py`: Determine how sensitive a dataset is to a model's complexity. diff --git a/notebooks/features/results_library.ipynb b/notebooks/features/results_library.ipynb new file mode 100644 index 00000000..49380f18 --- /dev/null +++ b/notebooks/features/results_library.ipynb @@ -0,0 +1,291 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Feature: Results Library\n", + "========================\n", + "\n", + "When you fit many datasets \u2014 hundreds of objects on a cluster, say \u2014 the hard question at the end is not \"what are\n", + "the results?\" but \"which results are *missing*?\". A fit that crashed, ran out of time, or completed without a product\n", + "you need leaves no error behind: it is simply not there, and a catalogue built from the output quietly loses it.\n", + "\n", + "The results library answers that question. You declare which results you expect (datasets \u00d7 searches, and which\n", + "products each must hold), and **PyAutoFit** compares that declaration with what is on disk, giving every gap a reason.\n", + "It can then add a new product to results that already exist, without rerunning any fit.\n", + "\n", + "__Contents__\n", + "\n", + "This script is split into the following sections:\n", + "\n", + "- **Fits**: Fit a few datasets, outputting the results to hard-disk.\n", + "- **Index**: Build an index of every result on disk.\n", + "- **Declare**: Declare which results the library is expected to hold.\n", + "- **Check**: Compare the declaration with the index and list every gap.\n", + "- **Enrich**: Add a new product to every completed result.\n", + "- **Command Line**: The same steps from the shell, e.g. on a cluster." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Google Colab Setup__\n", + "\n", + "Set up Google Colab as in [the introductory notebook](https://github.com/PyAutoLabs/autofit_workspace/blob/main/notebooks/overview/overview_1_the_basics.ipynb).\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "cellView": "form", + "jupyter": { + "source_hidden": true + } + }, + "outputs": [], + "source": [ + "# @title Set up Google Colab { display-mode: \"form\" }\n", + "try:\n", + " import google.colab\n", + "except ImportError:\n", + " from autofit import setup_colab as _setup_colab\n", + "else:\n", + " import importlib\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.check_call(\n", + " [sys.executable, \"-m\", \"pip\", \"install\", \"autonerves\", \"--no-deps\"]\n", + " )\n", + " _setup_colab = importlib.import_module(\"autonerves.setup_colab\")\n", + "\n", + "_setup_colab.setup(\"autofit\")" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from autofit import setup_notebook; setup_notebook()\n", + "\n", + "from os import path\n", + "from pathlib import Path\n", + "\n", + "import autofit as af\n", + "from autofit.aggregator import Aggregator\n", + "from autofit.results import ResultsIndex" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Fits__\n", + "\n", + "We fit two of the three `gaussian_x1` datasets, each written to hard-disk with its dataset name as `unique_tag`. The\n", + "third dataset is deliberately not fitted, so the library has a hole to find." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "results_path = af.with_test_mode_segment(Path(\"output\")) / \"features\" / \"results_library\"\n", + "\n", + "model = af.Collection(gaussian=af.ex.Gaussian)\n", + "\n", + "for dataset_name in [\"gaussian_x1_0\", \"gaussian_x1_1\"]:\n", + " dataset_path = path.join(\"dataset\", \"example_1d\", dataset_name)\n", + "\n", + " if not path.exists(dataset_path):\n", + " import subprocess\n", + " import sys\n", + "\n", + " subprocess.run(\n", + " [sys.executable, \"scripts/simulators/simulators.py\"],\n", + " check=True,\n", + " )\n", + "\n", + " data = af.util.numpy_array_from_json(file_path=path.join(dataset_path, \"data.json\"))\n", + " noise_map = af.util.numpy_array_from_json(\n", + " file_path=path.join(dataset_path, \"noise_map.json\")\n", + " )\n", + "\n", + " search = af.DynestyStatic(\n", + " name=\"fit\",\n", + " path_prefix=path.join(\"features\", \"results_library\"),\n", + " unique_tag=dataset_name,\n", + " nlive=50,\n", + " )\n", + " search.fit(model=model, analysis=af.ex.Analysis(data=data, noise_map=noise_map))" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Index__\n", + "\n", + "The results index finds every result under a folder and classifies it: completed, running, interrupted with a valid\n", + "checkpoint, failed, corrupt, or superseded by a later fit of the same search. Only new or changed results are opened,\n", + "so re-indexing thousands of results after a few new ones is quick." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "index = ResultsIndex(results_path)\n", + "index.update()\n", + "\n", + "print(index.counts())" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Declare__\n", + "\n", + "We expect each of the three datasets to have a completed `fit`, holding its samples summary and the `model.json` of\n", + "the fit. A required product is either a name the index records (`samples`, `samples_summary`, `latent`, `image`,\n", + "`dataset_identity`, `search_internal`) or a path inside the result.\n", + "\n", + "The same declaration can live in a `library.yaml` file (`af.ResultsLibrary.from_yaml`), and on a cluster it can be\n", + "taken straight from an hpc-campaign file with `from_campaign: campaign.yaml`, so the campaign stays the single\n", + "declaration of what was run." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "library = af.ResultsLibrary.grid(\n", + " datasets=[\"gaussian_x1_0\", \"gaussian_x1_1\", \"gaussian_x1_2\"],\n", + " searches={\"fit\": [\"samples_summary\", \"files/model.json\"]},\n", + " roots=results_path,\n", + " name=\"results_library\",\n", + ")" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Check__\n", + "\n", + "`check` gives every expected result a status \u2014 `done`, `missing`, `incomplete`, `failed` or `duplicate` \u2014 and every\n", + "gap a reason. Here `gaussian_x1_2` is missing, with the reason `no_result`.\n", + "\n", + "`write_missing_csv` writes one row per gap to `results_library.missing.csv`, the list to rerun or investigate." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "report = library.check()\n", + "\n", + "print(report.summary())\n", + "\n", + "for result in report.results:\n", + " print(result.expected.dataset, result.status, result.reason)\n", + "\n", + "report.write_missing_csv(results_path)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Enrich__\n", + "\n", + "Suppose that after the fits finished you need a new product in every result: here, a small JSON file with the\n", + "maximum likelihood centre of the Gaussian. `enrich` computes it from each saved result and writes it into the result\n", + "as `files/centre.json`, atomically: if the job is killed part-way, every result is either untouched or complete.\n", + "\n", + "Results that already hold the product are skipped, so an interrupted pass can simply be run again. On a cluster,\n", + "`shard=\"i/N\"` splits the results into N parts, one per array task." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "agg = Aggregator.from_index(results_path)\n", + "\n", + "\n", + "def centre(search_output):\n", + " return {\"centre\": search_output.instance.gaussian.centre}\n", + "\n", + "\n", + "enriched = agg.enrich(centre, name=\"centre\")\n", + "\n", + "print(enriched)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Command Line__\n", + "\n", + "Every step above also runs from the shell, which is how it is used on a cluster:\n", + "\n", + " python -m autofit.results index output/features/results_library\n", + " python -m autofit.results check library.yaml\n", + " python -m autofit.results enrich output/features/results_library --fn products:centre --name centre --shard 0/4\n", + "\n", + "`check` exits with status 1 while anything expected is not done, so a script can wait on it." + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.1" + }, + "colab": { + "aiContexts": { + "745cea84-9c0a-587f-88dd-633d222ca3f3": { + "id": "745cea84-9c0a-587f-88dd-633d222ca3f3", + "name": "PyAutoFit assistant", + "context": "These instructions were prepared by the PyAutoFit assistant\n(https://github.com/PyAutoLabs/autofit_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoFit knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoFit notebook (notebooks/features/results_library.ipynb in autofit_workspace).\nExplain what it does and help them adapt it to their own model and data.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoFit calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoFit docs (https://pyautofit.readthedocs.io).\n2. Real data needs a look first. Before helping fit the user's real data, ask them to\n plot it (or print a numerical summary when it cannot be plotted) and ask one\n question about known artefacts, outliers or selection effects: unmodelled data\n problems are the most common source of biased inference. Simulated data from the\n workspace is exempt.\n3. Their likelihood code is theirs. When wrapping the user's likelihood or model code\n in an `Analysis` class, never silently change its numerics (no re-parametrisation,\n added guards or \"fixes\"). If it looks wrong, say so and let them decide.\n4. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n5. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n6. For multi-step projects (their own model and data, a sample of datasets, a paper's\n analysis), point them to the PyAutoFit assistant\n https://github.com/PyAutoLabs/autofit_assistant, which runs in Claude Code or Codex\n with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: af_wrap_likelihood\n\n---\nname: af_wrap_likelihood\ndescription: Wrap the user's existing likelihood code into a PyAutoFit `Analysis` class \u2014 the assistant's defining task and the ideal domain-adaptation entry point. Takes a function or method the user already trusts (anything that scores parameters against their data), builds the `af.Analysis` subclass around it without altering its numerics, pairs it with a composed model, and validates the wrapper on hand-built instances before any fit. Use when the user says \"wrap my likelihood\", \"connect my code to PyAutoFit\", \"I already have a function that computes chi-squared/log-likelihood\", or brings analysis code of their own. Not for composing priors (af_compose_model) or running fits (af_run_search).\nuser-invocable: true\n---\n\n# Wrapping your likelihood\n\nThis is the assistant's defining task. You already have code that scores a parameter set\nagainst your data \u2014 a chi-squared, a log-likelihood, a forward model plus a noise model.\nWrapping it into an `af.Analysis` connects it to everything PyAutoFit has: every sampler,\nprior machinery, output/resumption, posterior analysis, graphical models. Your code keeps\ndoing the science; PyAutoFit does the inference around it.\n\n**The constitution's rule applies throughout** (`AGENTS.md` \"Safety invariants\"): the\nlikelihood code is *yours*. The wrapper never re-parametrises, adds guards, or \"fixes\"\nnumerics. If something in it looks wrong, the assistant says so and you decide.\n\n## Orient\n\nAn `Analysis` is a small class: it holds your data in `__init__` and implements one\nmethod, `log_likelihood_function(self, instance) -> float`, where `instance` is a real\ninstance of your model classes with the search's current parameter values filled in\n(`PyAutoFit:autofit/non_linear/analysis/`). The wrapper's whole job is translating\nbetween that `instance` and your function's calling convention.\n\nRead `wiki/core/concepts/bayesian_inference.md` for where the likelihood sits;\n`autofit_workspace:scripts/cookbooks/analysis.py` is the canonical worked example.\n\n## Ask\n\nFour things decide the wrapper's shape \u2014 get them before writing code:\n\n1. **The signature.** What does your function take \u2014 a parameter vector in a fixed\n order? Named arguments? An object? What does it return \u2014 log likelihood, chi-squared\n (\u2192 `-0.5 * chi2` plus the noise term, see below), or something else?\n2. **The data.** What arrays/objects does it need at call time, and how are they loaded?\n3. **Log or not, and complete or not.** Is the returned quantity already a *log*\n likelihood, and does it include the noise normalisation term? (For model comparison\n the constant terms matter \u2014 [[../wiki/core/concepts/evidence_and_model_comparison]].)\n4. **The parametrisation.** Which arguments are free parameters (\u2192 the model,\n `af_compose_model`) and which are fixed configuration?\n\n## Branch \u2014 the wrapper\n\nThe pattern, for a function `my_log_like(params: dict, data, noise)`:\n\n```python\n\"\"\"\nAnalysis: \n==============================\n\nWrap .my_log_like into a PyAutoFit Analysis. The likelihood code is\nunchanged \u2014 this class only translates the search's `instance` into the function's\ncalling convention.\n\n__Contents__\n\n- **Model component:** The class whose __init__ defines the free parameters.\n- **Analysis:** The wrapper.\n- **Validation:** Hand-built instances scored before any fit.\n\"\"\"\nimport autofit as af\nfrom my_package import my_log_like # the user's code, imported not copied\n\n\nclass MyModel:\n \"\"\"Free parameters of the fit \u2014 mirrors the arguments my_log_like expects.\"\"\"\n def __init__(self, centre=0.0, amplitude=1.0, width=1.0):\n self.centre = centre\n self.amplitude = amplitude\n self.width = width\n\n\nclass Analysis(af.Analysis):\n def __init__(self, data, noise):\n super().__init__()\n self.data = data\n self.noise = noise\n\n def log_likelihood_function(self, instance) -> float:\n \"\"\"Translate `instance` -> the user's convention; return their number.\"\"\"\n params = {\n \"centre\": instance.centre,\n \"amplitude\": instance.amplitude,\n \"width\": instance.width,\n }\n return my_log_like(params, self.data, self.noise)\n```\n\nVariations by input shape:\n\n- **Vector-in-fixed-order functions** \u2014 build the list from named attributes explicitly\n (`[instance.centre, instance.amplitude, ...]`); never rely on attribute iteration\n order.\n- **Chi-squared functions** \u2014 return `-0.5 * chi2` *plus* the noise normalisation\n (`-0.5 * sum(log(2\u03c0 \u03c3\u00b2))`) if evidence will ever be compared. Ask the user before\n adding the term \u2014 it belongs to *their* data model; adding it is their call.\n- **Expensive setup** (grids, kernels, splines) \u2014 do it once in `__init__`, not per\n likelihood call; this is packaging, not a numerics change.\n- **Multiple datasets** \u2014 one `Analysis` per dataset, combined with\n `af.AnalysisFactor` + `af.FactorGraphModel`\n ([[../wiki/core/concepts/graphical_models_and_ep]]).\n\n## Branch \u2014 validate before fitting\n\nNever hand a wrapper straight to a sampler. Three checks, in order:\n\n```python\n\"\"\"\n__Validation__\n\n1. A hand-built instance with known-good parameters returns a finite float.\n2. The value matches calling the user's function directly (same inputs, same number).\n3. A deliberately bad instance scores WORSE (lower log likelihood) \u2014 the sign\n convention is right.\n\nHand-built plain instances of the user's class \u2014 no priors needed yet, so validation\nruns before the prior conversation. (`instance_from_prior_medians()` etc. only work\nafter every parameter has a prior, from `af_compose_model` or prior config \u2014 a bare\n`af.Model(MyModel)` on a class without prior config raises ConfigException.)\n\"\"\"\nanalysis = Analysis(data=data, noise=noise)\n\ngood = MyModel(centre=50.0, amplitude=25.0, width=10.0) # known-good values\nll_good = analysis.log_likelihood_function(good)\nassert ll_good == my_log_like({\"centre\": good.centre, \"amplitude\": good.amplitude,\n \"width\": good.width}, data, noise)\n\nbad = MyModel(centre=-1e3, amplitude=1e-6, width=0.1) # known to fit poorly\nassert analysis.log_likelihood_function(bad) < ll_good\n```\n\nA wrapper that fails check 3 has a sign flip (chi-squared vs log-likelihood) \u2014 the most\ncommon wrapping bug, and one a sampler will happily *minimise your fit quality* with.\n\n## JAX triage (optional, one question)\n\nIf the user's function is pure JAX (or trivially convertible), gradient-based search\n(`af.BlackJAXNUTS`) and GPU execution open up. Ask once \u2014 \"is your likelihood\nJAX-compatible / worth making so?\" \u2014 and record the answer in `profile.md`\n(\"Likelihood & model code\"). Don't convert their code uninvited.\n\n## Combine\n\n- Priors for the new model: `af_compose_model` (each parameter's prior is a scientific\n statement \u2014 this conversation is where the user's domain knowledge lands).\n- First fit: `af_run_search` \u2014 start with a cheap sampler budget; the wrapper's cost per\n call, measured during validation, sets the budget arithmetic.\n- Record the wrap in `wiki/project/` (default-yes): the function wrapped, its\n convention, the validation numbers, and where the code lives \u2014 plus `profile.md`'s\n \"Likelihood & model code\" section, so future sessions skip this interview.\n\n## Skill: af_compose_model\n\n---\nname: af_compose_model\ndescription: Compose a PyAutoFit model from the user's parametrisation \u2014 turn Python classes into `af.Model` objects, combine components with `af.Collection`, and set every prior deliberately (uniform, log-uniform, Gaussian, fixed, linked, asserted). Use when the user wants to define what is being fitted \u2014 \"set up my model\", \"what priors should I use\", \"fix this parameter\", \"tie these two parameters together\". Not for writing the likelihood (that is `af_wrap_likelihood` / a custom Analysis) or for running the fit (that is `af_run_search`).\nuser-invocable: true\n---\n\n# Composing a model and its priors\n\nModel composition is where your science becomes a statistics problem: each free\nparameter you declare is a dimension of the space the non-linear search must explore,\nand each prior is a statement about what you believe before seeing the data. Getting\nthis step right matters more than any sampler setting \u2014 an over-free model wastes\ncompute and an ill-considered prior can silently drive the posterior.\n\nThe deliverable is a `scripts/` Python script (workspace style, `_style.md`) that\ncomposes the user's model, prints its `model.info` summary, and is ready to hand to\n`af_run_search`.\n\n## Orient\n\nPyAutoFit composes models from **plain Python classes** \u2014 usually the user's own. The\nclass's `__init__` arguments become the model's free parameters\n(`PyAutoFit:autofit/mapper/model.py`). If the user has already adapted the assistant to\ntheir domain, read `wiki/project/profile.md` for their standard parametrisation before\nproposing one.\n\nRead `wiki/core/concepts/model_composition_and_priors.md` for the underlying ideas\n(once the core wiki lands; until then the canonical reference is\n`autofit_workspace:scripts/cookbooks/model.py`).\n\n## Ask\n\n- What are the components of the model, physically? One class or several?\n- For each parameter: what is physically plausible, and is the scale known to within\n a factor of a few (\u2192 uniform/Gaussian) or uncertain over decades (\u2192 log-uniform)?\n- Should any parameter be fixed, or shared between components?\n\n## Branch \u2014 a single component\n\n```python\n\"\"\"\n__Model__\n\nThe Gaussian's three `__init__` arguments become free parameters. Priors are set\nexplicitly \u2014 never rely on defaults for a real analysis; each prior is a scientific\nstatement (`PyAutoFit:autofit/mapper/model.py`).\n\"\"\"\nimport autofit as af\n\nmodel = af.Model(Gaussian)\nmodel.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\nmodel.normalization = af.LogUniformPrior(lower_limit=1e-4, upper_limit=1e4)\nmodel.sigma = af.GaussianPrior(mean=10.0, sigma=5.0)\n\nprint(model.info)\n```\n\nPrior choice in one line each: `UniformPrior` = \"any value in this range, equally\";\n`LogUniformPrior` = \"the order of magnitude is unknown\" (strictly positive quantities\nonly \u2014 its log-prior diverges at zero); `GaussianPrior` = \"I have an estimate with an\nuncertainty\"; `TruncatedGaussianPrior` = the same, hard-bounded to a physical range.\n\n## Branch \u2014 customization: fixing, linking, asserting\n\n```python\n\"\"\"\n__Model Customization__\n\nFixed values remove a dimension from the search; links declare two parameters equal;\nassertions carve away unphysical corners of the space.\n\"\"\"\nmodel = af.Model(Gaussian)\nmodel.centre = 50.0 # fixed \u2014 no longer free\nmodel.sigma = model.normalization # linked \u2014 one dimension, two roles\nmodel.add_assertion(model.sigma > 0.0) # rejected regions get zero prior\n```\n\nPriors can also be passed at construction:\n`af.Model(Gaussian, centre=af.UniformPrior(lower_limit=0.0, upper_limit=1.0))`.\n\n## Branch \u2014 multiple components with `af.Collection`\n\n```python\n\"\"\"\n__Collection__\n\nA Collection groups components under named attributes; the search sees one flat\nparameter space, the likelihood receives a matching `instance` with the same named\nattributes (`instance.gaussian`, `instance.exponential`).\n\"\"\"\nmodel = af.Collection(gaussian=af.Model(Gaussian), exponential=af.Model(Exponential))\n\nmodel.gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0)\nmodel.exponential.rate = af.LogUniformPrior(lower_limit=1e-2, upper_limit=1e1)\n\n# Cross-component sharing works exactly like within-component linking:\nmodel.exponential.centre = model.gaussian.centre\n```\n\n## Branch \u2014 save and reload the model\n\n```python\n\"\"\"\n__Json Output__\n\nA composed model serialises to human-readable JSON \u2014 commit it with the analysis so\nthe exact parametrisation and priors are part of the paper's reproducibility record.\n\"\"\"\nmodel.output_to_json(file=\"scripts/model.json\")\nmodel = af.Model.from_json(file=\"scripts/model.json\")\n```\n\n## Sanity checks before fitting\n\n- `model.prior_count` \u2014 is the dimensionality what you expect?\n- `model.random_instance()` \u2014 instantiate from the priors and eyeball the values;\n wildly unphysical draws mean a prior is wrong.\n- `print(model.info)` \u2014 the full tree, priors included; paste it into the\n `wiki/project/` entry for the fit.\n\n## Combine\n\n- The model meets its data through an `Analysis` class \u2014 the user's own likelihood is\n wrapped via `af_wrap_likelihood`; simple built-in-style cases via `af_custom_analysis`.\n- Configure the sampler with `af_configure_search`, run with `af_run_search`.\n- Offer (default-yes) a dated `wiki/project/` entry recording the parametrisation and\n the reasoning behind each prior.\n\n## Further reading\n\n- **Student / new to inference** \u2014 HowToFit chapter 1: model composition from first\n principles.\n- **General reference** \u2014 [RTD: model cookbook](https://pyautofit.readthedocs.io/en/latest/cookbooks/model.html).\n- **Experienced PyAutoFit user** \u2014 `autofit_workspace:scripts/cookbooks/model.py`\n (also `model_internal.py`, `multi_level_model.py` for advanced composition).\n" + } + }, + "selectedAiContext": "745cea84-9c0a-587f-88dd-633d222ca3f3" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file diff --git a/scripts/features/README.md b/scripts/features/README.md index acdd86fa..0e1c023f 100644 --- a/scripts/features/README.md +++ b/scripts/features/README.md @@ -6,6 +6,7 @@ The `features` folder contains example scripts for using advanced **PyAutoFit** - `shared_analysis_state.py`: Share per-evaluation model state across the factors of a graphical model so identical work is computed once, not once per factor. - `interpolate.py`: Fit datasets which smoothly vary as a function of a continuous parameter (e.g. time) and interpolate between them. - `model_comparison.py`: Perform Bayesian model comparison between different models to determine which the data favours. +- `results_library.py`: Declare the results a set of fits should produce, list every one that is missing (and why), and add new products to finished results. - `search_chaining.py`: Chaining together multiple non-linear searches to automate the fitting of a complex model. - `search_grid_search.py`: Perform a massively parallel grid search of non-linear searches. - `sensitivity_mapping.py`: Determine how sensitive a dataset is to a model's complexity. diff --git a/scripts/features/results_library.py b/scripts/features/results_library.py new file mode 100644 index 00000000..005178fc --- /dev/null +++ b/scripts/features/results_library.py @@ -0,0 +1,147 @@ +""" +Feature: Results Library +======================== + +When you fit many datasets — hundreds of objects on a cluster, say — the hard question at the end is not "what are +the results?" but "which results are *missing*?". A fit that crashed, ran out of time, or completed without a product +you need leaves no error behind: it is simply not there, and a catalogue built from the output quietly loses it. + +The results library answers that question. You declare which results you expect (datasets × searches, and which +products each must hold), and **PyAutoFit** compares that declaration with what is on disk, giving every gap a reason. +It can then add a new product to results that already exist, without rerunning any fit. + +__Contents__ + +This script is split into the following sections: + +- **Fits**: Fit a few datasets, outputting the results to hard-disk. +- **Index**: Build an index of every result on disk. +- **Declare**: Declare which results the library is expected to hold. +- **Check**: Compare the declaration with the index and list every gap. +- **Enrich**: Add a new product to every completed result. +- **Command Line**: The same steps from the shell, e.g. on a cluster. +""" + +# from autofit import setup_notebook; setup_notebook() + +from os import path +from pathlib import Path + +import autofit as af +from autofit.aggregator import Aggregator +from autofit.results import ResultsIndex + +""" +__Fits__ + +We fit two of the three `gaussian_x1` datasets, each written to hard-disk with its dataset name as `unique_tag`. The +third dataset is deliberately not fitted, so the library has a hole to find. +""" +results_path = af.with_test_mode_segment(Path("output")) / "features" / "results_library" + +model = af.Collection(gaussian=af.ex.Gaussian) + +for dataset_name in ["gaussian_x1_0", "gaussian_x1_1"]: + dataset_path = path.join("dataset", "example_1d", dataset_name) + + if not path.exists(dataset_path): + import subprocess + import sys + + subprocess.run( + [sys.executable, "scripts/simulators/simulators.py"], + check=True, + ) + + data = af.util.numpy_array_from_json(file_path=path.join(dataset_path, "data.json")) + noise_map = af.util.numpy_array_from_json( + file_path=path.join(dataset_path, "noise_map.json") + ) + + search = af.DynestyStatic( + name="fit", + path_prefix=path.join("features", "results_library"), + unique_tag=dataset_name, + nlive=50, + ) + search.fit(model=model, analysis=af.ex.Analysis(data=data, noise_map=noise_map)) + +""" +__Index__ + +The results index finds every result under a folder and classifies it: completed, running, interrupted with a valid +checkpoint, failed, corrupt, or superseded by a later fit of the same search. Only new or changed results are opened, +so re-indexing thousands of results after a few new ones is quick. +""" +index = ResultsIndex(results_path) +index.update() + +print(index.counts()) + +""" +__Declare__ + +We expect each of the three datasets to have a completed `fit`, holding its samples summary and the `model.json` of +the fit. A required product is either a name the index records (`samples`, `samples_summary`, `latent`, `image`, +`dataset_identity`, `search_internal`) or a path inside the result. + +The same declaration can live in a `library.yaml` file (`af.ResultsLibrary.from_yaml`), and on a cluster it can be +taken straight from an hpc-campaign file with `from_campaign: campaign.yaml`, so the campaign stays the single +declaration of what was run. +""" +library = af.ResultsLibrary.grid( + datasets=["gaussian_x1_0", "gaussian_x1_1", "gaussian_x1_2"], + searches={"fit": ["samples_summary", "files/model.json"]}, + roots=results_path, + name="results_library", +) + +""" +__Check__ + +`check` gives every expected result a status — `done`, `missing`, `incomplete`, `failed` or `duplicate` — and every +gap a reason. Here `gaussian_x1_2` is missing, with the reason `no_result`. + +`write_missing_csv` writes one row per gap to `results_library.missing.csv`, the list to rerun or investigate. +""" +report = library.check() + +print(report.summary()) + +for result in report.results: + print(result.expected.dataset, result.status, result.reason) + +report.write_missing_csv(results_path) + +""" +__Enrich__ + +Suppose that after the fits finished you need a new product in every result: here, a small JSON file with the +maximum likelihood centre of the Gaussian. `enrich` computes it from each saved result and writes it into the result +as `files/centre.json`, atomically: if the job is killed part-way, every result is either untouched or complete. + +Results that already hold the product are skipped, so an interrupted pass can simply be run again. On a cluster, +`shard="i/N"` splits the results into N parts, one per array task. +""" +agg = Aggregator.from_index(results_path) + + +def centre(search_output): + return {"centre": search_output.instance.gaussian.centre} + + +enriched = agg.enrich(centre, name="centre") + +print(enriched) + +""" +__Command Line__ + +Every step above also runs from the shell, which is how it is used on a cluster: + + python -m autofit.results index output/features/results_library + python -m autofit.results check library.yaml + python -m autofit.results enrich output/features/results_library --fn products:centre --name centre --shard 0/4 + +`check` exits with status 1 while anything expected is not done, so a script can wait on it. +""" diff --git a/workspace_index.json b/workspace_index.json index 5ac30500..ba05c62a 100644 --- a/workspace_index.json +++ b/workspace_index.json @@ -316,6 +316,21 @@ "summary": "Common questions when fitting a model to data are: what model should I use? How many parameters should the model have? Is the model too complex or too simple?", "title": "Feature: Model Comparison" }, + { + "contents": [ + "Fits", + "Index", + "Declare", + "Check", + "Enrich", + "Command Line" + ], + "cross_refs": [], + "notebook": "notebooks/features/results_library.ipynb", + "path": "scripts/features/results_library.py", + "summary": "When you fit many datasets \u2014 hundreds of objects on a cluster, say \u2014 the hard question at the end is not \"what are the results?\" but \"which results are *missing*?\". A fit that crashed, ran out of time, or completed without a product you need leaves no error behind: it is simply not there, and a catalogue built from the output quietly loses it.", + "title": "Feature: Results Library" + }, { "contents": [ "Example Source Code (`af.ex`)",