{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# Lecture 0 — The Pantheon+ fit with one LangGraph agent\n\n*Multi-Agent Systems for Science · Boris Bolliet, University of Cambridge*\n\nWe ask one LangGraph agent to fit the matter density $\\Omega_m$ to Pantheon+ data ten times. The agent can write and run Python scripts. We compare its results with an independent fit and record calls, time and cost for Section 5 of the notes.",
   "id": "l01sa-00"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Setup\n\nSet `GOOGLE_API_KEY` as a Colab secret or an environment variable before starting Jupyter. To trace model calls, also set `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_SECRET_KEY` and `LANGFUSE_BASE_URL` from your Langfuse project. The saved runs were untraced.\n\nEach run has its own working directory. Scripts run in fresh processes with a 120 s limit and no API keys in their environment, but can still access your files. Use Colab or a container to isolate the work.",
   "id": "l01sa-01"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:38:28.419327Z",
     "iopub.status.busy": "2026-11-16T18:38:28.419074Z",
     "iopub.status.idle": "2026-11-16T18:38:28.913624Z",
     "shell.execute_reply": "2026-11-16T18:38:28.913008Z"
    }
   },
   "source": "%pip install -q langgraph langchain langchain-google-genai langfuse numpy scipy pandas",
   "execution_count": 1,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "id": "l01sa-02"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:38:28.915092Z",
     "iopub.status.busy": "2026-11-16T18:38:28.914971Z",
     "iopub.status.idle": "2026-11-16T18:38:29.643420Z",
     "shell.execute_reply": "2026-11-16T18:38:29.643066Z"
    }
   },
   "source": "%matplotlib inline\nimport json, os, platform, re, shutil, subprocess, sys, tempfile, time, urllib.request, warnings\nfrom datetime import datetime, timezone\nfrom importlib.metadata import version\nfrom pathlib import Path\n\nwarnings.filterwarnings(\"ignore\", category=SyntaxWarning)  # emitted by google-genai when it is first compiled\nimport numpy as np\nimport pandas as pd\nfrom IPython.display import display\nfrom scipy.integrate import cumulative_trapezoid\nfrom scipy.linalg import cho_factor, cho_solve\nfrom scipy.optimize import brentq, minimize_scalar\n\npd.set_option(\"display.width\", 160)\npd.set_option(\"display.max_columns\", 30)\nRESULTS_DIR = Path(\"results/table3\")\nRESULTS_DIR.mkdir(parents=True, exist_ok=True)\n\n\ndef installed(package):\n    try:\n        return version(package)\n    except Exception:\n        return None\n\nimport ast, threading\nfrom langchain.chat_models import init_chat_model\nfrom langchain_core.messages import HumanMessage, SystemMessage, ToolMessage\nfrom langchain_core.tools import tool\nfrom langgraph.graph import END, START, MessagesState, StateGraph\n\nVERSIONS = {\"python\": platform.python_version()} | {p: installed(p) for p in [\n    \"langgraph\", \"langchain\", \"langchain-core\", \"langchain-google-genai\", \"langfuse\", \"numpy\", \"scipy\", \"pandas\"]}\nprint(VERSIONS)",
   "execution_count": 2,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'python': '3.12.12', 'langgraph': '1.2.22', 'langchain': '1.5.0', 'langchain-core': '1.8.1', 'langchain-google-genai': '4.5.0', 'langfuse': '5.2.0', 'numpy': '2.5.4', 'scipy': '1.18.1', 'pandas': '3.1.1'}\n"
     ]
    }
   ],
   "id": "l01sa-03"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "### Model and run settings\n\n`MODEL` uses LangChain's `provider:model` form. Changing provider requires its integration package and key. The recorded cost uses gemini-3.1-flash-lite prices of US\\$0.25 per million input tokens and US\\$1.50 per million output tokens, including reasoning.",
   "id": "l01sa-04"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:38:29.644544Z",
     "iopub.status.busy": "2026-11-16T18:38:29.644455Z",
     "iopub.status.idle": "2026-11-16T18:38:29.646026Z",
     "shell.execute_reply": "2026-11-16T18:38:29.645721Z"
    }
   },
   "source": "ORGANISATION = \"single agent (LangGraph, code-execution tool)\"\nMODEL = \"google_genai:gemini-3.1-flash-lite\"\nRUNS = 10\nPRICE_INPUT, PRICE_OUTPUT = 0.25e-6, 1.50e-6   # US dollars per token, list price of gemini-3.1-flash-lite\nEXEC_TIMEOUT = 120          # seconds allowed to one script\nOUTPUT_LIMIT = 3000         # characters of script output returned to the model\nMAX_TURNS = 10              # model calls of one run",
   "execution_count": 3,
   "outputs": [],
   "id": "l01sa-05"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:38:29.646783Z",
     "iopub.status.busy": "2026-11-16T18:38:29.646739Z",
     "iopub.status.idle": "2026-11-16T18:38:29.762603Z",
     "shell.execute_reply": "2026-11-16T18:38:29.762175Z"
    }
   },
   "source": "def secret(name):\n    # A Colab secret if one exists, else an environment variable, else None.\n    try:\n        from google.colab import userdata\n        try:\n            return userdata.get(name)\n        except Exception:\n            return os.environ.get(name)\n    except ImportError:\n        return os.environ.get(name)\n\n\nGOOGLE_API_KEY = secret(\"GOOGLE_API_KEY\") or \"\"\nassert GOOGLE_API_KEY, \"Set GOOGLE_API_KEY as a Colab secret or as an environment variable.\"\nos.environ[\"GOOGLE_API_KEY\"] = GOOGLE_API_KEY\nos.environ.pop(\"GEMINI_API_KEY\", None)     # the client prints a notice when both variables are set\nLANGFUSE = {name: secret(name) for name in (\"LANGFUSE_PUBLIC_KEY\", \"LANGFUSE_SECRET_KEY\", \"LANGFUSE_BASE_URL\")}\nTRACED = all(LANGFUSE.values())\nprint(\"Langfuse tracing:\", \"on\" if TRACED else \"off\")\n\nllm = init_chat_model(MODEL, **({\"max_retries\": 1} if MODEL.startswith(\"google_genai:\") else {}))\nCALLBACKS = []\nif TRACED:\n    os.environ.update(LANGFUSE)\n    from langfuse.langchain import CallbackHandler\n    CALLBACKS = [CallbackHandler()]",
   "execution_count": 4,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Langfuse tracing: off\n"
     ]
    }
   ],
   "id": "l01sa-06"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "### Accounting and code execution\n\n`ask` records each completed model call in a `Ledger` and retries temporary API errors. `run_code` saves and executes a script, then returns its exit code and output to the model. Long outputs are shortened to `OUTPUT_LIMIT` characters.",
   "id": "l01sa-07"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:38:29.763515Z",
     "iopub.status.busy": "2026-11-16T18:38:29.763466Z",
     "iopub.status.idle": "2026-11-16T18:38:29.767520Z",
     "shell.execute_reply": "2026-11-16T18:38:29.767148Z"
    }
   },
   "source": "RETRY_ON = (\"429\", \"RESOURCE_EXHAUSTED\", \"RateLimit\", \"rate limit\", \"500\", \"503\", \"UNAVAILABLE\", \"overloaded\")\n\n\nclass Ledger:\n    def __init__(self):\n        self.start, self.calls, self.lock = time.perf_counter(), [], threading.Lock()\n\n\ndef ask(model, messages, ledger, attempts=6):\n    t0, waited = time.perf_counter(), 0.0\n    for attempt in range(attempts):\n        try:\n            reply = model.invoke(messages, {\"callbacks\": CALLBACKS})\n            break\n        except Exception as error:\n            message = f\"{type(error).__name__}: {error}\"\n            if attempt == attempts - 1 or not any(marker in message for marker in RETRY_ON):\n                raise\n            hint = re.search(r\"retry in (\\d+(?:\\.\\d+)?)\\s*s\", message)\n            delay = min(float(hint.group(1)) + 1 if hint else 5 * 2**attempt, 90)\n            time.sleep(delay)\n            waited += delay\n    usage = reply.usage_metadata or {}\n    with ledger.lock:\n        ledger.calls.append({\"t0\": t0 - ledger.start, \"t1\": time.perf_counter() - ledger.start, \"wait_s\": waited,\n                             \"input_tokens\": usage.get(\"input_tokens\", 0), \"output_tokens\": usage.get(\"output_tokens\", 0),\n                             \"reasoning_tokens\": (usage.get(\"output_token_details\") or {}).get(\"reasoning\", 0)})\n    return reply\n\n\nSAFE_ENV = {key: os.environ[key] for key in (\"PATH\", \"HOME\", \"LANG\", \"PYTHONPATH\", \"LD_LIBRARY_PATH\", \"SYSTEMROOT\", \"TEMP\", \"TMP\")\n            if key in os.environ}\n\n\ndef clip(text, limit=OUTPUT_LIMIT):\n    if len(text) <= limit:\n        return text\n    return text[: limit // 3] + f\"\\n[... {len(text) - limit} characters omitted ...]\\n\" + text[-2 * limit // 3:]\n\n\ndef run_code(code, workdir, ledger):\n    path = workdir / f\"script_{len(list(workdir.glob('script_*.py'))) + 1:02d}.py\"\n    path.write_text(code)\n    t0 = time.perf_counter()\n    try:\n        done = subprocess.run([sys.executable, path.name], cwd=workdir, capture_output=True, text=True,\n                              timeout=EXEC_TIMEOUT, env=SAFE_ENV | {\"MPLBACKEND\": \"Agg\"})\n        returncode, stdout, stderr = done.returncode, done.stdout, done.stderr\n    except subprocess.TimeoutExpired as error:\n        stdout = error.stdout.decode() if isinstance(error.stdout, bytes) else (error.stdout or \"\")\n        returncode, stderr = -1, f\"TimeoutExpired: the script was stopped after {EXEC_TIMEOUT} s.\"\n    report = f\"{path.name}: exit code {returncode} after {time.perf_counter() - t0:.1f} s\\n--- stdout ---\\n{clip(stdout)}\"\n    return report + (f\"\\n--- stderr ---\\n{clip(stderr)}\" if stderr.strip() else \"\")\n\n\ndef parse_tagged(text, tag):\n    for candidate in reversed(re.findall(re.escape(tag) + r\"\\W*?(\\{[^{}]*\\})\", text or \"\", flags=re.S)):\n        for parse in (json.loads, ast.literal_eval):\n            try:\n                return parse(candidate)\n            except (ValueError, SyntaxError):\n                pass\n    return None\n\n\ndef number(value):\n    try:\n        return float(value)\n    except (TypeError, ValueError):\n        return None",
   "execution_count": 5,
   "outputs": [],
   "id": "l01sa-08"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 1. Data\n\nPantheon+ contains 1701 light curves of Type Ia supernovae from 18 surveys (Scolnic et al. 2022; Brout et al. 2022). Some supernovae have more than one light curve.\n\nWe use `zHD` for the Hubble-diagram redshift, `zHEL` for the heliocentric redshift, and `m_b_corr` for the standardised peak magnitude. The full statistical and systematic covariance is in `Pantheon+SH0ES_STAT+SYS.cov`. We cache both files in `data/` and select rows with $z_\\mathrm{HD}>0.01$.",
   "id": "l01sa-09"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:38:29.768348Z",
     "iopub.status.busy": "2026-11-16T18:38:29.768303Z",
     "iopub.status.idle": "2026-11-16T18:38:29.900160Z",
     "shell.execute_reply": "2026-11-16T18:38:29.899825Z"
    }
   },
   "source": "DATA_URL = \"https://raw.githubusercontent.com/PantheonPlusSH0ES/DataRelease/main/Pantheon%2B_Data/4_DISTANCES_AND_COVAR/\"\nDATA_DIR = Path(\"data\")\nDATA_DIR.mkdir(exist_ok=True)\nTABLE_PATH = (DATA_DIR / \"Pantheon+SH0ES.dat\").resolve()\nCOV_PATH = (DATA_DIR / \"Pantheon+SH0ES_STAT+SYS.cov\").resolve()\nfor path, remote in [(TABLE_PATH, \"Pantheon%2BSH0ES.dat\"), (COV_PATH, \"Pantheon%2BSH0ES_STAT%2BSYS.cov\")]:\n    if not path.exists():\n        partial = path.with_suffix(\".part\")\n        urllib.request.urlretrieve(DATA_URL + remote, partial)\n        partial.rename(path)\n\ntable = pd.read_csv(TABLE_PATH, sep=r\"\\s+\")\nvalues = np.loadtxt(COV_PATH)\ncov = values[1:].reshape(int(values[0]), int(values[0]))\nselected = table[table.zHD > 0.01]\nprint(f\"{len(table)} light curves; zHD > 0.01 keeps {len(selected)} light curves of {selected.CID.nunique()} supernovae\")",
   "execution_count": 6,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1701 light curves; zHD > 0.01 keeps 1590 light curves of 1473 supernovae\n"
     ]
    }
   ],
   "id": "l01sa-10"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 2. Reference fit\n\nWe compute an independent reference fit for grading. The model magnitude is\n$$m = 5\\log_{10}(d_L/\\mathrm{Mpc}) + 25 + M, \\qquad d_L=(1+z_\\mathrm{HEL})D_C(z_\\mathrm{HD}),$$\nwhere $D_C$ is the comoving distance in flat ΛCDM with $H_0=70$ km/s/Mpc. At each $\\Omega_m$, we minimise $\\chi^2$ analytically over the offset $M$, using the full covariance.\n\nWe then minimise over $\\Omega_m$ and find the interval with $\\Delta\\chi^2\\leq1$. Half its width gives the quoted uncertainty. The agents receive the analysis requirements, but not this reference result.",
   "id": "l01sa-11"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:38:29.901256Z",
     "iopub.status.busy": "2026-11-16T18:38:29.901202Z",
     "iopub.status.idle": "2026-11-16T18:38:30.174513Z",
     "shell.execute_reply": "2026-11-16T18:38:30.174138Z"
    }
   },
   "source": "C_KM_S, H0 = 299792.458, 70.0\n\n\ndef reference_fit():\n    keep = (table.zHD > 0.01).to_numpy()\n    m, z, z_hel = (table.loc[keep, c].to_numpy() for c in (\"m_b_corr\", \"zHD\", \"zHEL\"))\n    C = cov[np.ix_(keep, keep)]\n    factor = cho_factor(C)\n    ones = np.ones(len(m))\n    ones_C_ones = ones @ cho_solve(factor, ones)\n\n    def chi2(omega_m):\n        grid = np.linspace(0.0, z.max() * 1.001, 20001)\n        D_C = cumulative_trapezoid(1 / np.sqrt(omega_m * (1 + grid) ** 3 + 1 - omega_m), grid, initial=0) * C_KM_S / H0\n        r = m - 5 * np.log10((1 + z_hel) * np.interp(z, grid, D_C)) - 25\n        C_r = cho_solve(factor, r)\n        return r @ C_r - (ones @ C_r) ** 2 / ones_C_ones\n\n    best = minimize_scalar(chi2, bounds=(0.01, 0.99), method=\"bounded\", options={\"xatol\": 1e-6})\n    lower = brentq(lambda x: chi2(x) - best.fun - 1, 0.001, best.x)\n    upper = brentq(lambda x: chi2(x) - best.fun - 1, best.x, 0.999)\n    return {\"omega_m\": best.x, \"omega_m_err\": (upper - lower) / 2, \"chi2_min\": best.fun, \"n_sn\": int(keep.sum())}\n\n\nREFERENCE = reference_fit()\nprint(f\"full covariance:  Omega_m = {REFERENCE['omega_m']:.4f} ± {REFERENCE['omega_m_err']:.4f} (chi2 = {REFERENCE['chi2_min']:.1f}, N = {REFERENCE['n_sn']})\")",
   "execution_count": 7,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "full covariance:  Omega_m = 0.3316 ± 0.0182 (chi2 = 1402.9, N = 1590)\n"
     ]
    }
   ],
   "id": "l01sa-12"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 3. Task\n\nAll three notebooks use the same task statement. It specifies the data selection, model, full covariance and fitting procedure. Each run receives the data in a fresh working directory. We test whether the agents implement this prescribed analysis reliably.\n\nThe system prompt describes the code-execution tool and requests a `FINAL` line for grading.",
   "id": "l01sa-13"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:38:30.175637Z",
     "iopub.status.busy": "2026-11-16T18:38:30.175580Z",
     "iopub.status.idle": "2026-11-16T18:38:30.177767Z",
     "shell.execute_reply": "2026-11-16T18:38:30.177410Z"
    }
   },
   "source": "TASK = '''Measure the matter density Omega_m of a flat LCDM cosmology from the Pantheon+ type Ia supernovae.\n\nData\n- Table: data/Pantheon+SH0ES.dat (in the working directory)\n  Whitespace-separated with one header row; columns include zHD, zHEL, zCMB, m_b_corr, m_b_corr_err_DIAG, RA, DEC.\n- Covariance: data/Pantheon+SH0ES_STAT+SYS.cov (in the working directory)\n  Statistical plus systematic covariance of m_b_corr. The first line is N = 1701; the N*N entries follow,\n  one per line, in row-major order; rows and columns follow the rows of the table.\n\nRequirements\n1. Use the light curves (table rows) with zHD > 0.01.\n2. Model: m_b_corr = 5 log10(d_L / Mpc) + 25 + M, with d_L = (1 + zHEL) D_C(zHD) and D_C the comoving distance of a flat LCDM cosmology with H0 = 70 km/s/Mpc.\n3. M is a free offset: minimise chi^2 over M analytically at each Omega_m.\n4. Weight the residuals with the full statistical and systematic covariance matrix, restricted to the rows and columns of the selected supernovae.\n5. Report Omega_m, its 1-sigma uncertainty from Delta chi^2 = 1, chi^2 at the minimum and the number of light curves (table rows) used.'''\nprint(TASK)\n\n\ndef new_workdir(prefix):\n    # A fresh working directory holding only data/ with the two Pantheon+ files.\n    work = Path(tempfile.mkdtemp(prefix=prefix))\n    (work / \"data\").mkdir()\n    for path in (TABLE_PATH, COV_PATH):\n        shutil.copy(path, work / \"data\" / path.name)\n    return work\n\nSYSTEM = f'''You are an astrophysicist who analyses data with Python.\nUse the run_python tool to execute scripts. Each call starts a fresh Python process in a working directory that\nkeeps the files written by earlier calls. Available packages: numpy, scipy, pandas, matplotlib.\nScripts are stopped after {EXEC_TIMEOUT} s, and output beyond {OUTPUT_LIMIT} characters is shortened.\nWhen the analysis is complete, reply with a short report whose last line is\nFINAL {{\"omega_m\": <value>, \"omega_m_err\": <value>, \"chi2_min\": <value>, \"n_sn\": <value>, \"covariance\": \"full\" or \"diagonal\"}}'''",
   "execution_count": 8,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Measure the matter density Omega_m of a flat LCDM cosmology from the Pantheon+ type Ia supernovae.\n",
      "\n",
      "Data\n",
      "- Table: data/Pantheon+SH0ES.dat (in the working directory)\n",
      "  Whitespace-separated with one header row; columns include zHD, zHEL, zCMB, m_b_corr, m_b_corr_err_DIAG, RA, DEC.\n",
      "- Covariance: data/Pantheon+SH0ES_STAT+SYS.cov (in the working directory)\n",
      "  Statistical plus systematic covariance of m_b_corr. The first line is N = 1701; the N*N entries follow,\n",
      "  one per line, in row-major order; rows and columns follow the rows of the table.\n",
      "\n",
      "Requirements\n",
      "1. Use the light curves (table rows) with zHD > 0.01.\n",
      "2. Model: m_b_corr = 5 log10(d_L / Mpc) + 25 + M, with d_L = (1 + zHEL) D_C(zHD) and D_C the comoving distance of a flat LCDM cosmology with H0 = 70 km/s/Mpc.\n",
      "3. M is a free offset: minimise chi^2 over M analytically at each Omega_m.\n",
      "4. Weight the residuals with the full statistical and systematic covariance matrix, restricted to the rows and columns of the selected supernovae.\n",
      "5. Report Omega_m, its 1-sigma uncertainty from Delta chi^2 = 1, chi^2 at the minimum and the number of light curves (table rows) used.\n"
     ]
    }
   ],
   "id": "l01sa-14"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 4. Runs\n\nThe graph alternates between `agent` and `tools` while the model requests code execution. It ends when the model answers without a tool call or reaches `MAX_TURNS`. We measure the elapsed time of each run.",
   "id": "l01sa-15"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:38:30.178700Z",
     "iopub.status.busy": "2026-11-16T18:38:30.178655Z",
     "iopub.status.idle": "2026-11-16T18:40:43.101149Z",
     "shell.execute_reply": "2026-11-16T18:40:43.099733Z"
    }
   },
   "source": "def make_agent(workdir, ledger):\n    @tool\n    def run_python(code: str) -> str:\n        \"Run a Python script in a fresh process and return its exit code and printed output.\"\n        return run_code(code, workdir, ledger)\n\n    model = llm.bind_tools([run_python])\n\n    def agent(state: MessagesState):\n        return {\"messages\": [ask(model, state[\"messages\"], ledger)]}\n\n    def tools(state: MessagesState):\n        outputs = []\n        for call in state[\"messages\"][-1].tool_calls:\n            try:\n                content = run_python.invoke(call[\"args\"])\n            except Exception as error:\n                content = f\"Tool error: {error}\"\n            outputs.append(ToolMessage(content, tool_call_id=call[\"id\"]))\n        return {\"messages\": outputs}\n\n    def after_agent(state: MessagesState):\n        return \"tools\" if state[\"messages\"][-1].tool_calls and len(ledger.calls) < MAX_TURNS else END\n\n    graph = StateGraph(MessagesState)\n    graph.add_node(\"agent\", agent)\n    graph.add_node(\"tools\", tools)\n    graph.add_edge(START, \"agent\")\n    graph.add_conditional_edges(\"agent\", after_agent, [\"tools\", END])\n    graph.add_edge(\"tools\", \"agent\")\n    return graph.compile()\n\n\ndef run_once(i):\n    ledger, workdir = Ledger(), new_workdir(\"l01_sa_\")\n    state = make_agent(workdir, ledger).invoke({\"messages\": [SystemMessage(SYSTEM), HumanMessage(TASK)]},\n                                               {\"recursion_limit\": 4 * MAX_TURNS, \"callbacks\": CALLBACKS})\n    final = parse_tagged(state[\"messages\"][-1].text, \"FINAL\") or {}\n    calls = ledger.calls\n    input_tokens, output_tokens = sum(c[\"input_tokens\"] for c in calls), sum(c[\"output_tokens\"] for c in calls)\n    return {\"run\": i, \"omega_m\": number(final.get(\"omega_m\")), \"omega_m_err\": number(final.get(\"omega_m_err\")),\n            \"n_sn\": final.get(\"n_sn\"), \"covariance_reported\": final.get(\"covariance\"), \"calls\": len(calls),\n            \"scripts\": len(list(workdir.glob(\"script_*.py\"))), \"input_tokens\": input_tokens, \"output_tokens\": output_tokens,\n            \"reasoning_tokens\": sum(c[\"reasoning_tokens\"] for c in calls),\n            \"time_s\": round(time.perf_counter() - ledger.start, 1),\n            \"cost_usd\": round(input_tokens * PRICE_INPUT + output_tokens * PRICE_OUTPUT, 5)}\n\n\nRUNS_DONE = []\nfor i in range(1, RUNS + 1):\n    RUNS_DONE.append(run_once(i))\n    run = RUNS_DONE[-1]\n    print(f\"run {i}: Omega_m = {run['omega_m']} ± {run['omega_m_err']}, {run['calls']} calls, {run['scripts']} scripts, \"\n          f\"{run['time_s']} s, ${run['cost_usd']}\")",
   "execution_count": 9,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "run 1: Omega_m = 0.3316 ± 0.0182, 5 calls, 4 scripts, 11.0 s, $0.00577\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "run 2: Omega_m = None ± None, 4 calls, 3 scripts, 12.4 s, $0.00535\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "run 3: Omega_m = 0.3316 ± 0.0182, 4 calls, 3 scripts, 14.1 s, $0.0055\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "run 4: Omega_m = 0.3316 ± 0.0182, 3 calls, 2 scripts, 7.4 s, $0.00342\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "run 5: Omega_m = 0.33158 ± 0.01819, 6 calls, 5 scripts, 14.7 s, $0.00902\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "run 6: Omega_m = None ± None, 10 calls, 9 scripts, 25.8 s, $0.02213\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "run 7: Omega_m = 0.3316 ± 0.0182, 3 calls, 2 scripts, 7.3 s, $0.00382\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "run 8: Omega_m = 0.3316 ± 0.0182, 3 calls, 2 scripts, 7.6 s, $0.00363\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "run 9: Omega_m = 0.3316 ± 0.0182, 5 calls, 4 scripts, 15.7 s, $0.0076\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "run 10: Omega_m = 0.3316 ± 0.0185, 6 calls, 5 scripts, 17.0 s, $0.00831\n"
     ]
    }
   ],
   "id": "l01sa-16"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 5. Grading\n\nA run matches when its estimate and uncertainty are each within 0.005 of the reference: $|\\Omega_m-0.3316|\\leq0.005$ and $|\\sigma-0.0182|\\leq0.005$. This tolerance is about a quarter of the statistical uncertainty. The grade checks numerical agreement; it does not verify the method described in a report.",
   "id": "l01sa-17"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:40:43.103515Z",
     "iopub.status.busy": "2026-11-16T18:40:43.103358Z",
     "iopub.status.idle": "2026-11-16T18:40:43.119394Z",
     "shell.execute_reply": "2026-11-16T18:40:43.118472Z"
    }
   },
   "source": "ROW_COLUMNS = [\"run\", \"grade\", \"omega_m\", \"omega_m_err\", \"n_sn\", \"covariance_reported\", \"calls\", \"scripts\", \"time_s\", \"cost_usd\"]\nPRIVATE_KEYS = set()\n\nTOLERANCE = 0.005\n\n\ndef grade(omega_m, omega_m_err):\n    if omega_m is None:\n        return \"no result\"\n    if abs(omega_m - REFERENCE[\"omega_m\"]) > TOLERANCE:\n        return \"wrong\"\n    if omega_m_err is None or abs(omega_m_err - REFERENCE[\"omega_m_err\"]) > TOLERANCE:\n        return \"wrong uncertainty\"\n    return \"match\"\n\n\nfor run in RUNS_DONE:\n    run[\"grade\"] = grade(run[\"omega_m\"], run[\"omega_m_err\"])\ndisplay(pd.DataFrame([{k: run.get(k) for k in ROW_COLUMNS} for run in RUNS_DONE]))",
   "execution_count": 10,
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>run</th>\n",
       "      <th>grade</th>\n",
       "      <th>omega_m</th>\n",
       "      <th>omega_m_err</th>\n",
       "      <th>n_sn</th>\n",
       "      <th>covariance_reported</th>\n",
       "      <th>calls</th>\n",
       "      <th>scripts</th>\n",
       "      <th>time_s</th>\n",
       "      <th>cost_usd</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>match</td>\n",
       "      <td>0.33160</td>\n",
       "      <td>0.01820</td>\n",
       "      <td>1590.0</td>\n",
       "      <td>full</td>\n",
       "      <td>5</td>\n",
       "      <td>4</td>\n",
       "      <td>11.0</td>\n",
       "      <td>0.00577</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>no result</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>12.4</td>\n",
       "      <td>0.00535</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3</td>\n",
       "      <td>match</td>\n",
       "      <td>0.33160</td>\n",
       "      <td>0.01820</td>\n",
       "      <td>1590.0</td>\n",
       "      <td>full</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>14.1</td>\n",
       "      <td>0.00550</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4</td>\n",
       "      <td>match</td>\n",
       "      <td>0.33160</td>\n",
       "      <td>0.01820</td>\n",
       "      <td>1590.0</td>\n",
       "      <td>full</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>7.4</td>\n",
       "      <td>0.00342</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>5</td>\n",
       "      <td>match</td>\n",
       "      <td>0.33158</td>\n",
       "      <td>0.01819</td>\n",
       "      <td>1590.0</td>\n",
       "      <td>full</td>\n",
       "      <td>6</td>\n",
       "      <td>5</td>\n",
       "      <td>14.7</td>\n",
       "      <td>0.00902</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>6</td>\n",
       "      <td>no result</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>10</td>\n",
       "      <td>9</td>\n",
       "      <td>25.8</td>\n",
       "      <td>0.02213</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>7</td>\n",
       "      <td>match</td>\n",
       "      <td>0.33160</td>\n",
       "      <td>0.01820</td>\n",
       "      <td>1590.0</td>\n",
       "      <td>full</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>7.3</td>\n",
       "      <td>0.00382</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>8</td>\n",
       "      <td>match</td>\n",
       "      <td>0.33160</td>\n",
       "      <td>0.01820</td>\n",
       "      <td>1590.0</td>\n",
       "      <td>full</td>\n",
       "      <td>3</td>\n",
       "      <td>2</td>\n",
       "      <td>7.6</td>\n",
       "      <td>0.00363</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>9</td>\n",
       "      <td>match</td>\n",
       "      <td>0.33160</td>\n",
       "      <td>0.01820</td>\n",
       "      <td>1590.0</td>\n",
       "      <td>full</td>\n",
       "      <td>5</td>\n",
       "      <td>4</td>\n",
       "      <td>15.7</td>\n",
       "      <td>0.00760</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>10</td>\n",
       "      <td>match</td>\n",
       "      <td>0.33160</td>\n",
       "      <td>0.01850</td>\n",
       "      <td>1590.0</td>\n",
       "      <td>full</td>\n",
       "      <td>6</td>\n",
       "      <td>5</td>\n",
       "      <td>17.0</td>\n",
       "      <td>0.00831</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   run      grade  omega_m  omega_m_err    n_sn covariance_reported  calls  scripts  time_s  cost_usd\n",
       "0    1      match  0.33160      0.01820  1590.0                full      5        4    11.0   0.00577\n",
       "1    2  no result      NaN          NaN     NaN                 NaN      4        3    12.4   0.00535\n",
       "2    3      match  0.33160      0.01820  1590.0                full      4        3    14.1   0.00550\n",
       "3    4      match  0.33160      0.01820  1590.0                full      3        2     7.4   0.00342\n",
       "4    5      match  0.33158      0.01819  1590.0                full      6        5    14.7   0.00902\n",
       "5    6  no result      NaN          NaN     NaN                 NaN     10        9    25.8   0.02213\n",
       "6    7      match  0.33160      0.01820  1590.0                full      3        2     7.3   0.00382\n",
       "7    8      match  0.33160      0.01820  1590.0                full      3        2     7.6   0.00363\n",
       "8    9      match  0.33160      0.01820  1590.0                full      5        4    15.7   0.00760\n",
       "9   10      match  0.33160      0.01850  1590.0                full      6        5    17.0   0.00831"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "id": "l01sa-18"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 6. Results\n\nWe summarise the matches, calls, time and cost for the comparison in Section 5 of the notes. The summary and individual run records are saved in `results/table3/`.\n\nCosts use the model's list prices; times cover complete runs.",
   "id": "l01sa-19"
  },
  {
   "cell_type": "code",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-16T18:40:43.121054Z",
     "iopub.status.busy": "2026-11-16T18:40:43.120936Z",
     "iopub.status.idle": "2026-11-16T18:40:43.127649Z",
     "shell.execute_reply": "2026-11-16T18:40:43.127138Z"
    }
   },
   "source": "ROW = {\n    \"organisation\": ORGANISATION,\n    \"runs\": len(RUNS_DONE),\n    \"matches\": sum(run[\"grade\"] == \"match\" for run in RUNS_DONE),\n    \"calls_mean\": round(float(np.mean([run[\"calls\"] for run in RUNS_DONE])), 1),\n    \"calls_range\": [min(run[\"calls\"] for run in RUNS_DONE), max(run[\"calls\"] for run in RUNS_DONE)],\n    \"time_s_mean\": round(float(np.mean([run[\"time_s\"] for run in RUNS_DONE])), 1),\n    \"time_s_range\": [min(run[\"time_s\"] for run in RUNS_DONE), max(run[\"time_s\"] for run in RUNS_DONE)],\n    \"cost_usd_mean\": round(float(np.mean([run[\"cost_usd\"] for run in RUNS_DONE])), 4) if all(run[\"cost_usd\"] is not None for run in RUNS_DONE) else None,\n    \"cost_usd_range\": [min(run[\"cost_usd\"] for run in RUNS_DONE), max(run[\"cost_usd\"] for run in RUNS_DONE)] if all(run[\"cost_usd\"] is not None for run in RUNS_DONE) else None,\n    \"cost\": \"list price of gemini-3.1-flash-lite: 0.25 USD per M input, 1.50 USD per M output tokens\",\n    \"time\": \"recorded wall time of a run\",\n}\nprint(f\"{ROW['organisation']}: {ROW['matches']}/{ROW['runs']} match; calls {ROW['calls_mean']} (range {ROW['calls_range']}); \"\n      f\"time {ROW['time_s_mean']} s (range {ROW['time_s_range']}); cost ${ROW['cost_usd_mean']} (range {ROW['cost_usd_range']})\")\nRECORD = {\"meta\": {\"date_utc\": datetime.now(timezone.utc).isoformat(timespec=\"seconds\"), \"model\": MODEL, \"versions\": VERSIONS,\n                     \"traced\": TRACED, \"tolerance\": TOLERANCE,\n                     \"reference\": {\"full\": REFERENCE}},\n          \"row\": ROW, \"runs\": [{k: v for k, v in run.items() if k not in PRIVATE_KEYS} for run in RUNS_DONE]}\n(RESULTS_DIR / \"single_agent.json\").write_text(json.dumps(RECORD, indent=1, default=str) + \"\\n\")\nprint(\"saved\", RESULTS_DIR / \"single_agent.json\")",
   "execution_count": 11,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "single agent (LangGraph, code-execution tool): 8/10 match; calls 4.9 (range [3, 10]); time 13.3 s (range [7.3, 25.8]); cost $0.0075 (range [0.00342, 0.02213])\n",
      "saved results/table3/single_agent.json\n"
     ]
    }
   ],
   "id": "l01sa-20"
  }
 ],
 "metadata": {
  "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.12.12"
  },
  "post_run_edits": [
   {
    "date_utc": "2026-11-16T20:18:48+00:00",
    "change": "Removed the diagonal-reference comparison and its grading category; revised explanatory prose.",
    "code_cells": [
     "l01sa-12",
     "l01sa-18",
     "l01sa-20"
    ],
    "validation": "Full-covariance reference recomputed locally; all recorded runs regraded; summary exports checked in scratch.",
    "reference_unchanged": true,
    "grades_and_summary_unchanged": true,
    "agent_code_and_prompts_unchanged": true,
    "agent_outputs_unchanged": true,
    "model_calls_made": 0
   }
  ]
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
