{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e78cb889",
   "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": "a40482fb",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "In this notebook, you will code a naive actor-critic algorithm in the tabular case. Then you will tune it using grid search and Bayesian optimization, potentially using the [optuna](https://optuna.readthedocs.io/en/stable/) library.\n",
    "Finally, you will get the best hyper-parameters obtained with both methods and perform a statistical test to see if there is a statistically significant difference between these methods and with respect to naive hyper-parameter values.\n",
    "\n",
    "## Install libraries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2acd548c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import gymnasium as gym\n",
    "import hydra\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import optuna\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import yaml\n",
    "import rl_mind.mazemdp_env\n",
    "from functools import partial\n",
    "from typing import List\n",
    "from mazemdp.mdp import Mdp\n",
    "from mazemdp.toolbox import sample_categorical\n",
    "from omegaconf import DictConfig, OmegaConf\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\n",
    "from scipy.stats import ttest_ind"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "73e90b58",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()\n",
    "\n",
    "# Every figure / file produced by this notebook goes in a fresh run directory\n",
    "output_dir = run_directory(\"actor-critic-2024\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "24078b65",
   "metadata": {},
   "source": [
    "# Step 1: Coding the naive Actor-critic algorithm\n",
    "\n",
    "We consider the naive actor-critic algorithm with a categorical policy.\n",
    "The algorithm learns a critic with the standard temporal difference mechanism\n",
    "using a learning rate $\\alpha_{critic}$.\n",
    "\n",
    "We consider a value-based critic $V(s)$. The extension to an action value function $Q(s,a)$ is straightforward.\n",
    "\n",
    "To update the critic, the algorithm computes the temporal difference error:\n",
    "\n",
    "$$\\delta_t = r(s_t, a_t) + \\gamma V^{(n)}(s_{t+1})-V^{(n)}(s_t).$$\n",
    "\n",
    "Then it applies it to the critic:\n",
    "\n",
    "$$V^{(n+1)}(s_t) = V^{(n)}(s_t) + \\alpha_{critic} \\delta_t.$$\n",
    "\n",
    "To update the actor, the general idea is the same, using the temporal difference error with another learning rate $\\alpha_{actor}$.\n",
    "\n",
    "However, naively applying the same learning rule 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, it may happen that the probability of an action gets negative or null, 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",
    "## Exercise 1\n",
    "\n",
    "### 1. Code the naive actor-critic algorithm as specified above.\n",
    "\n",
    "Some hints:\n",
    "\n",
    "- a good idea to build this code it to take inspiration from the code of Q-learning, to add an actor (a categorical policy), both learning rates,\n",
    "and to take care about the renormalization function.\n",
    "\n",
    "- for the next steps of this lab, having a function to repeatedly call your actor-critic algorithm and save the learning trajectories and\n",
    "norms of the value function is a good idea."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "41005740",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "# [[STUDENT]]...\n",
    "\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a3a31d41",
   "metadata": {},
   "source": [
    "### 2. Provide a plot function\n",
    "\n",
    "Your plot function should show the evolution through time of number of steps the agent takes to find the reward in the maze.\n",
    "If your algorithm works, this number of steps should decrease through time.\n",
    "\n",
    "Your plot function should also show a mean and a standard deviation (or some more advanced statistics) over a collection of learning runs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2e4ed70b",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "# [[STUDENT]]...\n",
    "\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dc74c05d",
   "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": "a59f14f9",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "ac_params = {\n",
    "    \"save_curves\": False,\n",
    "    \"save_heatmap\": True,\n",
    "    \"mdp\": {\n",
    "        \"name\": \"MazeMDP-v0\",\n",
    "        \"width\": 5,\n",
    "        \"height\": 5,\n",
    "        \"ratio\": 0.2,\n",
    "        \"render_mode\": \"rgb_array\",\n",
    "        },\n",
    "\n",
    "    \"log_dir\": \"./tmp\",\n",
    "    \"video_dir\": \"./tmp/videos\",\n",
    "\n",
    "    \"nb_episodes\": Profile.pick(100, fast_test=5),\n",
    "    \"timeout\": 200,\n",
    "    \"render\": False, # True, #\n",
    "    \"nb_repeats\": Profile.pick(5, fast_test=1),\n",
    "\n",
    "    \"alpha_critic\": 0.5,\n",
    "    \"alpha_actor\": 0.5,\n",
    "    }"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d83ac2d",
   "metadata": {},
   "source": [
    "### 3. Test your code\n",
    "\n",
    "Once everything looks OK, save the obtained plot for your lab report"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d74bc5f9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# [[STUDENT]]...\n",
    "\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1dc37ddf",
   "metadata": {},
   "source": [
    "# Step 2: Tuning hyper-parameters\n",
    "\n",
    "In this part, you have to optimize two hyper-parameters of the actor-critic algorithm, namely the actor and critic learning rates.\n",
    "You have to do so using a simple grid search method and some Bayesian optimization method.\n",
    "For the latter, we suggest using the default sampler from [optuna](https://optuna.readthedocs.io/en/stable/).\n",
    "Follow the above link to understand how optuna works.\n",
    "Note that it also supports grid search and many other hyper-parameters tuning algorithms.\n",
    "\n",
    "You should make sure that the hyper-parameters tuning algorithms that you compare benefit from the same training budget\n",
    "We suggest 400 training runs overall for each method,\n",
    "which means 20 values each for the actor and the critic learning rates in the case of grid search.\n",
    "\n",
    "## Exercise 2\n",
    "\n",
    "### 1. Perform hyper-parameters tuning with two algorithms as suggested above.\n",
    "\n",
    "### 2. Provide a \"heatmap\" of the norm of the value function given the hyper-parameters, after training for each pair of hyper-parameters.\n",
    "\n",
    "### 3. Collect the value of the best hyper-parameters found with each algorithm. You will need them for Step 3.\n",
    "\n",
    "### 4. Include in your report the heatmaps and the best hyper-parameters found for each method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0e77ee81",
   "metadata": {},
   "outputs": [],
   "source": [
    "# [[STUDENT]]...\n",
    "\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e9ad303",
   "metadata": {},
   "source": [
    "# Step 3: Statistical tests\n",
    "\n",
    "Now you have to compare the performance of the actor-critic algorithm tuned\n",
    "with all the best hyper-parameters you found before, using statistical tests.\n",
    "\n",
    "The functions below are provided to run Welch's T-test over learning curves.\n",
    "They have been adapted from a github repository: https://github.com/flowersteam/rl_stats\n",
    "You don't need to understand them in detail (though it is always a good idea to try to understand more code)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "717f2c26",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "def compute_central_tendency_and_error(id_central, id_error, sample):\n",
    "\n",
    "    try:\n",
    "        id_error = int(id_error)\n",
    "    except:\n",
    "        pass\n",
    "\n",
    "    if id_central == \"mean\":\n",
    "        central = np.nanmean(sample, axis=1)\n",
    "    elif id_central == \"median\":\n",
    "        central = np.nanmedian(sample, axis=1)\n",
    "    else:\n",
    "        raise NotImplementedError\n",
    "\n",
    "    if isinstance(id_error, int):\n",
    "        low = np.nanpercentile(sample, q=int((100 - id_error) / 2), axis=1)\n",
    "        high = np.nanpercentile(sample, q=int(100 - (100 - id_error) / 2), axis=1)\n",
    "    elif id_error == \"std\":\n",
    "        low = central - np.nanstd(sample, axis=1)\n",
    "        high = central + np.nanstd(sample, axis=1)\n",
    "    elif id_error == \"sem\":\n",
    "        low = central - np.nanstd(sample, axis=1) / np.sqrt(sample.shape[0])\n",
    "        high = central + np.nanstd(sample, axis=1) / np.sqrt(sample.shape[0])\n",
    "    else:\n",
    "        raise NotImplementedError\n",
    "\n",
    "    return central, low, high"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eecc9402",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "def run_test(test_id, data1, data2, alpha=0.05):\n",
    "    \"\"\"\n",
    "    Compute tests comparing data1 and data2 with confidence level alpha\n",
    "    :param test_id: (str) refers to what test should be used\n",
    "    :param data1: (np.ndarray) sample 1\n",
    "    :param data2: (np.ndarray) sample 2\n",
    "    :param alpha: (float) confidence level of the test\n",
    "    :return: (bool) if True, the null hypothesis is rejected\n",
    "    \"\"\"\n",
    "    data1 = data1.squeeze()\n",
    "    data2 = data2.squeeze()\n",
    "    n1 = data1.size\n",
    "    n2 = data2.size\n",
    "\n",
    "    # perform Welch t-test\":\n",
    "    _, p = ttest_ind(data1, data2, equal_var=False)\n",
    "    return p < alpha"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a779ff6a",
   "metadata": {},
   "source": [
    "This last function was adapted for the lab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dadfb08c",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "def perform_test(perf1, perf2, name1, name2, sample_size=20, downsampling_fact=5, confidence_level=0.01):\n",
    "\n",
    "    perf1 = perf1.transpose()\n",
    "    perf2 = perf2.transpose()\n",
    "    nb_datapoints = perf1.shape[1]\n",
    "    nb_steps = perf1.shape[0]\n",
    "\n",
    "    legend = [name1, name2]\n",
    "\n",
    "    # what do you want to plot ?\n",
    "    id_central = 'mean' # \"median\"  #\n",
    "    id_error = 80  # (percentiles), also: 'std', 'sem'\n",
    "\n",
    "    test_id = \"Welch t-test\"  # recommended\n",
    "\n",
    "    sample1 = perf1[:, np.random.randint(0, nb_datapoints, sample_size)]\n",
    "    sample2 = perf2[:, np.random.randint(0, nb_datapoints, sample_size)]\n",
    "\n",
    "    steps = np.arange(0, nb_steps, downsampling_fact)\n",
    "    sample1 = sample1[steps, :]\n",
    "    sample2 = sample2[steps, :]\n",
    "\n",
    "    # test\n",
    "    sign_diff = np.zeros([len(steps)])\n",
    "    for i in range(len(steps)):\n",
    "        sign_diff[i] = run_test(\n",
    "            test_id, sample1[i, :], sample2[i, :], alpha=confidence_level\n",
    "        )\n",
    "\n",
    "    central1, low1, high1 = compute_central_tendency_and_error(\n",
    "        id_central, id_error, sample1\n",
    "    )\n",
    "    central2, low2, high2 = compute_central_tendency_and_error(\n",
    "        id_central, id_error, sample2\n",
    "    )\n",
    "\n",
    "    # plot\n",
    "    _, ax = plt.subplots(1, 1, figsize=(20, 10))\n",
    "    lab1 = plt.xlabel(\"training steps\")\n",
    "    lab2 = plt.ylabel(\"performance\")\n",
    "\n",
    "    plt.plot(steps, central1, linewidth=10)\n",
    "    plt.plot(steps, central2, linewidth=10)\n",
    "    plt.fill_between(steps, low1, high1, alpha=0.3)\n",
    "    plt.fill_between(steps, low2, high2, alpha=0.3)\n",
    "    leg = ax.legend(legend, frameon=False)\n",
    "\n",
    "    # plot significative difference as dots\n",
    "    idx = np.argwhere(sign_diff == 1)\n",
    "    y = max(np.nanmax(high1), np.nanmax(high2))\n",
    "    plt.scatter(steps[idx], y * 1.05 * np.ones([idx.size]), s=100, c=\"k\", marker=\"o\")\n",
    "\n",
    "    # style\n",
    "    for line in leg.get_lines():\n",
    "        line.set_linewidth(10.0)\n",
    "    ax.spines[\"top\"].set_linewidth(5)\n",
    "    ax.spines[\"right\"].set_linewidth(5)\n",
    "    ax.spines[\"bottom\"].set_linewidth(5)\n",
    "    ax.spines[\"left\"].set_linewidth(5)\n",
    "\n",
    "    plt.savefig(\n",
    "        output_dir / f\"{name1}_{name2}.png\", bbox_extra_artists=(leg, lab1, lab2), bbox_inches=\"tight\", dpi=100\n",
    "    )\n",
    "    # plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "52ada3da",
   "metadata": {},
   "source": [
    "## Exercise 3\n",
    "\n",
    "As hyper-parameters, you will use:\n",
    "\n",
    "- naive tuning, that is a pair (0.5, 0.5) for the actor and critic learning rates,\n",
    "- the best hyper-parameters you found with the different tuning algorithms you used before.\n",
    "\n",
    "### 1. For each set of hyper-parameters, collect a large dataset of learning curves.\n",
    "\n",
    "We suggest using 150 training episodes.\n",
    "\n",
    "### 2. Perform statistical comparisons\n",
    "\n",
    "- Take two datasets of learning curves obtained with the hyper-parameters sets that you found with different tuning algorithms.\n",
    "- Use the ``` perform_test(...)``` function to compare each possible pair of sets.\n",
    "\n",
    "You should obtain an image for each pair you have tried.\n",
    "In this image, black dots signal the time step where there is a statistically significant difference between two learning curves.\n",
    "\n",
    " ### 3. Conclude."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "233c54d8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# [[STUDENT]]...\n",
    "\n",
    "assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7463bf81",
   "metadata": {},
   "source": [
    "# Lab report\n",
    "\n",
    "Your report should contain:\n",
    "- your source code (probably this notebook), do not forget to put your names on top of the notebook,\n",
    "- in a separate pdf file with your names in the name of the file:\n",
    "    + a detailed enough description of the choices you have made: the parameters you have set, the libraries you have used, etc.,\n",
    "    + the heatmaps obtained using the hyper-parameters tuning algorithms that you have used,\n",
    "    + the figures resulting from performing Welch's T-test using the best hyper-parameters from the above approaches,\n",
    "    + your conclusion from these experiments.\n",
    "\n",
    "Beyond the elements required in this report, any additional studies will be rewarded.\n",
    "For instance, you can try using a Q-function as critic, using random search as hyper-parameters tuning algorithm,\n",
    "using more challenging environments, etc."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_markers": "\"\"\"",
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "Grid search, Bayesian optimization with optuna, and a statistical test",
   "practical_name": "Tuning a tabular actor-critic (2024)"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
