# Welcome to kdFlex's documentation!

```{eval-rst}
.. toctree::
   :maxdepth: 2
   :caption: Contents:

   Chatbot <https://portal.karanadyn.com/chatbot/>
   installation
   examples
   key_concepts
   usage_guide
   recipes
   procedures
   api
   conventions
   glossary
```

# Indices and tables

```{eval-rst}
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
```

(concepts)=
# Concepts

**kdFlex** is a fast, hi-fidelity, rigid and flexible body multibody
dynamics modeling and simulation toolkit.  kdFlex is architected to
serve as a comprehensive solution for diverse modeling needs—spanning
multiple engineering disciplines, domains, projects, and applications.
kdFlex is built on the [Spatial Operator Algebra (SOA)](soa_sec) cutting-edge, high-performance,
computational dynamics techniques. SOA is mature, and has been used
across multiple mission critical applications.

# kdFlex key themes 

(soa_sec)=
## Core Methodology: Minimal Coordinates and Spatial Operator Algebra (SOA) 


 -  **kdFlex** primarily employs a minimal coordinates approach, aiming to
    avoid the complexities associated with explicit constraints and DAE
    integration methods found in non-minimal coordinate approaches. The
    software is fundamentally based on the **Spatial Operator Algebra
    (SOA)** methodology. SOA leverages mathematical operator techniques to
    exploit the inherent structure of minimal coordinate models, leading
    to the development of "low-cost recursive computational algorithms."

 -  SOA enables the derivation of "analytical operator expressions for
    the factorization of the mass matrix and its inverse for arbitrary
    tree multibody systems." These expressions are the foundation for
    efficient O(N) (linear scaling with the number of bodies) recursive
    methods for solving equations of motion. More information on the SOA
    methodology can be found in the
    [SOA book](https://www.springer.com/us/book/9781441972668), the
    [SOA lecture series](https://portal.karanadyn.com/publications) and
    [SOA publications](https://portal.karanadyn.com/publications).

## Handling Complex System Topologies

 - **Serial/Tree Rigid/Flexible Systems**: **kdFlex** implements the O(N)
   articulated-body inertia (ABI) recursive method for solving the
   equations of motion for tree-topology systems. A key advantage
   highlighted is that "SOA shows that these structure-based recursive
   methods for rigid multibody systems directly extend to flexible
   bodies as well." **kdFlex** supports both rigid and flexible body
   dynamics using assumed mode, small deformation models for flexible
   bodies.

 - **Closed-Chain Topology Systems**: Recursive methods are not directly
   applicable to systems with loops. **kdFlex** offers two approaches:

 - **Tree-Augmented (TA) Method**: This non-minimal coordinate approach
   introduces loop-cuts to create a spanning tree, applies O(N) methods
   to the spanning tree, and then corrects the solution for the
   loop-cuts using a SOA-based low-cost method for computing operational
   space inertias.

 - **Constraint Embedding (CE) Technique**: This is a SOA-based minimal
   coordinate method that "transforms the graph-topology systems into a
   minimal coordinate tree-topology system using compound,
   variable-geometry bodies." This transformation is
   structure-preserving, allowing the use of O(N) ABI recursive methods
   and ODE integrators even for closed-loop systems. Both CE and TA
   methods are available in **kdFlex**. (coming soon)

## Dynamics Features and Capabilities

 - **Run-Time Configuration Changes**: A significant feature of **kdFlex** is
   its ability to handle "run-time structural changes in the system
   topology such as from the attachment/detachment and addition/deletion
   of bodies." This is crucial for applications involving deployment,
   manipulation, and model refinement. The structure-based SOA
   algorithms seamlessly adapt to these changes by simply following the
   new system topology.

 - **Contact/Collision Dynamics**: **kdFlex** supports non-smooth dynamics. It
   includes "penalty-based methods" and "impulsive complementarity based
   solution methods that exploit minimal coordinate to reduce the size
   of the complementarity problem." Both linear and non-linear
   complementarity solution algorithms are available.

 - **Broad Family of Computational Algorithms**: Beyond standard forward
   dynamics, **kdFlex** offers:

 - **Jacobians**: Methods to compute the Jacobian matrix mapping generalized
   velocities to spatial velocities of any set of frames.

 - **Hybrid Dynamics**: An O(N) recursive algorithm where input can be a mix
   of generalized forces and prescribed generalized accelerations,
   allowing computation of unknown forces or accelerations. This
   algorithm can reduce to standard forward dynamics or inverse dynamics
   depending on the inputs.

 - **Operational Space Compliance Matrix (OSCM)**: A low-cost recursive algorithm
   (based on SOA) for computing the mass matrix reflected to a specific
   node, valuable for robotics control.

 - **Composite Body Properties**: Methods for computing
   configuration-dependent spatial inertia, momentum, and kinetic energy
   for subsets of bodies.

 - **CM Frame**: Automatically creates and tracks the center of mass (CM)
   location for any subgraph.

 - **Interbody Forces**: Provides an "inexpensive expression for computing
   this value for any pair of connected bodies" using the SOA algorithm,
   even though the standard ABI forward dynamics doesn't require it.

 - **Pruning Bodies**: Allows users to reduce computational cost by freezing
   and coalescing rigidly connected bodies.  (Coming soon)

 - **DCA Algorithm**: Includes an implementation of the divide-and-conquer
   algorithm for forward dynamics, suitable for parallelization with
   large models (e.g., molecular dynamics). (Coming soon)

 - **Linearization**: Provides methods for automatically computing and
   exporting linearized dynamics models, useful for control system
   design.

 - **Statistical Dynamics**: Supports statistical properties for molecular
   dynamics simulations, including a generalized equipartition principle
   (using SOA) and the use of a Fixman potential to correct statistical
   biases (also using SOA).

## Simulation Architecture and Design

 - **Frames Layer**: A general-purpose layer supporting "on demand
   computation of relative pose, velocity and accelerations for any pair
   of frames." Values are computed only when requested and are cached
   for efficiency. This layer supports run-time creation, deletion, and
   reattachment of frames.

 - **Multibody Elements**: Bodies, connector hinges, and nodes are
   represented as distinct C++ objects. Body and node classes are
   derived from a base frame class. Custom hinge types can be created,
   and bilateral loop constraints are defined via specific hinges.

 - **Subgraphs**: While computations are typically for the full system, SOA
   algorithms can be applied to "connected subgraphs of bodies." The
   full system is considered a subgraph. This distinction is important,
   particularly for the CE method for closed-loop systems.

 - **Python Interface**: A comprehensive Python interface is auto-generated. This allows users to "conveniently set up simulations
   using Python scripts without losing the speed benefits from the
   compiled C++ layer." It provides flexibility for model definition,
   configuration, and run-time interaction.

 - **Dynamics Solvers and Integrators**: **kdFlex** includes solver C++ classes
   to ensure compatibility between selected solution methods (e.g., O(N)
   ABI, TA) and appropriate numerical integrators (ODE integrators for
   minimal coordinate methods, DAE solvers or constraint error
   management for non-minimal coordinate methods).

 - **Visualization**: Includes 3D graphics visualization. A built-in
   capability generates a stick figure model for debugging, and users
   can attach primitive geometry or CAD parts for richer
   representation. Different graphics engines can be used.

 - **Other Features**: Includes nonlinear solvers for loop constraints and
   state initialization, and GUIs for model browsing, adjustment, and
   interactive animation.


- - -


# Key Questions

## What is distinctive and unique about kdFlex?

  - Short answer: **kdFlex** uses advanced algorithms, which are known to be
    the lowest cost and most robust techniques available for multi-body
    dynamics. These algorithms known as minimal coordinate techniques,
    are notoriously complex, and the few implementations that exist
    until now have narrow and very limited capabilities. **kdFlex** employs
    novel mathematical techniques from the Spatial Operator Algebra
    (SOA) (add link) to drive for improved efficiency as model
    complexity increases.

  - Long version: **kdFlex** employs minimal coordinate techniques, which
    offer several key advantages.

    - Firstly, by using minimal coordinates, (in contrast to redundant
      absolute coordinates), these methods avoid the need for managing
      constraints and constraint errors. They also reduce the size of
      the equations of motion that need to be solved.

    - Additionally, the use of minimal coordinates also allows the use
      of standard and significantly simpler ordinary differential
      equations for propagating system state. This is in contrast with a
      need for complex Differential Algebraic Equation solvers called
      DAE methods which propagate the state under algebraic
      constraints. The DAE methods require special purpose complex
      solvers, and the use of much smaller time steps for robust
      propagation. The minimal coordinate techniques on the other hand
      completely avoid the need for constraint error management.

    - Going beyond this, the minimal coordinate techniques have been
      shown to support what are referred to as order(N) recursive
      algorithms. So, while absolute coordinate techniques require
      methods whose cost goes up cubically with the number of bodies ,
      which can grow expensive very quickly, minimal coordinate
      technique’s exact algorithms cost only goes up linearly with the
      number of bodies. This is an extraordinary benefit in cost for
      even moderate to large size systems. 

    - The combination of these benefits makes the use of minimal
      coordinates a far more powerful approach. There have also been
      studies showing that the minimal coordinate techniques are also
      numerically more robust and accurate.

## Why are kdFlex’s recursive methods not used more widely?

  - Great question!  Dynamics models are
    complex, and minimal coordinated models ever more so. Conventional
    methods for minimal coordinate dynamics struggle with 
    even modest size and are limited to simple topologies and narrow
    (e.g., rigid body) capabilities. **kdFlex** overcomes the complexity of
    minimal coordinate dynamics by using the powerful Spatial Operator
    Algebra (SOA) methodology. SOA provides a mathematical framework and
    rich vocabulary for exploiting the rich underlying structure of
    minimal coordinate dynamics for analysis and the development of fast
    and recursive low cost, general purpose computational algorithms for
    rigid and flexible multibody dynamics The structure-based SOA
    algorithms also make it easy to easily accommodate run-time changes
    to system configuration from the addition/deletion of bodies or
    their reattachment.

## kdFlex seems new – how can I trust it?

  - **kdFlex** is a new and modern software product, but one based upon the
  proven and mature SOA methodology used over multiple decades for a
  variety of NASA and other mission critical applications including

    - NASA’s Cassini mission to Saturn, the Mars Pathfinder mission, and
    more recently for the Mars lander missions such as Mars Science Lab,
    Mars 2020, Mars Phoenix and Insight, the development to flight of
    the Mars Ingenuity helicopter,

    - the NASA Artemis I day of launch flight simulations ,and for
    ground vehicle simulations including platforms for DOD and planetary
    rovers for NASA. SOA has been used for several robotics research and
    technology development projects. These have included robotics
    manipulators, multi-limb robotic systems, and autonomous sampling
    systems. The SOA methods have also been used to develop advanced
    novel methods for protein folding simulation of large bio-molecular
    proteins under NIH research grants.

## What is the ROI with kdFlex?

  - Dynamics modeling is a complicated and expensive process requiring
    specialized expertise and tools used in engineering design process,
    for early concept development, to engineering design, to software
    development, V&V and operation of platforms in the
    field. Organizations often end up with expensive and fragmented
    solutions and and a plethora of tools and processes to meet such a
    variety of dynamics modeling needs. **kdFlex** is designed to provide a
    one-stop solution to enable the consolidation and streamlining of
    dynamics modeling across such life-cycles. **kdFlex** supports an
    extensive API for high fidelity flexible body models needs for loads
    and structures analysis as well as for guidance and control design
    and stability performance analysis, the speed and fidelity for
    closed-loop simulations including hardware in the loop, the
    versatility for robotics applications to handle ever-changing system
    constraints and topologies, an API to support the tailoring of
    system level models for multiple domain needs, and support for
    functionality well beyond solving the equations.

## How usable is kdFlex?

  - The **kdFlex** design is based on our belief (to borrow a phrase) that
    an informed customer is our best customer. Towards this, **kdFlex**
    includes a well structured, and feature complete API meant to allow
    a user to adapt and tailor its use as an SDK for the modeling and
    simulation application at hand. The APIs are available at the C++
    level (for computational heavy lifting), and mirrored at the Python
    level (for prototyping and scripting). Undoubtedly there will be a
    familiarization phase, but one that will empower a simulation
    engineer to use the toolkit far more effectively than GUIs - which
    tend to obfuscate rather than illuminate the powerful
    capabilities. Having said that, web-based 3D graphics support is
    built in to allow visualization and inspection of the model.

  - Furthermore, the **kdFlex** libraries are object oriented, with a family
    of objects for frames, bodies, hinges, subhinges, constraints etc,
    each with a well defined functionality and design. The objects serve
    a convenient way to interface with external user software, while
    also providing the benefits of information hiding and encapsulation
    that avoid fragile and error prone bookkeeping of the large amount
    of data within the simulation. For instance, adding or removing a
    body, or changing a hinge type and the number of degrees of freedom
    is trivial with no significantly impact on interface code such as is
    common in many applications.

  - The built-in general-purpose frames layer allows users to seamlessly
    make arbitrary relative pose, velocity and acceleration queries
    across the system. This does away with the burden on users to
    develop custom code - something that should be straight forward, but
    is notoriously error prone.

  - There is built in support for tagging input deck parameters with
    units and quantity types, to allow the use of such data from
    multiple sources as is a common. Avoiding the need for the user to
    carry out conversions avoids errors and maintain traceability.

  - There are built in important simulation services for 3D graphics
    visualization (web based), model importers, data logging, plotting,
    controlling message verbosity, exporting input decks in multiple
    formats etc.

  - There are architectural features that identify not ready
    parameters, improper clean up during configuration changes etc -
    that catch errors sooner than later - essential for developing and
    maintaining large scale, industrial strength complex simulations!

# Why is flexible body dynamics important?

  - Rigid bodies do not exist in reality, but the notion of idealized
    rigid bodies is extremely useful. However, there are situations
    where the deformation of bodies is very important, such as for loads
    and stress analysis, and for handling control/structure interaction
    and developing controllers that handle servo-elastic, aero-elastic
    effects. The data for such deformation properties typically
    originates from finite-element modeling using structural analysis
    tools. Accurate modeling the nonlinear dynamics of multibody systems
    with deformable bodies requires the integration of FEM data,
    component mode synthesis, model reduction and correctly modeling of
    the rigid/elastic dynamics coupling. There are only a small handful
    of tools, that do the this rigorously, but none with the with the
    fast computational speed **kdFlex**’s fast SOA recursive methods and
    minimal coordinate formulation. **kdFlex**’s unique and unparalleled
    ability to provide an integrated solution that combines fast
    performance with accurate flexible multibody dynamics modeling
    provides a critical bridge between the structures and control design
    disciplines. This bridge addresses gaps in tool-chains, modeling
    solutions and workflows between these disciplines that have for long
    plagued these communities and allows the streamlining of design
    iterations and simplify workflow pipelines with enormous savings in
    time and cost.


# Conventions

- no absolute positions, velocities, etc. - everything is relative 
- Unit quaternions  (see the {ref}`attitude_sec` section)
- Spatial vectors  (see the {ref}`spatial_notation_sec` section)
- Inertia positive/negative integral convention  (see the {ref}`spatial_notation_sec` section)
- Q, U, Udot, T for subhinges, hinges etc (see the {ref}`subhinges_sec` section)
- oframe, pframe (see the {ref}`create_frame_container_sec` section)
- onode/pnode  (see the {ref}`body_hinge_sec` section)
- quantities/units
- subtree virtual root does not belong to the subtree
- use create/discard methods, not constructors/destructors
- use object level getQ() methods and not take apart the CoordData etc
  level methods (see the {ref}`coord_data_sec` section)
- call ensureHealthy
- call allReady
- hop definition
- Ktime for time
