Skip to content

Commit d308931

Browse files
gabrielfrasantosgithub-actions[bot]Copilot
authored
feat: add dynamics (#97)
* add dynamics * add newton euler formulation * add rnea * Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * process review comments * fix aba * add simulator for dynamics * split dynamics and kinematics * more adjusts * Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * fix simulator * add missing ut --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
1 parent cb5dea1 commit d308931

50 files changed

Lines changed: 4189 additions & 1 deletion

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/copilot-instructions.md‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ This is a numerical algorithms library providing digital signal processing (DSP)
99
- **numerical/**: Core implementation of algorithms organized by domain:
1010
- `analysis/`: Signal analysis (FFT, PSD, DCT)
1111
- `controllers/`: Control algorithms (PID controllers)
12+
- `dynamics/`: Dynamics and modeling (Euler-Lagrange)
1213
- `estimators/`: Estimation algorithms (Linear Regression, Yule-Walker)
1314
- `filters/`: Digital filters (FIR, IIR, Kalman)
1415
- `math/`: Mathematical foundations (QNumber, Matrix, Complex, Trigonometric functions)
@@ -61,7 +62,7 @@ Place code here when it is:
6162
- Estimators and solvers
6263
- Neural network components
6364
- Hardware-agnostic and reusable across projects
64-
- Organized by domain (analysis, controllers, filters, estimators, math, neural_network, solvers, windowing)
65+
- Organized by domain (analysis, controllers, dynamics, filters, estimators, math, neural_network, solvers, windowing)
6566

6667
### Examples (`examples/`)
6768

@@ -244,6 +245,7 @@ class Algorithm
244245
- **NAMESPACE**: Use appropriate namespaces by domain:
245246
- `analysis::` - Signal analysis algorithms
246247
- `controllers::` - Control system algorithms
248+
- `dynamics::` - Dynamics and modeling algorithms
247249
- `estimators::` - Estimation algorithms
248250
- `filters::passive::` - Passive filters (FIR, IIR)
249251
- `filters::active::` - Active filters (Kalman)
@@ -418,6 +420,16 @@ Defined in `numerical/math/CompilerOptimizations.hpp`:
418420
- **Derivative Filtering**: Consider derivative kick prevention techniques
419421
- **Discretization**: Document the discretization method used (Tustin, forward Euler, etc.)
420422
423+
### Dynamics & Modeling (Euler-Lagrange, Newton-Euler)
424+
425+
- **Generalized Coordinates**: Use radians for revolute joints, meters for prismatic joints
426+
- **Mass Matrix**: Must be symmetric positive definite; verify in tests
427+
- **Coriolis Convention**: Interface returns $C(q,\dot{q})\dot{q}$ (the product), not the matrix $C$ alone
428+
- **Units**: Torques in N·m, forces in N, angles in radians, angular velocities in rad/s
429+
- **Float Only**: Dynamics values typically exceed Q15/Q31 range; use `float` unless inputs are scaled
430+
- **Forward Dynamics**: Use `GaussianElimination` for the $M^{-1}$ solve; avoid explicit matrix inversion
431+
- **DOF Sizes**: Explicitly instantiate for Dof = 1, 2, 3 (pendulum, planar arm, 3-link)
432+
421433
### Neural Networks
422434
423435
- **Layer Composition**: Use fluent interface for building networks

‎.vscode/launch.json‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,26 @@
6161
}
6262
]
6363
},
64+
{
65+
"name": "Robot Arm Simulator",
66+
"type": "cppdbg",
67+
"request": "launch",
68+
"program": "${workspaceFolder}/build/host/simulator/dynamics/RobotArm/Debug/numerical.simulator.dynamics.robot_arm",
69+
"args": [],
70+
"stopAtEntry": false,
71+
"cwd": "${workspaceFolder}",
72+
"environment": [],
73+
"externalConsole": false,
74+
"MIMode": "gdb",
75+
"miDebuggerPath": "/usr/bin/gdb",
76+
"setupCommands": [
77+
{
78+
"description": "Enable pretty-printing for gdb",
79+
"text": "-enable-pretty-printing",
80+
"ignoreFailures": true
81+
}
82+
]
83+
},
6484
{
6585
"name": "Linux Debug",
6686
"type": "cppdbg",
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# Articulated Body Algorithm (ABA)
2+
3+
## Overview & Motivation
4+
5+
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.
6+
7+
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.
8+
9+
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.
10+
11+
## Mathematical Theory
12+
13+
### Problem Statement
14+
15+
Given a serial chain of $n$ rigid bodies connected by revolute joints, find:
16+
17+
$$\ddot{q} = M(q)^{-1} [\tau - C(q, \dot{q})\dot{q} - g(q)]$$
18+
19+
ABA computes this without ever forming or inverting $M$.
20+
21+
### Algorithm Structure
22+
23+
ABA has three passes over the kinematic chain:
24+
25+
1. **Forward pass** (base → tip): Compute link kinematics — angular velocities, linear velocities, and velocity-product accelerations from joint positions and velocities.
26+
27+
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.
28+
29+
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.
30+
31+
### Key Formulas
32+
33+
**Articulated-body inertia** starts as the rigid-body spatial inertia of each link, then accumulates child contributions:
34+
35+
$$I^A_i \leftarrow I^A_i + X^*_{i+1} \hat{I}^A_{i+1} X_{i+1}$$
36+
37+
where $\hat{I}^A$ is the inertia after removing the joint DOF (the "downdate"):
38+
39+
$$\hat{I}^A_i = I^A_i - \frac{U_i U_i^T}{D_i}$$
40+
41+
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).
42+
43+
**Joint acceleration**:
44+
45+
$$\ddot{q}_i = \frac{u_i - U_i^T \hat{a}_i}{D_i}$$
46+
47+
where $u_i = \tau_i - s_i^T p^A_i$ and $\hat{a}_i$ is the spatial acceleration contribution from the parent.
48+
49+
## Complexity Analysis
50+
51+
| Case | Time | Space | Notes |
52+
|------|--------|--------|------------------------------------|
53+
| All | $O(n)$ | $O(n)$ | Three linear passes over the chain |
54+
55+
Each pass visits every link exactly once, performing constant-time spatial algebra (3×3 matrix operations) per link.
56+
57+
## Step-by-Step Walkthrough
58+
59+
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$.
60+
61+
**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.
62+
63+
**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.
64+
65+
**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$.
66+
67+
The result: both joints accelerate downward due to gravity, with the base joint carrying the larger moment from the full chain.
68+
69+
## Pitfalls & Edge Cases
70+
71+
- **Singular configurations**: When $D_i \to 0$, the joint becomes locked. This should not happen for well-formed revolute joint models with positive inertia.
72+
- **Numerical precision**: The division by $D_i$ amplifies errors if $D_i$ is small. Use `float` (not fixed-point) for dynamics computations.
73+
- **Floating-point only**: The algorithm involves trigonometric functions, divisions, and large dynamic ranges that are unsuitable for Q15/Q31 fixed-point.
74+
75+
## Variants & Generalizations
76+
77+
- **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).
78+
- **Extended ABA**: Supports branching chains (trees) by processing children before parents in the backward pass.
79+
- **ABA with friction**: Joint friction torques can be added directly to $\tau$.
80+
81+
## Applications
82+
83+
- Real-time simulation of robot arms and multi-body systems
84+
- Model-based control (computed torque, impedance control)
85+
- Forward integration of manipulator dynamics
86+
87+
## Connections to Other Algorithms
88+
89+
- [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`.
90+
- [Euler-Lagrange](EulerLagrange.md): equivalent $O(n^3)$ formulation using the mass matrix.
91+
- [Gaussian Elimination](../solvers/GaussianElimination.md): used if the mass matrix approach is taken instead.
92+
93+
## References & Further Reading
94+
95+
- Featherstone, R. (2008). *Rigid Body Dynamics Algorithms*. Springer. Chapter 7.
96+
- Featherstone, R. (1983). "The Calculation of Robot Dynamics Using Articulated-Body Inertias." *International Journal of Robotics Research*, 2(1), 13–30.

‎doc/dynamics/EulerLagrange.md‎

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
# Euler-Lagrange Dynamics
2+
3+
## Overview & Motivation
4+
5+
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.
6+
7+
For a robotic manipulator or any articulated mechanism with $n$ degrees of freedom, the Euler-Lagrange formulation yields a compact matrix equation:
8+
9+
$$M(q)\ddot{q} + C(q, \dot{q})\dot{q} + g(q) = \tau$$
10+
11+
Where:
12+
- $q \in \mathbb{R}^n$ — generalized coordinates (joint angles/positions)
13+
- $\dot{q}, \ddot{q}$ — generalized velocities and accelerations
14+
- $M(q) \in \mathbb{R}^{n \times n}$ — mass (inertia) matrix, symmetric positive definite
15+
- $C(q, \dot{q})\dot{q} \in \mathbb{R}^n$ — Coriolis and centrifugal terms
16+
- $g(q) \in \mathbb{R}^n$ — gravitational terms
17+
- $\tau \in \mathbb{R}^n$ — generalized forces/torques (inputs)
18+
19+
This formulation supports two fundamental computations:
20+
- **Forward dynamics**: given torques $\tau$, compute accelerations $\ddot{q} = M^{-1}(\tau - C\dot{q} - g)$
21+
- **Inverse dynamics**: given desired accelerations $\ddot{q}$, compute required torques $\tau = M\ddot{q} + C\dot{q} + g$
22+
23+
## Mathematical Theory
24+
25+
### Prerequisites
26+
27+
The **Lagrangian** of a system is defined as:
28+
29+
$$\mathcal{L}(q, \dot{q}) = T(q, \dot{q}) - V(q)$$
30+
31+
where $T$ is kinetic energy and $V$ is potential energy.
32+
33+
### Core Definitions
34+
35+
The **Euler-Lagrange equation** for coordinate $q_i$ is:
36+
37+
$$\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$$
38+
39+
For a rigid-body system, kinetic energy takes the form:
40+
41+
$$T = \frac{1}{2}\dot{q}^T M(q) \dot{q}$$
42+
43+
Applying the Euler-Lagrange equation to this quadratic form yields the standard manipulator equation:
44+
45+
$$M(q)\ddot{q} + C(q, \dot{q})\dot{q} + g(q) = \tau$$
46+
47+
### Mass Matrix $M(q)$
48+
49+
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:
50+
- The forward dynamics linear system $M\ddot{q} = f$ always has a unique solution
51+
- Physical kinetic energy is always non-negative
52+
53+
### Coriolis Matrix $C(q, \dot{q})$
54+
55+
The Coriolis matrix captures velocity-dependent forces using **Christoffel symbols of the first kind**:
56+
57+
$$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$$
58+
59+
A key property: $\dot{M} - 2C$ is skew-symmetric, which is important for passivity-based control.
60+
61+
### Gravity Vector $g(q)$
62+
63+
$$g_i(q) = \frac{\partial V}{\partial q_i}$$
64+
65+
where $V(q)$ is the total potential energy of the system.
66+
67+
## Complexity Analysis
68+
69+
| Operation | Time | Space | Notes |
70+
|------------------|-----------------|----------|------------------------------------------------------|
71+
| Forward dynamics | $O(n^3)$ | $O(n^2)$ | Dominated by $M^{-1}$ solve via Gaussian elimination |
72+
| Inverse dynamics | $O(n^2)$ | $O(n^2)$ | Matrix-vector multiplication $M \ddot{q}$ |
73+
| Model evaluation | Model-dependent | $O(n^2)$ | Computing $M(q)$, $C(q,\dot{q})$, $g(q)$ |
74+
75+
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.
76+
77+
## Step-by-Step Walkthrough
78+
79+
### Example: Simple Pendulum (1-DOF)
80+
81+
A point mass $m$ on a rigid rod of length $l$:
82+
83+
**System parameters:** $m = 1\,\text{kg}$, $l = 1\,\text{m}$, $g_0 = 9.81\,\text{m/s}^2$
84+
85+
**Model matrices:**
86+
- $M(q) = ml^2 = 1.0$
87+
- $C(q, \dot{q})\dot{q} = 0$ (single DOF → no Coriolis)
88+
- $g(q) = mgl\sin(q) = 9.81\sin(q)$
89+
90+
**Forward dynamics** at $q = 0.5\,\text{rad}$, $\dot{q} = 0$, $\tau = 0$:
91+
92+
$$\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$$
93+
94+
**Inverse dynamics** for holding position ($\ddot{q} = 0$):
95+
96+
$$\tau = M\ddot{q} + C\dot{q} + g = 0 + 0 + 9.81\sin(0.5) = 4.703\,\text{N·m}$$
97+
98+
### Example: Two-Link Planar Arm (2-DOF)
99+
100+
For a 2-DOF arm with equal links ($m_1 = m_2 = 1\,\text{kg}$, $l_1 = l_2 = 1\,\text{m}$):
101+
102+
**At rest** ($q = [0, 0]^T$, $\dot{q} = [0, 0]^T$):
103+
- $\sin(q_1) = 0$, $\sin(q_1 + q_2) = 0$
104+
- $g = [0, 0]^T$ → gravity terms vanish when links hang vertically
105+
- Forward dynamics with $\tau = 0$ produces $\ddot{q} = [0, 0]^T$ (equilibrium)
106+
107+
## Pitfalls & Edge Cases
108+
109+
- **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.
110+
- **Fixed-point arithmetic**: Dynamics values (torques, accelerations) typically exceed the $[-1, 1)$ range of Q15/Q31 formats. Use `float` unless inputs are carefully scaled.
111+
- **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.
112+
- **Energy consistency**: For simulation, ensure the model matrices satisfy the skew-symmetry property; otherwise, energy may not be conserved in numerical integration.
113+
- **Units**: Be explicit about whether angles are in radians (standard) and torques in N·m.
114+
115+
## Variants & Generalizations
116+
117+
| Variant | Trade-off | Use Case |
118+
|--------------------------------------|------------------------------------------|------------------------------------------------------|
119+
| **Euler-Lagrange** (this) | $O(n^3)$ forward, closed-form, intuitive | Small systems ($n \leq 6$), control design, analysis |
120+
| **Newton-Euler** | Body-by-body force balance | Single rigid bodies, intuitive for simple systems |
121+
| **Recursive Newton-Euler (RNEA)** | $O(n)$ inverse dynamics | Large kinematic chains, real-time control |
122+
| **Articulated Body Algorithm (ABA)** | $O(n)$ forward dynamics | Large chains, simulation |
123+
| **Hamiltonian formulation** | Phase-space, symplectic integration | Long-horizon simulation, energy preservation |
124+
125+
## Applications
126+
127+
- **Robot control**: Computed torque control, gravity compensation, impedance control
128+
- **Simulation**: Forward dynamics integration for physics simulation
129+
- **System identification**: Estimate dynamic parameters from measured motion
130+
- **Trajectory optimization**: Inverse dynamics as constraints in optimization
131+
- **Vibration analysis**: Linearized dynamics around equilibrium points
132+
133+
## Connections to Other Algorithms
134+
135+
- **Gaussian Elimination** ([GaussianElimination.md](../solvers/GaussianElimination.md)): Used internally to solve $M\ddot{q} = f$ in forward dynamics
136+
- **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
137+
- **Kalman Filter** (../filters/active/): State estimation for partially observed dynamical systems derived from Euler-Lagrange models
138+
- **DARE** ([DiscreteAlgebraicRiccatiEquation.md](../solvers/DiscreteAlgebraicRiccatiEquation.md)): Discretized Euler-Lagrange systems feed into DARE for optimal control gain computation
139+
140+
## References & Further Reading
141+
142+
- Siciliano, B., Sciavicco, L., Villani, L., & Oriolo, G. (2009). *Robotics: Modelling, Planning and Control*. Springer. Chapters 7–8.
143+
- Spong, M. W., Hutchinson, S., & Vidyasagar, M. (2020). *Robot Modeling and Control* (2nd ed.). Wiley. Chapter 6.
144+
- Murray, R. M., Li, Z., & Sastry, S. S. (1994). *A Mathematical Introduction to Robotic Manipulation*. CRC Press.
145+
- Featherstone, R. (2008). *Rigid Body Dynamics Algorithms*. Springer. (For RNEA and ABA extensions.)

0 commit comments

Comments
 (0)