.. _rl_with_agx_dynamics:

================================
Appendix 6: RL with AGX Dynamics
================================

This section shows how to wrap an AGX Dynamics simulation as an OpenAI gym environment, and how to use that environment to train intelligent agents using AGX Dynamics high fidelity physics and popular RL-libraries such as `stable-baselines <https://github.com/hill-a/stable-baselines>`_ or `pfrl <https://github.com/pfnet/pfrl>`_. 

.. _fig-rl_loop:

.. figure:: images/RL-loop.png

AGX Dynamics gives you reliable nonsmooth multidomain dynamics simulation. It can run faster than realtime, generating all the accurate data you need for training your agents. And easing the transition from simulations to the real life application.

Install the python requirements with the command :code:`pip install -r data/python/RL/requirements.txt` and test the included examples with the 
command :code:`python data/python/RL/cartpole.py` to run the cartpole example with random actions, or :code:`python data/python/RL/cartpole.py --load data/python/RL/agentModels/cartpole` to run it with a pre-trained agent.

----------------------
OpenAI gym environment
----------------------
An OpenAI gym environment typically contains one RL-agent that can (partially or fully) observe and act upon its surroundings, effectively changing the state of the environment. 

Developers of custom environments must implement these main gym environment API methods:

  * :code:`step()` - Sets the next action on the agent, steps the environment in time and returns the observation, reward, terminal and optional info.
  * :code:`reset()` - Resets the environment to an initial state and return an initial observation
  * :code:`render()` - Renders the environment.
  * :code:`close()` - Environments automatically close themselves when garbage collected or when the program exits
  * :code:`seed()` - Sets the seed for this env's random number generator(s)


And the following attributes

 * :code:`action_space` - The `gym.Space` object corresponding to valid actions
 * :code:`observation_space` - The `gym.Space` object corresponding to valid observations
 * :code:`reward_range` - A tuple corresponding to the min and max possible rewards

--------------------------
AGX OpenAI gym environment
--------------------------
The class :code:`AGXGymEnv` inherits from the OpenAI gym environment. It initializes AGX, creates an :code:`agxSDK::Simulation`, implements the main gym API methods and cleanup all the resources on exit. It can also initialize :code:`agxOSG::ExampleApplication` for rendering. Leaving the user of :code:`AGXGymEnv` with implementing methods for modeling the scene, settings actions and returning observations.

* :code:`_build_scene()` - Builds an AGX Dynamics simulation (models the environment). Much like the :code:`BuildScene()` function in the python tutorials. This method is called in :code:`env.reset()`.
* :code:`_set_action(action)` - Sets the action on the agent. This method is called in :code:`env.step()`
* :code:`_observe()` - returns the tuple :code:`(observation->numpy.array, reward->float, terminal->bool, info->dict)`. This method is called in :code:`env.step()`.
* :code:`_setup_gym_environment_spaces` - Creates and sets the action, observation and reward range attributes


^^^^^^^^^^^^^^^^^^^^
Cartpole environment
^^^^^^^^^^^^^^^^^^^^
Run the example with :code:`python data/python/RL/cartpole.py`. Add the argument :code:`--train` to train a new agent. Add the argument :code:`--load path/to/trained/agent` to load a previously trained agent, either to continue training it or just to demo the results.

The cartpole environment is an example on the classical environment with a cart allowed to move in one dimension. A pole rotating around one axis is attached to the cart. By moving the cart correctly it is possible to balance the pole. This is a example of how to implement cartpole as an :code:`AGXGymEnv` environment. The observations is the position of the cart, the rotation of the pole, the velocity of the cart and the angular velocity of the pole. And the action is the force applied to the cart at each timestep.

^^^^^^^^^^^^^^^^^^^^^^^^^
Pushing robot environment
^^^^^^^^^^^^^^^^^^^^^^^^^
Run the example with :code:`python data/python/RL/pushing_robot.py`. Add the argument :code:`--train` to train a new agent. Add the argument :code:`--load path/to/trained/agent` to load a previously trained agent, either to continue training it or just to demo the results.

The pushing robot environment is an example of how to create a bit more complicated environment. It is a robot with two free degrees of freedom that must find the box in front of it and use its end-effector to push it away from the robot. The observations are the angle and speed of the robot joints, the world position of the tool and the relative position between tool and box. The action is what torque to apply to each joint at each timestep. The reward is distance between the current position of the box and its starting position.
