fundamentals

AGENTS.md — Fundamentals of Active Inference (Python Companion)

This file guides AI assistants working with the Fundamentals of Active Inference Python companion repository.

The project is open source and maintained by the Active Inference Institute; ongoing cohort-based textbook reading groups run at textbook-group.activeinference.institute. Keep that link present in user-facing docs and the web-UI footer if you restructure them.

Repository Overview

This repo provides a tested Python implementation of the algorithms described in Sanjeev V. Namjoshi’s Fundamentals of Active Inference (MIT Press, 2026), plus thin orchestrator scripts that reproduce the figures and numerical examples of Chapters 1–14 and source-map Appendix A-D coverage where executable. Chapters 1–10 are the stable Part I/II spine; Chapters 11–14 are first-class Part III companion implementations that must stay source-backed as manuscript examples are audited into tests.

This repository ships no LLM/code-generation stage: every figure, raw-data sidecar, notebook, and test in output/ is produced by a script you run and a library you can read. The intended workflow is deliberate practice — run an orchestrator, observe the artifact, change a parameter, re-run — and the validators exist to catch real gaps, not to be satisfied by patched output. See docs/learn_by_hand.md for the by-hand learning loop.

Architecture

The codebase follows a two-layer architecture:

All business logic lives in src/. Scripts orchestrate; they do not contain domain logic.

Key Directories

Directory Purpose
run.sh Top-level thin wrapper around the chapter-runner text menu.
pyproject.toml / uv.lock PEP 621 metadata; uv is the recommended package manager.
src/active_inference/ Python package (import as active_inference)
src/active_inference/source_spine.py Static PDF-derived ledger: Ch.1–14 and Appendices A-D; explicitly no Ch.15 for the inspected source.
src/active_inference/core/ Distributions, generative process/model, exact inference, LGS, diagnostics, composition, posterior protocol, validators, Appendix math/noise/model comparison, variational free energy (Ch.4), thermodynamic/FEP bridge helpers, predictive coding (Ch.5), generalized filtering (Ch.6), continuous active inference (Ch.7), continuous learning/attention/hierarchy (Ch.8), discrete POMDP + learning + factorial/hierarchical depth (Ch.9–10) in pomdp.py, and Part III helpers.
src/active_inference/estimators/ MLE, MAP, gradient descent, linear regression, EM/factor analysis, variational inference (Ch.4), predictive coding (Ch.5), generalized filtering (Ch.6), active inference (Ch.7), continuous learning/attention (Ch.8), POMDP planning + learning + two-armed bandit + hierarchical agent (Ch.9–10)
src/active_inference/visualizations/ Static plots, Ch.4 variational figures, the composable Ch.4–10 unified layer, interactive slider widgets, matplotlib animations, diagnostic figures, repo-wide colourblind-safe style
src/active_inference/utils/ Grid constructors, logger factory, path helpers, and save_chapter_data / save_extra_data NPZ+JSON export helpers
src/active_inference/menu/ Stdlib-only text menu used by run.sh
src/active_inference/web/ Stdlib-only local HTTP server used by run.sh --web
chapters/chapter_01/ 4 concept orchestrators + 1 animation + 1 interactive for Part I Ch. 1
chapters/chapter_02/ 10 examples + 1 auxiliary + 2 animations + 2 interactive
chapters/chapter_03/ 7 examples + 8 animations + 3 diagnostic visualizations + 2 interactive
chapters/chapter_04/ 5 examples + 1 animation + 3 visualizations + 1 interactive (variational inference)
chapters/chapter_05/ 6 examples + 2 animations + 1 interactive (predictive coding)
chapters/chapter_06/ generalized filtering for perception (§6.1–6.6), including correlated embedding orders and Example 6.7
chapters/chapter_07/ active generalized filtering / action (§7.1–7.5), including multivariate AIF in generalized coordinates
chapters/chapter_08/ learning, attention, and hierarchy in continuous state-spaces (§8.1–8.6)
chapters/chapter_09/ discrete POMDP active inference (§9.1–§9.6)
chapters/chapter_10/ learning & extensions (§10.1–10.4): 8 examples + 1 visualization + 3 animations
chapters/chapter_11/ Part III planning extensions: free-energy variants, sophisticated inference, tree search, preferences, forgetting, structure learning
chapters/chapter_12/ factor graphs, belief propagation, smoothing, VMP, and hybrid message bridges
chapters/chapter_13/ robotics navigation/control and social-inference application examples
chapters/chapter_14/ ergodic density, entropy bounds, Bayesian mechanics, and Markov blankets
extras/ cross-cutting topic orchestrators beyond the chapter spine, generated from the active_inference.extra_topics registry
demo/ application demos (eye saccades, bicycle, drone flight) from active_inference.demo_topics + demo_workflows
tests/ pytest unit tests + chapter/extras smoke tests + provenance validators
docs/ Architecture, notation, chapter concept maps, topic walkthroughs, uv workflow, coverage/provenance references
scripts/ Batch figure renderer (run_all_figures.py), source-spine/raw-data/rendered/provenance validators, the GNN conformance validator, and per-chapter shell wrappers
specs/ GNN declaration of the Chapter 9 weather model (weather_pomdp.gnn.md) and the pinned upstream parser revision with its parser-file digests (gnn-pin.json)
output/figures/ Generated PNGs/GIFs (gitignored, regenerated via scripts)
output/data/ Generated raw-data NPZ arrays plus JSON metadata/manifests for every saved non-interactive chapter or extras artifact
output/notebooks/ Generated Jupyter notebooks per chapter, extras topic, and demo (gitignored, regenerated via scripts/export_notebooks.py)

Ground Truth Sources

Generative-model specification (GNN)

The Chapter 9 §9.1 weather model is declared in specs/weather_pomdp.gnn.md using Generalized Notation Notation, with the upstream parser revision pinned in specs/gnn-pin.json (GNN v5.0.3, commit 8f293d9ba810e6eda5c09842d9c7ed9ffa5f92c1).

See docs/gnn.md for the commands and for what each check does and does not prove.

Conventions

Orchestrator Contract Details

Gate

./gate.sh <arm> is the one entry point; each arm is separately runnable and calls the same command the matching CI job calls. ./gate.sh --list prints the arms (lint, fast, full, docs, validators, manuscript-check, manuscript, gnn, all). There is no types arm because the repository configures no type checker. Add a command to gate.sh and have CI call that arm rather than writing the command twice. docs/gate.md records each arm’s command and measured wall time.

Testing

# Everything CI runs, in one go
./gate.sh all

# Full suite (unit tests + chapter smoke tests)
uv run pytest                                # or: pytest

# Unit tests only — skip the slow subprocess smoke tests
uv run pytest tests/core tests/estimators tests/utils tests/visualizations

# Smoke tests (run every chapter script with --save)
uv run pytest tests/chapters -v

# Demo smoke tests
uv run pytest tests/demo tests/test_demo_workflows -v

# Validate generated raw-data sidecars
uv run python scripts/validate_raw_data_exports.py --root output/data --chapters 1 2 3 4 5 6 7 8 9 10 11 12 13 14
uv run python scripts/validate_raw_data_exports.py --root output/data --demos eye_saccades bicycle drone_flight

# Validate all generated chapter and extras raw-data sidecars
uv run python scripts/validate_raw_data_exports.py --root output/data

# Validate orchestrator contracts, rendered extras coverage, and source-method provenance
uv run python scripts/validate_orchestrator_contracts.py
uv run python scripts/validate_book_topic_coverage.py --require-rendered
uv run python scripts/validate_orchestrator_provenance.py
uv run python scripts/validate_source_spine.py --require-pdf
uv run pytest tests/test_gnn_spec.py
uv run python scripts/validate_gnn_spec.py --gnn-runtime <pinned-venv>/bin/python

# Export and validate Jupyter notebooks
uv run python scripts/export_notebooks.py
uv run python scripts/validate_notebook_exports.py

# Coverage
uv run pytest --cov=active_inference --cov-report=term-missing

Coverage targets: 90%+ for src/active_inference/ (excluding thin wrappers that mainly glue imports).

How to Add a New Example

  1. Add a method or class to the appropriate src/active_inference/ submodule (with corresponding unit tests in tests/<sub>/).
  2. Create a thin orchestrator in the appropriate chapters/chapter_<N>/, extras/<topic>/, or demo/<slug>/ directory (≤ ~120 lines; imports only from active_inference, stdlib, and narrowly scoped numpy / matplotlib / existing scipy rendering glue). Put reusable workflow logic in src/active_inference/, not in the wrapper.
  3. Accept --save; add --seed whenever the script samples or otherwise depends on pseudo-randomness.
  4. Document the script in the chapter or extras topic README.md.
  5. Ensure --save writes reconstructable raw data. Prefer plotting through save_or_show / save_animation; if the script has non-plotted arrays, call save_chapter_data(chapter, stem, arrays, metadata, figures=...) for chapter scripts, save_extra_data(topic, stem, arrays, metadata, figures=...) for extras, or save_demo_data(slug, stem, arrays, metadata, figures=...) for demos.
  6. The smoke tests and active_inference.menu discovery pick the file up automatically as long as it follows the example_*.py / animation_*.py / visualize_*.py / interactive_*.py / 0N_*.py naming convention.
  7. scripts/run_all_figures.py discovers the same way — no edit needed.

Environment management