{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a06b26ae",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "In this notebook we code the **Q-learning** algorithm on the tabular\n",
    "`MazeMDP-v0` environment: a $Q$-table updated by temporal differences, with\n",
    "$\\epsilon$-greedy exploration.\n",
    "\n",
    "Q-learning is *off-policy*: the update uses $\\max_a Q(s', a)$ (the greedy\n",
    "action) regardless of the (exploratory) action actually taken."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "db06ed79",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "**On Colab**: run the installation cell below (generated automatically,\n",
    "pinned versions). **Locally**: install the environment with `uv sync`, no\n",
    "need for this cell."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8e7e27d1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gymnasium as gym\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import rl_mind.mazemdp_env\n",
    "from dataclasses import dataclass, replace\n",
    "from mazemdp.toolbox import egreedy\n",
    "from tqdm.auto import tqdm\n",
    "from rl_mind.notebook import silence_known_warnings\n",
    "from rl_mind.mazemdp_env import MazeMDPEnv\n",
    "from rl_mind.profiles import Profile"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7bdf48b5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44e5b55f",
   "metadata": {},
   "source": [
    "# The maze\n",
    "\n",
    "`MazeMDP-v0` has discrete states (integer indices) and 4 actions. We create a\n",
    "small 5×5 maze."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "82c3d73c",
   "metadata": {},
   "outputs": [],
   "source": [
    "mdp = gym.make(\n",
    "    \"MazeMDP-v0\",\n",
    "    kwargs={\"width\": 5, \"height\": 5, \"ratio\": 0.2, \"hit\": 0.0, \"start_states\": [0]},\n",
    "    render_mode=\"human\",\n",
    ")\n",
    "env = mdp.unwrapped\n",
    "env.reset()\n",
    "env.init_draw(\"The maze\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fdfe47af",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# The Q-learning update\n",
    "\n",
    "For a transition $(s, a, r, s')$, Q-learning regresses $Q(s, a)$ towards the\n",
    "bootstrapped target $r + \\gamma \\max_{a'} Q(s', a')$:\n",
    "\n",
    "$$ Q(s, a) \\leftarrow Q(s, a) + \\alpha\\,\\big[\\, r + \\gamma\\,(1 -\n",
    "\\text{terminated})\\,\\max_{a'} Q(s', a') - Q(s, a) \\,\\big] $$\n",
    "\n",
    "where $\\alpha$ is the learning rate. When $s'$ is a **terminal** state, the\n",
    "bootstrap term is dropped (there is no future)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ac67ec07",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def q_learning_update(\n",
    "    q: np.ndarray,\n",
    "    alpha: float,\n",
    "    gamma: float,\n",
    "    state: int,\n",
    "    action: int,\n",
    "    reward: float,\n",
    "    next_state: int,\n",
    "    terminated: bool,\n",
    ") -> float:\n",
    "    \"\"\"Update the Q-table in place; return the TD error\n",
    "\n",
    "    :param q: The Q-table, shape `[nb_states, nb_actions]`\n",
    "    \"\"\"\n",
    "    # Compute the TD error and update Q(s, a)\n",
    "\n",
    "    max_next_q = ...\n",
    "    td_error = ...\n",
    "    q[state, action] += ...\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7a4f9b3c",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Hyper-parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "95624a2b",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "@dataclass(frozen=True)\n",
    "class QLearningConfig:\n",
    "    seed: int = 0\n",
    "    #: Number of training episodes\n",
    "    nb_episodes: int = Profile.pick(1_000, fast_test=20)\n",
    "    #: Learning rate and discount factor\n",
    "    alpha: float = 0.5\n",
    "    gamma: float = 0.99\n",
    "    #: epsilon-greedy exploration, decayed each episode\n",
    "    epsilon_start: float = 0.7\n",
    "    epsilon_end: float = 0.05\n",
    "    epsilon_decay: float = 0.999\n",
    "    #: Episodes between two evaluations, and number of evaluation episodes\n",
    "    eval_interval: int = Profile.pick(50, fast_test=5)\n",
    "    nb_evals: int = 20"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7fdb93e0",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Evaluation\n",
    "\n",
    "We evaluate the greedy policy ($\\arg\\max_a Q(s, a)$) by running a few episodes\n",
    "and averaging the cumulated reward."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed15390d",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def evaluate(mdp, q: np.ndarray, nb_episodes: int) -> float:\n",
    "    rewards = []\n",
    "    for _ in range(nb_episodes):\n",
    "        state, _ = mdp.reset(options={\"uniform\": True})\n",
    "        terminated = truncated = False\n",
    "        total = 0.0\n",
    "        while not (terminated or truncated):\n",
    "            state, r, terminated, truncated, _ = mdp.step(int(q[state].argmax()))\n",
    "            total += r\n",
    "        rewards.append(total)\n",
    "    return float(np.mean(rewards))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "84d3fd53",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Main training loop\n",
    "\n",
    "Each episode: reset the maze, then repeatedly pick an $\\epsilon$-greedy\n",
    "action, step, and apply the Q-learning update — until the episode ends."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b6888134",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_q_learning(cfg: QLearningConfig):\n",
    "    np.random.seed(cfg.seed)\n",
    "    q = np.zeros((env.nb_states, env.action_space.n))\n",
    "    epsilon = cfg.epsilon_start\n",
    "    history = []\n",
    "\n",
    "    for episode in tqdm(range(cfg.nb_episodes)):\n",
    "        state, _ = mdp.reset(options={\"uniform\": True})\n",
    "        terminated = truncated = False\n",
    "        while not (terminated or truncated):\n",
    "            action = egreedy(q, state, epsilon)\n",
    "            next_state, reward, terminated, truncated, _ = mdp.step(action)\n",
    "            q_learning_update(\n",
    "                q, cfg.alpha, cfg.gamma, state, action, reward, next_state, terminated\n",
    "            )\n",
    "            state = next_state\n",
    "\n",
    "        epsilon = max(epsilon * cfg.epsilon_decay, cfg.epsilon_end)\n",
    "\n",
    "        if episode % cfg.eval_interval == 0:\n",
    "            history.append((episode, evaluate(mdp, q, cfg.nb_evals)))\n",
    "\n",
    "    return q, history"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0f12373b",
   "metadata": {},
   "outputs": [],
   "source": [
    "cfg = QLearningConfig()\n",
    "q, history = run_q_learning(cfg)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2c2c102a",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The learned value function and greedy policy on the maze, and the learning\n",
    "curve."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b3d790d4",
   "metadata": {},
   "outputs": [],
   "source": [
    "env.current_state = 0\n",
    "env.draw_v_pi(q.max(axis=1), q.argmax(axis=1), title=\"Q-learning: V and policy\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3a4a274f",
   "metadata": {},
   "outputs": [],
   "source": [
    "episodes, rewards = zip(*history)\n",
    "plt.plot(episodes, rewards)\n",
    "plt.xlabel(\"episode\")\n",
    "plt.ylabel(\"mean cumulated reward\")\n",
    "plt.title(\"Q-learning on MazeMDP-v0\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "792eb6df",
   "metadata": {},
   "source": [
    "## Exercise\n",
    "\n",
    "Turn this into **SARSA** (on-policy): replace $\\max_{a'} Q(s', a')$ in the\n",
    "target with $Q(s', a')$ where $a'$ is the *next* $\\epsilon$-greedy action\n",
    "actually taken. Compare the value functions the two methods converge to,\n",
    "especially near risky states."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "A Q-table updated by temporal differences, on the MazeMDP environment",
   "practical_name": "Q-learning"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
