.. include:: definitions.rstinc

Robotics
==========

AGX dynamics offers flexibility in simulating robotics for various tasks and seamless integration with other software.
Robots based on CAD drawings or URDF can be imported and configured in ``Python`` or ``C++``.
Once the model is in place, AGX supports motion planning, testing, developing, and training controllers through reinforcement learning.
The controller can live directly in AGX or elsewhere and communicate with the simulation using middleware such as ``ROS2``.

Serial chains
-------------
Although AGX dynamics supports modelling all types of robot mechanisms, the most convenient way to do conventional robotics is to use a ``agxModel::SerialKinematicChain``.
It offers functionality for planning and control, including forward, inverse, and differential *kinematics*, as well as forward and inverse *dynamics*.

A kinematic chain is a description of a mechanical system.
The chain links are rigid bodies that are constrained to each other.
Depending on its topology, a chain is classified as either serial, tree, or graph structure.
Serial chains and trees are open without loops, whereas the graph can be closed.
A serial kinematic chain describes many mechanisms, such as industrial robots, excavator arms, and cranes.

The class ``agxModel::SerialKinematicChain`` in AGX represents an open serial chain.
There are two ways to initialize this class.
The first is to provide a simulation along with the base and end bodies, in which case the implementation searches through the simulation breadth first among the bodies and constraints.
The other way to create a chain is to provide a list of bodies and a list of constraints. 
In this case, the items' order in both lists is crucial to create a valid chain as it requires that ``constraint[i]`` connects ``body[i]`` and ``body[i+1]``.

.. _ref_forward_kinematics:

Forward kinematics
^^^^^^^^^^^^^^^^^^
Forward kinematics is concerned with finding the position and orientation of the end-effector, given the robot's joint configuration.
In the case of serial chains, joint configurations respecting limits result in valid end-effector poses in the task space.

AGX dynamics supports computing forward kinematics *relative to the base* from a ``agxModel::SerialKinematicChain``.
The method ``computeForwardKinematics`` computes an ``AffineMatrix4x4`` pose of the end-effector given a joint configuration, including the option to consider joint limits.
Similarly, ``computeForwardKinematicsAll`` computes the pose of all links in a chain.

Examples of forward computations can be seen in ``data/python/tutorials/RobotControl/tutorial_set_robot_pose.agxPy``.

Manipulator Jacobian
^^^^^^^^^^^^^^^^^^^^
The manipulator Jacobian :math:`J(q)` is a component of differential kinematics and essential for controlling and planning the motion of robotic manipulators.
It relates the joint velocities :math:`\dot{q}` with the velocity of the end-effector :math:`v` according to

.. math::

    v = J(q) \dot{q}.

The method ``computeManipulatorJacobian`` evaluates the manipulator Jacobian in fixed frame coordinates relative to the base.
It takes the joint positions :math:`q` as input and outputs the Jacobian matrix stored *by row* in a vector with size :math:`6 \times N_j`.

.. _ref_inverse_kinematics:

Inverse kinematics
^^^^^^^^^^^^^^^^^^
Inverse kinematics (IK) deals with finding joint configurations that correspond to the desired position and orientation of the end-effector in task space.
Unlike forward kinematics, the inverse problem can have zero, multiple, or infinitely many solutions.
If the desired pose is unreachable by the manipulator, IK has zero solutions.
When a robot has more joints than the dimension of the task space, it is called redundant.
While multiple solutions may exist for nonredundant manipulators, e.g. in the case of elbow up or elbow down, only redundant robots can have infinitely many solutions.

A general approach to solve the IK problem for open chains is to rely on iterative numerical algorithms.
These take advantage of the inverse of the manipulator Jacobian to find a solution when one exists.

The ``agxModel:SerialKinematicChain`` can compute IK via the method ``computeInverseKinematics``.
The input is a desired end-effector transform in task space relative to the base, current joint positions to help guide the algorithm toward a solution, and an optional solver tolerance.

We recommend checking the IK computations return status (enum) before using the output joint angles.
Also, the best practice is to use the latest joint positions as an initial guess.
This is to avoid cases where a slight change in end-effector transform causes an element in the output joint position to switch from :math:`\pi` to :math:`-\pi`.

.. _ref_inverse_dynamics:

Inverse dynamics
^^^^^^^^^^^^^^^^

Dynamics is the study of motions and the forces and torques that cause them.
AGX typically follows this process: Advancing the simulation based on current forces and torques acting on bodies and particles, resulting in a new state with updated positions and velocities.

The problem of inverse dynamics (ID) is to find the forces/torques that result in a certain state.
This is the opposite of forward dynamics, where the forces and torques are known, but the new state is not.

Unlike kinematics computations, inverse dynamics computations in the ``SerialKinematicChain`` require knowledge of the simulation.
Therefore, the chain must receive a simulation instance either through the constructor or by invoking ``setSimulation`` at a later stage.

With knowledge of the simulation, ``computeInverseDynamics`` performs the ID computations with an input corresponding to the desired joint accelerations, :math:`\ddot{q}_\mathrm{desired}`.
The rest of the state, current :math:`q` and :math:`\dot{q}` are available via the simulation.
The computed output is a vector with forces/torques :math:`\tau`.
One overload to ``computeInverseDynamics`` also accepts additional external forces acting on the chain's links.

Examples with ID including external forces are available both in python ``data/python/tutorials/RobotControl/tutorial_pick_and_place.agxPy`` and C++ ``tutorials/agxOSG/tutorial_robot_pick_and_place.cpp``.

.. image:: images/tutorial_pick_and_place.png
     :align: center
     :scale: 50%

|

Ensure thread safety when using ``computeInverseDynamics``.
The method reads data from the chain's components and transforms constraint attachment frames.
Therefore, calling this method from a separate thread while the solver runs in another may cause incorrect results or undefined behaviour.
Instead, recommended use is between calls to ``Simulation::stepForward`` or within a ``StepEventListener`` callback method, such as ``pre`` or ``preCollide``.

Robot control
-------------

How to control a robot to achieve the desired behaviour depends on the working environment and the task tries to solve.
AGX Dynamics aims to provide functionality that makes it easy to test, develop, and train controllers in dynamic simulation environments for various applications.

PID control
^^^^^^^^^^^^^^^^

The most basic controller is the Proportional-Integral-Derivative (PID) controller.
As a PID lacks a dynamic model of the robot, control relies entirely on feedback.
The following mathematical expression describes it:

.. math::

  u(t) = MV(t) = K_p e(t) + K_i \int_{0}^{t} e(\tau) d\tau + K_d \frac{de}{dt},

where :math:`u` is the output signal, also known as the Manipulated Variable (MV), :math:`e` is the error between the measured process variable and the set point, and :math:`K_p`, 
:math:`K_i`, and :math:`K_d` are the tuning parameters, or proportional gain, integral gain, and
derivative gain. 

A PID controller can be used on its own or as part of a controller.
For more details about the PID implementation in AGX and examples of PID control, see :ref:`agxmodel__pid_controller`.

Velocity control
^^^^^^^^^^^^^^^^
Although most robots use actuators with force or torque inputs, these may be set to velocity mode for control.
Velocity mode means that the velocities of the joints are controlled directly.

In AGX dynamics, joints are modelled as constraints with a single degree of freedom, i.e. either as a ``agx::Hinge`` or ``agx::Prismatic``.
These constraints can activate a ``agx::Motor1D``, which allows setting a desired joint velocity through the ``setSpeed`` method.

The tutorial ``data/python/tutorials/RobotControl/tutorial_differential_kinematics.agxPy`` demonstrates velocity control of the Franka Emika Panda when the task is to track a moving object.
In the tutorial, we implement a control method called *Position-based servoing*, which relies on the pseudoinverse of the manipulator Jacobian to compute joint velocities.

.. image:: images/tutorial_differential_kinematics.png
     :align: center
     :scale: 50%

|

Torque control
^^^^^^^^^^^^^^^
In contrast to calculating torques using a PID controller, precise torque control requires a dynamics model of the robot.
When a dynamics model is at hand, inverse dynamics calculates the torques that achieve a desired motion.
For instance, the tutorial ``data/python/tutorials/RobotControl/tutorial_gravity_compensation.agxPy`` demonstrates how to counteract gravity and maintain zero acceleration.

However, as no model is perfect, most practical controllers rely on feedback.
A motion control algorithm that combines feed-forward with feedback is *computed torque control* as demonstrated in ``data/python/tutorials/RobotControl/tutorial_computed_torque_control.agxPy``.

.. image:: images/tutorial_computed_torque_control.png
     :align: center
     :scale: 50%

|

Regardless of where the desired torques come from, a simple way to torque-control a robot in AGX dynamics is to use a ``agx::Motor1D`` on each joint.
An ``agx::Motor1D`` achieves the desired torque ``tau`` by setting the same value to the upper and lower limit through ``setForceRange(tau, tau)``.
For more accurate modelling of the actuator dynamics, refer to :ref:`rst_agxDriveTrain`.
However, ``agx::DriveTrain`` is currently not supported by ``computeInverseDynamics`` but is expected to be so in the near future.

.. include:: reinforcement_learning.rstinc

.. include:: agxros2.rstinc

.. include:: urdf.rstinc
