{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Training RL to do Cartpole Balancing\n",
    "\n",
    "This notebooks is part of [AI for Beginners Curriculum](http://aka.ms/ai-beginners). It has been inspired by [this blog post](https://medium.com/swlh/policy-gradient-reinforcement-learning-with-keras-57ca6ed32555), [official TensorFlow documentation](https://www.tensorflow.org/tutorials/reinforcement_learning/actor_critic) and [this Keras RL example](https://keras.io/examples/rl/actor_critic_cartpole/).\n",
    "\n",
    "In this example, we will use RL to train a model to balance a pole on a cart that can move left and right on horizontal scale. We will use [OpenAI Gym](https://www.gymlibrary.ml/) environment to simulate the pole.\n",
    "\n",
    "> **Note**: You can run this lesson's code locally (eg. from Visual Studio Code), in which case the simulation will open in a new window. When running the code online, you may need to make some tweaks to the code, as described [here](https://towardsdatascience.com/rendering-openai-gym-envs-on-binder-and-google-colab-536f99391cc7).\n",
    "\n",
    "We will start by making sure Gym is installed:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: gym in c:\\winapp\\miniconda3\\envs\\py38\\lib\\site-packages (0.23.1)\n",
      "Collecting pygame\n",
      "  Downloading pygame-2.1.2-cp38-cp38-win_amd64.whl (8.4 MB)\n",
      "Requirement already satisfied: importlib-metadata>=4.10.0 in c:\\winapp\\miniconda3\\envs\\py38\\lib\\site-packages (from gym) (4.11.3)\n",
      "Requirement already satisfied: cloudpickle>=1.2.0 in c:\\winapp\\miniconda3\\envs\\py38\\lib\\site-packages (from gym) (2.0.0)\n",
      "Requirement already satisfied: gym-notices>=0.0.4 in c:\\winapp\\miniconda3\\envs\\py38\\lib\\site-packages (from gym) (0.0.6)\n",
      "Requirement already satisfied: numpy>=1.18.0 in c:\\winapp\\miniconda3\\envs\\py38\\lib\\site-packages (from gym) (1.22.3)\n",
      "Requirement already satisfied: zipp>=0.5 in c:\\winapp\\miniconda3\\envs\\py38\\lib\\site-packages (from importlib-metadata>=4.10.0->gym) (3.6.0)\n",
      "Installing collected packages: pygame\n",
      "Successfully installed pygame-2.1.2\n"
     ]
    }
   ],
   "source": [
    "import sys\n",
    "!{sys.executable} -m pip install gym pygame"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's create the CartPole environment and see how to operate on it. An environment has the following properties:\n",
    "\n",
    "* **Action space** is the set of possible actions that we can perform at each step of the simulation\n",
    "* **Observation space** is the space of observations that we can make"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Action space: Discrete(2)\n",
      "Observation space: Box([-4.8000002e+00 -3.4028235e+38 -4.1887903e-01 -3.4028235e+38], [4.8000002e+00 3.4028235e+38 4.1887903e-01 3.4028235e+38], (4,), float32)\n"
     ]
    }
   ],
   "source": [
    "import gym\n",
    "\n",
    "env = gym.make(\"CartPole-v1\")\n",
    "\n",
    "print(f\"Action space: {env.action_space}\")\n",
    "print(f\"Observation space: {env.observation_space}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's see how the simulation works. The following loop runs the simulation, until `env.step` does not return the termination flag `done`. We will randomly chose actions using `env.action_space.sample()`, which means the experiment will probably fail very fast (CartPole environment terminates when the speed of CartPole, its position or angle are outside certain limits).\n",
    "\n",
    "> Simulation will open in the new window. You can run the code several times and see how it behaves."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[-0.04825775 -0.21918646 -0.00796685  0.27188525] -> 1.0\n",
      "[-0.05264147 -0.4141938  -0.00252914  0.5620448 ] -> 1.0\n",
      "[-0.06092535 -0.21903647  0.00871175  0.26856613] -> 1.0\n",
      "[-0.06530608 -0.41428167  0.01408308  0.56398404] -> 1.0\n",
      "[-0.07359171 -0.60959834  0.02536276  0.8610703 ] -> 1.0\n",
      "[-0.08578368 -0.4148308   0.04258416  0.57646877] -> 1.0\n",
      "[-0.09408029 -0.610523    0.05411354  0.88225687] -> 1.0\n",
      "[-0.10629076 -0.4161761   0.07175867  0.6070649 ] -> 1.0\n",
      "[-0.11461428 -0.22212696  0.08389997  0.33781925] -> 1.0\n",
      "[-0.11905681 -0.0282929   0.09065636  0.07272854] -> 1.0\n",
      "[-0.11962268  0.16542032  0.09211093 -0.19003159] -> 1.0\n",
      "[-0.11631427 -0.03089041  0.08831029  0.13022853] -> 1.0\n",
      "[-0.11693208 -0.22715913  0.09091487  0.44941387] -> 1.0\n",
      "[-0.12147526 -0.42344147  0.09990314  0.76931363] -> 1.0\n",
      "[-0.12994409 -0.61978614  0.11528942  1.0916848 ] -> 1.0\n",
      "[-0.14233981 -0.81622297  0.13712311  1.4182041 ] -> 1.0\n",
      "[-0.15866427 -1.01275     0.1654872   1.7504154 ] -> 1.0\n",
      "[-0.17891927 -1.2093195   0.2004955   2.0896728 ] -> 1.0\n",
      "[-0.20310566 -1.4058217   0.24228896  2.4370732 ] -> 1.0\n",
      "Total reward: 19.0\n"
     ]
    }
   ],
   "source": [
    "env.reset()\n",
    "\n",
    "done = False\n",
    "total_reward = 0\n",
    "while not done:\n",
    "   env.render()\n",
    "   obs, rew, done, info = env.step(env.action_space.sample())\n",
    "   total_reward += rew\n",
    "   print(f\"{obs} -> {rew}\")\n",
    "print(f\"Total reward: {total_reward}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Youn can notice that observations contain 4 numbers. They are:\n",
    "- Position of cart\n",
    "- Velocity of cart\n",
    "- Angle of pole\n",
    "- Rotation rate of pole\n",
    "\n",
    "`rew` is the reward we receive at each step. You can see that in CartPole environment you are rewarded 1 point for each simulation step, and the goal is to maximize total reward, i.e. the time CartPole is able to balance without falling.\n",
    "\n",
    "During reinforcement learning, our goal is to train a **policy** $\\pi$, that for each state $s$ will tell us which action $a$ to take, so essentially $a = \\pi(s)$.\n",
    "\n",
    "If you want probabilistic solution, you can think of policy as returning a set of probabilities for each action, i.e. $\\pi(a|s)$ would mean a probability that we should take action $a$ at state $s$.\n",
    "\n",
    "## Policy Gradient Method\n",
    "\n",
    "In simplest RL algorithm, called **Policy Gradient**, we will train a neural network to predict the next action."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 100,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "from tensorflow import keras\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "num_inputs = 4\n",
    "num_actions = 2\n",
    "\n",
    "model = keras.Sequential([\n",
    "    keras.layers.Dense(128, activation=\"relu\",input_shape=(num_inputs,)),\n",
    "    keras.layers.Dense(num_actions, activation=\"softmax\")\n",
    "])\n",
    "\n",
    "model.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.Adam(learning_rate=0.01))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will train the network by running many experiments, and updating our network after each run. Let's define a function that will run the experiment and return the results (so-called **trace**) - all states, actions (and their recommended probabilities), and rewards:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_episode(max_steps_per_episode = 10000,render=False):    \n",
    "    states, actions, probs, rewards = [],[],[],[]\n",
    "    state = env.reset()\n",
    "    for _ in range(max_steps_per_episode):\n",
    "        if render:\n",
    "            env.render()\n",
    "        action_probs = model(np.expand_dims(state,0))[0]\n",
    "        action = np.random.choice(num_actions, p=np.squeeze(action_probs))\n",
    "        nstate, reward, done, info = env.step(action)\n",
    "        if done:\n",
    "            break\n",
    "        states.append(state)\n",
    "        actions.append(action)\n",
    "        probs.append(action_probs)\n",
    "        rewards.append(reward)\n",
    "        state = nstate\n",
    "    return np.vstack(states), np.vstack(actions), np.vstack(probs), np.vstack(rewards)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can run one episode with untrained network and observe that total reward (AKA length of episode) is very low:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total reward: 13.0\n"
     ]
    }
   ],
   "source": [
    "s,a,p,r = run_episode()\n",
    "print(f\"Total reward: {np.sum(r)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One of the tricky aspects of policy gradient algorithm is to use **discounted rewards**. The idea is that we compute the vector of total rewards at each step of the game, and during this process we discount the early rewards using some coefficient $gamma$. We also normalize the resulting vector, because we will use it as weight to affect our training: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {},
   "outputs": [],
   "source": [
    "eps = 0.0001\n",
    "\n",
    "def discounted_rewards(rewards,gamma=0.99,normalize=True):\n",
    "    ret = []\n",
    "    s = 0\n",
    "    for r in rewards[::-1]:\n",
    "        s = r + gamma * s\n",
    "        ret.insert(0, s)\n",
    "    if normalize:\n",
    "        ret = (ret-np.mean(ret))/(np.std(ret)+eps)\n",
    "    return ret"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's do the actual training! We will run 300 episodes, and at each episode we will do the following:\n",
    "\n",
    "1. Run the experiment and collect the trace\n",
    "1. Calculate the difference (`gradients`) between the actions taken, and by predicted probabilities. The less the difference is, the more we are sure that we have taken the right action.\n",
    "1. Calculate discounted rewards and multiply gradients by discounted rewards - that will make sure that steps with higher rewards will make more effect on the final result than lower-rewarded ones\n",
    "1. Expected target actions for our neural network would be partly taken from the predicted probabilities during the run, and partly from calculated gradients. We will use `alpha` parameter to determine to which extent gradients and rewards are taken into account - this is called *learning rate* of reinforcement algorithm.\n",
    "1. Finally, we train our network on states and expected actions, and repeat the process "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 -> 44.0\n",
      "100 -> 105.0\n",
      "200 -> 145.0\n",
      "300 -> 70.0\n",
      "400 -> 190.0\n",
      "500 -> 298.0\n",
      "600 -> 289.0\n",
      "700 -> 499.0\n",
      "800 -> 499.0\n",
      "900 -> 499.0\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[<matplotlib.lines.Line2D at 0x25a320af370>]"
      ]
     },
     "execution_count": 73,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 25176 characters]",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "alpha = 1e-4\n",
    "\n",
    "history = []\n",
    "for epoch in range(300):\n",
    "    states, actions, probs, rewards = run_episode()\n",
    "    one_hot_actions = np.eye(2)[actions.T][0]\n",
    "    gradients = one_hot_actions-probs\n",
    "    dr = discounted_rewards(rewards)\n",
    "    gradients *= dr\n",
    "    target = alpha*np.vstack([gradients])+probs\n",
    "    model.train_on_batch(states,target)\n",
    "    history.append(np.sum(rewards))\n",
    "    if epoch%100==0:\n",
    "        print(f\"{epoch} -> {np.sum(rewards)}\")\n",
    "\n",
    "plt.plot(history)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's run the episode with rendering to see the result:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [],
   "source": [
    "_ = run_episode(render=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Hopefully, you can see that pole can now balance pretty well!\n",
    "\n",
    "## Actor-Critic Model\n",
    "\n",
    "Actor-Critic model is the further development of policy gradients, in which we build a neural network to learn both the policy and estimated rewards. The network will have two outputs (or you can view it as two separate networks):\n",
    "* **Actor** will recommend the action to take by giving us the state probability distribution, as in policy gradient model\n",
    "* **Critic** would estimate what the reward would be from those actions. It returns total estimated rewards in the future at the given state.\n",
    "\n",
    "Let's define such a model: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "metadata": {},
   "outputs": [],
   "source": [
    "num_inputs = 4\n",
    "num_actions = 2\n",
    "num_hidden = 128\n",
    "\n",
    "inputs = keras.layers.Input(shape=(num_inputs,))\n",
    "common = keras.layers.Dense(num_hidden, activation=\"relu\")(inputs)\n",
    "action = keras.layers.Dense(num_actions, activation=\"softmax\")(common)\n",
    "critic = keras.layers.Dense(1)(common)\n",
    "\n",
    "model = keras.Model(inputs=inputs, outputs=[action, critic])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We would need to slightly modify our `run_episode` function to return also critic results:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_episode(max_steps_per_episode = 10000,render=False):    \n",
    "    states, actions, probs, rewards, critic = [],[],[],[],[]\n",
    "    state = env.reset()\n",
    "    for _ in range(max_steps_per_episode):\n",
    "        if render:\n",
    "            env.render()\n",
    "        action_probs, est_rew = model(np.expand_dims(state,0))\n",
    "        action = np.random.choice(num_actions, p=np.squeeze(action_probs[0]))\n",
    "        nstate, reward, done, info = env.step(action)\n",
    "        if done:\n",
    "            break\n",
    "        states.append(state)\n",
    "        actions.append(action)\n",
    "        probs.append(tf.math.log(action_probs[0,action]))\n",
    "        rewards.append(reward)\n",
    "        critic.append(est_rew[0,0])\n",
    "        state = nstate\n",
    "    return states, actions, probs, rewards, critic"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we will run the main training loop. We will use manual network training process by computing proper loss functions and updating network parameters:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 105,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "running reward: 5.82 at episode 10\n",
      "running reward: 9.43 at episode 20\n",
      "running reward: 10.30 at episode 30\n",
      "running reward: 10.28 at episode 40\n",
      "running reward: 11.00 at episode 50\n",
      "running reward: 13.01 at episode 60\n",
      "running reward: 21.78 at episode 70\n",
      "running reward: 40.54 at episode 80\n",
      "running reward: 73.70 at episode 90\n",
      "running reward: 100.19 at episode 100\n",
      "running reward: 159.20 at episode 110\n",
      "Solved at episode 114!\n"
     ]
    }
   ],
   "source": [
    "optimizer = keras.optimizers.Adam(learning_rate=0.01)\n",
    "huber_loss = keras.losses.Huber()\n",
    "episode_count = 0\n",
    "running_reward = 0\n",
    "\n",
    "while True:  # Run until solved\n",
    "    state = env.reset()\n",
    "    episode_reward = 0\n",
    "    with tf.GradientTape() as tape:\n",
    "        _,_,action_probs, rewards, critic_values = run_episode()\n",
    "        episode_reward = np.sum(rewards)\n",
    "        \n",
    "        # Update running reward to check condition for solving\n",
    "        running_reward = 0.05 * episode_reward + (1 - 0.05) * running_reward\n",
    "\n",
    "        # Calculate discounted rewards that will be labels for our critic\n",
    "        dr = discounted_rewards(rewards)\n",
    "\n",
    "        # Calculating loss values to update our network\n",
    "        actor_losses = []\n",
    "        critic_losses = []\n",
    "        for log_prob, value, rew in zip(action_probs, critic_values, dr):\n",
    "            # When we took the action with probability `log_prob`, we received discounted reward of `rew`,\n",
    "            # while critic predicted it to be `value` \n",
    "            # First we calculate actor loss, to make actor predict actions that lead to higher rewards\n",
    "            diff = rew - value\n",
    "            actor_losses.append(-log_prob * diff)\n",
    "\n",
    "            # The critic loss is to minimize the difference between predicted reward `value` and actual\n",
    "            # discounted reward `rew`\n",
    "            critic_losses.append(\n",
    "                huber_loss(tf.expand_dims(value, 0), tf.expand_dims(rew, 0))\n",
    "            )\n",
    "\n",
    "        # Backpropagation\n",
    "        loss_value = sum(actor_losses) + sum(critic_losses)\n",
    "        grads = tape.gradient(loss_value, model.trainable_variables)\n",
    "        optimizer.apply_gradients(zip(grads, model.trainable_variables))\n",
    "\n",
    "    # Log details\n",
    "    episode_count += 1\n",
    "    if episode_count % 10 == 0:\n",
    "        template = \"running reward: {:.2f} at episode {}\"\n",
    "        print(template.format(running_reward, episode_count))\n",
    "\n",
    "    if running_reward > 195:  # Condition to consider the task solved\n",
    "        print(\"Solved at episode {}!\".format(episode_count))\n",
    "        break\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's run the episode and see how good our model is:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "metadata": {},
   "outputs": [],
   "source": [
    "_ = run_episode(render=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, let's close the environment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 106,
   "metadata": {},
   "outputs": [],
   "source": [
    "env.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Takeaway\n",
    "\n",
    "We have seen two RL algorithms in this demo: simple policy gradient, and more sophisticated actor-critic. You can see that those algorithms operate with abstract notions of state, action and reward - thus they can be applied to very different environments.\n",
    "\n",
    "Reinforcement learning allows us to learn the best strategy to solve the problem just by looking at the final reward. The fact that we do not need labelled datasets allows us to repeat simulations many times to optimize our models. However, there are still many challenges in RL, which you may learn if you decide to focus more on this interesting area of AI.   "
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "16af2a8bbb083ea23e5e41c7f5787656b2ce26968575d8763f2c4b17f9cd711f"
  },
  "kernelspec": {
   "display_name": "Python 3.8.12 ('py38')",
   "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.8.12"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
