{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3cfb26e8",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "In this notebook we study **partial observability** and how to mitigate it by\n",
    "*temporally extending* the agent, on the continuous `LunarLander-v3`\n",
    "environment trained with TD3.\n",
    "\n",
    "You will implement three gymnasium **wrappers**:\n",
    "\n",
    "1. a `FeatureFilterWrapper` that hides a feature from the observation (making\n",
    "   the environment non-Markovian);\n",
    "2. an `ObsTimeExtensionWrapper` that gives the agent a memory of the previous\n",
    "   observation;\n",
    "3. an `ActionTimeExtensionWrapper` that lets the agent prepare a sequence of\n",
    "   actions and play only the first.\n",
    "\n",
    "The TD3 algorithm itself is provided (it is the one from `04-ddpg-td3`)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "33da0d7c",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "**On Colab**: run the installation cell below (generated automatically,\n",
    "pinned versions). **Locally**: install the environment with `uv sync`, no\n",
    "need for this cell."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6ef5ffa9",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "import copy\n",
    "import gymnasium as gym\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "from dataclasses import dataclass, field, replace\n",
    "from torch import Tensor\n",
    "from torch.utils.tensorboard import SummaryWriter\n",
    "from tqdm.auto import tqdm\n",
    "from rl_mind.profiles import Profile\n",
    "from rl_mind.core import Action, Actor\n",
    "from rl_mind.nn import build_mlp, soft_update\n",
    "from rl_mind.env import VecEnv\n",
    "from rl_mind.data import ReplayBuffer, Transitions\n",
    "from rl_mind.collectors import TransitionCollector\n",
    "from rl_mind.evaluation import Evaluator\n",
    "from rl_mind.notebook import run_directory, setup_tensorboard, silence_known_warnings\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6f6b8b93",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pygame and tensorboard still use the deprecated `pkg_resources` API\n",
    "silence_known_warnings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "caa9b0fe",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# Temporal modification wrappers\n",
    "\n",
    "A gymnasium `Wrapper` intercepts `reset()` / `step()` to modify observations,\n",
    "actions or rewards without touching the underlying environment. Applied to\n",
    "each sub-environment of a `VecEnv` (via its `wrappers=` argument), they change\n",
    "the observation/action **dimensions** that the actor and critic see.\n",
    "\n",
    "### Example: `FeatureInverter`\n",
    "\n",
    "The given `FeatureInverter` swaps two features of the observation — a simple\n",
    "template for the wrappers you will write."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6ff0e624",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class FeatureInverter(gym.Wrapper):\n",
    "    \"\"\"Swap features `f1` and `f2` of the observation\"\"\"\n",
    "\n",
    "    def __init__(self, env, f1, f2):\n",
    "        super().__init__(env)\n",
    "        self.f1, self.f2 = f1, f2\n",
    "\n",
    "    def _invert(self, obs):\n",
    "        obs = obs.copy()\n",
    "        obs[[self.f1, self.f2]] = obs[[self.f2, self.f1]]\n",
    "        return obs\n",
    "\n",
    "    def reset(self, **kwargs):\n",
    "        obs, info = self.env.reset(**kwargs)\n",
    "        return self._invert(obs), info\n",
    "\n",
    "    def step(self, action):\n",
    "        obs, reward, terminated, truncated, info = self.env.step(action)\n",
    "        return self._invert(obs), reward, terminated, truncated, info"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5f35de5f",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Exercise 1: `FeatureFilterWrapper`\n",
    "\n",
    "Remove the feature at index `rank` from the observation (used to emulate\n",
    "partial observability, e.g. hiding a velocity). Remember to shrink the\n",
    "observation space accordingly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "98ac34b7",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class FeatureFilterWrapper(gym.Wrapper):\n",
    "    \"\"\"Remove the feature at index `rank` from the observation\"\"\"\n",
    "\n",
    "    def __init__(self, env, rank):\n",
    "        super().__init__(env)\n",
    "        self.rank = rank\n",
    "        # Shrink the observation space (remove the `rank`-th feature)\n",
    "\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "    def step(self, action):\n",
    "        observation, reward, terminated, truncated, info = self.env.step(action)\n",
    "        # Remove the feature from the observation\n",
    "\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "    def reset(self, **kwargs):\n",
    "        observation, info = self.env.reset(**kwargs)\n",
    "        # Remove the feature from the observation\n",
    "\n",
    "        assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f04ead27",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Exercise 2: `ObsTimeExtensionWrapper`\n",
    "\n",
    "Give the agent a memory of size 1: the wrapper concatenates the current\n",
    "observation with the **previous** one (reset to zeros at the start of an\n",
    "episode). For `LunarLander-v3`, remembering the previous position compensates\n",
    "for a hidden velocity, since $\\dot{a} \\approx a_t - a_{t-1}$. The observation\n",
    "space doubles in size."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cf12a81d",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class ObsTimeExtensionWrapper(gym.Wrapper):\n",
    "    \"\"\"Concatenate the current observation with the previous one (memory of 1)\"\"\"\n",
    "\n",
    "    def __init__(self, env):\n",
    "        super().__init__(env)\n",
    "        # Double the observation space and initialize the memory\n",
    "\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "    def step(self, action):\n",
    "        observation, reward, terminated, truncated, info = self.env.step(action)\n",
    "        # Concatenate with the memorized previous observation, then update the memory\n",
    "\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "    def reset(self, **kwargs):\n",
    "        observation, info = self.env.reset(**kwargs)\n",
    "        # Reset the memory to zeros\n",
    "\n",
    "        assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "999c7806",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Exercise 3: `ActionTimeExtensionWrapper`\n",
    "\n",
    "Let the agent output a sequence of **two** actions and play only the first\n",
    "(the critic then evaluates action *sequences*). The action space doubles in\n",
    "size; `step` receives a double-length action and forwards only the first half."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "652351ce",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class ActionTimeExtensionWrapper(gym.Wrapper):\n",
    "    \"\"\"Accept a sequence of two actions, play only the first\"\"\"\n",
    "\n",
    "    def __init__(self, env):\n",
    "        super().__init__(env)\n",
    "        # Double the action space\n",
    "\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "    def step(self, action):\n",
    "        # Forward only the first action to the inner environment\n",
    "\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "    def reset(self, **kwargs):\n",
    "        return self.env.reset(**kwargs)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d449713b",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "# TD3 (provided)\n",
    "\n",
    "The rest is the TD3 algorithm from `04-ddpg-td3`, unchanged — an actor, twin\n",
    "critics with target networks, Gaussian exploration noise, and a replay\n",
    "buffer. It is trained on the environment produced by applying the chosen\n",
    "wrappers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "000ed167",
   "metadata": {},
   "outputs": [],
   "source": [
    "class ContinuousDeterministicActor(Actor[Action]):\n",
    "    def __init__(self, obs_dim: int, hidden: tuple[int, ...], action_dim: int):\n",
    "        super().__init__()\n",
    "        self.model = build_mlp(\n",
    "            [obs_dim, *hidden, action_dim], output_activation=nn.Tanh()\n",
    "        )\n",
    "\n",
    "    def forward(self, obs: Tensor) -> Action:\n",
    "        return Action(value=self.model(obs))\n",
    "\n",
    "\n",
    "class GaussianNoise(Actor[Action]):\n",
    "    def __init__(self, actor: Actor[Action], sigma: float):\n",
    "        super().__init__()\n",
    "        self.actor = actor\n",
    "        self.sigma = sigma\n",
    "\n",
    "    def forward(self, obs: Tensor) -> Action:\n",
    "        action = self.actor(obs).value\n",
    "        return Action(value=action + self.sigma * torch.randn_like(action))\n",
    "\n",
    "    def act(self, obs: Tensor) -> Tensor:\n",
    "        return self.actor.act(obs)\n",
    "\n",
    "\n",
    "class ContinuousQNetwork(nn.Module):\n",
    "    def __init__(self, obs_dim: int, hidden: tuple[int, ...], action_dim: int):\n",
    "        super().__init__()\n",
    "        self.model = build_mlp([obs_dim + action_dim, *hidden, 1])\n",
    "\n",
    "    def forward(self, obs: Tensor, action: Tensor) -> Tensor:\n",
    "        return self.model(torch.cat([obs, action], dim=1)).squeeze(-1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2c199903",
   "metadata": {},
   "outputs": [],
   "source": [
    "@dataclass(frozen=True)\n",
    "class TD3Config:\n",
    "    env_name: str = \"LunarLander-v3\"\n",
    "    env_kwargs: dict = field(default_factory=lambda: {\"continuous\": True})\n",
    "    #: gymnasium wrappers applied to each sub-environment (partial-obs study)\n",
    "    wrappers: tuple = ()\n",
    "    seed: int = 2\n",
    "\n",
    "    max_steps: int = Profile.pick(300_000, fast_test=1_500)\n",
    "    n_envs: int = 1\n",
    "    steps_per_round: int = 100\n",
    "    updates_per_round: int = 100\n",
    "    learning_starts: int = Profile.pick(1_000, fast_test=200)\n",
    "\n",
    "    buffer_size: int = 1_000_000\n",
    "    batch_size: int = 256\n",
    "\n",
    "    gamma: float = 0.99\n",
    "    tau: float = 0.005\n",
    "    action_noise: float = 0.2\n",
    "    policy_delay: int = 2\n",
    "    target_noise: float = 0.2\n",
    "    target_noise_clip: float = 0.5\n",
    "    max_grad_norm: float = 0.5\n",
    "\n",
    "    actor_hidden: tuple[int, ...] = (64, 64)\n",
    "    critic_hidden: tuple[int, ...] = (400, 300)\n",
    "    lr: float = 1e-3\n",
    "\n",
    "    eval_interval: int = Profile.pick(5_000, fast_test=500)\n",
    "    n_eval_envs: int = 10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "34afa7e7",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_td3(cfg: TD3Config) -> Evaluator:\n",
    "    torch.manual_seed(cfg.seed)\n",
    "    env = VecEnv(\n",
    "        cfg.env_name, cfg.n_envs, seed=cfg.seed, wrappers=cfg.wrappers, **cfg.env_kwargs\n",
    "    )\n",
    "\n",
    "    actor = ContinuousDeterministicActor(\n",
    "        env.observation_dim, cfg.actor_hidden, env.action_dim\n",
    "    )\n",
    "    target_actor = copy.deepcopy(actor)\n",
    "    critic_1 = ContinuousQNetwork(\n",
    "        env.observation_dim, cfg.critic_hidden, env.action_dim\n",
    "    )\n",
    "    critic_2 = ContinuousQNetwork(\n",
    "        env.observation_dim, cfg.critic_hidden, env.action_dim\n",
    "    )\n",
    "    target_1, target_2 = copy.deepcopy(critic_1), copy.deepcopy(critic_2)\n",
    "\n",
    "    actor_optimizer = torch.optim.Adam(actor.parameters(), lr=cfg.lr)\n",
    "    critic_optimizer = torch.optim.Adam(\n",
    "        [*critic_1.parameters(), *critic_2.parameters()], lr=cfg.lr\n",
    "    )\n",
    "\n",
    "    collector = TransitionCollector(env, GaussianNoise(actor, cfg.action_noise))\n",
    "    buffer = ReplayBuffer(cfg.buffer_size)\n",
    "    run_dir = run_directory(f\"td3-{cfg.env_name}-S{cfg.seed}\")\n",
    "    writer = SummaryWriter(run_dir)\n",
    "    evaluator = Evaluator(\n",
    "        VecEnv(\n",
    "            cfg.env_name,\n",
    "            cfg.n_eval_envs,\n",
    "            seed=cfg.seed + 100,\n",
    "            wrappers=cfg.wrappers,\n",
    "            **cfg.env_kwargs,\n",
    "        ),\n",
    "        every=cfg.eval_interval,\n",
    "        run_dir=run_dir,\n",
    "        writer=writer,\n",
    "    )\n",
    "\n",
    "    updates = 0\n",
    "    pbar = tqdm(total=cfg.max_steps)\n",
    "    while collector.steps < cfg.max_steps:\n",
    "        buffer.add(collector.collect(cfg.steps_per_round))\n",
    "        pbar.update(collector.steps - pbar.n)\n",
    "        if len(buffer) < cfg.learning_starts:\n",
    "            continue\n",
    "\n",
    "        for _ in range(cfg.updates_per_round):\n",
    "            batch = buffer.sample(cfg.batch_size)\n",
    "            with torch.no_grad():\n",
    "                noise = (torch.randn_like(batch.action.value) * cfg.target_noise).clamp(\n",
    "                    -cfg.target_noise_clip, cfg.target_noise_clip\n",
    "                )\n",
    "                next_actions = (target_actor(batch.next_obs).value + noise).clamp(-1, 1)\n",
    "                q_next = torch.min(\n",
    "                    target_1(batch.next_obs, next_actions),\n",
    "                    target_2(batch.next_obs, next_actions),\n",
    "                )\n",
    "                target = batch.reward + cfg.gamma * q_next * (~batch.terminated).float()\n",
    "\n",
    "            critic_loss = F.mse_loss(\n",
    "                critic_1(batch.obs, batch.action.value), target\n",
    "            ) + F.mse_loss(critic_2(batch.obs, batch.action.value), target)\n",
    "            critic_optimizer.zero_grad()\n",
    "            critic_loss.backward()\n",
    "            critic_optimizer.step()\n",
    "\n",
    "            updates += 1\n",
    "            if updates % cfg.policy_delay == 0:\n",
    "                actor_loss = -critic_1(batch.obs, actor(batch.obs).value).mean()\n",
    "                actor_optimizer.zero_grad()\n",
    "                actor_loss.backward()\n",
    "                actor_optimizer.step()\n",
    "                soft_update(actor, target_actor, cfg.tau)\n",
    "                soft_update(critic_1, target_1, cfg.tau)\n",
    "                soft_update(critic_2, target_2, cfg.tau)\n",
    "\n",
    "        writer.add_scalar(\"loss/critic\", critic_loss.item(), collector.steps)\n",
    "        if result := evaluator.run_if_needed(collector.steps, actor):\n",
    "            pbar.set_description(\n",
    "                f\"eval={result.mean:7.1f} best={evaluator.best_reward:7.1f}\"\n",
    "            )\n",
    "\n",
    "    pbar.close()\n",
    "    return evaluator"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "659ad22a",
   "metadata": {},
   "source": [
    "## Launching tensorboard to visualize the results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "621b07f9",
   "metadata": {},
   "outputs": [],
   "source": [
    "setup_tensorboard()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b51e05fd",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## Exercise 4: the partial-observability study\n",
    "\n",
    "`LunarLander-v3`'s observation is `[x, y, vx, vy, angle, angular_vel, leg1,\n",
    "leg2]`. Using the wrappers above, produce and compare learning curves for:\n",
    "\n",
    "- the full (Markovian) environment;\n",
    "- hiding $\\dot{x}$ (index 2) or $\\dot\\theta$ (index 5), and hiding both;\n",
    "- the same, but adding the observation- and/or action-time-extension wrappers\n",
    "  to mitigate the partial observability.\n",
    "\n",
    "A configuration is one `wrappers` tuple. For example, hiding $\\dot{x}$ and\n",
    "$\\dot{y}$ then adding the observation memory:\n",
    "\n",
    "```python\n",
    "wrappers = (\n",
    "    lambda e: FeatureFilterWrapper(e, 3),   # remove the higher index first\n",
    "    lambda e: FeatureFilterWrapper(e, 2),\n",
    "    ObsTimeExtensionWrapper,\n",
    ")\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "18e160b4",
   "metadata": {},
   "outputs": [],
   "source": [
    "cfg = TD3Config(wrappers=())\n",
    "td3 = run_td3(cfg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f327e2a4",
   "metadata": {},
   "outputs": [],
   "source": [
    "td3.visualize_best()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "494f3df3",
   "metadata": {},
   "source": [
    "### Example: hide a velocity, then restore it with the observation memory"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "Wrappers that hide a feature, then extend the agent in time",
   "practical_name": "Partial observability: LunarLander"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
