{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9287b034",
   "metadata": {},
   "source": [
    " Copyright © Sorbonne University.\n",
    "\n",
    " This source code is licensed under the MIT license found in the\n",
    " LICENSE file in the root directory of this source tree."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e05b0d96",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "In this notebook we will study basic reinforcement learning\n",
    "algorithms: TD learning, Q-learning and SARSA. We will also investigate two\n",
    "basic exploration strategies: $\\epsilon$-greedy and softmax.\n",
    "\n",
    "\n",
    "## Initialization\n",
    "\n",
    "We begin by loading all the modules necessary for this notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2a52d063",
   "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 typing import List, Tuple\n",
    "from mazemdp import random_policy\n",
    "from mazemdp.mdp import Mdp\n",
    "from mazemdp.toolbox import egreedy, egreedy_loc, sample_categorical, softmax\n",
    "from rl_mind.notebook import silence_known_warnings\n",
    "from rl_mind.mazemdp_env import MazeMDPEnv\n",
    "from tqdm.auto import tqdm\n",
    "from rl_mind.profiles import Profile"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e8b432c8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a570a910",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# Reinforcement Learning\n",
    "\n",
    "Reinforcement Learning is about finding the optimal policy in an MDP which is\n",
    "initially unknown to the agent. More precisely, the state and action spaces\n",
    "are known, but the agent does not know the transition and reward functions.\n",
    "Generally speaking, the agent has to explore the MDP to figure out which\n",
    "action in which state leads to which other state and reward. The model-free\n",
    "case is about finding this optimal policy just through very local updates,\n",
    "without storing any information about previous interactions with the\n",
    "environment. Principles of these local updates can already be found in the\n",
    "Temporal Difference (TD) algorithm, which iteratively computes optimal values\n",
    "for all state using local updates. The most widely used model-free RL\n",
    "algorithms are **q-learning**, **SARSA** and **actor-critic** algorithms.\n",
    "\n",
    "As for dynamic programming, we first create a maze-like MDP. Reinforcement\n",
    "learning is slower than dynamic programming, so we will work with smaller\n",
    "mazes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "14257ee5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Environment with 20% of walls and no negative reward when hitting a wall\n",
    "mdp = gym.make(\n",
    "    \"MazeMDP-v0\",\n",
    "    kwargs={\"width\": 4, \"height\": 3, \"ratio\": 0.2, \"hit\": 0.0, \"start_states\": [0]},\n",
    "    render_mode=\"human\",\n",
    ")\n",
    "mdp.reset()\n",
    "mdp.unwrapped.init_draw(\"The maze\")\n",
    "\n",
    "MAX_EPISODES = Profile.pick(50, fast_test=10)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c0235ae2",
   "metadata": {},
   "source": [
    "# Temporal Difference (TD) learning ##\n",
    "\n",
    "Given a state and an action spaces as well as a policy, TD(0) computes the\n",
    "state value of this policy based on the following equations:\n",
    "\n",
    "$$\\delta_t = r(s_t,a_t) + \\gamma V^{(i)}(s_{t+1})-V^{(i)}(s_t)$$\n",
    "$$V^{(i+1)}(s_t) = V^{(i)}(s_t) + \\alpha\\delta_t$$\n",
    "\n",
    "where $\\delta$ is the TD error and $\\alpha$ is a parameter called \"learning\n",
    "rate\".\n",
    "\n",
    "Note however that when the episode terminates in state $s_t$,\n",
    "back-propagating the value of $s_{t+1}$ makes no sense,\n",
    "as the environment will be reset for the next episode.\n",
    "So, in such a case, we should ignore the $\\gamma V^{(i)}(s_{t+1})$ term.\n",
    "We could write this with if terminated: $\\delta_t = r(s_t,a_t) -V^{(i)}(s_t)$ else standard update,\n",
    "but since the `terminated` boolean can be seen as an integer,\n",
    "we can obtain the same behaviour with $\\delta_t = r(s_t,a_t) + \\gamma V^{(i)}(s_{t+1}) (1 - terminated) - V^{(i)}(s_t)$.\n",
    "\n",
    "The code is provided below, so that you can take inspiration later on. The\n",
    "important part is the computation of $\\delta$, and the update of the values of\n",
    "$V$.\n",
    "\n",
    "To run TD learning, a policy is needed as input. Such a policy can be\n",
    "retreived by using the `policy_iteration_q(mdp)` function defined in the\n",
    "dynamic programming notebook.\n",
    "\n",
    "If you want to run this notebook independently, you can use instead the\n",
    "`random_policy` provided in `mazemdp`. This is what we do here by default,\n",
    "replace it if you want to run TD learning from an optimal policy.\n",
    "\n",
    "The ```evaluate``` function below is not necessary for the lab, it is left here for its informative value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "53071a7e",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def evaluate(mdp, policy):\n",
    "    s, _ = mdp.reset(options={\"uniform\": True})\n",
    "    terminated = False\n",
    "    truncated = False\n",
    "    reward = 0\n",
    "\n",
    "    while not (terminated or truncated):\n",
    "        # Perform a step of the MDP\n",
    "        a = sample_categorical(policy[s])\n",
    "        _, r, terminated, truncated, *_ = mdp.step(a)\n",
    "        reward += r\n",
    "    return reward"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "02c4116f",
   "metadata": {},
   "source": [
    "**Question:** In the code of the *temporal_difference(...)* function below,\n",
    "fill the missing parts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "852a2864",
   "metadata": {},
   "outputs": [],
   "source": [
    "def temporal_difference(\n",
    "    mdp: MazeMDPEnv,\n",
    "    policy: np.ndarray,\n",
    "    nb_episodes: int = 50,\n",
    "    alpha: float = 0.2,  # alpha: learning rate\n",
    "    render: bool = True,\n",
    ") -> np.ndarray:\n",
    "    env = mdp.unwrapped\n",
    "\n",
    "    v = np.zeros(env.nb_states)  # initial state value v\n",
    "\n",
    "    if render:\n",
    "        env.init_draw(\"Temporal differences\")\n",
    "\n",
    "    for _ in tqdm(range(nb_episodes)):  # for each episode\n",
    "        # Draw an initial state randomly (if uniform is set to False, the state\n",
    "        # is drawn according to the P0 distribution)\n",
    "        s, _ = mdp.reset(options={\"uniform\": True})\n",
    "        terminated = False\n",
    "        truncated = False\n",
    "        while not (terminated or truncated):\n",
    "            # Show agent\n",
    "            if render:\n",
    "                env.draw_v_pi(v, policy)\n",
    "\n",
    "            # Step forward following the MDP: s=current state, pol[i]=agent's\n",
    "            # action according to policy pol, r=reward gained after taking\n",
    "            # action pol[i], terminated=tells whether  the episode ended, and info\n",
    "            # gives some info about the process\n",
    "            y, r, terminated, truncated, _ = mdp.step(\n",
    "                egreedy_loc(policy[s], env.action_space.n, epsilon=0.2)\n",
    "            )\n",
    "            # [[STUDENT]]...\n",
    "\n",
    "            # Update the state value of x\n",
    "            delta = ...\n",
    "            v[s] = ...\n",
    "            assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "            # Update agent's position (state)\n",
    "            s = y\n",
    "\n",
    "    if render:\n",
    "        env.current_state = 0\n",
    "        env.draw_v_pi(v, policy)\n",
    "    return v"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c7e34a84",
   "metadata": {},
   "source": [
    "Once this is done, you can run it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3d580b31",
   "metadata": {},
   "outputs": [],
   "source": [
    "policy = random_policy(mdp.unwrapped)\n",
    "v = temporal_difference(mdp, policy, nb_episodes=10)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aabe39fd",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "Unless you were lucky, the generated value function is boring: if the policy\n",
    "does not reach the final state, all values are 0. To avoid this, you can\n",
    "copy-paste a dynamic programming function on the Q function from the previous\n",
    "notebook, use it to get an optimal policy, and use this policy for TD\n",
    "learning. You should get a much more interesting value function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3bb340e6",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Put your code to obtain an optimal Q function here\n",
    "\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8a5d565a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Put your code to get a policy from a Q function here\n",
    "\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "223d916b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Put your code to run the algorithm here\n",
    "\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "84a4b132",
   "metadata": {},
   "source": [
    "# Q-learning ##\n",
    "\n",
    "The **Q-learning** algorithm accounts for an agent exploring an MDP and\n",
    "updating at each step a model of the state action-value function stored into a\n",
    "Q-table. It is updated as follows:\n",
    "\n",
    "$$\n",
    "\\delta_t = \\left( r(s_t,a_t) + \\gamma \\max_{a \\in A}\n",
    "Q^{(i)}(s_{t+1},a) \\right) -Q^{(i)}(s_t,a_t)\n",
    "$$\n",
    "\n",
    "$$Q^{(i+1)}(s_t, a_t) = Q^{(i)}(s_t,a_t) + \\alpha \\delta_t$$\n",
    "\n",
    "To visualize the policy, we need the `get_policy_from_q(q)` function that we defined in the\n",
    "dynamic programming notebook. If you have not done so yet, import it below."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3fa3cbed",
   "metadata": {},
   "source": [
    "Fill the code of the `q_learning(...)` function below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c9844d6c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# --------------------------- Q-Learning epsilon-greedy version -------------------------------#\n",
    "# Given an exploration rate epsilon, the QLearning algorithm computes the state action-value function\n",
    "# based on an epsilon-greedy policy\n",
    "# alpha is the learning rate\n",
    "\n",
    "\n",
    "def q_learning_eps(\n",
    "    mdp: MazeMDPEnv,\n",
    "    alpha: float = 0.2,  # alpha is the learning rate\n",
    "    epsilon: float = 0.02,\n",
    "    nb_episodes: int = 20,\n",
    "    render: bool = True,\n",
    "    init_q: float = 0.0,\n",
    "    uniform: bool = True,\n",
    ") -> Tuple[np.ndarray, List[float]]:\n",
    "\n",
    "    # Run learning cycle\n",
    "    env = mdp.unwrapped\n",
    "\n",
    "    # Initialize the state-action value function\n",
    "\n",
    "    q = np.zeros((env.nb_states, env.action_space.n))\n",
    "    q_min = np.zeros((env.nb_states, env.action_space.n))\n",
    "    q[:, :] = init_q\n",
    "    q_list = []\n",
    "    time_list = []\n",
    "\n",
    "    if render:\n",
    "        env.init_draw(\"Q Learning\")\n",
    "\n",
    "    for _ in range(nb_episodes):\n",
    "        # Draw the first state of episode i using a uniform distribution over all the states\n",
    "        s, _ = mdp.reset(options={\"uniform\": uniform})\n",
    "        cpt = 0\n",
    "\n",
    "        terminated = False\n",
    "        truncated = False\n",
    "        while not (terminated or truncated):\n",
    "            # Show the agent in the maze\n",
    "            if render:\n",
    "                env.draw_v_pi(q, q.argmax(axis=1))\n",
    "\n",
    "            # Draw an action using an epsilon-greedy policy\n",
    "            a = egreedy(q, s, epsilon)\n",
    "\n",
    "            # Perform a step of the MDP\n",
    "            y, r, terminated, truncated, _ = mdp.step(a)\n",
    "\n",
    "            # [[STUDENT]]...\n",
    "\n",
    "            # Update the state-action value function with q-Learning\n",
    "            delta = ...\n",
    "            q[...] = ...\n",
    "            assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "            # Update the agent position\n",
    "            s = y\n",
    "            cpt = cpt + 1\n",
    "\n",
    "        q_list.append(np.linalg.norm(np.maximum(q, q_min)))\n",
    "        time_list.append(cpt)\n",
    "\n",
    "    if render:\n",
    "        env.current_state = 0\n",
    "        env.draw_v_pi(q, get_policy_from_q(q))\n",
    "\n",
    "    return q_list, time_list"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8940c662",
   "metadata": {},
   "source": [
    "And run it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "61955321",
   "metadata": {},
   "outputs": [],
   "source": [
    "alpha = 0.5\n",
    "epsilon = 0.02\n",
    "q_list, time_list = q_learning_eps(mdp, alpha, epsilon, nb_episodes=MAX_EPISODES)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ca54e95",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Harder case: fixed starting point and exploration\n",
    "\n",
    "We now explore the case where the agent always start at the *beginning of the maze* (`uniform=False`), corresponding to the top-left corner when this is a free cell."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0974d187",
   "metadata": {},
   "outputs": [],
   "source": [
    "alpha = 0.5\n",
    "epsilon = 0.02\n",
    "start_q_list, time_list = q_learning_eps(\n",
    "    mdp, alpha, epsilon, nb_episodes=MAX_EPISODES, uniform=False\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "87ca80a9",
   "metadata": {},
   "source": [
    "You will observe that it is very difficult for the agent to learn to reach the\n",
    "final state (and the larger the maze, the more difficult). A simple trick to\n",
    "avoid this is to initialize the value of each $(s,a)$ pair to a small (lower\n",
    "than the final reward) value. Try it with the example above !"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d955e76d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# [[STUDENT]]...\n",
    "\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ddfc78e2",
   "metadata": {},
   "source": [
    "### Learning dynamics\n",
    "\n",
    "By watching carefully the values while the agent is learning, you can see that\n",
    "the agent favors certains paths over others which have a strictly equivalent value.\n",
    "This can be explained easily: as the agent chooses a path for the first\n",
    "time, it updates the values along that path, these values get higher than the\n",
    "surrounding values, and the agent chooses the same path again and again,\n",
    "increasing the phenomenon. Only steps of random exploration can counterbalance\n",
    "this effect, but they do so extremely slowly.\n",
    "\n",
    "### Exploration\n",
    "\n",
    "In the `q_learning(...)` function above, action selection is based on a\n",
    "$\\epsilon$-greedy policy. Instead, it could have relied on *`softmax`*.\n",
    "\n",
    "In the function below, you have to replace the call to the\n",
    "previous *$\\epsilon$-greedy* policy with a `softmax` policy. The\n",
    "`softmax(...)` and `egreedy(...)` functions are available in\n",
    "`mazemdp.toolbox`.\n",
    "\n",
    "`sofmax(...)` returns a distribution probability over actions. To sample\n",
    "an action according to their probabilities, you can use the\n",
    "`sample_categorical` function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1ad0aee2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# --------------------------- Q-Learning softmax version ----------------------------#\n",
    "# Given a temperature \"beta\", the QLearning algorithm computes the state action-value function\n",
    "# based on a softmax policy\n",
    "# alpha is the learning rate\n",
    "\n",
    "\n",
    "def q_learning_soft(\n",
    "    mdp: MazeMDPEnv,\n",
    "    alpha: float = 0.2,  # alpha: learning rate\n",
    "    beta: float = 0.6,\n",
    "    nb_episodes: int = 20,\n",
    "    render: bool = True,\n",
    ") -> Tuple[np.ndarray, List[float]]:\n",
    "\n",
    "    # Run learning cycle\n",
    "    env = mdp.unwrapped\n",
    "\n",
    "    # Initialize the state-action value function\n",
    "    # alpha is the learning rate\n",
    "    q = np.zeros((env.nb_states, env.action_space.n))\n",
    "    q_min = np.zeros((env.nb_states, env.action_space.n))\n",
    "    q_list = []\n",
    "    time_list = []\n",
    "\n",
    "    if render:\n",
    "        env.init_draw(\"Q Learning (Softmax)\")\n",
    "\n",
    "    for _ in range(nb_episodes):\n",
    "        # Draw the first state of episode i using a uniform distribution over all the states\n",
    "        s, _ = mdp.reset(options={\"uniform\": True})\n",
    "        cpt = 0\n",
    "\n",
    "        terminated = False\n",
    "        truncated = False\n",
    "        while not (terminated or truncated):\n",
    "            if render:\n",
    "                env.draw_v_pi(q, q.argmax(axis=1))\n",
    "\n",
    "            # [[STUDENT]]...\n",
    "\n",
    "            # Draw an action using a soft-max policy\n",
    "            a = ... # (here, call the softmax function)\n",
    "            assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "            # [[STUDENT]]...\n",
    "\n",
    "            # Copy-paste the rest from q_learning_eps\n",
    "            assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "            s = y\n",
    "            cpt = cpt + 1\n",
    "\n",
    "        q_list.append(np.linalg.norm(np.maximum(q, q_min)))\n",
    "        time_list.append(cpt)\n",
    "\n",
    "    if render:\n",
    "        env.current_state = 0\n",
    "        env.draw_v_pi(q, get_policy_from_q(q))\n",
    "\n",
    "    return q_list, time_list"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4a87d76",
   "metadata": {},
   "source": [
    " Run this new version"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f635ea95",
   "metadata": {},
   "outputs": [],
   "source": [
    "NB_EPISODES = 40\n",
    "alpha = 0.5\n",
    "beta = 0.16\n",
    "q_list, time_list = q_learning_soft(mdp, alpha, beta, nb_episodes=MAX_EPISODES)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79fd5a28",
   "metadata": {},
   "source": [
    "# Sarsa\n",
    "\n",
    "The **SARSA** algorithm is very similar to **Q-learning**. At first glance,\n",
    "the only difference is in the update rule. However, to perform the update in\n",
    "**SARSA**, one needs to know the action the agent will take when it will be at\n",
    "the next state, even if the agent is taking a random action.\n",
    "\n",
    "This implies that the next state action is determined in advance and stored\n",
    "for being played at the next time step.\n",
    "\n",
    "The update formula is as follows:\n",
    "\n",
    "$$ \\delta_t = \\left( r(s_t,a_t) + \\gamma Q^{(i)}(s_{t+1}, a_{t+1})\n",
    "\\right) -Q^{(i)}(s_t,a_t) $$\n",
    "\n",
    "$$ Q^{(i+1)}(s_t,a_t) = Q^{(i)}(s_t,a_t) + \\alpha \\delta_t $$\n",
    "\n",
    "\n",
    "## SARSA ($\\epsilon-greedy$ version)\n",
    "Fill the code below"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "be52e763",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Given an exploration rate epsilon, the SARSA algorithm computes the state action-value function\n",
    "# based on an epsilon-greedy policy\n",
    "# alpha is the learning rate\n",
    "\n",
    "\n",
    "def sarsa_eps(\n",
    "    mdp: MazeMDPEnv,\n",
    "    alpha: float = 0.2,  # alpha is the learning rate\n",
    "    epsilon: float = 0.02,\n",
    "    nb_episodes: int = 20,\n",
    "    render: bool = True,\n",
    ") -> Tuple[np.ndarray, List[float]]:\n",
    "\n",
    "    # Run learning cycle\n",
    "    env = mdp.unwrapped\n",
    "\n",
    "    # Initialize the state-action value function\n",
    "    q = np.zeros((env.nb_states, env.action_space.n))\n",
    "    q_min = np.zeros((env.nb_states, env.action_space.n))\n",
    "    q_list = []\n",
    "    time_list = []\n",
    "\n",
    "    if render:\n",
    "        env.init_draw(\"SARSA e-greedy\")\n",
    "\n",
    "    for _ in range(nb_episodes):\n",
    "        # Draw the first state of episode i using a uniform distribution over all the states\n",
    "        s, _ = mdp.reset(options={\"uniform\": True})\n",
    "        cpt = 0\n",
    "\n",
    "        # [[STUDENT]]...\n",
    "\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "        q_list.append(np.linalg.norm(np.maximum(q, q_min)))\n",
    "        time_list.append(cpt)\n",
    "\n",
    "    if render:\n",
    "        env.current_state = 0\n",
    "        env.draw_v_pi(q, get_policy_from_q(q))\n",
    "    return q_list, time_list"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6a02ad20",
   "metadata": {},
   "source": [
    "And run it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dbbb95a0",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "learning_rate = 0.5\n",
    "alpha = 0.5\n",
    "epsilon = 0.02\n",
    "q_list, time_list = sarsa_eps(mdp, alpha, epsilon, nb_episodes=MAX_EPISODES)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1989e2c2",
   "metadata": {},
   "source": [
    "As for **Q-learning** above, copy-paste the resulting code to get a\n",
    "*sarsa_soft(...)* and a *sarsa_eps(...)* function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "895449b7",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# --------------------------- SARSA, softmax version -------------------------------#\n",
    "# Given a temperature \"beta\", the SARSA algorithm computes the state action-value function\n",
    "# based on a softmax policy\n",
    "# alpha is the learning rate\n",
    "\n",
    "\n",
    "def sarsa_soft(\n",
    "    mdp: MazeMDPEnv,\n",
    "    alpha: float = 0.2,  # alpha is the learning rate\n",
    "    beta: float = 0.6,\n",
    "    nb_episodes: int = 20,\n",
    "    render: bool = True,\n",
    ") -> Tuple[np.ndarray, List[float]]:\n",
    "    # Run learning cycle\n",
    "    env = mdp.unwrapped\n",
    "\n",
    "    # Initialize the state-action value function\n",
    "\n",
    "    q = np.zeros((env.nb_states, env.action_space.n))\n",
    "    q_min = np.zeros((env.nb_states, env.action_space.n))\n",
    "    q_list = []\n",
    "    time_list = []\n",
    "\n",
    "    if render:\n",
    "        env.init_draw(\"SARSA (Softmax)\")\n",
    "\n",
    "    for _ in range(nb_episodes):\n",
    "        # Draw the first state of episode i using a uniform distribution over all the states\n",
    "        s, _ = mdp.reset(options={\"uniform\": True})\n",
    "        cpt = 0\n",
    "\n",
    "        # [[STUDENT]]...\n",
    "\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "        q_list.append(np.linalg.norm(np.maximum(q, q_min)))\n",
    "        time_list.append(cpt)\n",
    "\n",
    "    if render:\n",
    "        env.current_state = 0\n",
    "        env.draw_v_pi(q, get_policy_from_q(q))\n",
    "    return q_list, time_list"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f162b95b",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "And run it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d9dea454",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# [[STUDENT]]...\n",
    "\n",
    "# Put your code to run sarsa_soft here\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f98916d5",
   "metadata": {},
   "source": [
    "## Impact of `epsilon` and `temperature` on Q-learning and SARSA\n",
    "\n",
    "Compare the number of steps needed by **Q-learning** and **SARSA** to converge\n",
    "on a given MDP using the *softmax* and *$\\epsilon$-greedy* exploration\n",
    "strategies. To figure out, you can use the provided `plot_ql_sarsa(m, alpha, epsilon,\n",
    "beta, nb_episodes, alpha, render)` function below with various values\n",
    "for $\\epsilon$ (e.g. 0.001, 0.01, 0.1) and $\\beta$ (e.g. 0.1, 5, 10) and\n",
    "comment the obtained curves. Other visualizations are welcome, e.g. a heat map, see below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a8188c63",
   "metadata": {},
   "outputs": [],
   "source": [
    "# -------- plot learning curves of Q-Learning and Sarsa using epsilon-greedy and softmax ----------#\n",
    "def plot_ql_sarsa(mdp, alpha, epsilon, beta, nb_episodes, render):\n",
    "    q_list1, time_list1 = q_learning_eps(mdp, alpha, epsilon, nb_episodes, render)\n",
    "    q_list2, time_list2 = q_learning_soft(mdp, alpha, beta, nb_episodes, render)\n",
    "    q_list3, time_list3 = sarsa_eps(mdp, alpha, epsilon, nb_episodes, render)\n",
    "    q_list4, time_list4 = sarsa_soft(mdp, alpha, beta, nb_episodes, render)\n",
    "\n",
    "    plt.clf()\n",
    "    plt.plot(range(len(q_list1)), q_list1, label=\"Q-learning e-greedy\")\n",
    "    plt.plot(range(len(q_list2)), q_list2, label=\"Q-learning softmax\")\n",
    "    plt.plot(range(len(q_list3)), q_list3, label=\"SARSA e-greedy\")\n",
    "    plt.plot(range(len(q_list4)), q_list4, label=\"SARSA softmax\")\n",
    "\n",
    "    plt.xlabel(\"Number of episodes\")\n",
    "    plt.ylabel(\"Norm of Q values\")\n",
    "    plt.legend(loc=\"upper right\")\n",
    "    # plt.savefig(\"comparison_RL.png\")\n",
    "    plt.title(\"Comparison of convergence rates\")\n",
    "    plt.show()\n",
    "\n",
    "    plt.clf()\n",
    "    plt.figure(figsize=(10, 5))\n",
    "    plt.plot(range(len(time_list1)), time_list1, label=\"qlearning e-greedy\")\n",
    "    plt.plot(range(len(time_list2)), time_list2, label=\"qlearning softmax\")\n",
    "    plt.plot(range(len(time_list3)), time_list3, label=\"SARSA e-greedy\")\n",
    "    plt.plot(range(len(time_list4)), time_list4, label=\"SARSA softmax\")\n",
    "\n",
    "    plt.xlabel(\"Number of episodes\")\n",
    "    plt.ylabel(\"Steps to reach goal\")\n",
    "    plt.legend(loc=\"upper right\")\n",
    "    # plt.savefig(\"comparison_RL.png\")\n",
    "    plt.title(\"test\")\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5508cfa4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# example\n",
    "alpha = 0.5\n",
    "plot_ql_sarsa(\n",
    "    mdp, alpha, epsilon=0.02, beta=0.16, nb_episodes=MAX_EPISODES, render=False\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5197410d",
   "metadata": {},
   "source": [
    "### Effect of hyper-parameters\n",
    "\n",
    "The other two hyper-parameters of **Q-learning** and **SARSA** are $\\alpha$,\n",
    "and $\\gamma$. By varying the values of these hyper-parameters and watching the\n",
    "learning process and behavior of the agent, explain their impact on the\n",
    "algorithm. Using additional plotting functions is also welcome.\n",
    "\n",
    "A good idea to visualize the effect of two parameters is to generate a heat map\n",
    "by letting both parameters take values in a well-chosen interval.\n",
    "Make sure that your figure complies with [The figure checklist](https://master-dac.isir.upmc.fr/The_figure_checklist.pdf)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1023ffc3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# [[STUDENT]]...\n",
    "\n",
    "assert False, 'Not implemented yet'\n"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_markers": "\"\"\"",
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "TD learning, Q-learning and SARSA; ε-greedy and softmax exploration",
   "practical_name": "Tabular reinforcement learning"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
