=====================================
Inverse Dynamics 
=====================================

AGX Dynamics is computing forward dynamics. For the system to end up in a specific desired state
there has to exist some kind of control loop that makes sure the system converge toward a specific state.
The ``agxModel::InverseDynamics`` class offer a solution for a user of AGX Dynamics to choose a sub-set
of the simulation to be pre computed, making sure a certain state is reached at a certain time.

Imagine for example a multi axis robot moving its end effector to a specific point in space,
or following a specific straight line. The Inverse Dynamics will pre compute the torques and
forces needed to achieve this motion. With the limitation that the system is isolated from
interacting with other things before reaching the end state. If however a contact or other interaction
happens, the API provides partial results so re-planning of trajectories can be performed.


The Inverse Dynamics class will find one possible solution for integrating the forward dynamics
system to a specific state for one of the included rigid bodies. All other rigid bodies included
in the isolated sub system will be integrated according to the degrees of freedom available.
The rigid bodies of the sub system will obey the constraints included. If a certain path out of
many different ones is desired from the start pose to the end pose, then a ``solve``-method that
takes multiple delta times and transforms as input should be used, or the path between startpose
and endpose split up in several ``solve`` calls.

For example a robot arm may end up in an unwanted state, where one or more joints are near a range
limit, which could result in jerky motion. Then it can be adventagous to use a strategy where not
just startpose and endpose are used as inputs to Inverse Dynamics.

---------------------------
The InverseDynamics class
---------------------------

The class ``agxModel::InverseDynamics`` can be used to perform Inverse Dynamics computations.

When an instance of ``InverseDynamics`` is created the inputs are cloned and an internal
representation is made. This is so that the original simulation is not affected by the computations
and that the output then can be applied to the original system.

Two sets of bodies/constraints are maintained internally. One set is used for trajectory computations. 
These bodies are related to inverse kinematics. The other set is used for force/torque computations.

To analyze the state in the internal, cloned systems, their representation can be accessed by either

.. code-block:: c++

   const agxSDK::Assembly* internalMotionData = id->getMotionData();

to get the final state of the system used for calculating the trajectories. Or


.. code-block:: c++

   const agxSDK::Assembly* internalDynamicsData = id->getDynamicsData();

to get the final state of the system used for calculating forces and torques required to reach the desired transform.

The steps to use InverseDynamics are:

* Specify bodies/constraints that should be included in the computations.
* The inputs are mirrored when the InverseDynamics constructor is called.
* Use ``sync`` if needed to make sure that the ID internal bodies have matching 
  state as the source bodies.
* Call ``solve`` with a desired transform for a body that is part of the inputs and 
  with a delta time when the body should be at that transform.
* The amount of produced data depends on simulation timestep and delta time.
* Fetch results from ID via ``getJointForces`` by specifying which simulation frame 
  starting from 0. The output is a view into an array with structs that contains 
  joint index, angle index and the actual force/torque value.


An example of this is available in ``build_inverse_dynamics_scene`` in ``python/tutorials/tutorial_InverseDynamics.agxPy``.

.. note:: The sync method should not be called at the same time the source simulation is being stepped.


The different solve methods
----------------------------

The InverseDynamics has different versions of the solve method.
All tries to get to the target pose. The difference is the intermediate path, the number
of possible constraints that are connected to an equal number of kinematic bodies and 
whether the solve is pre calculated, or calculated on the fly.

The method ``solveLinear`` tries to follow a linear path from the current pose towards the target pose.
If for example a straight edge should be followed and it is all within reach, then this method generally works well.
If part of the path is beyond reach, the path will not be straight. Studying the angle for a single joint, it can move both
in positive and negative direction on its way from start pose to end pose.

.. image:: images/id-solvelinear.png


The ``solve`` method only uses the initial pose and the end pose and all angles inbetween are interpolated.
With this method each joint angle will monotonically change from start angle to end angle. 
This results in smoother movements, less force/torque spikes but a different trajectory. The downside
is instead that an edge of a box can not be traced by doing one solve call since the paths that are followed are generally
more curved.

Which to use depends on desired result. Overexagerating the difference, the robot to the left uses ``solveLinear`` and the
robot to the right uses ``solve``. Part of the trajectory was problematic to reach with the specified orientation for the end
effector.

.. image:: images/id-solve-comparison.png

There are two additional versions of the ``solveLinear`` method. 

``solveLinearN`` takes a list of ``MoveOperation``'s 
where each individual move will generate a kinematic trajectory body, which is constrained to a body in the motion simulation.
Each move can have an individual threshold for both rotation and translation, to be considered successful. Also the stiffness
of the constraint connecting the kinematic trajectory body to the chosen body can be tuned,
separating rotational and translational stiffness, to give the stiffer trajectory constraints the upper hand.

There is an adaptive solve linear method that will sync the dynamics simulation state with the source simulation
each frame. The adaptive will not calculate any trajectory in advance, but will require more computations
during runtime. The purpose is to give a planner the chance to make adjustments to unexpected interactions, and to 
do continous updates to a manipulation task. ``initializeAdaptiveSolveLinearN`` will initialize the adaptive solve with a set of 
defined moves. It is up to the user to each timestep call ``stepAdaptiveSolveN`` to compute new torques and angles. If the planner
somehow detects that it need to reconfugure the defined move operations, it can send the same, but reconfugured, operations to the
``updateAdaptiveSolveN``. If a complete new set of move operations are required ``finalizeAdaptiveSolveN`` must be called before
it can be initialized again.

All solve methods aims at landing on the target transform with zero velocity.

-----------------------
Gravity Compensation
-----------------------

Inverse dynamics can be used to compute gravity compensation for a constrained system.
Which forces/torques are needed to maintain current pose with zero velocity?

To use this functionality one creates an ``InverseDynamics`` instance. Then at each timestep,
a ``sync`` is needed and after that the forces/torques needs to be applied to the source
simulation before the solver is stepped.

Examples with a robot and gravity compensation is available 
in ``python/tutorials/tutorial_InverseDynamics.agxPy``. Examples are with and without powerlines.



---------------------------------
Inverse dynamics and agxPowerLine
---------------------------------

The InverseDynamics class has partial support for agxPowerLines connected to the input constraints.

Upon construction of an InverseDynamics instance, powerlines and units can be included. The requirements are:

* Each powerlines must have one or more Actuators that act upon constraints that are 
  part of the input to InverseDynamics.
* Each unit in the unit container must belong to one of the input powerlines.
* The units must be based upon RotationalUnit. This includes most units but excludes e.g. parts of agxHydraulics.

Output will be generated for the units in the unit container, not all units in the input powerlines.

When the different solve methods are used, the output for the units will be `value` (position) and `gradient` (velocity) for 
each unit as well as the regular force/torque output values for the joints. How the powerline unit values should be used
to control the actual joint is highly scene dependent and depends on power source (e.g. ElecticMotor, Engine, ...) and
use of differentials, clutches etc.

If gravity compensation is used then velocity constraints are used on rotational units to prevent movement and since the 
powerline components are connected to a joint via an actuator, the constrained bodies will not move. The outputs produced
are still returned as `value` and `gradient` but only the first one is to be used. Gradient will be set to 0. The value 
containes the load needed on the unit to maintain zero velocity at the constraint. Example of how this can be used is
available in the previously mentioned gravity compensation tutorial scenes.
