{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "759b2b87",
   "metadata": {},
   "source": [
    "# Outlook\n",
    "\n",
    "[SuperTuxKart](https://supertuxkart.net) (STK) is a kart racing game; the\n",
    "[`pystk2-gymnasium`](https://github.com/bpiwowar/pystk2-gymnasium) package\n",
    "turns a race into a gymnasium environment. Before training anything on it,\n",
    "this notebook answers two questions:\n",
    "\n",
    "1. **what does the agent see?** (the *observation space*), and\n",
    "2. **what can the agent do?** (the *action space*).\n",
    "\n",
    "The package registers *several* environments. They all run the very same\n",
    "race: what changes is how observations and actions are **presented** — as a\n",
    "nested dictionary of variable-length lists, as fixed-size arrays, as two\n",
    "flat vectors, or with discretized actions. Choosing one is choosing which\n",
    "family of algorithms can be plugged in (DQN needs a `Discrete` action\n",
    "space, DDPG/SAC a `Box` one, an MLP a fixed-size input…).\n",
    "\n",
    "There is no learning here: we open each environment, print its spaces,\n",
    "look at a real observation, try a hand-written driver, and finish with an\n",
    "agent written as in the STK project."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ad6e21a5",
   "metadata": {
    "tags": [
     "colab",
     "pip",
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "# Installing required packages\n",
    "\n",
    "%pip install swig==4.3.* setuptools\n",
    "\n",
    "# Installing main packages\n",
    "\n",
    "%pip install gymnasium==1.2.* matplotlib numpy pystk2-gymnasium==0.10.* rl-mind==0.4.* torch\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "caa3ee9f",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "import tempfile\n",
    "import gymnasium as gym\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pystk2\n",
    "import torch\n",
    "from pathlib import Path\n",
    "from gymnasium import spaces\n",
    "from pystk2_gymnasium import AgentSpec, ConstantSizedObservations, PolarObservations\n",
    "from rl_mind import Actor, RolloutCollector, StochasticAction, VecEnv\n",
    "from rl_mind.profiles import Profile\n",
    "from torch import nn\n",
    "from torch.distributions import Categorical\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce86e2f3",
   "metadata": {},
   "source": [
    "## The registered environments\n",
    "\n",
    "Importing `pystk2_gymnasium` registers the environments under the\n",
    "`supertuxkart/` namespace of gymnasium:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d0225a7d",
   "metadata": {},
   "outputs": [],
   "source": [
    "STK_ENVS = sorted(name for name in gym.registry if name.startswith(\"supertuxkart/\"))\n",
    "for name in STK_ENVS:\n",
    "    wrappers = [w.name for w in gym.registry[name].additional_wrappers]\n",
    "    print(f\"{name:45s} wrappers: {', '.join(wrappers) or '-'}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6abf0a9",
   "metadata": {},
   "source": [
    "All of them (except `multi-full-v0`, a multi-agent race we leave aside) are\n",
    "the base race `full-v0` plus a chain of **wrappers**:\n",
    "\n",
    "| wrapper | what it does |\n",
    "|---|---|\n",
    "| `constant-size` | keeps the *k* (=5) closest items/karts/path nodes, pads with zeros |\n",
    "| `polar` | 3D positions $(x, y, z)$ → (angle in the horizontal plane, vertical angle, distance) |\n",
    "| `obs-flattener` | concatenates all the observations into one `continuous` and one `discrete` vector (same for actions) |\n",
    "| `only-continous-actions` | drops the discrete actions (brake, drift, fire, nitro, rescue) |\n",
    "| `discrete-actions` | discretizes acceleration (5 levels) and steering (7 levels) |\n",
    "| `flatten-multi-discrete` | merges a `MultiDiscrete` action into a single `Discrete` one |\n",
    "\n",
    "Each environment starts STK in a **separate process** (STK only allows one\n",
    "race per process), so environments must be `close()`d once used. The\n",
    "common arguments are given to `gym.make`:\n",
    "\n",
    "- `agent=AgentSpec(use_ai=False)` — we control the kart (`use_ai=True`: the\n",
    "  game AI drives, see below);\n",
    "- `track` (`None` for a random track), `num_kart` (the others are driven by\n",
    "  the game AI), `difficulty` (0-2), `laps`, `max_paths` (how many path\n",
    "  nodes ahead are observed)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "140447be",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "TRACK = \"lighthouse\"\n",
    "STK_KWARGS = dict(track=TRACK, num_kart=5, difficulty=1)\n",
    "\n",
    "\n",
    "def make_stk(name: str, use_ai: bool = False, **kwargs) -> gym.Env:\n",
    "    \"\"\"Creates the `supertuxkart/<name>-v0` environment on our track\"\"\"\n",
    "    return gym.make(\n",
    "        f\"supertuxkart/{name}-v0\",\n",
    "        agent=AgentSpec(use_ai=use_ai),\n",
    "        **{**STK_KWARGS, **kwargs},\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "54937da0",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "A small helper prints a (possibly nested) gymnasium space in a readable\n",
    "form, and another one the matching observation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d2dd83c",
   "metadata": {},
   "outputs": [],
   "source": [
    "def _bounds(space: spaces.Box) -> str:\n",
    "    low, high = np.unique(space.low), np.unique(space.high)\n",
    "    if len(low) == 1 and len(high) == 1:\n",
    "        return f\"[{low[0]:g}, {high[0]:g}]\"\n",
    "    return f\"[{low.min():g}..{low.max():g}, {high.min():g}..{high.max():g}]\"\n",
    "\n",
    "\n",
    "def describe_space(space: gym.Space, name: str = \"\", indent: int = 0):\n",
    "    \"\"\"Pretty-prints a gymnasium space\"\"\"\n",
    "    pad = \"  \" * indent\n",
    "    label = f\"{pad}{name}: \" if name else pad\n",
    "    if isinstance(space, spaces.Dict):\n",
    "        print(f\"{label}Dict with {len(space)} keys\")\n",
    "        for key, sub in space.items():\n",
    "            describe_space(sub, key, indent + 1)\n",
    "    elif isinstance(space, spaces.Box):\n",
    "        print(f\"{label}Box{space.shape} {space.dtype} {_bounds(space)}\")\n",
    "    elif isinstance(space, spaces.Discrete):\n",
    "        print(f\"{label}Discrete({space.n})\")\n",
    "    elif isinstance(space, spaces.MultiDiscrete):\n",
    "        print(f\"{label}MultiDiscrete({space.nvec.tolist()})\")\n",
    "    elif isinstance(space, spaces.Sequence):\n",
    "        print(f\"{label}Sequence (variable length) of:\")\n",
    "        describe_space(space.feature_space, \"\", indent + 2)\n",
    "    else:\n",
    "        print(f\"{label}{space}\")\n",
    "\n",
    "\n",
    "def describe_obs(obs, name: str = \"\", indent: int = 0, max_values: int = 6):\n",
    "    \"\"\"Pretty-prints an observation (dict, tuple or array)\"\"\"\n",
    "    pad = \"  \" * indent\n",
    "    label = f\"{pad}{name}: \" if name else pad\n",
    "    if isinstance(obs, dict):\n",
    "        print(f\"{label}dict\")\n",
    "        for key, value in obs.items():\n",
    "            describe_obs(value, key, indent + 1, max_values)\n",
    "    elif isinstance(obs, tuple):\n",
    "        print(f\"{label}tuple of {len(obs)} × {np.shape(obs[0]) if obs else ()}\")\n",
    "    elif isinstance(obs, np.ndarray):\n",
    "        values = np.array2string(\n",
    "            obs.flatten()[:max_values], precision=2, suppress_small=True\n",
    "        )\n",
    "        more = \"…\" if obs.size > max_values else \"\"\n",
    "        print(f\"{label}array{obs.shape} {values}{more}\")\n",
    "    else:\n",
    "        print(f\"{label}{type(obs).__name__} {obs!r}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a8fd2904",
   "metadata": {},
   "source": [
    "## 1. The full environment: `supertuxkart/full-v0`\n",
    "\n",
    "### Actions\n",
    "\n",
    "The raw action is a dictionary: two continuous values and five binary\n",
    "ones."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d259f840",
   "metadata": {},
   "outputs": [],
   "source": [
    "env = make_stk(\"full\")\n",
    "print(\"Tracks:\", \", \".join(env.unwrapped.TRACKS))\n",
    "describe_space(env.action_space)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c552b99d",
   "metadata": {},
   "source": [
    "| key | meaning |\n",
    "|---|---|\n",
    "| `acceleration` | throttle, in $[0, 1]$ |\n",
    "| `steer` | steering, in $[-1, 1]$ (scaled by the kart's `max_steer_angle`) |\n",
    "| `brake` | brake, then drive backwards once stopped — only when `acceleration` is 0 (otherwise ignored) |\n",
    "| `drift` | skid — sharper turns, and a speed boost when released |\n",
    "| `fire` | use the current power-up (`powerup_type`) |\n",
    "| `nitro` | burn nitro (`energy`) for a speed boost |\n",
    "| `rescue` | call the rescue bird (puts the kart back on the track, costs time) |\n",
    "\n",
    "A random action is a dictionary with the same keys:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20075f3e",
   "metadata": {},
   "outputs": [],
   "source": [
    "env.action_space.sample()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e008a716",
   "metadata": {},
   "source": [
    "### Observations\n",
    "\n",
    "The observation is a dictionary too, with **fixed-size** entries (about the\n",
    "kart itself) and **variable-length** ones (`Sequence`: the items, the other\n",
    "karts and the track nodes ahead — their number depends on the track and on\n",
    "the moment of the race):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e80046cb",
   "metadata": {},
   "outputs": [],
   "source": [
    "describe_space(env.observation_space)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0fd90d8e",
   "metadata": {},
   "source": [
    "All positions are expressed **in the kart's frame**: $x$ points to the\n",
    "right, $y$ up and $z$ forward. An item at $(-2, 0, 10)$ is 10 m ahead and 2 m\n",
    "to the left, whatever the orientation of the kart on the track — which is\n",
    "what a driver needs.\n",
    "\n",
    "| keys | meaning |\n",
    "|---|---|\n",
    "| `velocity`, `front` | speed vector; position of the front of the kart |\n",
    "| `center_path`, `center_path_distance` | vector to (and signed distance from) the center of the track |\n",
    "| `distance_down_track` | how far the kart is along the lap |\n",
    "| `paths_start`, `paths_end`, `paths_width`, `paths_distance` | the track ahead, as a list of segments (the first one is the current one) |\n",
    "| `items_position`, `items_type` | items on the track (bonus boxes, bananas, nitro…) |\n",
    "| `karts_position` | the other karts, closest first |\n",
    "| `powerup_type`, `powerup_count`, `attachment`, `energy`, … | the kart's state (the last `attachment` value, 9, means *none*) |\n",
    "| `phase` | race phase (`READY`, `SET`, `GO`, `RACE`: karts cannot move before `GO`) |\n",
    "\n",
    "Let us reset the race and look at a real observation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a66c985b",
   "metadata": {},
   "outputs": [],
   "source": [
    "obs, info = env.reset(seed=1)\n",
    "describe_obs(obs)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b32ad32",
   "metadata": {},
   "source": [
    "The `Sequence` entries come as tuples of arrays; their lengths are what makes\n",
    "this space unusable as-is by a neural network with a fixed input size. We\n",
    "accelerate for two seconds (a step is 0.1 s of game time) so that the kart\n",
    "moves away from the start line, and draw what it sees from above:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f0b8a466",
   "metadata": {},
   "outputs": [],
   "source": [
    "ACCELERATE = {\n",
    "    \"acceleration\": np.array([1.0], dtype=np.float32),\n",
    "    \"steer\": np.array([0.0], dtype=np.float32),\n",
    "    \"brake\": 0,\n",
    "    \"drift\": 0,\n",
    "    \"fire\": 0,\n",
    "    \"nitro\": 0,\n",
    "    \"rescue\": 0,\n",
    "}\n",
    "for _ in range(20):\n",
    "    obs, reward, terminated, truncated, info = env.step(ACCELERATE)\n",
    "print(f\"reward={reward:.2f}, info={info}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1430f649",
   "metadata": {},
   "outputs": [],
   "source": [
    "ITEM_NAMES = {t.value: name for name, t in pystk2.Item.Type.__members__.items()}\n",
    "\n",
    "\n",
    "def plot_kart_view(obs, ax=None, n_paths: int = 20):\n",
    "    \"\"\"Draws the track ahead, the items and the karts in the kart frame\n",
    "    (seen from above: x to the right, z forward)\"\"\"\n",
    "    ax = ax or plt.gca()\n",
    "    starts = np.array(obs[\"paths_start\"])[:n_paths]\n",
    "    ends = np.array(obs[\"paths_end\"])[:n_paths]\n",
    "    for ix, (s, e) in enumerate(zip(starts, ends)):\n",
    "        ax.plot([s[0], e[0]], [s[2], e[2]], \"-\", color=\"gray\", lw=1)\n",
    "        ax.plot(e[0], e[2], \".\", color=\"gray\")\n",
    "        if ix < 5:\n",
    "            ax.annotate(str(ix), (e[0], e[2]), fontsize=8)\n",
    "    if obs[\"items_position\"]:\n",
    "        items = np.array(obs[\"items_position\"])\n",
    "        types = np.array(obs[\"items_type\"])\n",
    "        for t in np.unique(types):\n",
    "            sel = types == t\n",
    "            ax.scatter(items[sel, 0], items[sel, 2], s=20, label=ITEM_NAMES.get(t, t))\n",
    "    if obs[\"karts_position\"]:\n",
    "        karts = np.array(obs[\"karts_position\"])\n",
    "        ax.scatter(karts[:, 0], karts[:, 2], marker=\"s\", color=\"red\", label=\"karts\")\n",
    "    ax.scatter([0], [0], marker=\"^\", s=120, color=\"black\", label=\"our kart\")\n",
    "    ax.set_xlabel(\"x (right)\")\n",
    "    ax.set_ylabel(\"z (forward)\")\n",
    "    ax.set_aspect(\"equal\", adjustable=\"datalim\")\n",
    "    ax.legend(fontsize=7, loc=\"lower right\")\n",
    "\n",
    "\n",
    "plt.figure(figsize=(6, 6))\n",
    "plot_kart_view(obs)\n",
    "plt.title(f\"Kart view on {TRACK}\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aab40042",
   "metadata": {},
   "source": [
    "The path nodes are ordered from the current one onwards (the track as the\n",
    "kart will drive it), the items and karts from the closest *in front* to\n",
    "the closest behind.\n",
    "\n",
    "The **reward** at each step is the progress along the track (divided by\n",
    "10), a bonus depending on the position in the race, and a $-0.1$ penalty per\n",
    "step (plus a large bonus at the finish line); `info` gives the position and\n",
    "the distance travelled."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "769cc09e",
   "metadata": {},
   "outputs": [],
   "source": [
    "env.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2776beb4",
   "metadata": {},
   "source": [
    "### Watching the game AI drive\n",
    "\n",
    "With `AgentSpec(use_ai=True)`, the kart is driven by the game's own AI, the\n",
    "actions given to `step` are ignored, and the observation gets an extra\n",
    "`action` key — what the AI did. This is how expert demonstrations are\n",
    "collected (for imitation learning, behavioral cloning, GAIL…)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d6003d85",
   "metadata": {},
   "outputs": [],
   "source": [
    "env = make_stk(\"full\", use_ai=True)\n",
    "obs, _ = env.reset(seed=1)\n",
    "for _ in range(60):\n",
    "    obs, *_ = env.step(None)\n",
    "describe_obs(obs[\"action\"])\n",
    "env.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bea06e4f",
   "metadata": {},
   "source": [
    "## 2. Fixed size observations: `supertuxkart/simple-v0`\n",
    "\n",
    "`simple-v0` keeps the observation a dictionary, but\n",
    "\n",
    "- only the **5 closest** items, karts and path nodes are kept (padded with\n",
    "  zeros when there are fewer), so every entry has a fixed shape;\n",
    "- positions are in **polar** coordinates (angle in the horizontal plane,\n",
    "  vertical angle, distance): the angle to the next path node is directly a\n",
    "  steering hint."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "95047f9f",
   "metadata": {},
   "outputs": [],
   "source": [
    "env = make_stk(\"simple\")\n",
    "describe_space(env.observation_space)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "05c221fd",
   "metadata": {},
   "outputs": [],
   "source": [
    "obs, _ = env.reset(seed=1)\n",
    "for _ in range(60):\n",
    "    obs, *_ = env.step(ACCELERATE)\n",
    "np.set_printoptions(precision=2, suppress=True)\n",
    "for key in (\"paths_end\", \"karts_position\", \"items_position\", \"items_type\"):\n",
    "    print(f\"{key}:\\n{obs[key]}\")\n",
    "env.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8a35a773",
   "metadata": {},
   "source": [
    "Padding is ambiguous: an item type `0` is a `BONUS_BOX`, but also an empty\n",
    "slot; a kart at distance 0 could be a missing one. The wrapper can add\n",
    "*masks* telling which entries are real (`add_mask=True`); since the\n",
    "registered environments do not use this option, we build the chain\n",
    "ourselves on top of `full-v0`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f835bcdc",
   "metadata": {},
   "outputs": [],
   "source": [
    "env = PolarObservations(ConstantSizedObservations(make_stk(\"full\"), add_mask=True))\n",
    "obs, _ = env.reset(seed=1)\n",
    "print({key: obs[key] for key in (\"paths_mask\", \"items_mask\", \"karts_mask\")})\n",
    "env.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "066873fd",
   "metadata": {},
   "source": [
    "## 3. Flat observations: `supertuxkart/flattened-v0`\n",
    "\n",
    "Most algorithms of the course expect a vector. The `obs-flattener` wrapper\n",
    "sorts the keys alphabetically and concatenates\n",
    "\n",
    "- every `Box` into a single `continuous` vector,\n",
    "- every `Discrete`/`MultiDiscrete` into a single `discrete` vector,\n",
    "\n",
    "(and leaves `kart_type`, a string, as it is). Actions are flattened the\n",
    "same way."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c05431c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "env = make_stk(\"flattened\")\n",
    "print(\"Actions\")\n",
    "describe_space(env.action_space, indent=1)\n",
    "print(\"Observations\")\n",
    "describe_space(env.observation_space, indent=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "136e95cd",
   "metadata": {},
   "outputs": [],
   "source": [
    "obs, _ = env.reset(seed=1)\n",
    "describe_obs(obs)\n",
    "env.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c4670d9d",
   "metadata": {},
   "source": [
    "The vectors have lost the names: which values are what follows from the\n",
    "alphabetical order of the keys and their shapes (`attachment_time_left`\n",
    "first, `velocity` last in `continuous`). When names matter — as for the\n",
    "driver below — `simple-v0` is easier to work with."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fd3f98f4",
   "metadata": {},
   "source": [
    "## 4. Action variants\n",
    "\n",
    "The three remaining environments share the observations of `flattened-v0`\n",
    "and only differ by their action space:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0f8bdc11",
   "metadata": {},
   "outputs": [],
   "source": [
    "for name in (\n",
    "    \"flattened\",\n",
    "    \"flattened_continuous_actions\",\n",
    "    \"flattened_multidiscrete\",\n",
    "    \"flattened_discrete\",\n",
    "):\n",
    "    env = make_stk(name)\n",
    "    print(f\"{name:30s} {env.action_space}  e.g. {env.action_space.sample()}\")\n",
    "    env.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b9f0799e",
   "metadata": {},
   "source": [
    "- `flattened_continuous_actions-v0`: `Box(2)` = (acceleration, steer), the\n",
    "  discrete actions are always 0 — ready for DDPG, TD3, SAC, PPO…\n",
    "- `flattened_multidiscrete-v0`: one integer per action key, in alphabetical\n",
    "  order (acceleration, brake, drift, fire, nitro, rescue, steer), with\n",
    "  acceleration discretized in 5 levels and steering in 7;\n",
    "- `flattened_discrete-v0`: the same, as a **single** integer among\n",
    "  $5 \\times 2^5 \\times 7 = 1120$ — ready for DQN, at the price of a large\n",
    "  action set.\n",
    "\n",
    "In both discretized variants, the wrappers map each integer back to the\n",
    "original action (a level of acceleration or steering becomes a value of\n",
    "the `Box`, evenly spread between its bounds; a single integer is first\n",
    "split into one value per key): the agent only ever sees the integers."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d3a396eb",
   "metadata": {},
   "source": [
    "## 5. A hand-written driver\n",
    "\n",
    "With the polar observations of `simple-v0`, a reasonable driver fits in a\n",
    "few lines: steer towards a path node a little ahead (its angle is the first\n",
    "polar coordinate), full throttle. We compare it with a random policy on the\n",
    "same race."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7ba52194",
   "metadata": {},
   "outputs": [],
   "source": [
    "N_STEPS = Profile.pick(400, fast_test=30)\n",
    "\n",
    "\n",
    "def drive(policy, seed: int = 1) -> tuple[float, dict]:\n",
    "    \"\"\"Runs one race for N_STEPS, returns the total reward and the last info\"\"\"\n",
    "    env = make_stk(\"simple\")\n",
    "    obs, _ = env.reset(seed=seed)\n",
    "    total = 0.0\n",
    "    for _ in range(N_STEPS):\n",
    "        obs, reward, terminated, truncated, info = env.step(policy(env, obs))\n",
    "        total += reward\n",
    "        if terminated or truncated:\n",
    "            break\n",
    "    env.close()\n",
    "    return total, info\n",
    "\n",
    "\n",
    "def random_policy(env, obs):\n",
    "    return env.action_space.sample()\n",
    "\n",
    "\n",
    "def steer_to_path(env, obs, look_ahead: int = 2):\n",
    "    angle = obs[\"paths_end\"][look_ahead, 0]  # horizontal angle (radians)\n",
    "    steer = np.clip(2 * angle, -1, 1)\n",
    "    return {**ACCELERATE, \"steer\": np.array([steer], dtype=np.float32)}\n",
    "\n",
    "\n",
    "for policy in (random_policy, steer_to_path):\n",
    "    total, info = drive(policy)\n",
    "    print(f\"{policy.__name__:15s} reward={total:7.2f}  {info}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6774b985",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## 6. An agent, as in the STK project\n",
    "\n",
    "In the [STK project](https://git.isir.upmc.fr/bpiwowar/pystk2-project-template),\n",
    "an agent is a module `stk_actor/pystk_actor.py` defining a few names that\n",
    "the race runner (`pystk2 race`, and ML-Arena) looks up and calls:\n",
    "\n",
    "- `env_name` — the registered environment whose wrappers are applied,\n",
    "- `player_name` — shown above the kart,\n",
    "- `get_wrappers()` — extra wrappers, applied after those of `env_name`,\n",
    "- `create_state()` — a per-race state given to the actor at each step\n",
    "  (`None` for a stateless agent),\n",
    "- `get_actor(module_dir, observation_space, action_space)` — returns\n",
    "  `actor(state, obs) -> action`, called on **one** observation as gymnasium\n",
    "  gives it (numpy arrays, no batch dimension), and returning an action of\n",
    "  the (wrapped) action space.\n",
    "\n",
    "We use `flattened-v0`, whose spaces mix continuous and discrete values on\n",
    "both sides:\n",
    "\n",
    "- observations: `continuous` (a vector), `discrete` (a `MultiDiscrete`\n",
    "  vector: attachment, item types, phase, power-up…) and `kart_type`;\n",
    "- actions: `continuous` (acceleration, steer) and `discrete` (brake, drift,\n",
    "  fire, nitro, rescue, each in $\\{0, 1\\}$).\n",
    "\n",
    "The policy below is a plain torch module (only torch, gymnasium,\n",
    "`pystk2-gymnasium` and Stable-Baselines3 are available on ML-Arena) that\n",
    "deals with each part on its own terms:\n",
    "\n",
    "- **discrete observations** are categories, not quantities\n",
    "  (`powerup_type` 5 is not \"more\" than 4): each component goes through its\n",
    "  own `nn.Embedding`, whose sizes are read from `nvec`;\n",
    "- the embeddings and the continuous observations are concatenated and go\n",
    "  through a shared MLP (the *trunk*);\n",
    "- **continuous actions** come from a `tanh` head mapped onto the bounds of\n",
    "  the `Box`;\n",
    "- **discrete actions** come from one categorical distribution per\n",
    "  component: a single linear layer gives all the logits, `split` according\n",
    "  to `nvec`.\n",
    "\n",
    "It is trained in section 7; `get_actor` loads its weights from\n",
    "`pystk_actor.pth`, in the module directory, when there are some."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dc12cf17",
   "metadata": {},
   "outputs": [],
   "source": [
    "class STKPolicy(nn.Module):\n",
    "    def __init__(\n",
    "        self,\n",
    "        obs_space: spaces.Dict,\n",
    "        action_space: spaces.Dict,\n",
    "        hidden: int = 64,\n",
    "        embedding_dim: int = 4,\n",
    "    ):\n",
    "        super().__init__()\n",
    "        # Observations: one embedding table per discrete component\n",
    "        self.embeddings = nn.ModuleList(\n",
    "            nn.Embedding(int(n), embedding_dim) for n in obs_space[\"discrete\"].nvec\n",
    "        )\n",
    "        n_inputs = obs_space[\"continuous\"].shape[0]\n",
    "        n_inputs += embedding_dim * len(self.embeddings)\n",
    "        self.trunk = nn.Sequential(\n",
    "            nn.Linear(n_inputs, hidden),\n",
    "            nn.ReLU(),\n",
    "            nn.Linear(hidden, hidden),\n",
    "            nn.ReLU(),\n",
    "        )\n",
    "\n",
    "        # Continuous actions: tanh output, mapped onto the Box bounds\n",
    "        continuous = action_space[\"continuous\"]\n",
    "        self.continuous_head = nn.Linear(hidden, continuous.shape[0])\n",
    "        self.low = torch.as_tensor(continuous.low)\n",
    "        self.high = torch.as_tensor(continuous.high)\n",
    "\n",
    "        # Discrete actions: n logits for each component with n values\n",
    "        self.action_nvec = [int(n) for n in action_space[\"discrete\"].nvec]\n",
    "        self.discrete_head = nn.Linear(hidden, sum(self.action_nvec))\n",
    "\n",
    "    def forward(self, continuous: torch.Tensor, discrete: torch.Tensor):\n",
    "        \"\"\"Batched inputs ([..., n]) → continuous actions, list of distributions\"\"\"\n",
    "        embedded = [emb(discrete[..., i]) for i, emb in enumerate(self.embeddings)]\n",
    "        h = self.trunk(torch.cat([continuous, *embedded], dim=-1))\n",
    "\n",
    "        a = torch.tanh(self.continuous_head(h))\n",
    "        continuous_action = self.low + (a + 1) / 2 * (self.high - self.low)\n",
    "\n",
    "        logits = self.discrete_head(h).split(self.action_nvec, dim=-1)\n",
    "        return continuous_action, [Categorical(logits=x) for x in logits]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5e00c75c",
   "metadata": {},
   "source": [
    "The content of `pystk_actor.py` then glues this policy to the race: it\n",
    "adds the batch dimension, and turns the outputs back into an action of the\n",
    "`Dict` space (here, the most likely value of each discrete action; a\n",
    "training actor would sample them instead)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "12145fff",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# --- what goes in pystk_actor.py ---\n",
    "\n",
    "env_name = \"supertuxkart/flattened-v0\"\n",
    "player_name = \"Demo\"\n",
    "\n",
    "\n",
    "def get_wrappers():\n",
    "    return []\n",
    "\n",
    "\n",
    "def create_state():\n",
    "    return None\n",
    "\n",
    "\n",
    "def get_actor(module_dir, observation_space, action_space):\n",
    "    policy = STKPolicy(observation_space, action_space)\n",
    "    weights = Path(module_dir) / \"pystk_actor.pth\"\n",
    "    if weights.exists():  # the trained weights (see section 7)\n",
    "        policy.load_state_dict(torch.load(weights, weights_only=True))\n",
    "    policy.eval()\n",
    "\n",
    "    @torch.no_grad()\n",
    "    def actor(state, obs):\n",
    "        continuous = torch.as_tensor(obs[\"continuous\"], dtype=torch.float32)[None]\n",
    "        discrete = torch.as_tensor(obs[\"discrete\"], dtype=torch.long)[None]\n",
    "        continuous_action, dists = policy(continuous, discrete)\n",
    "        return {\n",
    "            \"continuous\": continuous_action[0].numpy(),\n",
    "            \"discrete\": np.array([d.probs.argmax(-1).item() for d in dists]),\n",
    "        }\n",
    "\n",
    "    return actor"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d1cd1d35",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "And here is, in substance, what the race runner does with those names (for\n",
    "each agent, all karts running in the same race):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5cf15f29",
   "metadata": {},
   "outputs": [],
   "source": [
    "def simulate_race(module_dir: Path, n_steps: int) -> dict:\n",
    "    env = gym.make(env_name, agent=AgentSpec(name=player_name), **STK_KWARGS)\n",
    "    for wrapper in get_wrappers():\n",
    "        env = wrapper(env)\n",
    "    actor = get_actor(module_dir, env.observation_space, env.action_space)\n",
    "\n",
    "    state = create_state()\n",
    "    obs, _ = env.reset(seed=1)\n",
    "    for _ in range(n_steps):\n",
    "        action = actor(state, obs)\n",
    "        obs, reward, terminated, truncated, info = env.step(action)\n",
    "        if terminated or truncated:\n",
    "            break\n",
    "    env.close()\n",
    "    print(\"last action:\", action)\n",
    "    return info\n",
    "\n",
    "\n",
    "# An empty module directory: no weights, an untrained policy\n",
    "simulate_race(Path(tempfile.mkdtemp()), Profile.pick(200, fast_test=20))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "72b22aaf",
   "metadata": {},
   "source": [
    "In the project, the same is run from a terminal with\n",
    "`pystk2 race --hide stk_actor` (`--web` to follow the race in a browser;\n",
    "see the template's README)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c81bf6a9",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "## 7. Training with `rl_mind`, then re-using the policy\n",
    "\n",
    "To train `STKPolicy` with the tools of the course, the environment goes\n",
    "through `rl_mind.VecEnv`, which needs two small wrappers:\n",
    "\n",
    "- `VecEnv` turns a `Dict` observation into a `TensorStruct` of tensors:\n",
    "  every entry must be numeric, so the text ones (`kart_type`) are removed;\n",
    "- `VecEnv.step` takes **one** action tensor: the `Dict` action is seen as a\n",
    "  single `Box`, continuous values first, then the discrete ones (rounded\n",
    "  back to integers on the way to the game)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "097daaee",
   "metadata": {},
   "outputs": [],
   "source": [
    "class NumericObservations(gym.ObservationWrapper):\n",
    "    \"\"\"Removes the non-numeric entries (e.g. text) of a Dict observation\"\"\"\n",
    "\n",
    "    NUMERIC = (spaces.Box, spaces.Discrete, spaces.MultiDiscrete, spaces.MultiBinary)\n",
    "\n",
    "    def __init__(self, env: gym.Env):\n",
    "        super().__init__(env)\n",
    "        self.observation_space = spaces.Dict(\n",
    "            {\n",
    "                key: space\n",
    "                for key, space in env.observation_space.items()\n",
    "                if isinstance(space, self.NUMERIC)\n",
    "            }\n",
    "        )\n",
    "\n",
    "    def observation(self, obs):\n",
    "        return {key: obs[key] for key in self.observation_space.keys()}\n",
    "\n",
    "\n",
    "class FlatActions(gym.ActionWrapper):\n",
    "    \"\"\"Dict(continuous=Box(n), discrete=MultiDiscrete(k)) actions → Box(n + k)\"\"\"\n",
    "\n",
    "    def __init__(self, env: gym.Env):\n",
    "        super().__init__(env)\n",
    "        #: The original action space (to build the policy)\n",
    "        self.dict_action_space = env.action_space\n",
    "        continuous = env.action_space[\"continuous\"]\n",
    "        nvec = env.action_space[\"discrete\"].nvec\n",
    "        self.n_continuous = continuous.shape[0]\n",
    "        self.action_space = spaces.Box(\n",
    "            low=np.concatenate([continuous.low, np.zeros(len(nvec))]).astype(\n",
    "                np.float32\n",
    "            ),\n",
    "            high=np.concatenate([continuous.high, nvec - 1]).astype(np.float32),\n",
    "            dtype=np.float32,\n",
    "        )\n",
    "\n",
    "    def action(self, action):\n",
    "        return {\n",
    "            \"continuous\": action[: self.n_continuous],\n",
    "            \"discrete\": np.rint(action[self.n_continuous :]).astype(np.int64),\n",
    "        }\n",
    "\n",
    "\n",
    "venv = VecEnv(\n",
    "    env_name,\n",
    "    num_envs=2,\n",
    "    same_step_reset=True,\n",
    "    wrappers=[NumericObservations, FlatActions],\n",
    "    agent=AgentSpec(use_ai=False),\n",
    "    **STK_KWARGS,\n",
    ")\n",
    "describe_space(venv.observation_space, \"observations\")\n",
    "describe_space(venv.gym_env.single_action_space, \"actions\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6727a05b",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "An `rl_mind` actor around the policy then does the conversions: the\n",
    "`discrete` observations arrive as floats in the `TensorStruct` (they are\n",
    "category indices), and the action becomes one tensor. Training samples the\n",
    "discrete actions (`forward`, with their log-probability — the continuous part\n",
    "is deterministic here, a Gaussian head would make it stochastic too),\n",
    "evaluation takes the most likely ones (`act`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a5309590",
   "metadata": {},
   "outputs": [],
   "source": [
    "class PolicyActor(Actor[StochasticAction]):\n",
    "    def __init__(self, policy: STKPolicy):\n",
    "        super().__init__()\n",
    "        self.policy = policy\n",
    "\n",
    "    def _run(self, obs):\n",
    "        return self.policy(obs.continuous, obs.discrete.long())\n",
    "\n",
    "    def forward(self, obs) -> StochasticAction:\n",
    "        continuous, dists = self._run(obs)\n",
    "        discrete = torch.stack([d.sample() for d in dists], dim=-1)\n",
    "        log_prob = sum(d.log_prob(discrete[..., i]) for i, d in enumerate(dists))\n",
    "        value = torch.cat([continuous, discrete.float()], dim=-1)\n",
    "        return StochasticAction(value=value, log_prob=log_prob)\n",
    "\n",
    "    def act(self, obs) -> torch.Tensor:\n",
    "        continuous, dists = self._run(obs)\n",
    "        discrete = torch.stack([d.probs.argmax(-1) for d in dists], dim=-1)\n",
    "        return torch.cat([continuous, discrete.float()], dim=-1)\n",
    "\n",
    "\n",
    "action_space = venv.gym_env.envs[0].get_wrapper_attr(\"dict_action_space\")\n",
    "policy = STKPolicy(venv.observation_space, action_space)\n",
    "actor = PolicyActor(policy)\n",
    "\n",
    "rollout = RolloutCollector(venv, actor).collect(Profile.pick(32, fast_test=4))\n",
    "print(\"observations:\", rollout.obs.continuous.shape, rollout.obs.discrete.shape)\n",
    "print(\"actions:\", rollout.action.value.shape, \"rewards:\", rollout.reward.shape)\n",
    "\n",
    "# ... the training loop of the practicals (PPO, SAC…) goes here ...\n",
    "\n",
    "venv.gym_env.close()  # stops the STK processes"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7a27a871",
   "metadata": {},
   "source": [
    "Only the **policy** is saved — a plain torch module, with no `rl_mind` in\n",
    "it — under the name the project expects; the agent of section 6 loads it in\n",
    "`get_actor`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "911ffa07",
   "metadata": {},
   "outputs": [],
   "source": [
    "module_dir = Path(tempfile.mkdtemp())  # in the project: stk_actor/\n",
    "torch.save(policy.state_dict(), module_dir / \"pystk_actor.pth\")\n",
    "simulate_race(module_dir, Profile.pick(200, fast_test=20))"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "rl-mind",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_description": "Exploring what the pystk2 environments show the agent, and what it can do",
   "practical_name": "SuperTuxKart: observations and actions"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
