Skip to content
Merged
14 changes: 13 additions & 1 deletion .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ This is a numerical algorithms library providing digital signal processing (DSP)
- **numerical/**: Core implementation of algorithms organized by domain:
- `analysis/`: Signal analysis (FFT, PSD, DCT)
- `controllers/`: Control algorithms (PID controllers)
- `dynamics/`: Dynamics and modeling (Euler-Lagrange)
- `estimators/`: Estimation algorithms (Linear Regression, Yule-Walker)
- `filters/`: Digital filters (FIR, IIR, Kalman)
- `math/`: Mathematical foundations (QNumber, Matrix, Complex, Trigonometric functions)
Expand Down Expand Up @@ -61,7 +62,7 @@ Place code here when it is:
- Estimators and solvers
- Neural network components
- Hardware-agnostic and reusable across projects
- Organized by domain (analysis, controllers, filters, estimators, math, neural_network, solvers, windowing)
- Organized by domain (analysis, controllers, dynamics, filters, estimators, math, neural_network, solvers, windowing)

### Examples (`examples/`)

Expand Down Expand Up @@ -244,6 +245,7 @@ class Algorithm
- **NAMESPACE**: Use appropriate namespaces by domain:
- `analysis::` - Signal analysis algorithms
- `controllers::` - Control system algorithms
- `dynamics::` - Dynamics and modeling algorithms
- `estimators::` - Estimation algorithms
- `filters::passive::` - Passive filters (FIR, IIR)
- `filters::active::` - Active filters (Kalman)
Expand Down Expand Up @@ -418,6 +420,16 @@ Defined in `numerical/math/CompilerOptimizations.hpp`:
- **Derivative Filtering**: Consider derivative kick prevention techniques
- **Discretization**: Document the discretization method used (Tustin, forward Euler, etc.)

### Dynamics & Modeling (Euler-Lagrange, Newton-Euler)

- **Generalized Coordinates**: Use radians for revolute joints, meters for prismatic joints
- **Mass Matrix**: Must be symmetric positive definite; verify in tests
- **Coriolis Convention**: Interface returns $C(q,\dot{q})\dot{q}$ (the product), not the matrix $C$ alone
- **Units**: Torques in N·m, forces in N, angles in radians, angular velocities in rad/s
- **Float Only**: Dynamics values typically exceed Q15/Q31 range; use `float` unless inputs are scaled
- **Forward Dynamics**: Use `GaussianElimination` for the $M^{-1}$ solve; avoid explicit matrix inversion
- **DOF Sizes**: Explicitly instantiate for Dof = 1, 2, 3 (pendulum, planar arm, 3-link)

### Neural Networks

- **Layer Composition**: Use fluent interface for building networks
Expand Down
20 changes: 20 additions & 0 deletions .vscode/launch.json
Comment thread
gabrielfrasantos marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,26 @@
}
]
},
{
"name": "Robot Arm Simulator",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/build/host/simulator/dynamics/RobotArm/Debug/numerical.simulator.dynamics.robot_arm",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
{
"name": "Linux Debug",
"type": "cppdbg",
Expand Down
96 changes: 96 additions & 0 deletions doc/dynamics/ArticulatedBodyAlgorithm.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# Articulated Body Algorithm (ABA)

## Overview & Motivation

The Articulated Body Algorithm (ABA) is the most efficient method for computing **forward dynamics** of serial kinematic chains. Given joint positions $q$, velocities $\dot{q}$, and applied torques $\tau$, it computes joint accelerations $\ddot{q}$ in $O(n)$ time — linear in the number of links.

This is the forward-dynamics counterpart of the [Recursive Newton-Euler Algorithm](RecursiveNewtonEuler.md) (which solves inverse dynamics). Together, they form the two fundamental $O(n)$ algorithms in rigid-body dynamics.

Alternatives like Euler-Lagrange require explicitly forming and inverting the $n \times n$ mass matrix ($O(n^3)$), making ABA significantly faster for chains with more than 3-4 links.

## Mathematical Theory

### Problem Statement

Given a serial chain of $n$ rigid bodies connected by revolute joints, find:

$$\ddot{q} = M(q)^{-1} [\tau - C(q, \dot{q})\dot{q} - g(q)]$$

ABA computes this without ever forming or inverting $M$.

### Algorithm Structure

ABA has three passes over the kinematic chain:

1. **Forward pass** (base → tip): Compute link kinematics — angular velocities, linear velocities, and velocity-product accelerations from joint positions and velocities.

2. **Backward pass** (tip → base): Compute articulated-body inertias $I^A_i$ and bias wrenches $p^A_i$ for each link. At each step, the joint projection removes one degree of freedom from the spatial inertia, and the remainder is propagated to the parent.

3. **Forward pass** (base → tip): Resolve joint accelerations using the articulated-body quantities. Each joint acceleration $\ddot{q}_i$ is computed from the projected articulated inertia and the transformed parent acceleration.

### Key Formulas

**Articulated-body inertia** starts as the rigid-body spatial inertia of each link, then accumulates child contributions:

$$I^A_i \leftarrow I^A_i + X^*_{i+1} \hat{I}^A_{i+1} X_{i+1}$$

where $\hat{I}^A$ is the inertia after removing the joint DOF (the "downdate"):

$$\hat{I}^A_i = I^A_i - \frac{U_i U_i^T}{D_i}$$

with $U_i = I^A_i s_i$, $D_i = s_i^T U_i$, and $s_i$ the joint motion subspace (joint axis for revolute joints).

**Joint acceleration**:

$$\ddot{q}_i = \frac{u_i - U_i^T \hat{a}_i}{D_i}$$

where $u_i = \tau_i - s_i^T p^A_i$ and $\hat{a}_i$ is the spatial acceleration contribution from the parent.

## Complexity Analysis

| Case | Time | Space | Notes |
|------|--------|--------|------------------------------------|
| All | $O(n)$ | $O(n)$ | Three linear passes over the chain |

Each pass visits every link exactly once, performing constant-time spatial algebra (3×3 matrix operations) per link.

## Step-by-Step Walkthrough

Consider a 2-link planar arm with unit masses, unit lengths, Y-axis joints, zero velocities, and zero applied torques under gravity $g = [0, 0, -9.81]^T$.

**Pass 1** — Forward kinematics: both links at $q = [0, 0]^T$ with $\dot{q} = [0, 0]^T$, so all velocities and velocity-product terms are zero.

**Pass 2** — Backward pass: starting from link 2, compute the rigid-body inertia, project out the joint DOF, transform to link 1's frame, and accumulate. The articulated inertia at the base now represents the effective inertia of the entire chain.

**Pass 3** — Forward pass: at the base, the gravitational acceleration is transformed into the base frame and used to compute $\ddot{q}_1$. The resulting acceleration is propagated to link 2 to compute $\ddot{q}_2$.

The result: both joints accelerate downward due to gravity, with the base joint carrying the larger moment from the full chain.

## Pitfalls & Edge Cases

- **Singular configurations**: When $D_i \to 0$, the joint becomes locked. This should not happen for well-formed revolute joint models with positive inertia.
- **Numerical precision**: The division by $D_i$ amplifies errors if $D_i$ is small. Use `float` (not fixed-point) for dynamics computations.
- **Floating-point only**: The algorithm involves trigonometric functions, divisions, and large dynamic ranges that are unsuitable for Q15/Q31 fixed-point.

## Variants & Generalizations

- **Composite Rigid Body Algorithm (CRBA)**: Computes the mass matrix $M(q)$ explicitly in $O(n^2)$. Useful when $M$ itself is needed (e.g., for operational-space control).
- **Extended ABA**: Supports branching chains (trees) by processing children before parents in the backward pass.
- **ABA with friction**: Joint friction torques can be added directly to $\tau$.

## Applications

- Real-time simulation of robot arms and multi-body systems
- Model-based control (computed torque, impedance control)
- Forward integration of manipulator dynamics

## Connections to Other Algorithms

- [Recursive Newton-Euler](RecursiveNewtonEuler.md): solves the inverse problem ($q, \dot{q}, \ddot{q} \to \tau$). ABA and RNEA are duals: `RNEA(q, qDot, ABA(q, qDot, tau)) ≈ tau`.
- [Euler-Lagrange](EulerLagrange.md): equivalent $O(n^3)$ formulation using the mass matrix.
- [Gaussian Elimination](../solvers/GaussianElimination.md): used if the mass matrix approach is taken instead.

## References & Further Reading

- Featherstone, R. (2008). *Rigid Body Dynamics Algorithms*. Springer. Chapter 7.
- Featherstone, R. (1983). "The Calculation of Robot Dynamics Using Articulated-Body Inertias." *International Journal of Robotics Research*, 2(1), 13–30.
145 changes: 145 additions & 0 deletions doc/dynamics/EulerLagrange.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
# Euler-Lagrange Dynamics

## Overview & Motivation

The Euler-Lagrange equations provide a systematic way to derive the equations of motion for mechanical systems from energy principles. Instead of tracking forces on each body (as in Newton's method), they express dynamics in terms of *generalized coordinates* $q$ and the system's kinetic and potential energy.

For a robotic manipulator or any articulated mechanism with $n$ degrees of freedom, the Euler-Lagrange formulation yields a compact matrix equation:

$$M(q)\ddot{q} + C(q, \dot{q})\dot{q} + g(q) = \tau$$

Where:
- $q \in \mathbb{R}^n$ — generalized coordinates (joint angles/positions)
- $\dot{q}, \ddot{q}$ — generalized velocities and accelerations
- $M(q) \in \mathbb{R}^{n \times n}$ — mass (inertia) matrix, symmetric positive definite
- $C(q, \dot{q})\dot{q} \in \mathbb{R}^n$ — Coriolis and centrifugal terms
- $g(q) \in \mathbb{R}^n$ — gravitational terms
- $\tau \in \mathbb{R}^n$ — generalized forces/torques (inputs)

This formulation supports two fundamental computations:
- **Forward dynamics**: given torques $\tau$, compute accelerations $\ddot{q} = M^{-1}(\tau - C\dot{q} - g)$
- **Inverse dynamics**: given desired accelerations $\ddot{q}$, compute required torques $\tau = M\ddot{q} + C\dot{q} + g$

## Mathematical Theory

### Prerequisites

The **Lagrangian** of a system is defined as:

$$\mathcal{L}(q, \dot{q}) = T(q, \dot{q}) - V(q)$$

where $T$ is kinetic energy and $V$ is potential energy.

### Core Definitions

The **Euler-Lagrange equation** for coordinate $q_i$ is:

$$\frac{d}{dt}\frac{\partial \mathcal{L}}{\partial \dot{q}_i} - \frac{\partial \mathcal{L}}{\partial q_i} = \tau_i \quad \text{for } i = 1, \ldots, n$$

For a rigid-body system, kinetic energy takes the form:

$$T = \frac{1}{2}\dot{q}^T M(q) \dot{q}$$

Applying the Euler-Lagrange equation to this quadratic form yields the standard manipulator equation:

$$M(q)\ddot{q} + C(q, \dot{q})\dot{q} + g(q) = \tau$$

### Mass Matrix $M(q)$

The mass matrix is always **symmetric** ($M = M^T$) and **positive definite** ($\dot{q}^T M \dot{q} > 0$ for $\dot{q} \neq 0$). These properties guarantee:
- The forward dynamics linear system $M\ddot{q} = f$ always has a unique solution
- Physical kinetic energy is always non-negative

### Coriolis Matrix $C(q, \dot{q})$

The Coriolis matrix captures velocity-dependent forces using **Christoffel symbols of the first kind**:

$$c_{ij} = \sum_{k=1}^{n} \frac{1}{2}\left(\frac{\partial m_{ij}}{\partial q_k} + \frac{\partial m_{ik}}{\partial q_j} - \frac{\partial m_{jk}}{\partial q_i}\right)\dot{q}_k$$

A key property: $\dot{M} - 2C$ is skew-symmetric, which is important for passivity-based control.

### Gravity Vector $g(q)$

$$g_i(q) = \frac{\partial V}{\partial q_i}$$

where $V(q)$ is the total potential energy of the system.

## Complexity Analysis

| Operation | Time | Space | Notes |
|------------------|-----------------|----------|------------------------------------------------------|
| Forward dynamics | $O(n^3)$ | $O(n^2)$ | Dominated by $M^{-1}$ solve via Gaussian elimination |
| Inverse dynamics | $O(n^2)$ | $O(n^2)$ | Matrix-vector multiplication $M \ddot{q}$ |
| Model evaluation | Model-dependent | $O(n^2)$ | Computing $M(q)$, $C(q,\dot{q})$, $g(q)$ |

For systems with $n \leq 6$ DOF (typical robotic manipulators), the $O(n^3)$ cost of Gaussian elimination is negligible. For larger systems, consider the Recursive Newton-Euler Algorithm (RNEA) which achieves $O(n)$ inverse dynamics.

## Step-by-Step Walkthrough

### Example: Simple Pendulum (1-DOF)

A point mass $m$ on a rigid rod of length $l$:

**System parameters:** $m = 1\,\text{kg}$, $l = 1\,\text{m}$, $g_0 = 9.81\,\text{m/s}^2$

**Model matrices:**
- $M(q) = ml^2 = 1.0$
- $C(q, \dot{q})\dot{q} = 0$ (single DOF → no Coriolis)
- $g(q) = mgl\sin(q) = 9.81\sin(q)$

**Forward dynamics** at $q = 0.5\,\text{rad}$, $\dot{q} = 0$, $\tau = 0$:

$$\ddot{q} = M^{-1}(\tau - C\dot{q} - g) = \frac{0 - 0 - 9.81\sin(0.5)}{1.0} = -4.703\,\text{rad/s}^2$$

**Inverse dynamics** for holding position ($\ddot{q} = 0$):

$$\tau = M\ddot{q} + C\dot{q} + g = 0 + 0 + 9.81\sin(0.5) = 4.703\,\text{N·m}$$

### Example: Two-Link Planar Arm (2-DOF)

For a 2-DOF arm with equal links ($m_1 = m_2 = 1\,\text{kg}$, $l_1 = l_2 = 1\,\text{m}$):

**At rest** ($q = [0, 0]^T$, $\dot{q} = [0, 0]^T$):
- $\sin(q_1) = 0$, $\sin(q_1 + q_2) = 0$
- $g = [0, 0]^T$ → gravity terms vanish when links hang vertically
- Forward dynamics with $\tau = 0$ produces $\ddot{q} = [0, 0]^T$ (equilibrium)

## Pitfalls & Edge Cases

- **Singular mass matrix**: Should not happen for physically valid systems, but numerical conditioning degrades near kinematic singularities (e.g., fully extended arm). The Gaussian elimination solver uses partial pivoting to help.
- **Fixed-point arithmetic**: Dynamics values (torques, accelerations) typically exceed the $[-1, 1)$ range of Q15/Q31 formats. Use `float` unless inputs are carefully scaled.
- **Coriolis computation**: The choice of Coriolis parameterization (Christoffel vs. factored form) affects the skew-symmetry property of $\dot{M} - 2C$. The interface returns the product $C(q,\dot{q})\dot{q}$ directly, leaving the parameterization choice to the user.
- **Energy consistency**: For simulation, ensure the model matrices satisfy the skew-symmetry property; otherwise, energy may not be conserved in numerical integration.
- **Units**: Be explicit about whether angles are in radians (standard) and torques in N·m.

## Variants & Generalizations

| Variant | Trade-off | Use Case |
|--------------------------------------|------------------------------------------|------------------------------------------------------|
| **Euler-Lagrange** (this) | $O(n^3)$ forward, closed-form, intuitive | Small systems ($n \leq 6$), control design, analysis |
| **Newton-Euler** | Body-by-body force balance | Single rigid bodies, intuitive for simple systems |
| **Recursive Newton-Euler (RNEA)** | $O(n)$ inverse dynamics | Large kinematic chains, real-time control |
| **Articulated Body Algorithm (ABA)** | $O(n)$ forward dynamics | Large chains, simulation |
| **Hamiltonian formulation** | Phase-space, symplectic integration | Long-horizon simulation, energy preservation |

## Applications

- **Robot control**: Computed torque control, gravity compensation, impedance control
- **Simulation**: Forward dynamics integration for physics simulation
- **System identification**: Estimate dynamic parameters from measured motion
- **Trajectory optimization**: Inverse dynamics as constraints in optimization
- **Vibration analysis**: Linearized dynamics around equilibrium points

## Connections to Other Algorithms

- **Gaussian Elimination** ([GaussianElimination.md](../solvers/GaussianElimination.md)): Used internally to solve $M\ddot{q} = f$ in forward dynamics
- **LQR Controller** ([Lqr.md](../controllers/Lqr.md)): Euler-Lagrange dynamics can be linearized to produce the $(A, B)$ state-space matrices needed for LQR design
- **Kalman Filter** (../filters/active/): State estimation for partially observed dynamical systems derived from Euler-Lagrange models
- **DARE** ([DiscreteAlgebraicRiccatiEquation.md](../solvers/DiscreteAlgebraicRiccatiEquation.md)): Discretized Euler-Lagrange systems feed into DARE for optimal control gain computation

## References & Further Reading

- Siciliano, B., Sciavicco, L., Villani, L., & Oriolo, G. (2009). *Robotics: Modelling, Planning and Control*. Springer. Chapters 7–8.
- Spong, M. W., Hutchinson, S., & Vidyasagar, M. (2020). *Robot Modeling and Control* (2nd ed.). Wiley. Chapter 6.
- Murray, R. M., Li, Z., & Sastry, S. S. (1994). *A Mathematical Introduction to Robotic Manipulation*. CRC Press.
- Featherstone, R. (2008). *Rigid Body Dynamics Algorithms*. Springer. (For RNEA and ABA extensions.)
Loading
Loading