Skip to content

docs: finish the math sweep, revive tutorial 3's priors and MCMC budget, fix self.noise_map - #60

Merged
Jammy2211 merged 2 commits into
mainfrom
feature/howtofit-tutorial-followups
Sep 14, 2026
Merged

Jammy2211 merged 2 commits into
mainfrom
feature/howtofit-tutorial-followups

Conversation

@Jammy2211

@Jammy2211 Jammy2211 commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Closes #59. The follow-ups reported out of #57 / #58, plus one bug found while doing them.

Stacked on #58, which is stacked on #56. Merge order: #56 → #58 → this. Both follow-ups touch files those PRs already modify, so this could not branch from main without conflicting. GitHub retargets this to main as the stack merges.

1. The math sweep, finished

#58 converted tutorials 1-3 only, because that task was scoped there. Neither \[ nor \( is a default MathJax delimiter in Jupyter, JupyterLab or Colab, so everything left rendered as raw LaTeX.

File \[ \] → $$ \( \) → $…$
tutorial_6_gradients.py 4 28
tutorial_7_the_details.py 1 0
tutorial_optional_bayesian_formalism.py 7 40

Conversion was AST-driven over module-level string-expression statements — the prose cells — so nothing inside code was touched. All 12 affected docstrings were already r""". \begin{equation*} environments are left alone; MathJax renders those, they were never the bug.

One hit deliberately left: tutorial_5_results_and_samples.py:693, suffix=" \\[-2pt]" — a LaTeX row-break passed as a Python string to af.text.Samples.latex(). It is code, not prose. That file is otherwise untouched by this follow-up.

2. Tutorial 3's __Priors__ block was dead and wrong

It set three priors on a model that all five fits then discarded by calling af.Model(Gaussian) again before search.fit. So it never applied, and the fits silently ran config/priors/gaussian.yaml:

Parameter Truth Block set Actually used
centre 50.0 Uniform(0, 100) Uniform(0, 100) — identical
normalization 25.0 Uniform(0, 10) — excludes the truth LogUniform(1e-6, 1e6)
sigma 10.0 Uniform(0, 10) — truth on the boundary Uniform(0, 25)

All five redundant re-creations are removed, so the block now takes effect for every fit.

Why the values restate the defaults instead of narrowing them

The obvious fix — widen normalization to something that contains 25.0 — breaks the tutorial, and not subtly.

af.LBFGS()'s default initializer is InitializerBall(lower_limit=0.49, upper_limit=0.51): a tight ball on the centre of each prior, not a broad random draw. Under normalization = Uniform(0, 50) that centre is exactly 25.0, the true value. The first MLE fit — the one whose failure is the entire teaching point of the MLE section — would start sitting on the answer.

Measured, 10 runs each, with a standalone harness that reuses the tutorial's own Gaussian, Analysis and dataset (the tutorial itself was not modified to measure):

Priors Uninitialised MLE outcome
Config defaults (baseline, today's behaviour) fails 10/10 — local max at norm ≈ 5.8-6.3, sigma ≈ 12.0-12.5, logL ≈ −3126 to −3300
Candidate: normalization Uniform(0, 50), sigma Uniform(0, 25) succeeds 10/10, identically: 49.8029 / 25.0478 / 10.0150, logL 176.1059 — lesson destroyed
Shipped: restate the config defaults, actually applied fails 10/10 — reproduces the baseline local maximum exactly

So the block is now live and correct, and the parameter space every search explores is provably unchanged.

The three real fits still recover the truth (50 / 25 / 10):

  • Initialised MLE: 49.803 / 25.045 / 10.014, logL 176.106
  • MCMC: median 49.77 (49.15, 50.63) / 24.65 (21.53, 25.76) / 10.09 (9.28, 10.77)
  • Nested sampling: median 49.80 (49.41, 50.18) / 25.07 (24.28, 25.79) / 10.01 (9.68, 10.42)

Prose

The claim "we are using UniformPriors in this tutorial due to their simplicity" was false — normalization runs log-uniform. Replaced with an explanation of why a parameter spanning orders of magnitude wants a LogUniformPrior, and a paragraph saying plainly that these three lines restate the config defaults so the API and the searched parameter space are visible in the script rather than hidden in a config file.

3. Bug found while doing the above: self.noise_map

Analysis.log_likelihood_function in tutorials 3, 4 and 5 computed

noise_normalization = np.sum(np.log(2 * np.pi * noise_map**2.0))

reading a module-level global, while every other line in the same method correctly used self.data / self.noise_map. It returns the right number inside the tutorial only because that global happens to be in scope — and this is the class the tutorials explicitly tell readers to copy into their own code, where it raises NameError. It broke the measurement harness above on first run, which is how it surfaced.

Now self.noise_map in all three, matching tutorials 6 and 7, which were already correct. Checked the whole chapter: the remaining bare noise_map uses are module-level scripts or a genuine function parameter (tutorial_2_fitting_data.py's log_likelihood_from), and are correct.

Testing

  • python .github/scripts/run_smoke.py — exit 0, 18/18 PASS, 0 FAIL (23 found, 5 excluded by no_run.yaml).
  • Tutorial 3 run in full outside test mode, exit 0.
  • black --check scripts/chapter_1_introduction/ — clean, 11 files unchanged.
  • Notebooks + catalogue regenerated (19 scripts). Tutorials 5/6/7/optional markdown cells: 0 \[, 0 \(. Tutorial 5's one \[ survives in a code cell, as intended. tutorial_8_scientific_workflow.ipynb still 0 code cells. llms-full.txt / workspace_index.json regenerate byte-identical.

4. Tutorial 3's MCMC fits now converge

The prose after the first, uninitialised Emcee fit claims it "succeeded, finding the same high-likelihood model that the MLE search with a good starting point identified". At nwalkers=10, nsteps=200 it succeeded 11 times out of 20. Success here means all three parameters within 5% of truth (50 / 25 / 10) and log likelihood > 150; the failures were gross, not marginal (e.g. sigma=5.6 at logL -2333).

Two calibration facts first: the global MLE of the on-disk dataset is (50.164, 24.983, 9.991) at logL 188.39, and the Fisher 1-sigma widths are (0.135, 0.291, 0.134) — so the 5% window is +/-18.6 / 4.3 / 3.7 sigma. A converged chain passes essentially always; the failures are genuine non-convergence, not posterior width.

nwalkers, nsteps evals success median wall-clock
10, 200 (before) 2 000 11/20 3.9 s
10, 500 5 000 18/20 7.1 s
20, 300 6 000 77/80 6.4 s
30, 300 9 000 20/20 9.5 s
20, 500 (chosen) 10 000 80/80 9.8 s
10, 1000 10 000 20/20 16.7 s
30, 500 15 000 80/80 10.6 s
20, 1000 20 000 20/20 16.9 s
50, 1000 50 000 20/20 21.1 s

Walkers, not steps, are the lever — 20x300 at 6 000 evaluations beats 10x500 at 5 000. The three 20x300 failures were marginal under-convergence, which is why the leaders were re-confirmed at 80 runs rather than stopping at the first 20/20.

nwalkers=20, nsteps=500 is the smallest budget that survives the stress test, at a median 9.8 s against a 120 s ceiling. Both Emcee searches get it, so the only remaining difference between them is the initializer. The initialised fit re-checks 5/5.

CI cost is unchanged. config/build/profile_smoke.yaml sets PYAUTO_TEST_MODE: "2" — skip sampler — in defaults with no tutorial 3 override, so the sampler never runs in CI. Measured test-mode runtime before 1.81 / 1.87 / 1.89 s, after 1.50 / 1.42 / 1.41 s.

The nsteps limitation paragraph stays — it is a real teaching point — and now covers nwalkers too, with a note that a budget is only confirmed by running the fit more than once.

Found while doing this: a PyAutoFit bug (fixed separately)

Emcee.samples_via_internal_from pairs a thinned, burn-in-discarded parameter chain with an unthinned, undiscarded tail slice of the log-probability array, so every Emcee sample's reported likelihood belongs to a different sample. result.max_log_likelihood_instance is therefore the argmax of a scrambled array and the "Maximum Log Likelihood" line of every Emcee result.info is wrong. Verified independently in this session: a fit reported 188.9628 for parameters whose true likelihood under the tutorial's own Analysis is 188.8337. Zeus has the same defect via a silent zip() truncation. Tracked and fixed in PyAutoFit, not here — this PR touches only scripts/.

It does not affect the calibration above, which gates on likelihoods recomputed from the tutorial's own Analysis rather than on the reported values.

🤖 Generated with Claude Code

https://claude.ai/code/session_0132v5TNVbbvBBESAefHwnwG

Jammy2211 and others added 2 commits September 14, 2026 22:27
…se_map

Three fixes to HowToFit chapter 1, following #58.

The math sweep started in #58 now covers the rest of the chapter: tutorials
6, 7 and the optional Bayesian formalism tutorial move 12 display blocks off
`\[ \]` and 68 inline spans off `\( \)` onto `$$ $$` and `$ $`, which Jupyter
and Colab actually typeset. Conversion was AST-driven over module-level
docstrings only; `tutorial_5_results_and_samples.py` keeps its single `\[`,
which is a LaTeX row-break inside a Python string argument, not prose.

Tutorial 3's `__Priors__` block set three priors on a model that all five
fits then discarded by re-calling `af.Model(Gaussian)`, so it never applied —
and two of the three were wrong: `normalization` `Uniform(0, 10)` excludes the
true 25.0 and `sigma` `Uniform(0, 10)` puts the true 10.0 on the boundary. The
five redundant re-creations are gone, so the block now takes effect.

The prior values deliberately restate the `config/priors` defaults rather than
narrowing them, because narrowing breaks the tutorial. The first MLE fit is
meant to fail, and `af.LBFGS()` initialises with `InitializerBall(0.49, 0.51)`
— a tight ball on the centre of each prior, not a broad random draw. Under a
`normalization` of `Uniform(0, 50)` that centre is exactly 25.0, the true
value, and the fit that teaches "MLE gets stuck in a local maximum" succeeded
10/10 runs at log likelihood 176.1. Measured: config priors fail 10/10, the
narrowed candidate succeeds 10/10, the restated defaults fail 10/10 and
reproduce the baseline local maximum exactly. The prose now explains why
`normalization` wants a log-uniform prior and says plainly that these lines
restate the defaults so the searched space is visible in the script.

Separately, `Analysis.log_likelihood_function` in tutorials 3, 4 and 5 read a
module-level `noise_map` global for its noise normalization while every other
line in the method used `self.`. It returns the right number inside the
tutorial only because that global happens to exist; this is the class the
tutorials tell readers to copy into their own code, where it raises
`NameError`. Now `self.noise_map`, matching tutorials 6 and 7.

Closes #59

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132v5TNVbbvBBESAefHwnwG
The prose after the first, uninitialised Emcee fit asserts that "the MCMC
search succeeded, finding the same high-likelihood model that the MLE search
with a good starting point identified". Measured over 20 runs at the existing
`nwalkers=10, nsteps=200`, it succeeded 11 times — the tutorial asserted an
outcome it produced 55% of the time.

Both Emcee searches move to `nwalkers=20, nsteps=500`. Walkers, not steps,
were the binding constraint: 20 walkers x 300 steps (6000 evaluations) beats
10 x 500 (5000) and 10 x 200, and an ensemble of 10 is only ~3x the model
dimension. The chosen budget succeeded 80/80 in a stress test at a median 9.8s,
against 3.9s before. CI is unaffected — `config/build/profile_smoke.yaml` sets
`PYAUTO_TEST_MODE: "2"` (skip sampler) for every script with no tutorial 3
override, and the measured test-mode runtime is unchanged at ~1.5s.

Both fits get the same budget, so the only remaining difference between them
is the initializer — which is what that section claims to demonstrate.

The `nsteps` limitation paragraph stays and now covers `nwalkers` too, since
the measurement says walkers were what mattered, with a note that a budget is
only ever confirmed by running the fit more than once.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132v5TNVbbvBBESAefHwnwG
@Jammy2211 Jammy2211 changed the title docs: finish the math sweep, revive tutorial 3's priors, fix self.noise_map docs: finish the math sweep, revive tutorial 3's priors and MCMC budget, fix self.noise_map Sep 14, 2026
Base automatically changed from feature/howtofit-tutorials-1-3 to main September 14, 2026 22:49
@Jammy2211
Jammy2211 merged commit 335fdb3 into main Sep 14, 2026
7 checks passed
@Jammy2211
Jammy2211 deleted the feature/howtofit-tutorial-followups branch September 14, 2026 22:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

docs: finish the math sweep and fix tutorial 3's dead Priors block

1 participant