{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Info\n",
    "\n",
    "\n",
    "DQN Implemented with Tensorflow tf-agent module.\n",
    "\n",
    "Using same environment as in [tutorial](https://www.tensorflow.org/agents/tutorials/1_dqn_tutorial#hyperparameters): `CartPole-v0`.\n",
    "\n",
    "Purpose is to see hwo easy it is to use the tf-agent library and how the results compare to other implementations."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'2.2.0'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "from tf_agents.networks import q_network\n",
    "from tf_agents.environments import suite_gym\n",
    "from tf_agents.environments import tf_py_environment\n",
    "from tf_agents.utils import common\n",
    "from tf_agents.policies import random_tf_policy\n",
    "from tf_agents.replay_buffers import tf_uniform_replay_buffer\n",
    "from tf_agents.trajectories import trajectory\n",
    "import matplotlib.pyplot as plt\n",
    "from tf_agents.agents.dqn import dqn_agent\n",
    "plt.style.use('ggplot')\n",
    "\n",
    "\n",
    "tf.__version__"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Hyperparameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "num_iterations = 20000 # @param {type:\"integer\"}\n",
    "\n",
    "initial_collect_steps = 1000  # @param {type:\"integer\"} \n",
    "collect_steps_per_iteration = 1  # @param {type:\"integer\"}\n",
    "replay_buffer_max_length = 100000  # @param {type:\"integer\"}\n",
    "\n",
    "batch_size = 64  # @param {type:\"integer\"}\n",
    "learning_rate = 1e-3  # @param {type:\"number\"}\n",
    "log_interval = 200  # @param {type:\"integer\"}\n",
    "\n",
    "num_eval_episodes = 10  # @param {type:\"integer\"}\n",
    "eval_interval = 1000  # @param {type:\"integer\"}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Environment"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "env_name = 'CartPole-v0'#'LunarLander-v2'#'CartPole-v0'\n",
    "\n",
    "train_py_env = suite_gym.load(env_name)\n",
    "eval_py_env = suite_gym.load(env_name)\n",
    "\n",
    "train_env = tf_py_environment.TFPyEnvironment(train_py_env)\n",
    "eval_env = tf_py_environment.TFPyEnvironment(eval_py_env)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "fc_layer_params = (256,)\n",
    "\n",
    "q_net = q_network.QNetwork(\n",
    "    train_env.observation_spec(),\n",
    "    train_env.action_spec(),\n",
    "    fc_layer_params=fc_layer_params)\n",
    "\n",
    "optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=learning_rate)\n",
    "\n",
    "train_step_counter = tf.Variable(0)\n",
    "\n",
    "agent = dqn_agent.DqnAgent(\n",
    "    train_env.time_step_spec(),\n",
    "    train_env.action_spec(),\n",
    "    q_network=q_net,\n",
    "    optimizer=optimizer,\n",
    "    td_errors_loss_fn=common.element_wise_squared_loss,\n",
    "    train_step_counter=train_step_counter)\n",
    "\n",
    "agent.initialize()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Policies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "eval_policy = agent.policy\n",
    "collect_policy = agent.collect_policy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "random_policy = random_tf_policy.RandomTFPolicy(train_env.time_step_spec(),\n",
    "                                                train_env.action_spec())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "def compute_avg_return(environment, policy, num_episodes=10):\n",
    "    \"\"\"Metrics and Evaluation\n",
    "    \"\"\"\n",
    "    total_return = 0.0\n",
    "    for _ in range(num_episodes):\n",
    "        time_step = environment.reset()\n",
    "        episode_return = 0.0\n",
    "        while not time_step.is_last():\n",
    "            action_step = policy.action(time_step)\n",
    "            time_step = environment.step(action_step.action)\n",
    "            episode_return += time_step.reward\n",
    "        total_return += episode_return\n",
    "    avg_return = total_return / num_episodes\n",
    "    return avg_return.numpy()[0]\n",
    "\n",
    "\n",
    "def collect_step(environment, policy, buffer):\n",
    "    \"\"\"Data Collection\n",
    "    \"\"\"\n",
    "    time_step = environment.current_time_step()\n",
    "    action_step = policy.action(time_step)\n",
    "    next_time_step = environment.step(action_step.action)\n",
    "    traj = trajectory.from_transition(time_step, action_step, next_time_step)\n",
    "\n",
    "    # Add trajectory to the replay buffer\n",
    "    buffer.add_batch(traj)\n",
    "\n",
    "def collect_data(env, policy, buffer, steps):\n",
    "    \"\"\"Data Collection\n",
    "    \"\"\"\n",
    "    for _ in range(steps):\n",
    "        collect_step(env, policy, buffer)\n",
    "\n",
    "# Replay Buffer\n",
    "replay_buffer = tf_uniform_replay_buffer.TFUniformReplayBuffer(\n",
    "    data_spec=agent.collect_data_spec,\n",
    "    batch_size=train_env.batch_size,\n",
    "    max_length=replay_buffer_max_length)\n",
    "\n",
    "collect_data(train_env, random_policy, replay_buffer, steps=100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# (Optional) Optimize by wrapping some of the code in a graph using TF function.\n",
    "agent.train = common.function(agent.train)\n",
    "\n",
    "# Reset the train step\n",
    "agent.train_step_counter.assign(0)\n",
    "\n",
    "# Evaluate the agent's policy once before training.\n",
    "avg_return = compute_avg_return(eval_env, agent.policy, num_eval_episodes)\n",
    "returns = [avg_return]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<tensorflow.python.data.ops.iterator_ops.OwnedIterator object at 0x7ff5ac1b8490>\n"
     ]
    }
   ],
   "source": [
    "dataset = replay_buffer.as_dataset(\n",
    "    num_parallel_calls=3, \n",
    "    sample_batch_size=batch_size, \n",
    "    num_steps=2).prefetch(3)\n",
    "\n",
    "iterator = iter(dataset)\n",
    "\n",
    "print(iterator)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Training the agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "step = 1000: Average Return = 32.900001525878906\n",
      "step = 2000: Average Return = 34.29999923706055\n",
      "step = 3000: Average Return = 43.79999923706055\n",
      "step = 4000: Average Return = 84.0999984741211\n",
      "step = 5000: Average Return = 177.10000610351562\n",
      "step = 6000: Average Return = 185.39999389648438\n",
      "step = 7000: Average Return = 197.3000030517578\n",
      "step = 8000: Average Return = 153.1999969482422\n",
      "step = 9000: Average Return = 193.8000030517578\n",
      "step = 10000: Average Return = 190.8000030517578\n",
      "step = 11000: Average Return = 168.8000030517578\n",
      "step = 12000: Average Return = 193.8000030517578\n",
      "step = 13000: Average Return = 176.6999969482422\n",
      "step = 14000: Average Return = 197.5\n",
      "step = 15000: Average Return = 194.8000030517578\n",
      "step = 16000: Average Return = 196.39999389648438\n",
      "step = 17000: Average Return = 194.89999389648438\n",
      "step = 18000: Average Return = 197.6999969482422\n",
      "step = 19000: Average Return = 200.0\n",
      "step = 20000: Average Return = 200.0\n"
     ]
    }
   ],
   "source": [
    "for _ in range(num_iterations):\n",
    "\n",
    "    # Collect a few steps using collect_policy and save to the replay buffer.\n",
    "    for _ in range(collect_steps_per_iteration):\n",
    "        collect_step(train_env, agent.collect_policy, replay_buffer)\n",
    "\n",
    "    # Sample a batch of data from the buffer and update the agent's network.\n",
    "    experience, unused_info = next(iterator)\n",
    "    train_loss = agent.train(experience).loss\n",
    "    step = agent.train_step_counter.numpy()\n",
    "\n",
    "#     if step % log_interval == 0:\n",
    "#         print('step = {0}: loss = {1}'.format(step, train_loss))\n",
    "\n",
    "    if step % eval_interval == 0:\n",
    "        avg_return = compute_avg_return(train_env, agent.policy, num_eval_episodes)\n",
    "        print('step = {0}: Average Return = {1}'.format(step, avg_return))\n",
    "        returns.append(avg_return)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Plots"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(2.390000200271606, 250.0)"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 18236 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "iterations = range(0, num_iterations + 1, eval_interval)\n",
    "plt.plot(iterations, returns)\n",
    "plt.ylabel('Average Return')\n",
    "plt.xlabel('Iterations')\n",
    "plt.ylim(top=250)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
