{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e473d040-c3c7-498b-99be-cd238e11bd6c",
   "metadata": {},
   "source": [
    "# Train the inverted double link cartpole model\n",
    "We will now demonstrate training the model using StableBaselines 3"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43988613",
   "metadata": {},
   "source": [
    "```bash\n",
    "pip install stable-baselines3\n",
    "pip install gymnasium\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "57da3f1b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from env import TwoLinkCartPoleEnv\n",
    "import gymnasium as gym\n",
    "from stable_baselines3 import SAC\n",
    "from stable_baselines3.common.vec_env import DummyVecEnv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "78a43647",
   "metadata": {},
   "outputs": [],
   "source": [
    "gym.register(\n",
    "    id=\"kdFlex-2link-CartPole\",\n",
    "    entry_point=TwoLinkCartPoleEnv,\n",
    "    max_episode_steps=1000,\n",
    ")\n",
    "\n",
    "# use render_mode=\"human\" if you want to visualize training\n",
    "train_env = gym.make(\"kdFlex-2link-CartPole\", render_mode=\"none\")\n",
    "train_env = DummyVecEnv([lambda: train_env])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d67112d1",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = SAC(\n",
    "    policy=\"MlpPolicy\",\n",
    "    env=train_env,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c1180295",
   "metadata": {},
   "outputs": [],
   "source": [
    "# check if this is running in a test environment\n",
    "if os.getenv(\"DTEST_RUNNING\", True):\n",
    "    # in a testing environment, run for less\n",
    "    model.learn(total_timesteps=1000)\n",
    "else:\n",
    "    # this will take around 50 minutes\n",
    "    model.learn(total_timesteps=400000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "aca87959",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[WebUI] Listening at http://newton:34393\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"100%\"\n",
       "            height=\"300px\"\n",
       "            src=\"http://newton:34393\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "            \n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x73fca65eb320>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "train_env.close()\n",
    "test_env = gym.make(\"kdFlex-2link-CartPole\", render_mode=\"human\", sync_real_time=True)\n",
    "test_env = DummyVecEnv([lambda: test_env])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "fba09fbc",
   "metadata": {},
   "outputs": [],
   "source": [
    "terminated = False\n",
    "obs = test_env.reset()\n",
    "while not terminated:\n",
    "    action, _states = model.predict(obs)\n",
    "    obs, reward, terminated, info = test_env.step(action)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "421eb34e",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = SAC.load(\"./models/demo_model\", env=test_env)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "58f919e1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# cleanup\n",
    "test_env.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0a7cc646",
   "metadata": {},
   "source": [
    "## Summary\n",
    "Amazing! You can now implement a custom gymnasium environment using kdFlex. By solving \n",
    "\n",
    "## Further Readings\n"
   ]
  }
 ],
 "metadata": {
  "docs": {
   "tags": [
    "dynamics",
    "cart pole",
    "machine learning"
   ]
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
