{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f1e27f72",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "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": "e42b4367",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "source": [
    "# Outlook\n",
    "\n",
    "In this notebook we study tabular actor-critic algorithms using $V$ or $Q$ and different critic update rules.\n",
    "\n",
    "In particular, we are interested in the behavior of these algorithms under a uniform (state, action) pair sampling regime and the standard on-policy regime.\n",
    "\n",
    "We compare the capability of these algorithms to approximate the optimal critic\n",
    "and their performance in terms of number of steps to exit a maze.\n",
    "\n",
    "we also investigate the case where the action is drawn from the actor, or from the critic, in the case where we are using a $Q$ critic.\n",
    "\n",
    "The underlying question is whether all these algorithms are off-policy or on-policy and why.\n",
    "\n",
    "## Install libraries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b55cec37",
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "import gymnasium as gym\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import rl_mind.mazemdp_env\n",
    "from enum import Enum\n",
    "from functools import partial\n",
    "from pathlib import Path\n",
    "from types import SimpleNamespace\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 run_directory, 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": "68dfa313",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Every figure produced by this notebook goes in a fresh run directory\n",
    "output_dir = run_directory(\"actor-critic-2025\")\n",
    "\n",
    "\n",
    "def ns(d):\n",
    "    \"\"\"Recursively turn a (nested) dict into a dotted-access namespace\"\"\"\n",
    "    return SimpleNamespace(\n",
    "        **{k: ns(v) if isinstance(v, dict) else v for k, v in d.items()}\n",
    "    )\n",
    "\n",
    "\n",
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d17936f7",
   "metadata": {},
   "source": [
    "# Studied critic update rules\n",
    "\n",
    "In what follows you will implement the following update rules for the V-values and Q-values:\n",
    "\n",
    "#### Type 0: Standard V-based TD Update Rule:\n",
    "\n",
    "We first compute the TD error: $delta = r_{t+1} + \\gamma V(s_{t+1}) - V(s_t)$\n",
    "\n",
    "Then we apply it to the critic: $V(s_t) ← V(s_t) + \\alpha_{critic} delta$\n",
    "\n",
    "That is: $V(s_t) ← V(s_t) + \\alpha_{critic} [r_{t+1} + \\gamma V(s_{t+1}) - V(s_t)]$\n",
    "\n",
    "Which can also be written: $V(s_t) ← (1- \\alpha_{critic}) V(s_t) + \\alpha_{critic}[r_{t+1} + \\gamma V(s_{t+1})]$\n",
    "\n",
    "This rule is the standard temporal difference update rule\n",
    "\n",
    "#### Type 1: Q-learning Update Rule:\n",
    "\n",
    "$Q(s_t, a_t) ← Q(s_t, a_t) + \\alpha_{critic} [r_{t+1} + \\gamma max_a Q(s_{t+1}, a) - Q(s_t, a_t)]$\n",
    "\n",
    "Which can also be written: $Q(s_t, a_t) ← (1- \\alpha_{critic}) Q(s_t, a_t) + \\alpha_{critic}[r_{t+1} + \\gamma max_a Q(s_{t+1}, a)]$\n",
    "\n",
    "This rule is the standard Q-learning update rule, it follows the off-policy approach.\n",
    "\n",
    "#### Type 2: SARSA Update Rule:\n",
    "\n",
    "$Q(s_t, a_t) ← Q(s_t, a_t) + \\alpha_{critic} [r_{t+1} + \\gamma Q(s_{t+1}, a_{t+1}) - Q(s_t, a_t)]$\n",
    "\n",
    "Which can also be written: $Q(s_t, a_t) ← (1- \\alpha_{critic}) Q(s_t, a_t) + \\alpha_{critic}[r_{t+1} + \\gamma Q(s_{t+1}, a_{t+1})]$\n",
    "\n",
    "where $a_{t+1}$ is given by the current policy\n",
    "\n",
    "This rule follows the on-policy approach, where we take the Q value of the next action according to the policy.\n",
    "\n",
    "#### Type 3: \"Expectation\" Q-learning Update Rule:\n",
    "\n",
    "$Q(s_t, a_t) ← Q(s_t, a_t) + \\alpha_{critic} [r_{t+1} + \\gamma \\sum_a \\pi(a|s_{t+1}) Q(s_{t+1}, a) -  Q(s_t, a)]$\n",
    "\n",
    "Which can also be written: $Q(s_t, a_t) ← (1- \\alpha_{critic}) Q(s_t, a_t) + \\alpha_{critic}[r_{t+1} + \\gamma \\sum_a \\pi(a|s_{t+1}) max_a Q(s_{t+1}, a) -  Q(s_t, a)]$\n",
    "\n",
    "This rule leverages the expected value of the Q-function over all actions given the current policy.\n",
    "\n",
    "If follows from the relation between the value function and the action value function $V^pi(s_t) = \\sum_a \\pi(a|s_t) Q(s_t, a)]$.\n",
    "\n",
    "#### Type 4: \"Max\" Q-learning Update Rule:\n",
    "\n",
    "$Q(s_t, a_t) ← Q(s_t, a_t) + \\alpha_{critic} [r_{t+1} + \\gamma max_a Q(s_{t+1}, a) - max_a Q(s_t, a)]$\n",
    "\n",
    "This rule makes little sense when one considers the $Q(s_t, a_t) ← (1- \\alpha_{critic}) Q(s_t, a_t) + \\alpha_{critic}[something else]$ notation,\n",
    "But we keep it because its behavior is interesting."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6163957a",
   "metadata": {},
   "source": [
    "### Implementation of the critic update rules\n",
    "\n",
    "You have to implement the above critic update rules yourself.\n",
    "\n",
    "We suggest using a single `update_critic()` function that works both for $V$ and $Q$\n",
    "though $V$ uses only the state as parameter whereas $Q$ uses a (state, action) pair.\n",
    "\n",
    "The price to pay for this unification is that we call `q` the corresponding array, no matter whether it represents $V$ or $Q$.\n",
    "Students can change the code if they want to move away from this approach.\n",
    "\n",
    "We need to return the temporal difference error delta because it can be used to also update the actor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9b3fd6f2",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Useful to plot curves and to enumerate the different cases with explicit labels\n",
    "\n",
    "type_names = [\"TD\", \"Qlearning\", \"SARSA\", \"ExpectationQlearning\", \"MaxQlearning\"]\n",
    "action_choice_names = [\"Critic-based\", \"Policy-based\"]\n",
    "nb_types = 5\n",
    "\n",
    "\n",
    "class UpdateType(Enum):\n",
    "    TD = 0\n",
    "    Qlearning = 1\n",
    "    SARSA = 2\n",
    "    ExpectationQlearning = 3\n",
    "    MaxQlearning = 4\n",
    "\n",
    "\n",
    "class ActionChoice(Enum):\n",
    "    Critic = 0\n",
    "    Policy = 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b0f95d6",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def update_critic(\n",
    "    update_type: int,\n",
    "    policy: np.array,\n",
    "    q: np.array,\n",
    "    alpha_critic: float,\n",
    "    state: int,\n",
    "    action: int,\n",
    "    next_state: int,\n",
    "    next_action: int,\n",
    "    terminated: bool,\n",
    "    reward: float,\n",
    ") -> float:\n",
    "    \"\"\"\n",
    "    Update a critic with different update types and return the temporal difference error\n",
    "    :param update_type: from 0 to 4, corresponds to the above update rules\n",
    "    :param policy: the current policy that is trained\n",
    "    :param q: the critic, can represent either a $V$ or a $Q$ function\n",
    "    :param alpha_critic: the critic learning rate\n",
    "    :param state: the current state where the update is performed\n",
    "    :param action: the current action (can come from the current policy or from uniform sampling)\n",
    "    :param next_state: the next state\n",
    "    :param next_action: the next action (can come from the current policy or from uniform sampling)\n",
    "    :param terminated: whether the trajectory terminates (if True, the Bellman backup should be ignored)\n",
    "    :param reward: the received reward\n",
    "    :return delta: the computed temporal difference error\n",
    "    \"\"\"\n",
    "\n",
    "    # [[STUDENT]]...\n",
    "\n",
    "    assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "    # Update the critic\n",
    "    if update_type == 0:\n",
    "        q[state] += alpha_critic * delta\n",
    "    else:\n",
    "        q[state, action] += alpha_critic * delta\n",
    "    return delta"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "60d7a8a5",
   "metadata": {},
   "source": [
    "## Actor update\n",
    "\n",
    "To update the actor, naively applying the same learning rule\n",
    "would not ensure that the probabilities of all actions in a state sum to 1.\n",
    "Besides, when the temporal difference error $\\delta_t$ is negative,\n",
    "it may happen that the probability of an action gets negative or null,\n",
    "which raises an issue when applying renormalization.\n",
    "\n",
    "So, instead of applying the naive rule, we apply the following one:\n",
    "$$\n",
    "\\pi_{temp}(a_t|s_t) =  \\begin{cases}\n",
    "\\pi^{(i)}(a_t|s_t) + \\alpha_{actor} \\delta_t & \\mathrm{if } \\pi^{(i)}(a_t|s_t) + \\alpha_{actor} \\delta_t > 10^{-8}\\\\\n",
    "10^{-8} & \\mathrm{otherwise.} \\\\\n",
    "\\end{cases}\n",
    "$$\n",
    "\n",
    "Then we can apply renormalization so that the probabilities of actions still sum to 1, with\n",
    "$$\n",
    "\\forall a, \\pi^{(i+1)}(a|s_t) = \\frac{\\pi_{temp}^{(i+1)}(a|s_t)} {\\sum_{a'} \\pi_{temp}^{(i+1)}(a'|s_t)}\n",
    "$$ with\n",
    "$$\n",
    "\\pi_{temp}^{(i+1)}(a|s_t) =  \\begin{cases}\n",
    "\\pi_{temp}(a|s_t) & \\mathrm{if } a = a_t\\\\\n",
    "\\pi^{(i)}(a|s_t) & \\mathrm{otherwise.} \\\\\n",
    "\\end{cases}\n",
    "$$\n",
    "\n",
    "You have to provide the corresponding code below.\n",
    "\n",
    "### Implementation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2cdca733",
   "metadata": {},
   "outputs": [],
   "source": [
    "def renormalize(\n",
    "    policy: np.array,\n",
    "    state: int,\n",
    ") -> None:\n",
    "    \"\"\"\n",
    "    Renormalize the probability of actions so that the sum of probabilities over actions is always 1.\n",
    "    We made sure in the calling function that the probabilities of action never get negative when they are decreased.\n",
    "    :param policy: the current policy, before normalization\n",
    "    :param state: the state where the actions need to be renormalized\n",
    "    :return: nothing\n",
    "    \"\"\"\n",
    "    # [[STUDENT]]...\n",
    "\n",
    "    assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "\n",
    "def update_policy(\n",
    "    policy: np.array,\n",
    "    delta: np.array,\n",
    "    state: int,\n",
    "    action: int,\n",
    "    alpha_actor: float,\n",
    ") -> None:\n",
    "    \"\"\"\n",
    "    Update the policy from the temporal difference error, using renormalization\n",
    "    :param policy: the current policy\n",
    "    :param delta: the temporal difference error\n",
    "    :param state: the current state\n",
    "    :param delta: the current action\n",
    "    :param alpha_actor: the actor learning rate\n",
    "    :return: nothing\n",
    "    \"\"\"\n",
    "\n",
    "    # [[STUDENT]]...\n",
    "\n",
    "    assert False, 'Not implemented yet'\n",
    "\n",
    "    # Used to make sure normalization works properly\n",
    "    assert np.isclose(np.sum(policy[state]), 1.0), \"Policy is not properly normalized!\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "763ec44e",
   "metadata": {},
   "source": [
    "# Utilities\n",
    "\n",
    "Once you have coded the core algorithms above, most of the code below is provided\n",
    "to let you obtain curves and analyze them on your own\n",
    "(apart from value iteration functions that you have coded during labs).\n",
    "\n",
    "Feel free to change anything in this code if you want to provide other analyses."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "481a6f6f",
   "metadata": {},
   "source": [
    "## Actor-critic hyper-parameters\n",
    "\n",
    "To represent the hyper-parameters of the experiments performed in this notebook, we suggest using the dictionary below.\n",
    "This dictionary can be read using omegaconf.\n",
    "Using it is not mandatory.\n",
    "You can also change the value of hyper-parameters or environment parameters at will."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d650c9e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "ac_params = {\n",
    "    \"maze\": {\n",
    "        \"name\": \"MazeMDP-v0\",\n",
    "        \"width\": 5,\n",
    "        \"height\": 5,\n",
    "        \"ratio\": 0.2,\n",
    "        \"render_mode\": \"human\",\n",
    "    },\n",
    "    \"nb_episodes\": Profile.pick(150, fast_test=5),\n",
    "    \"nb_samples\": Profile.pick(1500, fast_test=50),\n",
    "    \"nb_repeats\": Profile.pick(5, fast_test=1),\n",
    "    \"alpha_critic\": 0.98,\n",
    "    \"alpha_actor\": 0.95,\n",
    "    \"gamma\": 0.95,\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "424e05a2",
   "metadata": {},
   "source": [
    "## Create the mdp"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ac3cc902",
   "metadata": {},
   "outputs": [],
   "source": [
    "def make_mdp(cfg):\n",
    "    \"\"\"\n",
    "    Return the MazeMDP and an unwrapped version, used to access the attributes and function without raising a warning.\n",
    "    We also need the not unwrapped env for calling steps otherwise truncation beyond time limit will not apply\n",
    "    \"\"\"\n",
    "    # Environment with 20% of walls and no negative reward when hitting a wall\n",
    "    mdp = gym.make(\n",
    "        \"MazeMDP-v0\",\n",
    "        kwargs={\n",
    "            \"width\": cfg.maze.width,\n",
    "            \"height\": cfg.maze.height,\n",
    "            \"ratio\": cfg.maze.ratio,\n",
    "            \"hit\": 0.0,\n",
    "            \"start_states\": [0],\n",
    "        },\n",
    "        render_mode=cfg.maze.render_mode,\n",
    "    )\n",
    "    env = (\n",
    "        mdp.unwrapped\n",
    "    )  # the .unwrapped removes a warning from gymnasium when accessing an attribute or function\n",
    "    return mdp, env\n",
    "\n",
    "\n",
    "cfg = ns(ac_params)\n",
    "mdp, env = make_mdp(cfg)\n",
    "mdp.reset()\n",
    "env.init_draw(\"The maze\")\n",
    "env.gamma = cfg.gamma"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0cbdc263",
   "metadata": {},
   "source": [
    "## Get optimal critic\n",
    "\n",
    "To evaluate the above algorithms, you will compare the obtained $V$ and $Q$ critics to their optimal counterpart.\n",
    "\n",
    "To obtain the optimal $V$ and $Q$ critics, we suggest using the value iteration algorithm with the $V$ function and the $Q$ function\n",
    "that you have coded during labs (and `get_policy_from_v()` if need be)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ae2ec8a8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# [[STUDENT]]...\n",
    "\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f19f383e",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "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(render: bool = True) -> Tuple[np.ndarray, List[float]]:\n",
    "    q = np.zeros(\n",
    "        (env.nb_states, env.action_space.n)\n",
    "    )  # initial action values are set to 0\n",
    "    q_list = []\n",
    "    stop = False\n",
    "\n",
    "    while not stop:\n",
    "        qold = q.copy()\n",
    "\n",
    "        for x in range(env.nb_states):\n",
    "            for u in range(env.action_space.n):\n",
    "                if x in env.terminal_states:\n",
    "                    q[x, u] = env.r[x, u]\n",
    "                else:\n",
    "                    summ = 0\n",
    "                    for y in range(env.nb_states):\n",
    "                        summ += env.P[x, u, y] * np.max(qold[y, :])\n",
    "\n",
    "                    # Compléter d'après la formule ci-dessus\n",
    "\n",
    "                    q[x, u] = ...\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",
    "    return q, q_list"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b76c7440",
   "metadata": {},
   "source": [
    "## IQM and percentiles\n",
    "\n",
    "These utilities are useful to provide meaningful measures of variability\n",
    "when plotting learning curves.\n",
    "\n",
    "### Calculate IQM and percentiles\n",
    "\n",
    "Calculate the interquartile mean using the percentiles between min_bound and max_bound"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c6e98782",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def calculate_iqm(all_steps, min_bound, max_bound):\n",
    "    \"\"\"\n",
    "    Calculate the Interquartile Mean (IQM) for the given data.\n",
    "    :param all_steps: Array of steps from multiple runs\n",
    "    :return: IQM array\n",
    "    \"\"\"\n",
    "    # Calculate the min and max percentiles\n",
    "    steps_min = np.percentile(all_steps, min_bound, axis=0)\n",
    "    steps_max = np.percentile(all_steps, max_bound, axis=0)\n",
    "\n",
    "    # IQM calculation: mean of values between min and max percentiles\n",
    "    steps_iqm = np.mean(np.clip(all_steps, steps_min, steps_max), axis=0)\n",
    "\n",
    "    return steps_iqm, steps_min, steps_max"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "440b9049",
   "metadata": {},
   "source": [
    "###  Plot function: IQM and percentiles\n",
    "\n",
    "Plot the Interquartile mean and corresponding percentiles with a label"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "63e00b99",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def plot_quartiles(q_iqm, q_low, q_high, label):\n",
    "    plt.plot(range(len(q_iqm)), q_iqm, label=label)\n",
    "    plt.fill_between(range(len(q_iqm)), q_low, q_high, alpha=0.2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3285ce1",
   "metadata": {},
   "source": [
    "###  Plot function: errors, steps or norms\n",
    "\n",
    "The plot results function below receives some data to be plotted that can correspond\n",
    "to critic errors, number of steps to exit the maze or norms of critic arrays."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb2e0f7b",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def plot_results(results, results_string):\n",
    "\n",
    "    plt.figure(figsize=(12, 8))\n",
    "    plt.title(f\"{results_string} - Comparison of Update Rules (gamma={env.gamma})\")\n",
    "    plt.xlabel(\"Number of episodes\")\n",
    "    plt.ylabel(f\"{results_string}\")\n",
    "    plt.grid(True, linestyle=\"--\", alpha=0.6)\n",
    "\n",
    "    for type in range(nb_types):\n",
    "        res = np.array(results[type])\n",
    "        results_iqm, results_min, results_max = calculate_iqm(res, 25, 75)\n",
    "        plot_quartiles(\n",
    "            results_iqm, results_min, results_max, f\"type {type}: {type_names[type]}\"\n",
    "        )\n",
    "\n",
    "    plt.legend(loc=\"upper right\")\n",
    "\n",
    "    plot_filepath = output_dir / f\"{results_string}_alpha_critic_{cfg.alpha_critic}.pdf\"\n",
    "\n",
    "    plt.savefig(plot_filepath)\n",
    "    print(f\"Plot saved to {plot_filepath}\")\n",
    "\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6eb4ddbd",
   "metadata": {},
   "source": [
    "### Uniform sampling of state, action, next action triples"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "147f3854",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def draw_full_uniform() -> Tuple[int, int, int]:\n",
    "    state = random.randint(0, env.nb_states - 1)\n",
    "    action = env.action_space.sample()\n",
    "    next_action = env.action_space.sample()\n",
    "    return state, action, next_action"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b0dcec7",
   "metadata": {},
   "source": [
    "### Uniform sampling of state, action, and using the policy for the next action"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4f6f19da",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def draw_uniform(policy) -> Tuple[int, int, int]:\n",
    "    state = random.randint(0, env.nb_states - 1)\n",
    "    action = env.action_space.sample()\n",
    "    env.state = state\n",
    "    next_state, _, _, _, _ = env.step(action)\n",
    "    next_action = sample_categorical(policy[next_state])  # draw action from the policy\n",
    "    return state, action, next_action"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b0d956db",
   "metadata": {},
   "source": [
    "### Choosing the action, either from the critic (when using a $Q$ fuynction) or the policy\n",
    "\n",
    "If we are using a stochastic policy, we sample from that policy.\n",
    "If we are using a critic, we add epsilon greedy noise to determine the action."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9904cec6",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def get_action(action_choice, update_type, policy, critic, state, epsilon):\n",
    "    if action_choice == ActionChoice.Policy.value:\n",
    "        action = sample_categorical(policy[state])\n",
    "    elif action_choice == ActionChoice.Critic.value:\n",
    "        assert (\n",
    "            update_type != UpdateType.TD.value\n",
    "        ), \"cannot choose action from a V critic\"\n",
    "        action = egreedy(critic, state, epsilon)\n",
    "    else:\n",
    "        raise ValueError(f\"Invalid update type: {update_type}\")\n",
    "    return action"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0f8a59bd",
   "metadata": {},
   "source": [
    "### Performing episodes, with or without training the critic and policy\n",
    "\n",
    "Perform an episode where the action is chosen either by the stochastic policy or by the critic"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "edbf095f",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def perform_episode(\n",
    "    training: bool,\n",
    "    update_type: int,\n",
    "    action_choice: int,\n",
    "    policy: np.array,\n",
    "    critic: np.array,\n",
    "    critic_ref: np.array,\n",
    "    alpha_critic: float,\n",
    "    alpha_actor: float,\n",
    "    epsilon=0.4,\n",
    ") -> Tuple[float, int]:\n",
    "    \"\"\"\n",
    "    Perform an episode\n",
    "    :param training: whether the policy is trained or not while performing the episode (useful to separate training and evaluation)\n",
    "    :param update_type: int indicating the chosen update rule.\n",
    "    :return: the number of steps before it stops and the norm of the error with respect to the optimal critic.\n",
    "    \"\"\"\n",
    "    state, _ = mdp.reset()  # reinit env, get initial state\n",
    "    terminated = False\n",
    "    truncated = False\n",
    "    steps = 0\n",
    "\n",
    "    action = get_action(action_choice, update_type, policy, critic, state, epsilon)\n",
    "\n",
    "    while not (terminated or truncated):\n",
    "\n",
    "        next_state, reward, terminated, truncated, _ = mdp.step(action)\n",
    "\n",
    "        next_action = get_action(\n",
    "            action_choice, update_type, policy, critic, next_state, epsilon\n",
    "        )\n",
    "\n",
    "        if training:\n",
    "            delta = update_critic(\n",
    "                update_type,\n",
    "                policy,\n",
    "                critic,\n",
    "                alpha_critic,\n",
    "                state,\n",
    "                action,\n",
    "                next_state,\n",
    "                next_action,\n",
    "                terminated,\n",
    "                reward,\n",
    "            )\n",
    "            update_policy(policy, delta, state, action, cfg.alpha_actor)\n",
    "\n",
    "        # Move to the next state\n",
    "        state = next_state\n",
    "        steps += 1\n",
    "        action = next_action\n",
    "\n",
    "        # Track the difference between the critic and the optimal critic\n",
    "\n",
    "        critic_norm = np.linalg.norm(critic - critic_ref)\n",
    "\n",
    "    return steps, critic_norm"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a69b9d4",
   "metadata": {},
   "source": [
    "## Study of the uniform sampling case"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "464d383e",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def actor_critic_uniform(\n",
    "    update_type: int,\n",
    "    action_choice: int,\n",
    "    nb_samples: int,\n",
    "    critic: np.array,\n",
    "    critic_ref: np.array,\n",
    "    alpha_critic: float,\n",
    "    alpha_actor: float,\n",
    ") -> np.array:\n",
    "    \"\"\"\n",
    "    Train a critic using samples drawn uniformly.\n",
    "    The obtained critic is compared through time to a reference critic\n",
    "    :param update_type: int indicating the chosen update rule\n",
    "    :return: a list of norm of difference between Q values and reference Q values, and a list of number of steps to exit the maze\n",
    "    \"\"\"\n",
    "\n",
    "    # Initialize uniform policy\n",
    "    policy = np.ones((env.nb_states, env.action_space.n)) / env.action_space.n\n",
    "\n",
    "    nb_steps = []\n",
    "    q_errors = []\n",
    "\n",
    "    for step in range(nb_samples):\n",
    "        state, action, next_action = draw_uniform(policy)\n",
    "        env.mdp.current_state = state\n",
    "        next_state, reward, terminated, _, _ = mdp.step(action)\n",
    "        delta = update_critic(\n",
    "            update_type,\n",
    "            policy,\n",
    "            critic,\n",
    "            alpha_critic,\n",
    "            state,\n",
    "            action,\n",
    "            next_state,\n",
    "            next_action,\n",
    "            terminated,\n",
    "            reward,\n",
    "        )\n",
    "        error = np.linalg.norm(critic - critic_ref)\n",
    "\n",
    "        update_policy(policy, delta, state, action, cfg.alpha_actor)\n",
    "        q_errors.append(error)\n",
    "\n",
    "        if step % 10 == 0:\n",
    "            steps, _ = perform_episode(\n",
    "                False,\n",
    "                update_type,\n",
    "                action_choice,\n",
    "                policy,\n",
    "                critic,\n",
    "                critic_ref,\n",
    "                alpha_critic,\n",
    "                alpha_actor=0.0,\n",
    "            )\n",
    "            nb_steps.append(steps)\n",
    "\n",
    "    return q_errors, nb_steps"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "833dc53f",
   "metadata": {},
   "source": [
    "Running evaluation based on uniform sampling"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c1f55166",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def run_uniform():\n",
    "    v_ref, _ = value_iteration_v()\n",
    "    q_ref, _ = value_iteration_q()\n",
    "    errors = np.zeros((nb_types, cfg.nb_repeats, cfg.nb_samples))\n",
    "    steps = np.zeros((nb_types, cfg.nb_repeats, int(cfg.nb_samples / 10)))\n",
    "    for action_choice in range(2):\n",
    "        print(f\"action choice : {action_choice_names[action_choice]}\")\n",
    "        for update_type in range(nb_types):\n",
    "            errors_list = []\n",
    "            steps_list = []\n",
    "            for _ in range(cfg.nb_repeats):\n",
    "                # Initialize Q-values and V-values to zero\n",
    "                v = np.zeros(env.nb_states)\n",
    "                q = np.zeros((env.nb_states, env.action_space.n))\n",
    "                if update_type == UpdateType.TD.value:\n",
    "                    error, step = actor_critic_uniform(\n",
    "                        update_type,\n",
    "                        ActionChoice.Policy.value,\n",
    "                        cfg.nb_samples,\n",
    "                        v,\n",
    "                        v_ref,\n",
    "                        cfg.alpha_critic,\n",
    "                        cfg.alpha_actor,\n",
    "                    )\n",
    "                else:\n",
    "                    error, step = actor_critic_uniform(\n",
    "                        update_type,\n",
    "                        action_choice,\n",
    "                        cfg.nb_samples,\n",
    "                        q,\n",
    "                        q_ref,\n",
    "                        cfg.alpha_critic,\n",
    "                        cfg.alpha_actor,\n",
    "                    )\n",
    "                errors_list.append(error)\n",
    "                steps_list.append(step)\n",
    "            errors[update_type] = errors_list\n",
    "            steps[update_type] = steps_list\n",
    "        plot_results(\n",
    "            errors, f\"critic_error_uniform_{action_choice_names[action_choice]}\"\n",
    "        )\n",
    "        plot_results(steps, f\"steps2exit_uniform_{action_choice_names[action_choice]}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17721b85",
   "metadata": {},
   "source": [
    "## Standard online, on-policy learning case"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2914dde9",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "def actor_critic_online(\n",
    "    update_type: int,\n",
    "    action_choice: int,\n",
    "    nb_episodes: int,\n",
    "    v_ref: np.array,\n",
    "    q_ref: np.array,\n",
    "    alpha_critic: float,\n",
    "    alpha_actor: float,\n",
    ") -> Tuple[np.array, int, np.array, np.array]:\n",
    "    \"\"\"\n",
    "    Perform actor-critic training over a number of episodes with Q-values.\n",
    "    :param update_type: int indicating the chosen update rule\n",
    "    :return: a list of number of steps of episodes and a list of norm of critic values\n",
    "    \"\"\"\n",
    "    # Initialize Q-values and V-values to zero\n",
    "    q = np.zeros((env.nb_states, env.action_space.n))\n",
    "    v = np.zeros(env.nb_states)\n",
    "\n",
    "    # Initialize uniform policy\n",
    "    policy = np.ones((env.nb_states, env.action_space.n)) / env.action_space.n\n",
    "\n",
    "    # Store the number of steps and norms\n",
    "    nb_steps = []\n",
    "    critic_errors = []\n",
    "\n",
    "    for ep in range(nb_episodes):\n",
    "        if update_type == 0:\n",
    "            steps, critic_error = perform_episode(\n",
    "                True,\n",
    "                update_type,\n",
    "                ActionChoice.Policy.value,\n",
    "                policy,\n",
    "                v,\n",
    "                v_ref,\n",
    "                alpha_critic,\n",
    "                alpha_actor,\n",
    "            )\n",
    "        else:\n",
    "            steps, critic_error = perform_episode(\n",
    "                True,\n",
    "                update_type,\n",
    "                action_choice,\n",
    "                policy,\n",
    "                q,\n",
    "                q_ref,\n",
    "                alpha_critic,\n",
    "                alpha_actor,\n",
    "            )\n",
    "        critic_errors.append(critic_error)\n",
    "        nb_steps.append(steps)\n",
    "\n",
    "    return nb_steps, critic_errors"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "05a6c145",
   "metadata": {},
   "source": [
    "Running evaluation based on online RL"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d6c270a4",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_online():\n",
    "    v_ref, _ = value_iteration_v()\n",
    "    q_ref, _ = value_iteration_q()\n",
    "    steps = np.zeros((nb_types, cfg.nb_repeats, cfg.nb_episodes))\n",
    "    vals = np.zeros((nb_types, cfg.nb_repeats, cfg.nb_episodes))\n",
    "\n",
    "    for action_choice in range(2):\n",
    "        print(f\"action choice : {action_choice_names[action_choice]}\")\n",
    "        for update_type in range(nb_types):\n",
    "            vals_list = []\n",
    "            steps_list = []\n",
    "            for _ in range(cfg.nb_repeats):\n",
    "                nb_steps, critic_errors = actor_critic_online(\n",
    "                    update_type,\n",
    "                    action_choice,\n",
    "                    cfg.nb_episodes,\n",
    "                    v_ref,\n",
    "                    q_ref,\n",
    "                    cfg.alpha_critic,\n",
    "                    cfg.alpha_actor,\n",
    "                )\n",
    "                vals_list.append(critic_errors)\n",
    "                steps_list.append(nb_steps)\n",
    "            steps[update_type] = steps_list\n",
    "            vals[update_type] = vals_list\n",
    "        plot_results(\n",
    "            vals, f\"critic_error_on-policy_{action_choice_names[action_choice]}\"\n",
    "        )\n",
    "        plot_results(\n",
    "            steps, f\"steps2exit_on-policy_{action_choice_names[action_choice]}\"\n",
    "        )"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f4ab0cc9",
   "metadata": {},
   "source": [
    "Run the whole thing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b25220e1",
   "metadata": {},
   "outputs": [],
   "source": [
    "run_uniform()\n",
    "run_online()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f660da55",
   "metadata": {},
   "source": [
    "Write a report\n",
    "\n",
    "Now your job is to write a pdf report which may contain the curves you have generated,\n",
    "which explains what you see and which draws conclusions from these evaluations.\n",
    "Fill free to remove curves that you don't want to comment or to provide additional\n",
    "curves or figures.\n",
    "\n",
    "Beware that if you want to assert that an algorithm outperforms another, you should validate your claim with a statistical test.\n",
    "\n",
    "The report should be a pdf named name1_name2.pdf where name1 and name2 are the names of the authors.\n",
    "It should not be longer than 6 pages and written in english.\n",
    "Using LLMs to improve formulation is welcome, using it to generate thoughts about the work is strongly discouraged.\n",
    "Do not forget you are here to learn how to think by yourselves."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_markers": "\"\"\"",
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "V or Q critics, uniform against on-policy sampling: what is off-policy?",
   "practical_name": "Tabular actor-critic: the critic update rules (2025)"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
