Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,10 +141,17 @@ how it paces the work, not which workflows exist:
the user asks for a long or multi-session run, scale up: clarify the goal, plan in phases,
execute with checkpoints — proactive but not silent; state in `wiki/project/`. The dial is
in [`modes/assistant.md`](./modes/assistant.md) "The autonomy dial".

Select (first match): explicit instruction → `.mode` file → `profile.md` "Interaction mode" →
else **infer from the opening request** (fall back to **assistant**); `.maintainer` outranks
`.mode`. State an inferred mode in one line and invite correction; acknowledge an explicit
- **Start here** — *the guided tour*: the six-step natural-language workflow of the RTD
Natural Language Inference page run on the bundled 1D Gaussian, then the same six steps on
the user's own project. One step per turn; the user types each prompt themselves. It adds
no capability — it scripts the existing skills at newcomer depth — and hands off to
assistant (or teacher) mode when it ends. See [`modes/start_here.md`](./modes/start_here.md).

Select (first match): the **published start-here prompt** (`README.md` "Getting Started"), or
"start here" / "start_here" → explicit instruction → `.mode` file → `profile.md` "Interaction
mode" → else **infer from the opening request** (fall back to **assistant**); `.maintainer`
outranks all of them. The start-here trigger outranks inference from the rest of the opening
request. State an inferred mode in one line and invite correction; acknowledge an explicit
one only if it changes behavior. Read `modes/<mode>.md`; depth still follows
`skills/_style.md` "Adaptive depth".

Expand Down
191 changes: 129 additions & 62 deletions README.md

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions docs/setup/claude_code.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ Explain the model, priors, likelihood, search and results as we go.
```

New to Bayesian inference? Start the prompt with `Teacher mode.` and the assistant explains
the concepts as it goes. You do not have to let it run anything: ask it to plan the analysis and
discuss the model and priors before any search is submitted.
the concepts as it goes — or just ask, the start-here tour takes questions at every step. You do
not have to let it run anything: ask it to plan the analysis and discuss the model and priors
before any search is submitted.

Experimental alternative if you cannot use Claude Code or Codex: [OpenCode](opencode_cli.md).
5 changes: 3 additions & 2 deletions docs/setup/codex_cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ Explain the model, priors, likelihood, search and results as we go.
```

New to Bayesian inference? Start the prompt with `Teacher mode.` and the assistant explains
the concepts as it goes. You do not have to let it run anything: ask it to plan the analysis and
discuss the model and priors before any search is submitted.
the concepts as it goes — or just ask, the start-here tour takes questions at every step. You do
not have to let it run anything: ask it to plan the analysis and discuss the model and priors
before any search is submitted.

Experimental alternative if you cannot use Claude Code or Codex: [OpenCode](opencode_cli.md).
458 changes: 458 additions & 0 deletions modes/start_here.md

Large diffs are not rendered by default.

132 changes: 132 additions & 0 deletions scripts/start_here/analysis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
"""
Start Here: The Likelihood
==========================

The `Analysis` class that connects the Gaussian model to the bundled dataset. An Analysis holds
the data in `__init__` and implements one method, `log_likelihood_function`, which scores a
model instance against that data (`PyAutoFit:autofit/non_linear/analysis/`). Everything
PyAutoFit does — every search, the output tree, the posterior machinery — is built on that one
method, which is why wrapping an existing likelihood is the assistant's defining task
(`skills/af_wrap_likelihood.md`, `skills/af_custom_analysis.md`).

__The likelihood__

The data are 100 independent measurements with known, uncorrelated Gaussian errors, so the log
likelihood is the usual chi-squared sum,

ln L = -1/2 sum_i [ (d_i - m_i(theta)) / sigma_i ]^2

with the noise-normalisation term dropped because it is a constant: it cancels in every
posterior and in every evidence *difference* between models fitted to the same data, which is
the only way evidences are compared here.

__Contents__

- **Visualizer:** Figures written into the search's own output tree, refreshed as it runs.
- **Analysis:** The likelihood, plus the dataset it is evaluated against.
"""

import numpy as np

import autofit as af


class Visualizer(af.Visualizer):
"""
Live figures for the fit. `visualize_before_fit` runs once, before the search starts, and
plots the data on its own; `visualize` runs at the search's update intervals and at
completion, receiving the best model found so far, and plots it over the data with the
normalised residuals underneath.

The figures land in the search's own output directory (`paths.image_path`), which is why the
output folder is worth opening the moment a fit starts rather than when it ends
(`skills/_style.md` "Output folder announcement").
"""

@staticmethod
def visualize_before_fit(analysis, paths: af.AbstractPaths, model):
import matplotlib.pyplot as plt

xvalues = np.arange(analysis.data.shape[0])

fig, ax = plt.subplots(figsize=(7, 4))
ax.errorbar(
xvalues, analysis.data, yerr=analysis.noise_map, fmt=".k", ms=4, elinewidth=0.7
)
ax.set_xlabel("x")
ax.set_ylabel("profile normalization")
ax.set_title("The 1D dataset being fitted")

paths.image_path.mkdir(parents=True, exist_ok=True)
fig.savefig(paths.image_path / "data.png", dpi=140, bbox_inches="tight")
plt.close(fig)

@staticmethod
def visualize(analysis, paths: af.DirectoryPaths, instance, during_analysis: bool):
import matplotlib.pyplot as plt

xvalues = np.arange(analysis.data.shape[0])
model_data = analysis.model_data_from(instance=instance)

fig, (ax0, ax1) = plt.subplots(
2, 1, figsize=(7, 5), sharex=True, height_ratios=[3, 1]
)
ax0.errorbar(
xvalues, analysis.data, yerr=analysis.noise_map, fmt=".k", ms=4, elinewidth=0.7
)
ax0.plot(xvalues, model_data, "r-", lw=1.5)
ax0.set_ylabel("profile normalization")
ax0.set_title("Best fit so far" if during_analysis else "Maximum likelihood fit")

ax1.plot(xvalues, (analysis.data - model_data) / analysis.noise_map, ".k", ms=4)
ax1.axhline(0.0, color="r", lw=0.8)
ax1.set_ylabel("residual / sigma")
ax1.set_xlabel("x")

paths.image_path.mkdir(parents=True, exist_ok=True)
fig.savefig(paths.image_path / "subplot_fit.png", dpi=140, bbox_inches="tight")
plt.close(fig)


class Analysis(af.Analysis):
"""
The likelihood for the bundled 1D Gaussian dataset.

Attaching `Visualizer` as a class attribute is what makes the search write fit and residual
images as it runs (`skills/af_custom_analysis.md` "a custom Visualizer").
"""

Visualizer = Visualizer

def __init__(self, data: np.ndarray, noise_map: np.ndarray):
super().__init__()

self.data = data
self.noise_map = noise_map

def model_data_from(self, instance) -> np.ndarray:
"""
The model's prediction for the data.

A single-component model arrives as an instance of the `Gaussian` class itself; a
`Collection` arrives as an iterable of such instances, whose profiles sum. Handling both
here is what lets steps 4 and 6 of the tour share one likelihood across the one-Gaussian
and three-Gaussian models.
"""
xvalues = np.arange(self.data.shape[0])

try:
return sum(profile.model_data_from(xvalues=xvalues) for profile in instance)
except TypeError:
return instance.model_data_from(xvalues=xvalues)

def log_likelihood_function(self, instance) -> float:
"""
The log likelihood of a model instance: independent Gaussian errors, so a chi-squared
sum (see the module docstring for the dropped constant).
"""
model_data = self.model_data_from(instance=instance)

chi_squared_map = ((self.data - model_data) / self.noise_map) ** 2.0

return float(-0.5 * np.sum(chi_squared_map))
68 changes: 68 additions & 0 deletions scripts/start_here/gaussian.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
"""
Start Here: The Model Component
===============================

The 1D Gaussian profile fitted by the "start here" tour, as a plain Python class. PyAutoFit
composes models from ordinary classes like this one — the `__init__` arguments become the
model's free parameters and `model_data_from` evaluates the profile — so the model code stays
the user's own rather than a framework object (`PyAutoFit:autofit/mapper/model.py`).

__Normalisation convention__

This Gaussian is **peak-normalised**: `normalization` is the profile's peak amplitude, matching
the equation quoted on the RTD natural-language page and in `dataset/gaussian_x1/README.md`:

g(x) = N exp[-1/2 ((x - c) / sigma)^2]

The bundled dataset was simulated in that convention (`centre=50.0`, `normalization=25.0`,
`sigma=10.0`, per-pixel noise sigma 2.0), so a correct fit recovers a normalization near 25.

PyAutoFit's own example class, `af.ex.Gaussian`, is instead **area-normalised** — it divides by
`sigma * sqrt(2 pi)` — which on this dataset would put the normalization near 620, outside the
uniform 0-100 prior the tour prescribes. Neither convention is more correct; the point is that
the model class defines it, and the class is yours. If a user's own model uses the area
convention, their priors follow their convention.

__Contents__

- **Gaussian:** The model component whose three `__init__` arguments are the free parameters.
"""

import numpy as np


class Gaussian:
def __init__(
self,
centre: float = 0.0,
normalization: float = 1.0,
sigma: float = 1.0,
):
"""
A 1D Gaussian profile, peak-normalised (see the module docstring).

Parameters
----------
centre
The x coordinate of the profile's centre.
normalization
The peak amplitude of the profile.
sigma
The standard deviation, setting the profile's width.
"""
self.centre = centre
self.normalization = normalization
self.sigma = sigma

def model_data_from(self, xvalues: np.ndarray) -> np.ndarray:
"""
The profile evaluated on a 1D grid of x coordinates.

Parameters
----------
xvalues
The x coordinates in the reference frame of the data.
"""
return self.normalization * np.exp(
-0.5 * ((xvalues - self.centre) / self.sigma) ** 2
)
92 changes: 92 additions & 0 deletions scripts/start_here/step_1_compose_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
"""
Start Here Step 1: Compose the Model
====================================

The first step of the "start here" tour. A model in PyAutoFit is a plain Python class whose
`__init__` arguments become the free parameters of the fit, wrapped in an `af.Model`. Here the
class is the 1D Gaussian profile in `gaussian.py` and the three free parameters are its centre,
normalization and width, each given an explicit prior stating what we believe before seeing the
data.

The bundled dataset in `dataset/gaussian_x1/` was simulated from this profile with
`centre=50.0`, `normalization=25.0`, `sigma=10.0` and per-pixel noise sigma 2.0, so the fit in
step 4 has a known truth to be judged against.

__Contents__

- **Imports:** autofit and the tour's Gaussian class.
- **Model:** Wrap the class in `af.Model` and state every prior explicitly.
- **Variation - Two Gaussians:** The same request reworded as a two-component model.
"""

import autofit as af

from gaussian import Gaussian

"""
__Model__

`af.Model(Gaussian)` inspects the class's `__init__` signature and creates one free parameter
per argument. Every prior is stated explicitly — defaults are convenient for a demonstration,
but a prior is a scientific statement, so a real analysis always states it
(`PyAutoFit:autofit/mapper/prior/`, and `skills/af_compose_model.md`).

`UniformPrior` says "any value in this range, equally likely". The centre is bounded by the
100-pixel grid, the normalization by the observed dynamic range, and sigma is kept strictly
positive by a lower limit of 0.1.

The priors are passed as keyword arguments **at construction** rather than assigned afterwards.
Both forms compose the same model; passing them at construction means the priors printed in
`model.info` carry the ids `[0]`, `[1]`, `[2]`, because assigning after construction first
mints the class's default priors and the surviving ids then start at `[3]`. The ids are a
creation-order counter over every prior made in the process — worth knowing before they look
surprising.
"""

model = af.Model(
Gaussian,
centre=af.UniformPrior(lower_limit=0.0, upper_limit=100.0),
normalization=af.UniformPrior(lower_limit=0.0, upper_limit=100.0),
sigma=af.UniformPrior(lower_limit=0.1, upper_limit=30.0),
)

print(model.info)

print(f"\nFree parameters: {model.prior_count}")

"""
__Variation - Two Gaussians__

The point of describing a model in natural language is that rewording the description rewords
the model. "Make it two Gaussians" becomes an `af.Collection` of two `af.Model` objects: the
search explores a single flat six-dimensional space and the likelihood receives an instance
with two named attributes, `instance.gaussian_0` and `instance.gaussian_1`
(`PyAutoFit:autofit/mapper/prior_model/collection.py`).

Nothing else about the workflow changes — the same likelihood, the same search and the same
result machinery apply to the wider model. That is the point of the tour's "describe it
differently" nudge: the model is the part you restate, not the pipeline around it.

Prior ids continue from the single-Gaussian model above, so this collection's ids run `[3]` to
`[8]`; run the variation on its own and they run `[0]` to `[5]`.
"""


def gaussian_model() -> af.Model:
return af.Model(
Gaussian,
centre=af.UniformPrior(lower_limit=0.0, upper_limit=100.0),
normalization=af.UniformPrior(lower_limit=0.0, upper_limit=100.0),
sigma=af.UniformPrior(lower_limit=0.1, upper_limit=30.0),
)


model_x2 = af.Collection(gaussian_0=gaussian_model(), gaussian_1=gaussian_model())

print("\n" + "=" * 70)
print('Variation: "make it two Gaussians"')
print("=" * 70 + "\n")

print(model_x2.info)

print(f"\nFree parameters: {model_x2.prior_count}")
Loading
Loading