Welcome to the powerful world of kdFlex! As a new user, you’re about to embark on a journey with a state-of-the-art multibody dynamics modeling and simulation toolkit. kdFlex is renowned for its speed and fidelity, built on cutting-edge Spatial Operator Algebra (SOA) and minimal coordinate techniques, enabling efficient O(N) computational algorithms for both rigid and flexible bodies.
To help you hit the ground running, this section highlights the key concepts you should grasp early on, the ones you will need on a regular day-to-day basis, and highlights some important and less common advanced topics. Understanding these foundational elements will make your kdFlex experience smoother and more productive.
Diving In#
1. Dipping toes#
kdFlex: The Underlying Framework#
Before diving deep into kdFlex, it’s crucial to understand its foundational framework which provides infrastructure, core functionalities and data types that you will use constantly.
Key kdFlex modules you’ll encounter:
Karana.Math: This module is your toolkit for all mathematical operations. You’ll frequently use:Vectors and matrices: At the Python level, these arenumpy.arrayproxies for the underlying C++Karana::Math::VecandKarana::Math::Matclasses.blah
SpatialVector: For representing spatial forces, velocities, and accelerations in 6D space.HomTran(Homogeneous Transformation): For representing position and orientation (pose) in 3D space.UnitQuaternion: For representing orientation.SpatialInertia: For defining the mass and inertia properties of bodies.
Karana.Core: Contains fundamental utilities like:MsgLogger: Karana’s powerful logging system for debugging and information output.Ktime(often represented bynumpy.timedelta64in Python): Karana’s internal time representation.
Karana.Frame: The cornerstone of spatial relationships, discussed next.
Why it matters: You’ll be working with kdFlex’s specific data types and methods for everything from defining geometry to applying forces. Familiarize yourself with them! See Math layer section for details.
Frames: The Foundation of Spatial Relationships#
In kdFlex spatial poses, velocities and accelerations are defined
with respect to Frames. A Frame is simply a coordinate system that
defines a position and orientation in 3D space.
Frame: The frame instances associated with coordinate frames for locations of interest.FrameToFrame: Defines relative pose, velocity and acceleration relationships across arbitraryframepairs.NewtonianFrame: This is your “world” or inertial reference frame. All absolute positions and orientations are ultimately referenced to theNewtonianframe.Frame Hierarchies: Frames are organized in a hierarchy, with parent-child relationships. A
homogeneous transform(Homogeneous Transformation) describes the relationship between a child frame and its parent, andspatial vectorthe relative spatial velocity and acceleration quantities.FrameContainer: Manages all the frames in your system.
Why it matters: Understanding how to define, relate, and transform
between frames (HomTran) is fundamental. Whether you’re placing a
sensor, defining a joint, or applying a force, you’ll specify its
location and orientation relative to a particular frame. See
Frames Layer section for details.
Multibody Systems: Building Your Vehicle Platform#
The heart of your kdFlex model is the
Karana.Dynamics.Multibody object. This represents your entire
mechanical system—your robot, vehicle, or mechanism.
You typically define your multibody system using a data structure approach:
Multibody: This top-level container class allows you to declaratively define your system’s bodies, their connection topology and properties.Key Components of
multibody:PhysicalBody: Defines a rigid body. You specify its name, parent frame, andPhysicalBodyParams(mass,SpatialInertia, and transformations defining its local frames).PhysicalHinge: Connects two bodies (or a body to the Newtonian frame) and defines the degrees of freedom (DOF) between them. kdFlex supports variousHINGE_TYPEs:FULL6DOF: A free-floating body (6 DOFs).REVOLUTE: A single rotational DOF.PRISMATIC: A single translational DOF.And many others for specific joint types.
Base Bodies: These are the bodies directly attached to theNewtonianframe, forming the “base” of your system’s kinematic tree.Node: Aframeattached to aKarana.Dynamics.PhysicalBodyfor sensing and applying external forces.
The mb.ensureHealthy() method: After defining your multibody
Karana.Dynamics.Multibody instance, always call
mb.ensureHealthy(). This crucial step finalizes the internal
structure of the multibody system, making it ready for dynamics
computations.
Why it matters: This is how you construct your model. A well-defined
multibody is the prerequisite for any simulation. See Multibody Layer section for
details.
Dynamics and Simulation: Bringing Your System to Life#
Once your multibody system is defined, the
Karana.Dynamics.StatePropagator instance takes center stage for time-domain
simulations.
Role of
state propagator: It integrates the system’s equations of motion over time, advancing its generalized positions (Q) and velocities (U).Integrator Types:
"cvode_stiff": Often the recommended choice for general robustness, especially with stiff systems (common in robotics and complex mechanisms)."rk4": A simpler, fixed-step Runge-Kutta 4th order integrator, useful for non-stiff systems or when precise fixed steps are required.
Setting Initial Conditions: You must provide the
state propagatorwith aninitial_timeand aninitial_state_vector(containingQandUfor your system).Advancing the Simulation: Use methods like
sp.advanceBy(duration)orsp.advanceTo(target_time)to run your simulation.Applying Forces/Torques: To interact with your system (e.g., apply gravity, control forces), you’ll use methods like
body.applySpatialForce(spatial_vector). These are typically applied within specialized callback functions registered with thestate propagator(seepre_deriv_fnsbelow).
Why it matters: The state propagator is how you observe your model’s
behavior over time. Mastering its configuration and usage is key to
running meaningful simulations. See Time-domain simulations section for
details.
kdFlex is a powerful tool, and like any powerful tool, it has a learning curve. By focusing on these core concepts—Karana’s types, Frames, Multibody definition, StatePropagator, DataCaches, and debugging utilities—you’ll build a strong foundation for creating robust and efficient simulations.
Don’t hesitate to explore the rest of the kdFlex documentation, notebook examples and the kdFlex Chatbot. Happy simulating!
2. Free swim#
As you start to use kdFlex, you will want to go beyond the essentials described in the previous section. Here is an introductory overview of some key topics that you will find useful for day-to-day use.
Computational Algorithms#
kdFlex provides a comprehensive and fast collection of computational algorithms designed for multibody, subgraph, and subtree instances. These algorithms are built upon advanced techniques, notably the Spatial Operator Algebra (SOA), which is recognized for its high-performance and robust computational dynamics capabilities. kdFlex specifically leverages SOA-based low-cost, minimal coordinate recursive techniques, which are considered among the lowest cost and most robust methods available for multibody dynamics. The algorithms are available for systems that include rigid as well as flexible bodies.
Here’s an introductory summary of the types of computational algorithms supported:
Kinematics Algorithms: kdFlex includes algorithms for both inverse kinematics, which determines the joint configurations needed to achieve a desired end-effector pose, and forward kinematics, which calculates the end-effector pose given the joint configurations.
Dynamics Algorithms:
Forward Dynamics: Computes the accelerations of the system given the applied forces and torques. This is a standard capability, and kdFlex offers various methods, including O(N) ABI (Articulated Body Inertia) and Tree-Augmented (TA) methods for tree and graph systems. The TA method is particularly used for closed-chain topology systems, where it creates a spanning tree by introducing loop-cuts, applies O(N) methods, and then corrects the solution for the loop-cuts. For closed-chain systems, kdFlex also includes the advanced Constraint-Embedding (CE) methods that transforms the system into a tree-topology system for the direct use of the fast O(N) ABI methods and avoiding the need for constraint error management and complex DAE solvers.
Inverse Dynamics: Calculates the forces and torques required to achieve a desired motion or acceleration for tree and graph systems.
System Property Computations: Algorithms are available for calculating essential system properties, such as:
System spatial momentum
Mass properties
Kinetic energy
Contact/Collision Dynamics Algorithms: kdFlex supports collision detection and non-smooth dynamics related to contact and collision using penalty-based methods.
Efficient Inter-Body Force Computation: kdFlex provides an inexpensive way for computing inter-body forces using the SOA algorithm. While not strictly required for primary forward dynamics, this efficient computation can be an optional step when detailed force information is needed.
Recursive OSCM Algorithms: For certain computationally expensive tasks, such as evaluating expressions involving the Operational Space Mass Matrix (OSCM), kdFlex uses recursive SOA algorithms. These algorithms exploit the structure of the OSCM to develop decompositions that avoid the direct computation and inversion of the mass matrix, offering significant computational benefits.
Dynamics Solvers and Integrators: kdFlex incorporates C++ solver classes to ensure proper compatibility between chosen solution methods (e.g., O(N) ABI, TA) and appropriate numerical integrators, such as ODE integrators for minimal coordinate formulations.
Overall, kdFlex is designed with a broad family of computational algorithms to provide fast performance and accurate flexible multibody dynamics modeling, addressing diverse engineering needs. See Computational Algorithms section for details.
KModels#
KModels are a core component of kdFlex’s simulation layer, providing a structured way to interact with objects in a simulation. They act as component models that can be used to perform various tasks, such as:
Sensing the position and velocity of a joint or sensor node, as well as using complex models for body mounted sensors such as IMUs, cameras etc.
Applying direct forces via a joint or actuator node, as well as models such as terramechanics, aerodynamics for environmental interactions.
Supporting actions to support simulation services such as data logging, plotting, visualization updates etc..
The Karana.Dynamics.ModelManager class is responsible for registering
these component models, allowing their methods and functionality to be
integrated into the overall system dynamics.
In C++, KModels are created by deriving from a Karana::Models::KModel
base class, with the introspection capacity to determine which methods a
derived class has defined. Python models derive from a different class,
Karana.Models.PyKModelBase, and use object attributes. KModels support
custom parameter classes (e.g., derived from
Karana::Models::KModelParams) and can be configured for multi-rate
operations. Parameters for a KModel are typically initialized via member
variables on its params member or through setter methods. See KModel component models section for
details.
Examples of KModels include ComputedTorque, DataLogger,
GraphicalSceneMovie, PID, PenaltyContact, and UniformGravity.
Scene for Geometry#
The Scene layer in kdFlex defines an abstract interface for
managing 3D geometries attached to physical bodies within a multibody
system. This layer is implemented through classes like
Karana.Scene.Scene, Karana.Scene.SceneNode, and
Karana.Scene.ScenePart.
Karana.Scene.Scene: A base container for a hierarchy of geometries.Karana.Scene.SceneNode: Represents an object with a transform (position, rotation, and uniform scale factor) relative to a parent. Scene nodes can be attached to one another, forming a tree structure for the overall scene. They also have a visibility flag.Karana.Scene.ScenePart: A type of scene node that additionally possesses a 3D geometry and a material.
kdFlex supports various geometry types for scene parts, including
analytical primitive shapes like BoxGeometry, CapsuleGeometry,
ConeGeometry, CylinderGeometry, RoundFrustumGeometry, and
SphereGeometry, as well as triangular meshes
(StaticMeshGeometry). User-defined geometry types can also be
incorporated. Materials, such as Phong and PBR, describe the surface
properties and appearance of scene parts. The Karana.Scene.ProxyScene
acts as a manager for multiple client scenes, allowing for filtering of
scene parts. See Geometry Layer section for
details.
Visualization#
kdFlex includes robust 3D graphics visualization capabilities to
inspect and debug models. The primary implementation for visualization
is Karana.Scene.WebScene, and uses WebGL
for hardware-accelerated 3D rendering in a web browser. This allows for
live, interactive visualization of a simulation by simply opening a
URL. A standalone Electron application is also available for local 3D
visualization.
Setting up visualization is streamlined using the setupGraphics helper
method, typically called on a multibody object. This method returns a
cleanup function and a Karana.Scene.WebScene instance, which can then
be used to programmatically set the camera position and orientation
(e.g., web_scene.defaultCamera().pointCameraAt(...)). Visualization
can display a built-in stick figure model for debugging or attach
primitive geometries or CAD parts for richer representations. See Visualization section for
details.
Data Plotting#
kdFlex provides tools for dynamic data plotting, allowing plots to
be updated in real-time as a simulation progresses. Key classes for this
functionality are Karana.KUtils.DataPlotter.DashApp and
Karana.KUtils.DataPlotter.SinglePlotData.
Karana.KUtils.DataPlotter.DashApp: Used to create a live plotting instance. It can take a list ofPlotDataDSinstances to display multiple plots on the same web frontend. It automatically starts a websocket and HTTP server, printing a URL for users to view the plots in a web browser.Karana.KUtils.DataPlotter.SinglePlotData: Defines the data to be plotted. This includes the title of the graph, the name and callable function for the x-axis data (independent variable), and a dictionary of names and callable functions for the y-axis data (dependent variables), which can be scalar or vector values.
Plots can be updated manually by calling the update method on the
DashApp instance, or automatically during a simulation step using the
Karana.Models.DataPlotter KModel. See Plotting section for
details.
Data Logging#
Data logging in kdFlex allows for recording simulation data into
HDF5 files. This is primarily managed by the Karana.KUtils.H5Writer
class, which leverages Karana.KUtils.PacketTableConfig to define
tables and functions that populate their columns.
The general process for data logging involves:
Defining Data Structure: Using
PacketTableConfiginstances to define each table you wish to create in the HDF5 file. These configurations include callable functions (defined in C++ or Python) that calculate new row data each timeH5Writer.logis called.Initializing the Logger: Creating an instance of
H5Writer.Registering Data Configurations: Calling
createTableon theH5Writerfor eachPacketTableConfig.Logging Data: Invoking the
logmethod on theH5Writerto write data for all active tables, orlogTableto log a specific table regardless of its active status.
For automatically logging simulation data at regular intervals, the
Karana.Models.DataLogger KModel is used. This model can be registered
with the StatePropagator, and its log_first_step parameter can
ensure an initial data entry at time 0. Data logging can also be
performed independently of a running simulation. See Data logging section for
details.
Cut-Joint Loop Constraints#
In kdFlex, a multibody system with a closed-chain topology is
represented as a physical body tree combined with an additional set of
cut-joint constraints, defined as
Karana.Dynamics.LoopConstraintHinge instances. For systems with a
regular serial or tree topology, there are no loops, and thus no
cut-joints. Cut-joint constraints have hinges that define the
unconstrained motion across the cut-joint. The number of loops in a
multibody’s topology establishes the lower bound on the number of
required cut-joint constraints, and the preferred option is to minimize
the number cut-joint constraints. However a larger number of cut-joint
constraints is permissible, and in the extreme case, all the tree hinges
can be replaced by cut-joint constraints to yield what is referred to as
the fully-augmented (FA) model. In the FA model, the multibody
topology consists of independent bodies, held together by cut-joint
constraints. The FA model is by far the predominant modeling approach by
most dynamics modeling tools.
kdFlex offers a numerical inverse kinematics solver through the
Karana.Dynamics.ConstraintKinematicsSolver class that can be used to
iteratively solve Q and U coordinates that satisfy the
constraints. See Cut-Joint constraints section for details.
Contact Dynamics#
kdFlex supports contact and collision dynamics, which are considered non-smooth dynamics. Contact dynamics is based on penalty-based methods that simulate contact forces based on penetration depth and Coulomb friction.
Collision Detection: Handled by collision engines, which detect object collisions and provide information such as penetration depth and collision normals. The
Karana.Collision.FrameColliderclass is used to capture this information.Contact Force Calculation: Once collision information is gathered, contact forces are calculated and applied. This often involves creating a
PenaltyContactinstance withFrameColliderandContactForceBaseas arguments.
An example notebook, “2 link pendulum (collisions),” illustrates how to use collision dynamics within kdFlex. See Collision dynamics section for details.
Model Parameters#
kdFlex supports the assignment of quantities and units for numerical parameters and includes helper functions for unit conversion. See Units and Quantities section for details.
Proper initialization of parameter and state data is essential for correct simulation results. kdFlex includes mechanisms to detect initialization gaps and raise errors early so they can be fixed. When undetected, such gaps otherwise be notoriously difficult to detect and fix. See Math layer section for details.
Model and State Import/Export#
kdFlex includes support for exporting the simulation model information
to the file system in standard formats such as yaml, json, hdf5
and more. The model data from these files can be imported in simulations
to recreate the model. In a similar way, state data and be exported to
the file system, and later imported to initialize system state in other
simulations. See DataStruct section for
details.
Environment variables#
There are a number of environment variables in kdFlex that can be used to configure its behavior based on your environment:
KARANA_LICENSE_FILE: This must be set to the filepath of your license file.KARANA_LOG_LEVEL: Sets the logging verbosity level. This should be one of the options inLogLevelsuch as"WARN"or"DEBUG".KARANA_SHARE_DIR: Ifkdflexis installed to a nonstandard location, this should be set to the absolute path of theshare/Karanadirectory.
3. Deep dive#
While the sections above focused on the important main stream kdFlex capabilities, there are several additional advanced kdFlex capabilities - some of which are described below.
SubTrees and SubGraphs#
While most computations are carried out on the full multibody system, kdFlex supports the ability to limit the computations to just a part of the multibody system by defining sub-tree and sub-graph instances. Sub-trees are a connected subset of bodies in the multibody system. Sub-graphs are sub-trees with additional constraints. The multibody class itself is a specialization of the sub-graph class. Most of the kdFlex algorithms take a sub-tree or sub-graph argument and will limit their computations to just the bodies defined for them.
There is no restriction on the number of sub-trees and sub-graphs that can be defined. However, computations can only be carried out on sub-graphs that have been explicitly enabled for algorithmic computations. While multiple subgraphs may be simultaneously enabled for algorithmic computation, there is a requirement that all enabled ones be disjoint, i.e. there can be no overlap in the bodies they contain. See Sub-Trees section for details.
Non cut-joint constraints#
kdFlex supports additional constraint types beyond cut-joint constraints. Coordinate constraints are an important constraint type which can be used to define geared constraints that directly constrain the coordinate rates of a pair of joints to a specific gear ration scale factor. The coupling can be either pairing of rotational/rotational coordinates or rotational/translational ones. See Coordinate constraints section for details.
Flexible Body Dynamics#
Flexible body dynamics in kdFlex extends the simulation capabilities beyond purely rigid bodies to include components that deform under load. kdFlex supports flexible body dynamics using the modal analysis approach.
Key aspects include:
Modal Representation: Flexible bodies are typically represented using a set of assumed modes (e.g., normal modes from FEM analysis) that describe their deformation. The motion of the flexible body is then described by the rigid body motion of a reference frame and the time-varying amplitudes of these modes.
Coupling with Rigid Bodies: kdFlex seamlessly couples the dynamics of these flexible bodies with the rigid bodies in the system, ensuring accurate interaction and force transmission.
Computational Efficiency: kdFlex extends the O(N) ABI recursive methods to such deformable bodies as well to support fast dynamics computations. multibody simulation.
This capability is vital for applications where component flexibility significantly influences the overall system behavior, such as in aerospace, automotive, and advanced robotics. See Flexible body systems section for details.
System Kinematics Analysis#
Kinematic analysis in kdFlex focuses on analyzing closed-chain topology systems. The kinematics analysis methods allow for the computation, of system level constraint matrices, evaluating the independence of the constraints on the system, and assessing the best subset of coordinates to choose for independent coordinates - should such a choice be needed. See Constraints Related Algorithms section for details.
Variable topology#
kdFlex supports mid-stream structural changes to the multibody system from body deletion, body addition, and body reattachment. Also support are changes from the enabling and disabling of constraints at run-time. The recursive nature of the SOA based computational dynamics algorithms allows them to adapt to such changes with very little overhead. Such powerful versatility allows kdFlex to support a rich set of behaviors and broad range of realistic simulation scenarios. See Multibody configuration changes section for details.
Compound Bodies#
Compound bodies in kdFlex allow for the creation of complex rigid bodies by combining multiple simpler rigid bodies into a single entity. This is particularly useful when dealing with assemblies of parts that move together as a single rigid unit. Instead of modeling each sub-component individually and linking them with rigid joints (which can increase computational cost), kdFlex allows you to compute the combined mass, center of mass, and inertia tensor for the entire compound body. This simplifies the model, improves computational efficiency, and makes the system easier to manage. Compound bodies are often used to represent structures like a robot’s end-effector, a vehicle chassis, or other rigid assemblies.
Constraint Embedding#
Constraint embedding is a technique used in kdFlex to incorporate kinematic constraints directly into the system’s equations of motion. Instead of using Lagrange multipliers or penalty methods to enforce constraints, embedding modifies the system’s dynamics equations such that the constraints are inherently satisfied. This approach can lead to more stable and efficient simulations, especially for systems with complex closed-loop constraints.
kdFlex uses minimal coordinate techniques, which inherently embed certain types of constraints (like those imposed by joints) by describing the system’s configuration with the smallest possible number of independent variables. For more general constraints (e.g., loop closures or specific contact conditions), kdFlex might use methods that reformulate the dynamics to eliminate dependent coordinates, effectively “embedding” the constraint into the system’s reduced set of equations. This contrasts with approaches that add constraint forces as external terms.
Timed Events#
The kdFlex state propagator allows the registering of user defined timed events. The time event executions can be one time, irregular, or periodic. The state propagator that state propagation supports the execution of the registered time events at the correct time with valid states. See Timed events section for details.
Multi-rate State Propagation#
kdFlex supports multi-rate simulations. Models can register specific rates at which they need to run. The kdFlex scheduler will take into account the different rate requirements to automatically determine the propagation hops required to meet the overall rates for all of the models. In addition, the propagator allows the specification of zero-crossing conditions. When such conditions are registered, the state propagation will detect the exact time when the condition is successfully and ensure that the associated callback is invoked at that time. See Model methods and zero_crossings_sec) sections for details.
Equilibration#
Equilibration in kdFlex refers to the process of finding a static equilibrium configuration for a multibody system. This involves determining the set of generalized coordinates (e.g., joint angles) and potentially external forces (e.g., actuator torques) where the net forces and torques on all bodies in the system are zero, and the system remains motionless. This is a crucial capability for finding a equilibrium starting configuration for a simulation to avoid large transients and instabilities in the simulation runs. The equilibration solver typically employs iterative numerical methods to converge to a state where all forces and moments are balanced.
FEMBridge#
FEMBridge in kdFlex is a capability that facilitates the integration of Finite Element Method (FEM) models with the multibody dynamics environment. It acts as a bridge, allowing users to incorporate flexible bodies whose properties and behavior are derived from FEM analyses.
This means you can: take deformation modes, mass, and stiffness matrices from a pre-computed FEM analysis (e.g., from Nastran, Abaqus, or other FEA software) and use them to represent a flexible body within kdFlex.
FEMBridge is essential for accurately simulating systems where structural flexibility plays a significant role, such as lightweight robotic arms, aircraft components, or compliant mechanisms, without having to perform the full, computationally expensive FEM analysis at each time step of the multibody simulation.
State Space Model Generation#
State space model generation in kdFlex involves deriving a set of first-order ordinary differential equations (ODEs) that describe the system’s dynamics. A state-space model represents the system’s behavior using a minimal set of state variables (e.g., positions and velocities) and inputs, and provides outputs that are functions of these states and inputs.
kdFlex can:
Linearize Dynamics: Linearize the non-linear multibody dynamics equations around an operating point (e.g., an equilibrium configuration).
Generate A, B, C, D Matrices: Output the
A,B,C, andDmatrices that define the linear time-invariant (LTI) state-space model:dx/dt = Ax + Buy = Cx + Duwherexis the state vector,uis the input vector, andyis the output vector.
This capability is extremely valuable for:
Control System Design: Designing controllers using linear control theory (e.g., LQR, H-infinity).
System Analysis: Analyzing stability, controllability, and observability of the multibody system.
Model Reduction: Creating simplified models for higher-level simulations or embedded applications.
See Linearized state space models section for details.
Modal Analysis#
Modal analysis in kdFlex is a technique used to understand the inherent dynamic characteristics of a flexible structure. It involves calculating the natural frequencies and corresponding mode shapes (eigenvectors) of a system. These modes represent the patterns of vibration that a structure would exhibit if disturbed from its equilibrium position.
In kdFlex:
Basis for Flexible Bodies: The results of modal analysis (often derived from FEM software) are used as the basis for representing flexible bodies within the multibody dynamics simulation. Instead of modeling every finite element, the flexible body’s deformation is approximated by a superposition of its dominant mode shapes.
Understanding Vibrations: Modal analysis helps engineers identify potential resonance issues, predict how a structure will vibrate under dynamic loads, and design structures to avoid undesirable vibrational characteristics.
Using modal analysis, kdFlex can support the development of reduced order models for the system that are important for control system design and analysis. See Guidance and Control Related Algorithms section for details.