Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

iLQR example

iLQR example

This notebook solves a nonlinear optimal control problem using a factor-graph formulation in GTSAM. The objective is to minimize a quadratic cost over a nonlinear dynamical system using a structure similar to iterative Linear Quadratic Regulation (iLQR). The results are compared against results from classical implementation of iLQR recursions.

Author(s): Zhouyu Zhang

Open In Colab

GTSAM Copyright 2010-2025, Georgia Tech Research Corporation, Atlanta, Georgia 30332-0415 All Rights Reserved

Authors: Frank Dellaert, et al. (see THANKS for the full author list)

See LICENSE for the license information

   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 27.2/27.2 MB 18.5 MB/s eta 0:00:00

iLQR Problem Setup and Algorithm Overview

Problem Statement

We are solving an optimal control problem for a nonlinear system with the following discrete-time dynamics:

xt+1=f(xt,ut)x_{t+1} = f(x_t, u_t)

where the system evolves according to:

f(xt,ut)=[post+1velt+1]=[post+veltΔtvelt+(ut0.1velt2)Δt]f(x_t, u_t) = \begin{bmatrix} \text{pos}_{t+1} \\ \text{vel}_{t+1} \end{bmatrix} = \begin{bmatrix} \text{pos}_t + \text{vel}_t \cdot \Delta t \\ \text{vel}_t + (u_t - 0.1 \cdot \text{vel}_t^2) \cdot \Delta t \end{bmatrix}

We aim to drive the system from an initial state:

x0=[0.01.0]x_0 = \begin{bmatrix} 0.0 \\ 1.0 \end{bmatrix}

to a goal state:

xgoal=[10.00.0]x_{\text{goal}} = \begin{bmatrix} 10.0 \\ 0.0 \end{bmatrix}

over a finite time horizon N=30N = 30, by choosing a sequence of control inputs {u0,u1,,uN1} \{u_0, u_1, \dots, u_{N-1}\} that minimize the cost function:

J=t=0N1(12(xtxgoal)TQ(xtxgoal)+12utTRut)+12(xNxgoal)TQf(xNxgoal)J = \sum_{t=0}^{N-1} \left( \frac{1}{2}(x_t - x_{\text{goal}})^T Q (x_t - x_{\text{goal}}) + \frac{1}{2} u_t^T R u_t \right) + \frac{1}{2}(x_N - x_{\text{goal}})^T Q_f (x_N - x_{\text{goal}})

where the cost matrices are:

  • Q=diag(1.0,0.1)Q = \text{diag}(1.0, 0.1): running state cost (position and velocity)

  • R=0.01R = 0.01: running control cost

  • Qf=diag(10.0,1.0)Q_f = \text{diag}(10.0, 1.0): final state cost


What is iLQR?

Iterative Linear Quadratic Regulator (iLQR) is an algorithm for solving nonlinear optimal control problems. It generalizes the classic LQR by iteratively approximating the nonlinear system and cost function with local linear and quadratic models.

At each iteration, iLQR linearizes the dynamics around the current trajectory, solves the LQR problem to obtain updated control policies, and rolls out a new trajectory.


iLQR Algorithm Steps

  1. Initialization:

    • Start with an initial guess for the control sequence {u0(0),,uN1(0)} \{u_0^{(0)}, \dots, u_{N-1}^{(0)} \}

    • Roll out the trajectory {x0,x1,,xN} \{x_0, x_1, \dots, x_N \} using the nonlinear dynamics

  2. Backward Pass:

    • Linearize the dynamics around the nominal trajectory:

      δxt+1Atδxt+Btδut\delta x_{t+1} \approx A_t \delta x_t + B_t \delta u_t
    • Quadratically approximate the cost-to-go using second-order Taylor expansion

    • Solve a Riccati-like recursion to compute:

      • Feedback gain KtK_t

      • Feedforward term ktk_t

  3. Forward Pass:

    • Generate a new trajectory by applying:

      utnew=ut+αkt+Kt(xtnewxt)u_t^{\text{new}} = u_t + \alpha k_t + K_t(x_t^{\text{new}} - x_t)
    • Use line search over α\alpha to ensure cost decreases

  4. Repeat:

    • Until convergence criteria are met (e.g., change in cost or trajectory below a threshold)


Properties of iLQR

  • Produces a time-varying control policy of the form ut=kt+Ktxt u_t = k_t + K_t x_t

  • Solves large-horizon problems efficiently (backward pass is linear in time)

  • Can handle nonlinear dynamics and nonzero initial conditions


Limitations

  • Local method: can converge to local minima

  • Requires differentiable dynamics and cost

  • Sensitive to initialization and constraint handling


Comparison to GTSAM-Based Optimization

In this notebook, we also construct a factor graph representation of the same problem using GTSAM. Each cost term and dynamic constraint is encoded as a nonlinear factor, and the optimization is solved using Gauss-Newton or Levenberg-Marquardt methods. We compare the results (trajectory, control, and total cost) between iLQR and GTSAM to validate correctness and analyze the effect of constraint regularization.

GTSAM-Based Trajectory Optimization with Custom Factors

Overview

In addition to solving the optimal control problem via iLQR, we implemented the same trajectory optimization problem using the GTSAM (Georgia Tech Smoothing and Mapping) library. GTSAM is a factor graph optimization framework that is particularly powerful for structure-exploiting nonlinear problems. While originally developed for SLAM and robotics problems, it is highly suitable for optimal control when the problem can be expressed in factor graph form.

In our case, we modeled the trajectory optimization as a nonlinear least-squares problem over a factor graph, with each factor corresponding to:

  • Dynamics constraints between consecutive states and controls

  • Quadratic running cost on state and control deviation

  • Terminal state cost

  • Prior on the initial state


Factor Graph Structure

The variables in our optimization problem are:

  • x0,x1,,xNx_0, x_1, \dots, x_N (state trajectory)

  • u0,u1,,uN1u_0, u_1, \dots, u_{N-1} (control inputs)

The factor graph includes:

  1. Initial Prior
    A tight prior on x0x_0 using PriorFactorVector to fix the initial state:

    Factor:x0xinit2\text{Factor:} \quad \|x_0 - x_{\text{init}}\|^2
  2. Dynamics Constraints
    Modeled with a custom factor that enforces the nonlinear dynamics:

    Factor:f(xt,ut)xt+12\text{Factor:} \quad \|f(x_t, u_t) - x_{t+1}\|^2
  3. Running State Cost
    Penalizes deviation from the goal at each time step:

    Factor:(xtxgoal)Q2\text{Factor:} \quad \|(x_t - x_{\text{goal}})\|_Q^2
  4. Running Control Cost
    Penalizes control magnitude:

    Factor:utR2\text{Factor:} \quad \|u_t\|_R^2
  5. Terminal Cost
    A custom factor added to the final state xNx_N:

    Factor:(xNxgoal)Qf2\text{Factor:} \quad \|(x_N - x_{\text{goal}})\|_{Q_f}^2

All of these are implemented as gtsam.CustomFactor objects with manually specified residuals and Jacobians, making this approach highly flexible and comparable to symbolic optimal control pipelines.


Notes on Implementation

  • Dynamics Residual: The residual encodes f(xt,ut)xt+1f(x_t, u_t) - x_{t+1}, matching iLQR’s forward rollout. We implemented analytic Jacobians for both state and control for efficient optimization.

  • Cost Residuals: Quadratic costs are represented as residuals of the form xxrefx - x_{\text{ref}} and uurefu - u_{\text{ref}}, and the information matrices used in each CustomFactor encode the weighting (i.e., QQ, RR, QfQ_f).

  • Noise Models:
    We carefully matched the cost matrices from iLQR by passing the information matrix (inverse covariance) to GTSAM’s Gaussian.Information(...).

  • Relaxed Dynamics:
    We discovered that overly tight noise models on the dynamics (e.g., σ=1e6\sigma=1e^{-6}) can cause GTSAM to overfit the dynamics and fail to explore alternative control paths, leading to local minima or convergence failures. Relaxing this to σ=1e2\sigma=1e^{-2} allowed the optimizer more flexibility, enabling convergence to a better solution closer to the iLQR result.


Comparison with iLQR

We ran both the GTSAM and iLQR solvers on the same task and compared:

  • Final trajectory and control sequence

  • Cost function values

  • Convergence speed and behavior

When dynamics constraints were relaxed appropriately, the GTSAM trajectory matched the iLQR solution almost exactly. This demonstrates that GTSAM can replicate iLQR results while offering the benefit of symbolic graph-based optimization, extensibility to constraints, and smoother integration with SLAM or mapping pipelines.


Takeaways

  • GTSAM with CustomFactor provides a highly modular and extensible framework for nonlinear trajectory optimization.

  • Proper balancing of dynamics tightness is crucial to avoid poor local minima.

  • With correct Jacobians and cost encoding, GTSAM can match classical optimal control solutions like iLQR while allowing more complex problem structure to be encoded directly.

This implementation serves as a bridge between classical control algorithms and modern factor graph optimization tools.

GTSAM optimization completed successfully!
Final state: [ 1.00032476e+01 -8.94305312e-03]
Goal state: [10.  0.]
Final error: 0.009514

iLQR optimization completed!
Final state: [ 1.00032671e+01 -8.98543275e-03]
Goal state: [10.  0.]
Final error: 0.009561

Trajectory comparison:
Max state difference: 0.025441
Max control difference: 0.148897
<Figure size 1500x1000 with 6 Axes>

Total cost comparison:
  GTSAM Cost: 314.7621
  iLQR  Cost: 315.5805