{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4daeeb39",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    " Copyright © Sorbonne University.\n",
    "\n",
    " This source code is licensed under the MIT license found in the LICENSE file\n",
    " in the root directory of this source tree."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "53d164c9",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "In this notebook, we study the **value iteration** and **policy\n",
    "iteration** algorithms in a maze environment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6eb25cab",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gymnasium as gym\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import torch\n",
    "import rl_mind.mazemdp_env\n",
    "from pathlib import Path\n",
    "from typing import List, Tuple\n",
    "from mazemdp import random_policy\n",
    "from torch import Tensor\n",
    "from rl_mind.notebook import silence_known_warnings\n",
    "from rl_mind.mazemdp_env import MazeMDPEnv\n",
    "from rl_mind.profiles import Profile\n",
    "from rl_mind.core import Action, Actor\n",
    "from rl_mind.env import VecEnv\n",
    "from rl_mind.evaluation import Evaluator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6c5b5edf",
   "metadata": {
    "tags": [
     "colab",
     "pip",
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "# Installing required packages\n",
    "\n",
    "%pip install swig==4.3.* setuptools\n",
    "\n",
    "# Installing main packages\n",
    "\n",
    "%pip install gymnasium==1.2.* matplotlib mazemdp==1.3.* numpy rl-mind==0.4.* torch\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "627e08cf",
   "metadata": {
    "tags": [
     "colab"
    ]
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    # Allows to enable custom widgets\n",
    "    from google.colab import output\n",
    "\n",
    "    output.enable_custom_widget_manager()\n",
    "except ModuleNotFoundError:\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2385c890",
   "metadata": {},
   "source": [
    "# Installation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "da8dcd01",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "674f49a5",
   "metadata": {},
   "source": [
    "# Agents and MDPs\n",
    "\n",
    "A reinforcement learning agent interacts with an environment represented as a\n",
    "Markov Decision Process (MDP). It is defined by a tuple $(S, A, P, r, \\gamma)$\n",
    "where $S$ is the state space, $A$ is the action space, $P(state_t, action_t,\n",
    "state_{t+1})$ is the transition function, $r(state_t, action_t)$ is the reward\n",
    "function and $\\gamma \\in [0, 1]$ is the discount factor.\n",
    "\n",
    "In what follows we import code to create an MDP corresponding to a maze\n",
    "(see https://github.com/osigaud/SimpleMazeMDP for documentation).\n",
    "\n",
    "The mazes below are drawn at random, but from a **seed**: the walls then come\n",
    "from a private random generator, so that the same seed always gives back the\n",
    "same maze, whatever else was drawn in between. Two consequences: your results\n",
    "are reproducible from one run to the next, and the very same description\n",
    "rebuilds *the same* maze elsewhere — which is what we need at the end of the\n",
    "notebook, where `VecEnv` constructs its own copies of the environment (an\n",
    "unseeded maze would give a different layout in each copy).\n",
    "\n",
    "Change `MAZE` to work on a bigger problem: the larger the maze, the longer\n",
    "dynamic programming takes to converge, and the less likely a random walk is\n",
    "to ever reach the goal. Changing a seed simply gives another maze of the same\n",
    "size."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23bff145",
   "metadata": {},
   "outputs": [],
   "source": [
    "MAZES = {\n",
    "    \"small\": {\"width\": 5, \"height\": 5, \"ratio\": 0.2, \"seed\": 2},  # 20 states\n",
    "    \"medium\": {\"width\": 8, \"height\": 8, \"ratio\": 0.2, \"seed\": 0},  # 51 states\n",
    "    \"large\": {\"width\": 10, \"height\": 10, \"ratio\": 0.2, \"seed\": 1},  # 80 states\n",
    "}\n",
    "\n",
    "MAZE = MAZES[\"small\"]\n",
    "\n",
    "env = gym.make(\"MazeMDP-v0\", kwargs=MAZE, render_mode=\"human\")\n",
    "env.reset()\n",
    "\n",
    "# in dynamic programming, there is no agent moving in the environment\n",
    "env.unwrapped.set_no_agent()\n",
    "env.unwrapped.init_draw(\"The maze\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "15b22e12",
   "metadata": {},
   "source": [
    "Dynamic programming\n",
    "\n",
    "The goal of an RL agent is to find the optimal behaviour, defined by a policy\n",
    "$\\pi$ that assigns an action (or distribution over actions) to each state so\n",
    "as to maximize the agent's total expected reward. In order to estimate how\n",
    "good a state is, either a state value function $V(x)$ or a state-action value\n",
    "function $Q(s, a)$ is used.\n",
    "\n",
    "Dynamic programming algorithms are used for planning, they require a full\n",
    "knowledge of the MDP from the agent (in contrast to \"true\" RL where the agent\n",
    "does not know the transition and reward functions). They find the optimal\n",
    "policy by computing a value function $V$ or an action-value function $Q$ over\n",
    "the state space or state-action space of the given MDP. **Value iteration**\n",
    "and **policy iteration** are two standard dynamic programming algorithms. You\n",
    "should study both of them using both $V$ and $Q$, as these algorithms contain\n",
    "the basic building blocks for most RL algorithms.\n",
    "\n",
    "# Value Iteration\n",
    "\n",
    "## Value Iteration with the V function\n",
    "\n",
    "When using the $V$ function, **value iteration** aims at finding the optimal\n",
    "values $V^*$ based on the Bellman Optimality Equation: $$V^*(s) = \\max_a\n",
    "\\big[r(s,a) + \\gamma \\sum_{y \\in S} P(s,a,y)V^*(y) \\big],$$ where:\n",
    "\n",
    "*   $r(s, a)$ is the reward obtained from taking action $a$ in state $s$,\n",
    "*   $P(s, a, y)$ is the probability of reaching state $y$ when taking action\n",
    "    $a$ in state $s$,\n",
    "*   $\\gamma \\in [0,1]$ is a discount factor defining the relative importance\n",
    "    of long term rewards over short term ones (the closer to 0, the more the\n",
    "    agent focuses on immediate rewards).\n",
    "\n",
    "In practice, we start with an initial value function $V^0$ (for instance, the\n",
    "values of all states are 0), and then we iterate for all states $s$\n",
    "$$V^{i+1}(s) = \\max_a \\big[ r(s,a) + \\gamma \\sum_{y \\in S} P(s,a,y)V^i(y)\n",
    "\\big],$$\n",
    "\n",
    "until the values converge, that is $\\forall s, V^{i+1}(s) \\approx V^i(s)$. It\n",
    "is shown that at convergence, $\\forall s, V^i(s)= V^*(s)$.\n",
    "\n",
    "To visualize the policy obtained from **value iteration**, we need to first\n",
    "define the `get_policy_from_V()` function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ec139ac1",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def get_policy_from_v(mdp: MazeMDPEnv, v: np.ndarray) -> np.ndarray:\n",
    "    \"\"\"Outputs a policy given the state values\"\"\"\n",
    "\n",
    "    # Sets initial state values are set to 0\n",
    "    policy = np.zeros(mdp.nb_states)\n",
    "\n",
    "    # Loop over MDP states\n",
    "    for s in range(mdp.nb_states):\n",
    "        if s in mdp.terminal_states:\n",
    "            # Takes the reward associated with the terminal state\n",
    "            policy[s] = np.argmax(mdp.r[s, :])\n",
    "        else:\n",
    "            # Compute the value V(x) for state x\n",
    "            v_temp = []\n",
    "\n",
    "            # Loop over actions\n",
    "            for a in range(mdp.action_space.n):\n",
    "                # Process sum of the values of the neighbouring states\n",
    "                summ = 0\n",
    "                for y in range(mdp.nb_states):\n",
    "                    summ = summ + mdp.P[s, a, y] * v[y]\n",
    "                v_temp.append(mdp.r[s, a] + mdp.gamma * summ)\n",
    "            policy[s] = np.argmax(v_temp)\n",
    "    return policy"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0daf16d2",
   "metadata": {},
   "source": [
    "The `value_iteration_v(mdp)` function below provides the code of **value\n",
    "iteration** using the $V$ function. It is given as an example from which you\n",
    "can derive other instances of dynamic programming algorithms. Look at it more\n",
    "closely, this will help for later questions:\n",
    "\n",
    "* you can ignore the `mdp.new_render()` and `mdp.render(...)` functions which\n",
    "  are here to provide the visualization of the iterations.\n",
    "* find in the code the loop over states, the main loop that performs these\n",
    "  updates until the values don't change significantly anymore, the main update\n",
    "  equation. Found them? OK, you can continue..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b57540b4",
   "metadata": {},
   "outputs": [],
   "source": [
    "def value_iteration_v(\n",
    "    mdp: MazeMDPEnv, render: bool = True\n",
    ") -> Tuple[np.ndarray, List[float]]:\n",
    "    # Value Iteration using the state value v\n",
    "    v = np.zeros(mdp.nb_states)  # initial state values are set to 0\n",
    "    v_list = []\n",
    "    stop = False\n",
    "\n",
    "    mdp.init_draw(\"Value iteration V\")\n",
    "\n",
    "    mdp.draw_v(v)\n",
    "\n",
    "    while not stop:\n",
    "        v_old = v.copy()\n",
    "        mdp.draw_v(v)\n",
    "\n",
    "        for s in range(mdp.nb_states):  # for each state x\n",
    "            # Compute the value of the state x for each action u of the MDP action space\n",
    "            if s in mdp.terminal_states:\n",
    "                v[s] = np.max(mdp.r[s, :])\n",
    "            else:\n",
    "                v_temp = []\n",
    "                for a in range(mdp.action_space.n):\n",
    "                    # Process sum of the values of the neighbouring states\n",
    "                    summ = 0\n",
    "                    for y in range(mdp.nb_states):\n",
    "                        summ = summ + mdp.P[s, a, y] * v_old[y]\n",
    "                    v_temp.append(mdp.r[s, a] + mdp.gamma * summ)\n",
    "\n",
    "                # Select the highest state value among those computed\n",
    "                v[s] = np.max(v_temp)\n",
    "\n",
    "        # Test if convergence has been reached\n",
    "        if (np.linalg.norm(v - v_old)) < 0.01:\n",
    "            stop = True\n",
    "        v_list.append(np.linalg.norm(v))\n",
    "\n",
    "    policy = get_policy_from_v(mdp, v)\n",
    "    mdp.draw_v_pi(v, policy)\n",
    "    return v, v_list"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e2288ca",
   "metadata": {},
   "source": [
    "Let us run it on the previously defined MDP"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ac83b8e6",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "v, v_list = value_iteration_v(env.unwrapped, render=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e4fd618",
   "metadata": {},
   "source": [
    "### Value iteration with the $Q$ function ###\n",
    "\n",
    "The state-action value function $Q^{\\pi}(s,a)$ defines the value of being in\n",
    "state $s$, taking action $a$ then following policy $\\pi$. The Bellman\n",
    "Optimality Equation for $Q^*$ is $$ Q^*(s,a) =  r(s,a) + \\gamma \\sum_{y}\n",
    "P(s,a,y) \\max_{a'}Q^*(y,a'). $$\n",
    "\n",
    "**Question:** By taking inspiration from the `value_iteration_v(mdp)` function\n",
    "above, fill the blank (given with '\\#Q[s, a]=...') in the code of\n",
    "`value_iteration_q(mdp)`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "48869af8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ------------------ Value Iteration with the Q function ---------------------#\n",
    "# Given a MDP, this algorithm computes the optimal action value function Q\n",
    "# It then derives the optimal policy based on this function\n",
    "\n",
    "\n",
    "def value_iteration_q(\n",
    "    mdp: MazeMDPEnv, render: bool = True\n",
    ") -> Tuple[np.ndarray, List[float]]:\n",
    "    q = np.zeros(\n",
    "        (mdp.nb_states, mdp.action_space.n)\n",
    "    )  # initial action values are set to 0\n",
    "    q_list = []\n",
    "    stop = False\n",
    "\n",
    "    mdp.init_draw(\"Value iteration Q\")\n",
    "\n",
    "    mdp.draw_v(q)\n",
    "\n",
    "    while not stop:\n",
    "        qold = q.copy()\n",
    "\n",
    "        mdp.draw_v(q)\n",
    "\n",
    "        for s in range(mdp.nb_states):\n",
    "            for a in range(mdp.action_space.n):\n",
    "                if s in mdp.terminal_states:\n",
    "                    q[s, a] = mdp.r[s, a]\n",
    "                else:\n",
    "                    summ = 0\n",
    "                    for y in range(mdp.nb_states):\n",
    "                        summ += mdp.P[s, a, y] * np.max(qold[y, :])\n",
    "\n",
    "                    # Compléter d'après la formule ci-dessus\n",
    "\n",
    "                    q[s, a] = ...\n",
    "                    assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "        if (np.linalg.norm(q - qold)) <= 0.01:\n",
    "            stop = True\n",
    "        q_list.append(np.linalg.norm(q))\n",
    "\n",
    "    mdp.draw_v(q)\n",
    "\n",
    "    return q, q_list"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "08b6ce9f",
   "metadata": {},
   "source": [
    "Once you are done, run it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6b2f2f1e",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "q, q_list = value_iteration_q(env.unwrapped, render=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9332f9a3",
   "metadata": {},
   "source": [
    "## Policy Iteration ##\n",
    "\n",
    "The **policy iteration** algorithm is more complicated than **value\n",
    "iteration**. Given a MDP and a policy $\\pi$, **policy iteration** iterates the\n",
    "following steps:\n",
    "\n",
    "*   Evaluate policy $\\pi$: compute $V$ or $Q$ based on the policy $\\pi$;\n",
    "*   Improve policy $\\pi$: compute a better policy based on $V$ or $Q$.\n",
    "\n",
    "This process is repeated until convergence, i.e. when the policy cannot be\n",
    "improved anymore.\n",
    "\n",
    "### Policy iteration with the $V$ function ###\n",
    "\n",
    "When using $V$, $V^{\\pi}(s)$ is the expected return when starting from state\n",
    "$s$ and following policy $\\pi$. It is processed based on the Bellman\n",
    "Optimality Equation for deterministic policies:\n",
    "\n",
    "$$V^\\pi(s) = r(s, \\pi(s)) + \\gamma \\sum_{y \\in S}P(s, \\pi(s), y)V^\\pi(y),$$\n",
    "\n",
    "where:\n",
    "\n",
    "*   $\\pi$ is a deterministic policy, meaning that in a state $s$, the agent\n",
    "    always selects the same action,\n",
    "*   $V^\\pi(y)$ is the value of the state $y$ under policy $\\pi$.\n",
    "\n",
    "Thus, given a policy $\\pi$, one must first compute its value function\n",
    "$V^\\pi(s)$ for all states $s$ iterating the Bellman Optimality Equation until\n",
    "convergence, that is using **value iteration**. Then, one must determine if\n",
    "policy $\\pi$ can be improved based on $V$. For that, in each state $s$, one\n",
    "can compute the Q-value $Q(s,a)$ of applying action $a$ and then following\n",
    "policy $\\pi$ based on the just computed $V^\\pi$, and replace the action\n",
    "$\\pi(s)$ with $\\arg\\max_a Q(s,a)$.\n",
    "\n",
    "In order to facilitate the coding of **policy iteration** algorithms, we first\n",
    "define a set of useful functions.\n",
    "\n",
    "The `improve_policy_from_v(mdp, v, policy)` function is very similar to the\n",
    "`get_policy_from_v(v)` function which was given above. The main difference is\n",
    "that it takes a policy as argument and improves this policy when possible,\n",
    "thus is more in the spirit of the `policy improvement` step of **policy\n",
    "iteration**. But both functions can be used interchangeably.\n",
    "\n",
    "The functions `evaluate_one_step_v(mdp, v, policy)`, where `mdp` is a given\n",
    "MDP, `v` is some value function in this MDP and `policy` is some policy and\n",
    "the function `evaluate_v(mdp, policy)` are also given. These functions are\n",
    "used to build the value function $V^\\pi$ corresponding to policy $\\pi$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20af0e5c",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def improve_policy_from_v(\n",
    "    mdp: MazeMDPEnv, v: np.ndarray, policy: np.ndarray\n",
    ") -> np.ndarray:\n",
    "    # Improves a policy given the state values\n",
    "    for s in range(mdp.nb_states):  # for each state x\n",
    "        # Compute the value of the state x for each action u of the MDP action space\n",
    "        if s in mdp.terminal_states:\n",
    "            policy[s] = np.argmax(mdp.r[s, :])\n",
    "        else:\n",
    "            v_temp = np.zeros(mdp.action_space.n)\n",
    "            for a in range(mdp.action_space.n):\n",
    "                # Process sum of the values of the neighbouring states\n",
    "                summ = 0\n",
    "                for y in range(mdp.nb_states):\n",
    "                    summ = summ + mdp.P[s, a, y] * v[y]\n",
    "                v_temp[a] = mdp.r[s, a] + mdp.gamma * summ\n",
    "\n",
    "            for a in range(mdp.action_space.n):\n",
    "                if v_temp[a] > v_temp[policy[s]]:\n",
    "                    policy[s] = a\n",
    "    return policy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb791326",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def evaluate_one_step_v(\n",
    "    mdp: MazeMDPEnv, v: np.ndarray, policy: np.ndarray\n",
    ") -> np.ndarray:\n",
    "    # Outputs the state value function after one step of policy evaluation\n",
    "    # Corresponds to one application of the Bellman Operator\n",
    "    v_new = np.zeros(mdp.nb_states)  # initial state values are set to 0\n",
    "    for s in range(mdp.nb_states):  # for each state x\n",
    "        # Compute the value of the state x for each action u of the MDP action space\n",
    "        if s in mdp.terminal_states:\n",
    "            v_new[s] = mdp.r[s, policy[s]]\n",
    "        else:\n",
    "            # Process sum of the values of the neighbouring states\n",
    "            summ = 0\n",
    "            for y in range(mdp.nb_states):\n",
    "                summ = summ + mdp.P[s, policy[s], y] * v[y]\n",
    "            v_new[s] = mdp.r[s, policy[s]] + mdp.gamma * summ\n",
    "    return v_new"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "113c21ba",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def evaluate_v(mdp: MazeMDPEnv, policy: np.ndarray) -> np.ndarray:\n",
    "    # Outputs the state value function of a policy\n",
    "    v = np.zeros(mdp.nb_states)  # initial state values are set to 0\n",
    "    stop = False\n",
    "    while not stop:\n",
    "        vold = v.copy()\n",
    "        v = evaluate_one_step_v(mdp, vold, policy)\n",
    "\n",
    "        # Test if convergence has been reached\n",
    "        if (np.linalg.norm(v - vold)) < 0.01:\n",
    "            stop = True\n",
    "    return v"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e356d91",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "To perform **policy iteration** we also need an initial random policy."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c4fc078",
   "metadata": {},
   "source": [
    "**Question:** By using the above functions, fill the code of the `policy_iteration_v(mdp)` function below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "02779c3b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ---------------- Policy Iteration with the V function -----------------#\n",
    "# Given an MDP, this algorithm simultaneously computes\n",
    "# the optimal state value function V and the optimal policy\n",
    "\n",
    "\n",
    "def policy_iteration_v(\n",
    "    mdp: MazeMDPEnv, render: bool = True\n",
    ") -> Tuple[np.ndarray, List[float]]:\n",
    "    # policy iteration over the v function\n",
    "    v = np.zeros(mdp.nb_states)  # initial state values are set to 0\n",
    "    v_list = []\n",
    "    policy = random_policy(mdp)\n",
    "\n",
    "    stop = False\n",
    "\n",
    "    mdp.init_draw(\"Policy Iteration (V)\")\n",
    "\n",
    "    while not stop:\n",
    "        vold = v.copy()\n",
    "\n",
    "        mdp.draw_v(v, title=\"Policy iteration Q\")\n",
    "\n",
    "        # Step 1 : Policy Evaluation\n",
    "        # [[STUDENT]]...\n",
    "\n",
    "        v = ...\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "        # Step 2 : Policy Improvement\n",
    "        # [[STUDENT]]...\n",
    "\n",
    "        policy = ...\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "        # Check convergence\n",
    "        if (np.linalg.norm(v - vold)) < 0.01:\n",
    "            stop = True\n",
    "        v_list.append(np.linalg.norm(v))\n",
    "\n",
    "    mdp.draw_v_pi(v, get_policy_from_v(mdp, v))\n",
    "\n",
    "    return v, v_list"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "68d5d63c",
   "metadata": {},
   "source": [
    "And finally run it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3d6fe289",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "v, v_list = policy_iteration_v(env.unwrapped, render=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9b6495c0",
   "metadata": {},
   "source": [
    "### Policy iteration with the $Q$ function ###\n",
    "\n",
    "The **policy iteration** algorithm with the $Q$ function is the same as with\n",
    "the $V$ function, but the policy improvement step is more straightforward.\n",
    "\n",
    "When using $Q$, the Bellman Optimality Equation with deterministic policy\n",
    "$\\pi$ for $Q$ becomes: $$Q^{\\pi}(s,a) = r(s,a) + \\gamma \\sum_{y \\in\n",
    "S}P(s,a,y)Q^{\\pi}(y,\\pi(y)).$$\n",
    "\n",
    "The policy can then be updated as follows: $$\\pi^{(t+1)}(s) =\n",
    "\\arg\\max_aQ^{\\pi^{(t)}}(s,a).$$\n",
    "\n",
    "First, we need to determine a policy from the $Q$ function.\n",
    "\n",
    "**Question:**  fill the `get_policy_from_q(q)` function, where $q$ is the\n",
    "state-action value function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7c821c8e",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def get_policy_from_q(q: np.ndarray) -> np.ndarray:\n",
    "    # Outputs a policy given the action values\n",
    "\n",
    "    return ...\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b895addc",
   "metadata": {},
   "source": [
    "**Question:** By drawing inspiration on the functions give with the $v$\n",
    "function, fill the code of the `evaluate_one_step_q(mdp, q, policy)` function\n",
    "below, where $q$ is some action value function, and the `evaluate_q(mdp,\n",
    "policy)` function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "69c2600e",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def evaluate_one_step_q(\n",
    "    mdp: MazeMDPEnv, q: np.ndarray, policy: np.ndarray\n",
    ") -> np.ndarray:\n",
    "    # Outputs the state value function after one step of policy evaluation\n",
    "    qnew = np.zeros(\n",
    "        (mdp.nb_states, mdp.action_space.n)\n",
    "    )  # initial action values are set to 0\n",
    "    for s in range(mdp.nb_states):  # for each state x\n",
    "        # Compute the value of the state x for each action u of the MDP action space\n",
    "        for a in range(mdp.action_space.n):\n",
    "            if s in mdp.terminal_states:\n",
    "                qnew[s, a] = mdp.r[s, a]\n",
    "            else:\n",
    "                # Process sum of the values of the neighbouring states\n",
    "                summ = 0\n",
    "                for y in range(mdp.nb_states):\n",
    "                    # [[STUDENT]]...\n",
    "\n",
    "                    summ += ...\n",
    "                    assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "                # [[STUDENT]]...\n",
    "\n",
    "                qnew[s, a] = ...\n",
    "                assert False, 'Not implemented yet'\n",
    "\n",
    "    return qnew"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b5185593",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def evaluate_q(mdp: MazeMDPEnv, policy: np.ndarray) -> np.ndarray:\n",
    "    # Outputs the state value function of a policy\n",
    "    q = np.zeros(\n",
    "        (mdp.nb_states, mdp.action_space.n)\n",
    "    )  # initial action values are set to 0\n",
    "    stop = False\n",
    "    while not stop:\n",
    "        qold = q.copy()\n",
    "\n",
    "        # [[STUDENT]]...\n",
    "\n",
    "        q = ...\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "        # Test if convergence has been reached\n",
    "        if (np.linalg.norm(q - qold)) < 0.01:\n",
    "            stop = True\n",
    "    return q"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3bb8f6b",
   "metadata": {},
   "source": [
    "**Question:** By using the above functions, fill the code of the `policy_iteration_q(mdp)` function below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a8e63396",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ---------------- Policy Iteration with the Q function -----------------#\n",
    "# Given a MDP, this algorithm simultaneously computes\n",
    "# the optimal action value function Q and the optimal policy\n",
    "\n",
    "\n",
    "def policy_iteration_q(\n",
    "    mdp: MazeMDPEnv, render: bool = True\n",
    ") -> Tuple[np.ndarray, List[float]]:\n",
    "    \"\"\"policy iteration over the q function.\"\"\"\n",
    "    q = np.zeros(\n",
    "        (mdp.nb_states, mdp.action_space.n)\n",
    "    )  # initial action values are set to 0\n",
    "    q_list = []\n",
    "    policy = random_policy(mdp)\n",
    "\n",
    "    stop = False\n",
    "\n",
    "    mdp.init_draw(\"Policy iteration Q\")\n",
    "\n",
    "    while not stop:\n",
    "        qold = q.copy()\n",
    "        mdp.draw_v(q)\n",
    "\n",
    "        # Step 1 : Policy evaluation\n",
    "\n",
    "        q = ...\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "        # Step 2 : Policy improvement\n",
    "\n",
    "        policy = ...\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "        # Check convergence\n",
    "        if (np.linalg.norm(q - qold)) <= 0.01:\n",
    "            stop = True\n",
    "        q_list.append(np.linalg.norm(q))\n",
    "\n",
    "    mdp.draw_v_pi(q, get_policy_from_q(q))\n",
    "    return q, q_list"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9de51989",
   "metadata": {},
   "source": [
    "Finally, run it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fd02a60c",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "q, q_list = policy_iteration_q(env.unwrapped, render=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "42c6242b",
   "metadata": {},
   "source": [
    "### Study part: Experimental comparisons\n",
    "\n",
    "We will now compare the efficiency of the various dynamic programming methods using either the $V$ or the  $Q$ functions.\n",
    "\n",
    "In all your dymanic programming functions, add code to count the number of iterations and the number of elementary $V$ or $Q$ updates. Use the provided `mazemdp.Chrono` class to measure the time taken. You may generate various mazes of various sizes to figure out the influence of the maze topology.\n",
    "\n",
    "Build a table where you compare the various dymanic programming functions in terms of iterations, elementary operations and time taken.\n",
    "\n",
    "You can run the `plot_convergence_vi_pi(...)` function provided below to visualize the convergence of the various algorithms."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "afae6d2d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# --- plot the evolution of the norm of value and action value functions over dynamic programming iterations ----#\n",
    "\n",
    "\n",
    "def plot_convergence_vi_pi(m, render):\n",
    "    v, v_list1 = value_iteration_v(m, render)\n",
    "    q, q_list1 = value_iteration_q(m, render)\n",
    "    v, v_list2 = policy_iteration_v(m, render)\n",
    "    q, q_list2 = policy_iteration_q(m, render)\n",
    "\n",
    "    plt.plot(range(len(v_list1)), v_list1, label=\"value_iteration_v\")\n",
    "    plt.plot(range(len(q_list1)), q_list1, label=\"value_iteration_q\")\n",
    "    plt.plot(range(len(v_list2)), v_list2, label=\"policy_iteration_v\")\n",
    "    plt.plot(range(len(q_list2)), q_list2, label=\"policy_iteration_q\")\n",
    "\n",
    "    plt.xlabel(\"Number of episodes\")\n",
    "    plt.ylabel(\"Norm of V or Q value\")\n",
    "    plt.legend(loc=\"upper right\")\n",
    "    # plt.savefig(\"comparison_DP.png\")\n",
    "    plt.title(\"Comparison of convergence rates\")\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2bbf7380",
   "metadata": {},
   "source": [
    "**Question:** Run the code below and visualize the results of the different algorithms"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "25e9d05d",
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_convergence_vi_pi(env.unwrapped, False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21b6152f",
   "metadata": {},
   "source": [
    "Given the results above, discuss the relative computational efficiency of these methods.\n",
    "\n",
    "# Study part: Generalized Policy Iteration\n",
    "\n",
    "In this last part, we will code the **generalized policy iteration** algorithm and study the influence of the number of evaluation steps between each improvement step.\n",
    "More precisely, we will consider an algorithm which starts from a policy, evaluates it **using only K iterations**, then computes the new policy corresponding to this value function, and so on until it converges.\n",
    "\n",
    "The goal of the study is to find the value of K which leads to convergence in the smallest number of iterations, and to see how efficient it is with respect to using standard policy iteration (where each policy is evaluated until convergence of this evaluation). We will do this with the Q function and the V function.\n",
    "\n",
    "## Generalized Policy Iteration with the Q function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "85f5c1fe",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def evaluate_one_step_q_count(\n",
    "    mdp: MazeMDPEnv, q: np.ndarray, policy: np.ndarray\n",
    ") -> np.ndarray:\n",
    "    # Outputs the state value function after one step of policy evaluation\n",
    "    # [[STUDENT]]...\n",
    "\n",
    "    ...\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eed3418e",
   "metadata": {},
   "source": [
    "A difference with respect to the standard policy iteration version is that now we pass the number of iterations K\n",
    "K=-1 can be used to account for the case where we evaluate until convergence."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f3879b6a",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def evaluate_q_K_steps(\n",
    "    mdp: MazeMDPEnv, policy: np.ndarray, q: np.array, K: int\n",
    ") -> np.ndarray:\n",
    "    # Outputs the state value function of a policy\n",
    "    # [[STUDENT]]...\n",
    "\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "618a320b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def generalized_policy_iteration_q(\n",
    "    mdp: MazeMDPEnv, render: bool = True, K: int = 1\n",
    ") -> Tuple[np.ndarray, List[float]]:\n",
    "    \"\"\"policy iteration over the q function.\"\"\"\n",
    "    # [[STUDENT]]...\n",
    "\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9dc6ecf5",
   "metadata": {},
   "outputs": [],
   "source": [
    "q, q_list = generalized_policy_iteration_q(env.unwrapped, render=True, K=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "587fdf37",
   "metadata": {},
   "source": [
    "## Generalized Policy Iteration with the V function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "572e1fd1",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def evaluate_one_step_v(\n",
    "    mdp: MazeMDPEnv, v: np.ndarray, policy: np.ndarray\n",
    ") -> np.ndarray:\n",
    "    # Outputs the state value function after one step of policy evaluation\n",
    "    # Corresponds to one application of the Bellman Operator\n",
    "    # [[STUDENT]]...\n",
    "\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "949f1ac1",
   "metadata": {},
   "source": [
    "A difference with respect to the previous version is that now we pass the number of iterations K"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d27888c9",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def generalized_evaluate_v(\n",
    "    mdp: MazeMDPEnv,\n",
    "    policy: np.ndarray,\n",
    "    v: np.array,\n",
    "    norms: np.array,\n",
    "    K: int,\n",
    "    threshold: float,\n",
    ") -> np.ndarray:\n",
    "    # Outputs the state value function of a policy\n",
    "    # [[STUDENT]]...\n",
    "\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b65134ef",
   "metadata": {},
   "outputs": [],
   "source": [
    "def generalized_policy_iteration_v(\n",
    "    mdp: MazeMDPEnv, K: int = 1, threshold: float = 0.01, render: bool = True\n",
    ") -> Tuple[np.ndarray, List[float]]:\n",
    "    \"\"\"policy iteration over the q function.\"\"\"\n",
    "    # [[STUDENT]]...\n",
    "\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e5d628ef",
   "metadata": {},
   "source": [
    "Visualization of the results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ebfed50b",
   "metadata": {},
   "outputs": [],
   "source": [
    "max = 10\n",
    "threshold = 0.00001\n",
    "for k in range(max):\n",
    "    norms = np.zeros(max)\n",
    "    v, norm = generalized_policy_iteration_v(env.unwrapped, k, threshold, render=False)\n",
    "    # print(k, \":\", norm)\n",
    "    plt.plot(range(len(norm)), norm, label=k)\n",
    "    plt.legend(loc=\"upper right\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "99f799eb",
   "metadata": {},
   "source": [
    "Once you have completed the code, perform a study over the values of K and conclude. Among other things, you may try different mazes with different sizes (`MAZES[\"medium\"]`, `MAZES[\"large\"]`)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0ae79a5f",
   "metadata": {},
   "source": [
    "# From planning to acting\n",
    "\n",
    "Everything above worked on the **model** of the MDP ($P$ and $r$): dynamic\n",
    "programming computes an optimal policy without ever moving an agent. The rest\n",
    "of the course does the opposite — it learns from **interaction**, and never\n",
    "sees the model.\n",
    "\n",
    "Let us close the gap by actually running the policy that value iteration\n",
    "computed, using the same tools as every other notebook of the course:\n",
    "\n",
    "- `VecEnv` runs several copies of a gymnasium environment in parallel, with\n",
    "  torch tensors. In a tabular environment an observation is simply a **state\n",
    "  index**, so a policy is a table read with `policy[obs]`;\n",
    "- `Actor` is the base class of all the policies of the course: `act(obs)`\n",
    "  returns the action to play;\n",
    "- `Evaluator` runs one episode per environment and returns the cumulated\n",
    "  rewards.\n",
    "\n",
    "`VecEnv` builds its own copies of the environment, so we hand it the `MAZE`\n",
    "description used at the top of the notebook — this is exactly why that\n",
    "description carries a seed: without one, each copy would draw its own maze.\n",
    "\n",
    "One last ingredient: by default an episode always starts in the same state,\n",
    "and the ten copies would replay the very same episode. Dynamic programming\n",
    "computed a policy that is optimal **from every state**, so we want to start\n",
    "anywhere in the maze — that is what the *wrapper* below does. A gymnasium\n",
    "wrapper intercepts the calls made to an environment; this one adds the\n",
    "`uniform` option to every `reset`, including the automatic resets that\n",
    "`VecEnv` performs at the end of an episode."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d0b982e8",
   "metadata": {},
   "outputs": [],
   "source": [
    "class TabularActor(Actor[Action]):\n",
    "    \"\"\"An actor playing a fixed tabular policy: one action per state\"\"\"\n",
    "\n",
    "    def __init__(self, policy: np.ndarray):\n",
    "        super().__init__()\n",
    "        # a buffer rather than a plain attribute, so that the actor behaves\n",
    "        # like any other `torch.nn.Module` (it can be copied, moved, saved)\n",
    "        self.register_buffer(\"policy\", torch.as_tensor(policy, dtype=torch.int64))\n",
    "\n",
    "    def forward(self, obs: Tensor) -> Action:\n",
    "        \"\"\"`obs` is a batch of state indices, shape `[B]`\"\"\"\n",
    "        return Action(value=self.policy[obs])\n",
    "\n",
    "\n",
    "class RandomWalk(Actor[Action]):\n",
    "    \"\"\"Picks one of the `n_actions` actions uniformly at random, at each step\"\"\"\n",
    "\n",
    "    def __init__(self, n_actions: int):\n",
    "        super().__init__()\n",
    "        self.n_actions = n_actions\n",
    "\n",
    "    def forward(self, obs: Tensor) -> Action:\n",
    "        return Action(value=torch.randint(0, self.n_actions, obs.shape))\n",
    "\n",
    "\n",
    "class UniformStart(gym.Wrapper):\n",
    "    \"\"\"Start every episode in a state drawn uniformly at random\"\"\"\n",
    "\n",
    "    def reset(self, *, seed=None, options=None):\n",
    "        options = {**(options or {}), \"uniform\": True}\n",
    "        return self.env.reset(seed=seed, options=options)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ae6b7311",
   "metadata": {},
   "outputs": [],
   "source": [
    "torch.manual_seed(0)\n",
    "q, _ = value_iteration_q(env.unwrapped, render=False)\n",
    "optimal_actor = TabularActor(get_policy_from_q(q))\n",
    "random_actor = RandomWalk(env.action_space.n)\n",
    "\n",
    "# One episode in each of the 20 environments, each from a different state\n",
    "evaluator = Evaluator(\n",
    "    VecEnv(\"MazeMDP-v0\", 20, seed=0, kwargs=MAZE, wrappers=[UniformStart]), every=1\n",
    ")\n",
    "for name, actor in [(\"optimal\", optimal_actor), (\"random walk\", random_actor)]:\n",
    "    rewards = evaluator.run(actor)\n",
    "    reached = float((rewards > 0).float().mean())\n",
    "    print(f\"{name:>8}: reward {rewards.mean():.2f} | goal reached {reached:.0%}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5e708391",
   "metadata": {},
   "source": [
    "The optimal policy reaches the goal from **every** starting state — that is\n",
    "precisely what value iteration guarantees — while the random walk only\n",
    "stumbles onto it before the time limit truncates the episode. And the gap\n",
    "widens with the size of the maze: the random walk arrives most of the time on\n",
    "the small maze, but only about a quarter of the time on `MAZES[\"large\"]`.\n",
    "Exploring by chance does not scale, which is the whole difficulty of the\n",
    "algorithms that follow.\n",
    "\n",
    "Everything that follows in the course is about finding such a policy\n",
    "**without** knowing $P$ and $r$, by interacting with the environment."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_markers": "\"\"\"",
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "Value iteration and policy iteration, in a maze",
   "practical_name": "Dynamic programming"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
