diff --git a/CITATION.cff b/CITATION.cff index 56c8a16..1493676 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -2,7 +2,7 @@ cff-version: 1.2.0 message: "If you use this teaching material, or the models in it, please cite it as below." title: "Teaching notebooks for IE 3315, IE 5301 and REE 4301" abstract: >- - Seventeen executed teaching notebooks and an accompanying Python package, + Eighteen executed teaching notebooks and an accompanying Python package, organised by subject across three courses in industrial engineering and energy systems modelling. Each notebook builds its model by hand and then asserts agreement with the packaged implementation, so the two cannot drift apart diff --git a/CLAUDE.md b/CLAUDE.md index 040b23a..07e88fa 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -136,7 +136,7 @@ They belong with the repository. Moved twice so far: to `C:\dev\` on 2026-09-05, ## Status, measured 2026-09-05 -Seventeen notebooks across twelve subjects (`02` empty on purpose), sixteen package modules, thirty- +Eighteen notebooks (seventeen as of 2026-09-05) across twelve subjects (`02` empty on purpose), sixteen package modules, thirty- odd tables in `data/raw/`, 170 tests, and `tools/check_notebooks.py`. README.md has the table. **What to run before believing anything:** `python -m pytest tests/ -q`, diff --git a/README.md b/README.md index e1c5560..423e7dd 100644 --- a/README.md +++ b/README.md @@ -125,7 +125,7 @@ ahead of LP formulation, which is backwards. ## What is here, measured 2026-09-05 -Seventeen teaching notebooks in twelve subjects, each with its package module, its tables and its +Eighteen teaching notebooks in twelve subjects, each with its package module, its tables and its tests. `02_simplex_and_bases` is empty on purpose. Every notebook ships executed, ends in the agreement assertion, and passes `tools/check_notebooks.py`. @@ -139,7 +139,7 @@ agreement assertion, and passes `tools/check_notebooks.py`. | 07 | `newsvendor` | `newsvendor`, `data` | | 08 | `monte_carlo` | `montecarlo` | | 09 | `markov_and_queues` | `markov`, `queueing` | -| 10 | `zero_sum_game` | `games` | +| 10 | `zero_sum_game`, `saddle_points` | `games` | | 11 | `capital_budgeting` | `capital_budgeting` | | 12 | `dispatch_to_pypsa` (own kernel — see its README) | `energy` | | 13 | `sourcing_and_resilience` | `sourcing` | diff --git a/data/raw/coin_2x2.csv b/data/raw/coin_2x2.csv new file mode 100644 index 0000000..795a9a8 --- /dev/null +++ b/data/raw/coin_2x2.csv @@ -0,0 +1,3 @@ +row,heads,tails +heads,1,-1 +tails,-1,1 diff --git a/data/raw/flu_advertising_3x4.csv b/data/raw/flu_advertising_3x4.csv new file mode 100644 index 0000000..34a5ae8 --- /dev/null +++ b/data/raw/flu_advertising_3x4.csv @@ -0,0 +1,4 @@ +row,B1,B2,B3,B4 +A1,8,-2,9,-3 +A2,6,5,6,8 +A3,-2,4,-9,5 diff --git a/notebooks/10_game_theory/README.md b/notebooks/10_game_theory/README.md index d971b4a..171670a 100644 --- a/notebooks/10_game_theory/README.md +++ b/notebooks/10_game_theory/README.md @@ -2,6 +2,11 @@ `zero_sum_game.ipynb` — a two-person zero-sum game as a pair of dual LPs. Package: `orteach.games`. +`saddle_points.ipynb` — when a game needs an LP at all: the coin game, the flu-medicine advertising +game from Taha (a saddle point at TV against TV), and the same game with that one entry changed, +which removes the saddle point (value 42/17). Same package; tables `coin_2x2.csv` and +`flu_advertising_3x4.csv`. + ## Non-zero-sum games with a planner are in the advopt repository The planner-and-game sequence — a cooperative benchmark against competing firms, best response and @@ -9,5 +14,6 @@ collusion — is the lithium supply-chain library's, and stays there: https://github.com/sear-labs/advopt-lithiumsc → 04ab_planner_and_game, and lithium/games.py -The IE 4315 zero-sum notebook (`04_Zero_Sum_Game_LP.ipynb`, in the Curriculum Working Folder) is not -this library's course and is not migrated. +`saddle_points.ipynb` migrates the three examples of `04_Zero_Sum_Game_LP.ipynb`, the notebook IE 3315 +and IE 5301 use in 2026 (in each course's code folder): same games, same numbers, built by hand +and checked against `orteach.games` instead of by a helper defined before the narration. diff --git a/notebooks/10_game_theory/saddle_points.ipynb b/notebooks/10_game_theory/saddle_points.ipynb new file mode 100644 index 0000000..ff0a541 --- /dev/null +++ b/notebooks/10_game_theory/saddle_points.ipynb @@ -0,0 +1,582 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "781da6cc", + "metadata": {}, + "source": [ + "# When the table already holds the answer, and when one entry takes it away\n", + "\n", + "`zero_sum_game.ipynb` in this folder builds both players' LPs for a game that needs them. This one\n", + "asks a prior question: when does a game need an LP at all?\n", + "\n", + "Three games. The coin game, whose answer you already know. The flu-medicine advertising game from\n", + "Taha's *Operations Research* (the game theory chapter), whose answer can be read straight off its\n", + "table. And the same advertising game with\n", + "one entry changed, whose answer cannot." + ] + }, + { + "cell_type": "markdown", + "id": "ca96b632", + "metadata": {}, + "source": [ + "## Setup: where the package lives\n", + "\n", + "This notebook builds its models by hand and then checks them against `orteach`, the package in\n", + "`src/`. Run from a clone of the repository, `../../src` is right there. On Colab there is no clone\n", + "until this cell makes one, and no `gurobipy` until it installs it. Nothing here needs a secret." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "5d1a5fd8", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:44:05.535544Z", + "iopub.status.busy": "2026-10-27T13:44:05.535365Z", + "iopub.status.idle": "2026-10-27T13:44:05.548516Z", + "shell.execute_reply": "2026-10-27T13:44:05.547915Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "package: src\\orteach\n" + ] + } + ], + "source": [ + "import os, subprocess, sys\n", + "\n", + "REPO_URL = \"https://github.com/sear-labs/teaching-code\"\n", + "REF = \"v1.0.0\" # the release this notebook ships in: Colab clones THIS\n", + "\n", + "try:\n", + " import google.colab # noqa: F401 - succeeds only on Colab\n", + " ON_COLAB = True\n", + "except ImportError:\n", + " ON_COLAB = False\n", + "\n", + "if ON_COLAB:\n", + " if not os.path.isdir(\"/content/teaching-code\"):\n", + " subprocess.run([\"git\", \"clone\", \"--quiet\", \"--depth\", \"1\", \"--branch\", REF, REPO_URL, \"/content/teaching-code\"], check=True)\n", + " os.chdir(\"/content/teaching-code/notebooks/10_game_theory\")\n", + " subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"--quiet\", \"gurobipy>=11,<14\"], check=True)\n", + "\n", + "sys.path.insert(0, os.path.abspath(os.path.join(\"..\", \"..\", \"src\")))\n", + "try:\n", + " import orteach # noqa: F401\n", + "except ImportError:\n", + " raise SystemExit(\"orteach not found: run this notebook from its own folder inside the repository, \"\n", + " \"so that ../../src exists.\")\n", + "root = os.path.abspath(os.path.join(\"..\", \"..\"))\n", + "print(\"package:\", os.path.relpath(os.path.dirname(orteach.__file__), root))" + ] + }, + { + "cell_type": "markdown", + "id": "79c19f1c", + "metadata": {}, + "source": [ + "## Licence setup\n", + "\n", + "Nothing here needs a key: `pip install gurobipy` ships a size-limited licence and the models below\n", + "sit well inside it. A machine with its own licence file uses that instead, and on Colab three\n", + "secrets read from the key icon in the left sidebar are used when they are there — three named here,\n", + "none contained. The environment starts silent, so no licence number lands in an output cell." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "3ba869c6", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:44:05.550742Z", + "iopub.status.busy": "2026-10-27T13:44:05.550568Z", + "iopub.status.idle": "2026-10-27T13:44:05.602458Z", + "shell.execute_reply": "2026-10-27T13:44:05.602042Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "licence: local gurobi.lic\n" + ] + } + ], + "source": [ + "import gurobipy as gp\n", + "from gurobipy import GRB\n", + "\n", + "env = gp.Env(empty=True)\n", + "env.setParam(\"OutputFlag\", 0) # start silent: the licence banner, and its licence number, stay out of the outputs\n", + "try:\n", + " from google.colab import userdata\n", + " try:\n", + " env.setParam(\"WLSACCESSID\", userdata.get(\"GRB_WLSACCESSID\"))\n", + " env.setParam(\"WLSSECRET\", userdata.get(\"GRB_WLSSECRET\"))\n", + " env.setParam(\"LICENSEID\", int(userdata.get(\"GRB_LICENSEID\")))\n", + " licence = \"Colab Secrets (WLS)\"\n", + " except (userdata.SecretNotFoundError, userdata.NotebookAccessError):\n", + " licence = \"the size-limited licence pip ships\" # no key needed; see the note above\n", + "except ImportError:\n", + " licence = \"local gurobi.lic\"\n", + "env.start()\n", + "print(\"licence:\", licence)" + ] + }, + { + "cell_type": "markdown", + "id": "20c5f7c6", + "metadata": {}, + "source": [ + "## The coin game\n", + "\n", + "Both players show heads or tails at once. A match pays the row player one dollar; a mismatch costs\n", + "one. Each table is instance data, so it lives in `data/raw/` and this notebook and the package read\n", + "the same file." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "2e015d18", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:44:05.604476Z", + "iopub.status.busy": "2026-10-27T13:44:05.604281Z", + "iopub.status.idle": "2026-10-27T13:44:05.615662Z", + "shell.execute_reply": "2026-10-27T13:44:05.615181Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " heads tails\n", + "heads 1 -1\n", + "tails -1 1\n" + ] + } + ], + "source": [ + "from orteach import tolerance\n", + "from orteach.games import load_game\n", + "\n", + "coin = load_game(\"coin_2x2.csv\")\n", + "print(f\"{'':7}\" + \"\".join(f\"{c:>7}\" for c in coin.cols))\n", + "for r in coin.rows:\n", + " print(f\"{r:7}\" + \"\".join(f\"{coin.payoff[r, c]:7.0f}\" for c in coin.cols))" + ] + }, + { + "cell_type": "markdown", + "id": "313846cb", + "metadata": {}, + "source": [ + "You already know the answer here. Write down the mix and the value before running, so the LP has\n", + "something to agree or disagree with. The row player's LP has one constraint per column: against\n", + "each, the expected payment must be at least $v$." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "8f3ce9b5", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:44:05.617661Z", + "iopub.status.busy": "2026-10-27T13:44:05.617490Z", + "iopub.status.idle": "2026-10-27T13:44:05.623643Z", + "shell.execute_reply": "2026-10-27T13:44:05.623173Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "value 0.0000 p {'heads': 0.5, 'tails': 0.5}\n" + ] + } + ], + "source": [ + "mc = gp.Model(\"coin, row player\", env=env)\n", + "tolerance.apply(mc)\n", + "pc = mc.addVars(coin.rows, lb=0.0, name=\"p\")\n", + "vc = mc.addVar(lb=-GRB.INFINITY, name=\"value\")\n", + "mc.addConstr(pc[\"heads\"] + pc[\"tails\"] == 1, name=\"probability\")\n", + "mc.addConstr(coin.payoff[\"heads\", \"heads\"] * pc[\"heads\"] + coin.payoff[\"tails\", \"heads\"] * pc[\"tails\"] >= vc, name=\"against[heads]\")\n", + "mc.addConstr(coin.payoff[\"heads\", \"tails\"] * pc[\"heads\"] + coin.payoff[\"tails\", \"tails\"] * pc[\"tails\"] >= vc, name=\"against[tails]\")\n", + "mc.setObjective(vc, GRB.MAXIMIZE)\n", + "mc.optimize()\n", + "coin_value = mc.ObjVal + 0.0 # + 0.0 turns a printed -0.0 into 0.0\n", + "coin_p = {r: pc[r].X for r in coin.rows}\n", + "print(f\"value {coin_value:.4f} p {({r: round(x, 4) for r, x in coin_p.items()})}\")" + ] + }, + { + "cell_type": "markdown", + "id": "715b0058", + "metadata": {}, + "source": [ + "## Taha's advertising game\n", + "\n", + "Two companies sell flu medicine. A advertises on radio, TV or in newspapers (A1–A3); B on radio,\n", + "TV, in newspapers or by e-mail (B1–B4). Each entry is the share of the market, in percent, that A\n", + "gains from B.\n", + "\n", + "Before any LP, the pure-strategy check from the lecture: the row player's maximin (the best of each\n", + "row's worst column) and the column player's minimax (the least of each column's worst row)." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "d7b26a11", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:44:05.625586Z", + "iopub.status.busy": "2026-10-27T13:44:05.625420Z", + "iopub.status.idle": "2026-10-27T13:44:05.631335Z", + "shell.execute_reply": "2026-10-27T13:44:05.630775Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " B1 B2 B3 B4\n", + "A1 8 -2 9 -3\n", + "A2 6 5 6 8\n", + "A3 -2 4 -9 5\n", + "\n", + "each row's worst {'A1': -3.0, 'A2': 5.0, 'A3': -9.0} -> maximin 5.0\n", + "each column's worst {'B1': 8.0, 'B2': 5.0, 'B3': 9.0, 'B4': 8.0} -> minimax 5.0\n" + ] + } + ], + "source": [ + "flu = load_game(\"flu_advertising_3x4.csv\")\n", + "print(f\"{'':5}\" + \"\".join(f\"{c:>5}\" for c in flu.cols))\n", + "for r in flu.rows:\n", + " print(f\"{r:5}\" + \"\".join(f\"{flu.payoff[r, c]:5.0f}\" for c in flu.cols))\n", + "\n", + "row_worst = {r: min(flu.payoff[r, c] for c in flu.cols) for r in flu.rows}\n", + "col_worst = {c: max(flu.payoff[r, c] for r in flu.rows) for c in flu.cols}\n", + "print(\"\\neach row's worst \", row_worst, \" -> maximin\", max(row_worst.values()))\n", + "print(\"each column's worst\", col_worst, \" -> minimax\", min(col_worst.values()))" + ] + }, + { + "cell_type": "markdown", + "id": "bee5ed5f", + "metadata": {}, + "source": [ + "They meet. Predict what the row player's LP will do with that, then build it: four constraints, one\n", + "per column, each reading its three coefficients from the table. The `against` dictionary keeps a\n", + "handle on each constraint, because the next section changes one of them." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "8493331d", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:44:05.633701Z", + "iopub.status.busy": "2026-10-27T13:44:05.633522Z", + "iopub.status.idle": "2026-10-27T13:44:05.641483Z", + "shell.execute_reply": "2026-10-27T13:44:05.640851Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "value 5.0000\n", + "p {'A1': 0.0, 'A2': 1.0, 'A3': 0.0}\n", + "q from the duals {'B1': 0.0, 'B2': 1.0, 'B3': 0.0, 'B4': 0.0}\n" + ] + } + ], + "source": [ + "m = gp.Model(\"advertising, row player\", env=env)\n", + "tolerance.apply(m)\n", + "p = m.addVars(flu.rows, lb=0.0, name=\"p\")\n", + "v = m.addVar(lb=-GRB.INFINITY, name=\"value\")\n", + "a = flu.payoff\n", + "m.addConstr(p[\"A1\"] + p[\"A2\"] + p[\"A3\"] == 1, name=\"probability\")\n", + "against = {}\n", + "against[\"B1\"] = m.addConstr(a[\"A1\", \"B1\"] * p[\"A1\"] + a[\"A2\", \"B1\"] * p[\"A2\"] + a[\"A3\", \"B1\"] * p[\"A3\"] >= v, name=\"against[B1]\")\n", + "against[\"B2\"] = m.addConstr(a[\"A1\", \"B2\"] * p[\"A1\"] + a[\"A2\", \"B2\"] * p[\"A2\"] + a[\"A3\", \"B2\"] * p[\"A3\"] >= v, name=\"against[B2]\")\n", + "against[\"B3\"] = m.addConstr(a[\"A1\", \"B3\"] * p[\"A1\"] + a[\"A2\", \"B3\"] * p[\"A2\"] + a[\"A3\", \"B3\"] * p[\"A3\"] >= v, name=\"against[B3]\")\n", + "against[\"B4\"] = m.addConstr(a[\"A1\", \"B4\"] * p[\"A1\"] + a[\"A2\", \"B4\"] * p[\"A2\"] + a[\"A3\", \"B4\"] * p[\"A3\"] >= v, name=\"against[B4]\")\n", + "m.setObjective(v, GRB.MAXIMIZE)\n", + "m.optimize()\n", + "flu_value = m.ObjVal\n", + "flu_p = {r: p[r].X for r in flu.rows}\n", + "flu_q = {c: -against[c].Pi + 0.0 for c in flu.cols} # minus the duals: the column player's mix (+ 0.0: no -0.0)\n", + "print(f\"value {flu_value:.4f}\")\n", + "print(\"p\", {r: round(x, 4) for r, x in flu_p.items()})\n", + "print(\"q from the duals\", {c: round(x, 4) for c, x in flu_q.items()})" + ] + }, + { + "cell_type": "markdown", + "id": "521512f7", + "metadata": {}, + "source": [ + "Nobody told the LP there was a saddle point; it put all its weight on one row anyway, and the duals\n", + "put all of B's on one column. Which cell of the table is that?\n", + "\n", + "## Change one entry\n", + "\n", + "Set A's payoff for TV against TV, the saddle cell, from 5 to 2. It is the knob this section turns,\n", + "so it is written out here and passed to everything below, including the package check." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "0ad07480", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:44:05.643847Z", + "iopub.status.busy": "2026-10-27T13:44:05.643674Z", + "iopub.status.idle": "2026-10-27T13:44:05.648202Z", + "shell.execute_reply": "2026-10-27T13:44:05.647720Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "maximin 2.0 minimax 4.0\n" + ] + } + ], + "source": [ + "TV_VS_TV = 2.0\n", + "\n", + "flu2 = load_game(\"flu_advertising_3x4.csv\")\n", + "flu2.payoff[\"A2\", \"B2\"] = TV_VS_TV\n", + "row_worst2 = {r: min(flu2.payoff[r, c] for c in flu2.cols) for r in flu2.rows}\n", + "col_worst2 = {c: max(flu2.payoff[r, c] for r in flu2.rows) for c in flu2.cols}\n", + "print(\"maximin\", max(row_worst2.values()), \" minimax\", min(col_worst2.values()))" + ] + }, + { + "cell_type": "markdown", + "id": "264bd0ab", + "metadata": {}, + "source": [ + "They no longer meet, so the value must lie strictly between them, and nothing on the table says\n", + "where. Predict the value and the support of A's mix.\n", + "\n", + "The model is still in memory. One coefficient changed, so change one coefficient: `chgCoeff` sets\n", + "the entry for $p_{A2}$ in the constraint against B2. Nothing else in the model moves." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "5b82c208", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:44:05.650129Z", + "iopub.status.busy": "2026-10-27T13:44:05.649960Z", + "iopub.status.idle": "2026-10-27T13:44:05.656118Z", + "shell.execute_reply": "2026-10-27T13:44:05.655444Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "value 2.4706\n", + "p {'A1': 0.0, 'A2': 0.7647, 'A3': 0.2353}\n", + "q from the duals {'B1': 0.0, 'B2': 0.8824, 'B3': 0.1176, 'B4': 0.0}\n", + "slack against each column {'B1': -1.6471, 'B2': 0.0, 'B3': 0.0, 'B4': -4.8235}\n" + ] + } + ], + "source": [ + "m.chgCoeff(against[\"B2\"], p[\"A2\"], TV_VS_TV)\n", + "m.optimize()\n", + "flu2_value = m.ObjVal\n", + "flu2_p = {r: p[r].X for r in flu2.rows}\n", + "flu2_q = {c: -against[c].Pi + 0.0 for c in flu2.cols}\n", + "print(f\"value {flu2_value:.4f}\")\n", + "print(\"p\", {r: round(x, 4) for r, x in flu2_p.items()})\n", + "print(\"q from the duals\", {c: round(x, 4) for c, x in flu2_q.items()})\n", + "print(\"slack against each column\", {c: round(against[c].Slack, 4) for c in flu2.cols})" + ] + }, + { + "cell_type": "markdown", + "id": "30ea09be", + "metadata": {}, + "source": [ + "Look at which columns B mixes over and which constraints have zero slack. What does complementary\n", + "slackness say the connection is, and would you have guessed those two columns from the table?\n", + "\n", + "---\n", + "\n", + "# Now the streamlined version\n", + "\n", + "Three LPs built by hand, one of them edited in place, so the package owns the construction from\n", + "here: `games.solve_row` and `games.solve_column` for the two LPs, `games.has_saddle_point` for the\n", + "check you did by hand. Each takes the same game objects, including the edited one." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "534ff4a0", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:44:05.658453Z", + "iopub.status.busy": "2026-10-27T13:44:05.658277Z", + "iopub.status.idle": "2026-10-27T13:44:05.665085Z", + "shell.execute_reply": "2026-10-27T13:44:05.664581Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "coin value 0.0000 saddle point False p {'heads': 0.5, 'tails': 0.5}\n", + "flu value 5.0000 saddle point True p {'A1': 0.0, 'A2': 1.0, 'A3': 0.0}\n", + "flu, one entry changed value 2.4706 saddle point False p {'A1': 0.0, 'A2': 0.7647, 'A3': 0.2353}\n" + ] + } + ], + "source": [ + "from orteach import games\n", + "from orteach.tolerance import AGREEMENT_RTOL, rel_diff\n", + "\n", + "pkg = {name: (games.solve_row(g, env=env), games.solve_column(g, env=env), games.has_saddle_point(g))\n", + " for name, g in ((\"coin\", coin), (\"flu\", flu), (\"flu, one entry changed\", flu2))}\n", + "for name, (row, col, saddle) in pkg.items():\n", + " print(f\"{name:24} value {row.value + 0.0:7.4f} saddle point {saddle} p {({k: round(x, 4) for k, x in row.probs.items()})}\")" + ] + }, + { + "cell_type": "markdown", + "id": "98d12b08", + "metadata": {}, + "source": [ + "## The agreement assertion\n", + "\n", + "Values and both players' strategies, hand-built against the package, for all three games. Each\n", + "optimal mix here is unique (checked when this notebook was written, by maximising and minimising\n", + "every probability over the optimal set), so whole vectors are compared, not only guarantees." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "1c83412c", + "metadata": { + "execution": { + "iopub.execute_input": "2026-10-27T13:44:05.667010Z", + "iopub.status.busy": "2026-10-27T13:44:05.666842Z", + "iopub.status.idle": "2026-10-27T13:44:05.672788Z", + "shell.execute_reply": "2026-10-27T13:44:05.672321Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "20 comparisons, plus the three saddle-point verdicts\n", + " coin value hand 0.0000 package 0.0000 rel 0.00e+00\n", + " flu value hand 5.0000 package 5.0000 rel 0.00e+00\n", + " changed value hand 2.4706 package 2.4706 rel 0.00e+00\n", + " changed: row = column value hand 2.4706 package 2.4706 rel 0.00e+00\n", + " ...\n", + "\n", + "notebook and package agree to 0.0e+00\n" + ] + } + ], + "source": [ + "checks = [(\"coin value\", coin_value, pkg[\"coin\"][0].value),\n", + " (\"flu value\", flu_value, pkg[\"flu\"][0].value),\n", + " (\"changed value\", flu2_value, pkg[\"flu, one entry changed\"][0].value),\n", + " (\"changed: row = column value\", flu2_value, pkg[\"flu, one entry changed\"][1].value)]\n", + "for r in coin.rows:\n", + " checks.append((f\"coin p[{r}]\", coin_p[r], pkg[\"coin\"][0].probs[r]))\n", + "for r in flu.rows:\n", + " checks.append((f\"flu p[{r}]\", flu_p[r], pkg[\"flu\"][0].probs[r]))\n", + " checks.append((f\"changed p[{r}]\", flu2_p[r], pkg[\"flu, one entry changed\"][0].probs[r]))\n", + "for c in flu.cols:\n", + " checks.append((f\"flu q[{c}]\", flu_q[c], pkg[\"flu\"][1].probs[c]))\n", + " checks.append((f\"changed q[{c}]\", flu2_q[c], pkg[\"flu, one entry changed\"][1].probs[c]))\n", + "assert pkg[\"flu\"][2] and not pkg[\"flu, one entry changed\"][2] and not pkg[\"coin\"][2], \"saddle-point verdicts differ\"\n", + "\n", + "worst = max(rel_diff(h, k) for _, h, k in checks)\n", + "print(f\"{len(checks)} comparisons, plus the three saddle-point verdicts\")\n", + "for name, hand, packaged in checks[:4]:\n", + " print(f\" {name:28} hand {hand + 0.0:8.4f} package {packaged + 0.0:8.4f} rel {rel_diff(hand, packaged):.2e}\")\n", + "print(\" ...\")\n", + "assert worst < AGREEMENT_RTOL, f\"notebook and package disagree by {worst:.2e}\"\n", + "print(f\"\\nnotebook and package agree to {worst:.1e}\")" + ] + }, + { + "cell_type": "markdown", + "id": "e7266bbd", + "metadata": {}, + "source": [ + "---\n", + "\n", + "## Where to take this next\n", + "\n", + "- Add 100 to every entry of the changed game and re-solve. Predict which numbers move and which do\n", + " not, then check.\n", + "- Is any of B's columns dominated in the changed game, by another column or by a mix of two? If\n", + " you find one, delete it from the table and confirm the value does not change.\n", + "- With A's mix fixed at the changed game's optimum, compute A's expected payoff against each of\n", + " B's four columns. Which ones equal the value, and is that the set B mixes over?\n", + "- Try `TV_VS_TV` at 4. Is there a saddle point, and what does the LP do?" + ] + } + ], + "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.13.9" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/tests/test_games.py b/tests/test_games.py index ce135ae..c4a358e 100644 --- a/tests/test_games.py +++ b/tests/test_games.py @@ -87,3 +87,36 @@ def test_column_optimum_is_a_segment(game, col): for d in (0.0, 0.0625, 0.125): q = {"c1": 0.0, "c2": 0.5 - 4 * d, "c3": 0.5 + 3 * d, "c4": d} assert games.worst_case(game, q, "column") <= col.value + FEASIBILITY_ATOL + + +# ---------------------------------------------------- saddle_points.ipynb (2026-10-27) + +def test_the_coin_game_is_a_fair_coin_and_worth_nothing(): + g = games.load_game("coin_2x2.csv") + r = games.solve_row(g) + assert not games.has_saddle_point(g) + assert abs(r.value) < FEASIBILITY_ATOL + assert all(abs(p - 0.5) < FEASIBILITY_ATOL for p in r.probs.values()) + + +def test_the_advertising_game_has_its_saddle_point_at_tv_against_tv(): + g = games.load_game("flu_advertising_3x4.csv") + assert games.has_saddle_point(g) + assert games.maximin(g) == (5.0, "A2") and games.minimax(g) == (5.0, "B2") + r, c = games.solve_row(g), games.solve_column(g) + assert rel_diff(r.value, 5.0) < AGREEMENT_RTOL and rel_diff(c.value, 5.0) < AGREEMENT_RTOL + assert r.support() == ["A2"] and c.support() == ["B2"] + + +def test_one_changed_entry_removes_the_saddle_point_and_the_value_is_42_over_17(): + g = games.load_game("flu_advertising_3x4.csv") + g.payoff["A2", "B2"] = 2.0 + assert not games.has_saddle_point(g) + lo, hi = games.maximin(g)[0], games.minimax(g)[0] + r, c = games.solve_row(g), games.solve_column(g) + assert lo < r.value < hi + assert rel_diff(r.value, 42 / 17) < AGREEMENT_RTOL and rel_diff(c.value, 42 / 17) < AGREEMENT_RTOL + for k, want in {"A1": 0.0, "A2": 13 / 17, "A3": 4 / 17}.items(): + assert abs(r.probs[k] - want) < FEASIBILITY_ATOL, (k, r.probs[k]) + for k, want in {"B1": 0.0, "B2": 15 / 17, "B3": 2 / 17, "B4": 0.0}.items(): + assert abs(c.probs[k] - want) < FEASIBILITY_ATOL, (k, c.probs[k]) diff --git a/tools/seeds/seed_saddle.py b/tools/seeds/seed_saddle.py new file mode 100644 index 0000000..2cc9fb8 --- /dev/null +++ b/tools/seeds/seed_saddle.py @@ -0,0 +1,292 @@ +"""Seed for the saddle-point teaching notebook (10_game_theory). Writes the notebook without outputs; execute it afterwards (README.md here).""" +import json +import os + +REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +OUT = os.path.join(REPO, "notebooks", "10_game_theory", "saddle_points.ipynb") +cells = [] + + +def md(t): + cells.append({"cell_type": "markdown", "metadata": {}, "source": t.strip("\n").splitlines(keepends=True)}) + + +def code(t): + cells.append({"cell_type": "code", "execution_count": None, "metadata": {}, "outputs": [], + "source": t.strip("\n").splitlines(keepends=True)}) + + +md(r""" +# When the table already holds the answer, and when one entry takes it away + +`zero_sum_game.ipynb` in this folder builds both players' LPs for a game that needs them. This one +asks a prior question: when does a game need an LP at all? + +Three games. The coin game, whose answer you already know. The flu-medicine advertising game from +Taha's *Operations Research* (the game theory chapter), whose answer can be read straight off its +table. And the same advertising game with +one entry changed, whose answer cannot. +""") + +md(r""" +## Setup: where the package lives + +This notebook builds its models by hand and then checks them against `orteach`, the package in +`src/`. Run from a clone of the repository, `../../src` is right there. On Colab there is no clone +until this cell makes one, and no `gurobipy` until it installs it. Nothing here needs a secret. +""") +code(r''' +import os, subprocess, sys + +REPO_URL = "https://github.com/sear-labs/teaching-code" +REF = "v1.0.0" # the release this notebook ships in: Colab clones THIS + +try: + import google.colab # noqa: F401 - succeeds only on Colab + ON_COLAB = True +except ImportError: + ON_COLAB = False + +if ON_COLAB: + if not os.path.isdir("/content/teaching-code"): + subprocess.run(["git", "clone", "--quiet", "--depth", "1", "--branch", REF, REPO_URL, "/content/teaching-code"], check=True) + os.chdir("/content/teaching-code/notebooks/10_game_theory") + subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "gurobipy>=11,<14"], check=True) + +sys.path.insert(0, os.path.abspath(os.path.join("..", "..", "src"))) +try: + import orteach # noqa: F401 +except ImportError: + raise SystemExit("orteach not found: run this notebook from its own folder inside the repository, " + "so that ../../src exists.") +root = os.path.abspath(os.path.join("..", "..")) +print("package:", os.path.relpath(os.path.dirname(orteach.__file__), root)) +''') + +md(r""" +## Licence setup + +Nothing here needs a key: `pip install gurobipy` ships a size-limited licence and the models below +sit well inside it. A machine with its own licence file uses that instead, and on Colab three +secrets read from the key icon in the left sidebar are used when they are there — three named here, +none contained. The environment starts silent, so no licence number lands in an output cell. +""") +code(r''' +import gurobipy as gp +from gurobipy import GRB + +env = gp.Env(empty=True) +env.setParam("OutputFlag", 0) # start silent: the licence banner, and its licence number, stay out of the outputs +try: + from google.colab import userdata + try: + env.setParam("WLSACCESSID", userdata.get("GRB_WLSACCESSID")) + env.setParam("WLSSECRET", userdata.get("GRB_WLSSECRET")) + env.setParam("LICENSEID", int(userdata.get("GRB_LICENSEID"))) + licence = "Colab Secrets (WLS)" + except (userdata.SecretNotFoundError, userdata.NotebookAccessError): + licence = "the size-limited licence pip ships" # no key needed; see the note above +except ImportError: + licence = "local gurobi.lic" +env.start() +print("licence:", licence) +''') + +md(r""" +## The coin game + +Both players show heads or tails at once. A match pays the row player one dollar; a mismatch costs +one. Each table is instance data, so it lives in `data/raw/` and this notebook and the package read +the same file. +""") +code(r''' +from orteach import tolerance +from orteach.games import load_game + +coin = load_game("coin_2x2.csv") +print(f"{'':7}" + "".join(f"{c:>7}" for c in coin.cols)) +for r in coin.rows: + print(f"{r:7}" + "".join(f"{coin.payoff[r, c]:7.0f}" for c in coin.cols)) +''') + +md(r""" +You already know the answer here. Write down the mix and the value before running, so the LP has +something to agree or disagree with. The row player's LP has one constraint per column: against +each, the expected payment must be at least $v$. +""") +code(r''' +mc = gp.Model("coin, row player", env=env) +tolerance.apply(mc) +pc = mc.addVars(coin.rows, lb=0.0, name="p") +vc = mc.addVar(lb=-GRB.INFINITY, name="value") +mc.addConstr(pc["heads"] + pc["tails"] == 1, name="probability") +mc.addConstr(coin.payoff["heads", "heads"] * pc["heads"] + coin.payoff["tails", "heads"] * pc["tails"] >= vc, name="against[heads]") +mc.addConstr(coin.payoff["heads", "tails"] * pc["heads"] + coin.payoff["tails", "tails"] * pc["tails"] >= vc, name="against[tails]") +mc.setObjective(vc, GRB.MAXIMIZE) +mc.optimize() +coin_value = mc.ObjVal + 0.0 # + 0.0 turns a printed -0.0 into 0.0 +coin_p = {r: pc[r].X for r in coin.rows} +print(f"value {coin_value:.4f} p {({r: round(x, 4) for r, x in coin_p.items()})}") +''') + +md(r""" +## Taha's advertising game + +Two companies sell flu medicine. A advertises on radio, TV or in newspapers (A1–A3); B on radio, +TV, in newspapers or by e-mail (B1–B4). Each entry is the share of the market, in percent, that A +gains from B. + +Before any LP, the pure-strategy check from the lecture: the row player's maximin (the best of each +row's worst column) and the column player's minimax (the least of each column's worst row). +""") +code(r''' +flu = load_game("flu_advertising_3x4.csv") +print(f"{'':5}" + "".join(f"{c:>5}" for c in flu.cols)) +for r in flu.rows: + print(f"{r:5}" + "".join(f"{flu.payoff[r, c]:5.0f}" for c in flu.cols)) + +row_worst = {r: min(flu.payoff[r, c] for c in flu.cols) for r in flu.rows} +col_worst = {c: max(flu.payoff[r, c] for r in flu.rows) for c in flu.cols} +print("\neach row's worst ", row_worst, " -> maximin", max(row_worst.values())) +print("each column's worst", col_worst, " -> minimax", min(col_worst.values())) +''') + +md(r""" +They meet. Predict what the row player's LP will do with that, then build it: four constraints, one +per column, each reading its three coefficients from the table. The `against` dictionary keeps a +handle on each constraint, because the next section changes one of them. +""") +code(r''' +m = gp.Model("advertising, row player", env=env) +tolerance.apply(m) +p = m.addVars(flu.rows, lb=0.0, name="p") +v = m.addVar(lb=-GRB.INFINITY, name="value") +a = flu.payoff +m.addConstr(p["A1"] + p["A2"] + p["A3"] == 1, name="probability") +against = {} +against["B1"] = m.addConstr(a["A1", "B1"] * p["A1"] + a["A2", "B1"] * p["A2"] + a["A3", "B1"] * p["A3"] >= v, name="against[B1]") +against["B2"] = m.addConstr(a["A1", "B2"] * p["A1"] + a["A2", "B2"] * p["A2"] + a["A3", "B2"] * p["A3"] >= v, name="against[B2]") +against["B3"] = m.addConstr(a["A1", "B3"] * p["A1"] + a["A2", "B3"] * p["A2"] + a["A3", "B3"] * p["A3"] >= v, name="against[B3]") +against["B4"] = m.addConstr(a["A1", "B4"] * p["A1"] + a["A2", "B4"] * p["A2"] + a["A3", "B4"] * p["A3"] >= v, name="against[B4]") +m.setObjective(v, GRB.MAXIMIZE) +m.optimize() +flu_value = m.ObjVal +flu_p = {r: p[r].X for r in flu.rows} +flu_q = {c: -against[c].Pi + 0.0 for c in flu.cols} # minus the duals: the column player's mix (+ 0.0: no -0.0) +print(f"value {flu_value:.4f}") +print("p", {r: round(x, 4) for r, x in flu_p.items()}) +print("q from the duals", {c: round(x, 4) for c, x in flu_q.items()}) +''') + +md(r""" +Nobody told the LP there was a saddle point; it put all its weight on one row anyway, and the duals +put all of B's on one column. Which cell of the table is that? + +## Change one entry + +Set A's payoff for TV against TV, the saddle cell, from 5 to 2. It is the knob this section turns, +so it is written out here and passed to everything below, including the package check. +""") +code(r''' +TV_VS_TV = 2.0 + +flu2 = load_game("flu_advertising_3x4.csv") +flu2.payoff["A2", "B2"] = TV_VS_TV +row_worst2 = {r: min(flu2.payoff[r, c] for c in flu2.cols) for r in flu2.rows} +col_worst2 = {c: max(flu2.payoff[r, c] for r in flu2.rows) for c in flu2.cols} +print("maximin", max(row_worst2.values()), " minimax", min(col_worst2.values())) +''') + +md(r""" +They no longer meet, so the value must lie strictly between them, and nothing on the table says +where. Predict the value and the support of A's mix. + +The model is still in memory. One coefficient changed, so change one coefficient: `chgCoeff` sets +the entry for $p_{A2}$ in the constraint against B2. Nothing else in the model moves. +""") +code(r''' +m.chgCoeff(against["B2"], p["A2"], TV_VS_TV) +m.optimize() +flu2_value = m.ObjVal +flu2_p = {r: p[r].X for r in flu2.rows} +flu2_q = {c: -against[c].Pi + 0.0 for c in flu2.cols} +print(f"value {flu2_value:.4f}") +print("p", {r: round(x, 4) for r, x in flu2_p.items()}) +print("q from the duals", {c: round(x, 4) for c, x in flu2_q.items()}) +print("slack against each column", {c: round(against[c].Slack, 4) for c in flu2.cols}) +''') + +md(r""" +Look at which columns B mixes over and which constraints have zero slack. What does complementary +slackness say the connection is, and would you have guessed those two columns from the table? + +--- + +# Now the streamlined version + +Three LPs built by hand, one of them edited in place, so the package owns the construction from +here: `games.solve_row` and `games.solve_column` for the two LPs, `games.has_saddle_point` for the +check you did by hand. Each takes the same game objects, including the edited one. +""") +code(r''' +from orteach import games +from orteach.tolerance import AGREEMENT_RTOL, rel_diff + +pkg = {name: (games.solve_row(g, env=env), games.solve_column(g, env=env), games.has_saddle_point(g)) + for name, g in (("coin", coin), ("flu", flu), ("flu, one entry changed", flu2))} +for name, (row, col, saddle) in pkg.items(): + print(f"{name:24} value {row.value + 0.0:7.4f} saddle point {saddle} p {({k: round(x, 4) for k, x in row.probs.items()})}") +''') + +md(r""" +## The agreement assertion + +Values and both players' strategies, hand-built against the package, for all three games. Each +optimal mix here is unique (checked when this notebook was written, by maximising and minimising +every probability over the optimal set), so whole vectors are compared, not only guarantees. +""") +code(r''' +checks = [("coin value", coin_value, pkg["coin"][0].value), + ("flu value", flu_value, pkg["flu"][0].value), + ("changed value", flu2_value, pkg["flu, one entry changed"][0].value), + ("changed: row = column value", flu2_value, pkg["flu, one entry changed"][1].value)] +for r in coin.rows: + checks.append((f"coin p[{r}]", coin_p[r], pkg["coin"][0].probs[r])) +for r in flu.rows: + checks.append((f"flu p[{r}]", flu_p[r], pkg["flu"][0].probs[r])) + checks.append((f"changed p[{r}]", flu2_p[r], pkg["flu, one entry changed"][0].probs[r])) +for c in flu.cols: + checks.append((f"flu q[{c}]", flu_q[c], pkg["flu"][1].probs[c])) + checks.append((f"changed q[{c}]", flu2_q[c], pkg["flu, one entry changed"][1].probs[c])) +assert pkg["flu"][2] and not pkg["flu, one entry changed"][2] and not pkg["coin"][2], "saddle-point verdicts differ" + +worst = max(rel_diff(h, k) for _, h, k in checks) +print(f"{len(checks)} comparisons, plus the three saddle-point verdicts") +for name, hand, packaged in checks[:4]: + print(f" {name:28} hand {hand + 0.0:8.4f} package {packaged + 0.0:8.4f} rel {rel_diff(hand, packaged):.2e}") +print(" ...") +assert worst < AGREEMENT_RTOL, f"notebook and package disagree by {worst:.2e}" +print(f"\nnotebook and package agree to {worst:.1e}") +''') + +md(r""" +--- + +## Where to take this next + +- Add 100 to every entry of the changed game and re-solve. Predict which numbers move and which do + not, then check. +- Is any of B's columns dominated in the changed game, by another column or by a mix of two? If + you find one, delete it from the table and confirm the value does not change. +- With A's mix fixed at the changed game's optimum, compute A's expected payoff against each of + B's four columns. Which ones equal the value, and is that the set B mixes over? +- Try `TV_VS_TV` at 4. Is there a saddle point, and what does the LP do? +""") + +nb = {"cells": cells, "metadata": {"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}, + "language_info": {"name": "python", "version": "3.13"}}, "nbformat": 4, "nbformat_minor": 5} +os.makedirs(os.path.dirname(OUT), exist_ok=True) +with open(OUT, "w", encoding="utf-8") as f: + json.dump(nb, f, indent=1, ensure_ascii=False) + f.write("\n") +print("wrote %s (%d cells)" % (OUT, len(cells)))