Repository navigation
docs: finish the math sweep, revive tutorial 3's priors and MCMC budget, fix self.noise_map - #60
Merged
Merged
Conversation
…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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #59. The follow-ups reported out of #57 / #58, plus one bug found while doing them.
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.\[ \]→$$\( \)→$…$tutorial_6_gradients.pytutorial_7_the_details.pytutorial_optional_bayesian_formalism.pyConversion 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 toaf.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 wrongIt set three priors on a model that all five fits then discarded by calling
af.Model(Gaussian)again beforesearch.fit. So it never applied, and the fits silently ranconfig/priors/gaussian.yaml:centreUniform(0, 100)Uniform(0, 100)— identicalnormalizationUniform(0, 10)— excludes the truthLogUniform(1e-6, 1e6)sigmaUniform(0, 10)— truth on the boundaryUniform(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
normalizationto something that contains 25.0 — breaks the tutorial, and not subtly.af.LBFGS()'s default initializer isInitializerBall(lower_limit=0.49, upper_limit=0.51): a tight ball on the centre of each prior, not a broad random draw. Undernormalization = 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,Analysisand dataset (the tutorial itself was not modified to measure):normalizationUniform(0, 50),sigmaUniform(0, 25)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):
Prose
The claim "we are using
UniformPriorsin this tutorial due to their simplicity" was false —normalizationruns log-uniform. Replaced with an explanation of why a parameter spanning orders of magnitude wants aLogUniformPrior, 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_mapAnalysis.log_likelihood_functionin tutorials 3, 4 and 5 computedreading 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 raisesNameError. It broke the measurement harness above on first run, which is how it surfaced.Now
self.noise_mapin all three, matching tutorials 6 and 7, which were already correct. Checked the whole chapter: the remaining barenoise_mapuses are module-level scripts or a genuine function parameter (tutorial_2_fitting_data.py'slog_likelihood_from), and are correct.Testing
python .github/scripts/run_smoke.py— exit 0, 18/18 PASS, 0 FAIL (23 found, 5 excluded byno_run.yaml).black --check scripts/chapter_1_introduction/— clean, 11 files unchanged.\[, 0\(. Tutorial 5's one\[survives in a code cell, as intended.tutorial_8_scientific_workflow.ipynbstill 0 code cells.llms-full.txt/workspace_index.jsonregenerate 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=200it 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.6at 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.
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=500is 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.yamlsetsPYAUTO_TEST_MODE: "2"— skip sampler — indefaultswith 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
nstepslimitation paragraph stays — it is a real teaching point — and now coversnwalkerstoo, 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_frompairs 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_instanceis therefore the argmax of a scrambled array and the "Maximum Log Likelihood" line of every Emceeresult.infois wrong. Verified independently in this session: a fit reported 188.9628 for parameters whose true likelihood under the tutorial's ownAnalysisis 188.8337.Zeushas the same defect via a silentzip()truncation. Tracked and fixed in PyAutoFit, not here — this PR touches onlyscripts/.It does not affect the calibration above, which gates on likelihoods recomputed from the tutorial's own
Analysisrather than on the reported values.🤖 Generated with Claude Code
https://claude.ai/code/session_0132v5TNVbbvBBESAefHwnwG