iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🚃

Can AI Agents Control an Inverted Pendulum on a Cart?

に公開

Introduction

Who is this article for?

  • People interested in the performance of LLMs and AI agents
  • People interested in web app development using generative AI
  • People interested in control engineering
Deployment Environment
Mini PC (M30A): N100 (4 cores) @ 3.40GHz, 16GB, Ubuntu Server 24.04 LTS

Overview

  • Developed a web app that performs control simulations of a cart-pole inverted pendulum.
  • Developed using Cursor + o3-mini + Claude 3.5 Sonnet.
  • Verified whether the system can be stabilized by having Cursor + Claude 3.5 Sonnet design the control gains.

The Web App Created

First, here is the web app I created this time.

https://inverted-pendulum.robustonian.com

A game where you determine four control gains to aim for stabilization of a cart-pole inverted pendulum.
It turns out that not only people familiar with control engineering but also LLMs and AI agents can achieve gain design in the linear region if their performance is high enough.

https://x.com/gosrum/status/1893830860727623696

What this means is that it can also be used to evaluate the performance of LLMs and AI agents.

The difficulty level is on a completely different level between control in the linear region and the non-linear region, but for now, since this application only covers linear feedback input, we will verify whether stabilization in the linear region can be achieved. I would like to expand it to support non-linear control in the future.

Article Structure

In this article, I will explain the following topics in order. Since each section covers quite different fields, please feel free to jump to any section you are interested in.

  • Web app configuration and development flow

  • Dynamics and control system design of the cart-pole inverted pendulum

  • Prompts for performance evaluation of LLMs and AI agents

Web App Configuration and Development Flow

Basic Game Rules

Configuration Items

App Architecture and Development Flow

App Architecture

The following diagram illustrates the app's architecture.

Technical Stack

Development Flow

Initially, when I developed using only Claude 3.5 Sonnet in Cursor composer (agent mode), I encountered an issue where the dynamics were not consistent at all.

However, the development went smoothly when I followed the flow shown below.

While I had the impression that Claude 3.5 Sonnet is unrivaled in web app development, I gained the firsthand insight that it is better to use a reasoning model like o3-mini when handling mathematical derivations.

By the way, I used o3-mini in Chat mode rather than Composer (agent) mode.

I believe the same results could be achieved without using Cursor by combining o3-mini from the ChatGPT app with Cline + Claude 3.5 Sonnet.

Dynamics of the Cart-Pole Inverted Pendulum

Below is an example of formulating the cart-pole system where counter-clockwise is positive (specifically, \theta represents the counter-clockwise rotation from the vertically upward position as positive). Here, we derive the non-linear equations of motion using the Lagrangian method.


1. Definition of Coordinates

  • Horizontal position of the cart: x
  • Pendulum length: \ell
  • Pendulum mass: m
  • Cart mass: M
  • Gravitational acceleration: g
  • Angle: \theta
    • When \theta = 0, the pendulum is "vertically upward" (unstable equilibrium).
    • Positive \theta is counter-clockwise (meaning rotation to the left from the vertical position).

In this setup, the coordinates of the pendulum's center of mass are defined as:

\begin{aligned} x_p &= x - \ell\sin\theta, \\ y_p &= \ell\cos\theta, \end{aligned}

2. Kinetic and Potential Energy

(1) Kinetic Energy T

Kinetic Energy of the Cart

T_{\text{cart}} = \frac{1}{2}M\dot{x}^2.

Kinetic Energy of the Pendulum

The coordinates of the center of mass of the pendulum are:

x_p = x - \ell\sin\theta,\quad y_p = \ell\cos\theta.

Their time derivatives are:

\dot{x}_p = \dot{x} - \ell\,\dot{\theta}\cos\theta,\quad \dot{y}_p = -\ell\,\dot{\theta}\sin\theta.

Therefore, the kinetic energy of the pendulum is:

\begin{aligned} T_{\text{pendulum}} &= \frac{1}{2}m\Bigl[(\dot{x}_p)^2+(\dot{y}_p)^2\Bigr] \\ &=\frac{1}{2}m\Bigl[(\dot{x}-\ell\cos\theta\,\dot{\theta})^2+(\ell\sin\theta\,\dot{\theta})^2\Bigr] \\ &=\frac{1}{2}m\left[\dot{x}^2-2\ell\cos\theta\,\dot{x}\dot{\theta}+\ell^2\dot{\theta}^2\ (\cos^2\theta+\sin^2\theta)\right] \\ &=\frac{1}{2}m\left[\dot{x}^2-2\ell\cos\theta\,\dot{x}\dot{\theta}+\ell^2\dot{\theta}^2\right]. \end{aligned}

Total Kinetic Energy

T = T_{\text{cart}} + T_{\text{pendulum}} = \frac{1}{2}(M+m)\dot{x}^2 - m\ell\cos\theta\,\dot{x}\dot{\theta} + \frac{1}{2}m\ell^2\dot{\theta}^2.

(2) Potential Energy V

Since the cart only moves horizontally, its potential energy does not need to be considered. Therefore, we only consider the center of mass of the pendulum. Since the vertical coordinate of the center of mass is $ y_p = \ell\cos\theta $, it can be written as:

V = mgy_p = mg\ell\cos\theta.
  • Note: Normally, potential energy is often defined relative to a "low position," but here, since the constant term does not affect the dynamics of the system, we handle it in this form for convenience.

3. Lagrangian Formulation

The Lagrangian is

L = T - V,

so,

L = \frac{1}{2}(M+m)\dot{x}^2 - m\ell\cos\theta\,\dot{x}\dot{\theta} + \frac{1}{2}m\ell^2\dot{\theta}^2 - mg\ell\cos\theta.

4. Deriving Equations of Motion from Euler–Lagrange Equations

Assume that F (horizontal force) acts on the cart as an external force. For generalized coordinates q, it can be written as:

\frac{d}{dt}\frac{\partial L}{\partial \dot{q}}-\frac{\partial L}{\partial q}=Q,

where Q is the external force corresponding to q (for x, it is F; for \theta, assume no external torque acts).

(1) Differential Equation for x

First,

\frac{\partial L}{\partial \dot{x}} = (M+m)\dot{x} - m\ell\cos\theta\,\dot{\theta}.

Its time derivative is

\frac{d}{dt}\frac{\partial L}{\partial \dot{x}} = (M+m)\ddot{x} + m\ell\sin\theta\,\dot{\theta}^2 - m\ell\cos\theta\,\ddot{\theta}.

On the other hand, since there is no explicit dependence on x,

\frac{\partial L}{\partial x}=0.

Thus, considering the external force F,

(M+m)\ddot{x} + m\ell\sin\theta\,\dot{\theta}^2 - m\ell\cos\theta\,\ddot{\theta}=F.

(2) Equation for \theta

First,

\frac{\partial L}{\partial \dot{\theta}} = -m\ell\cos\theta\,\dot{x} + m\ell^2\dot{\theta}.

Its time derivative is

\frac{d}{dt}\frac{\partial L}{\partial \dot{\theta}} = m\ell\sin\theta\,\dot{x}\,\dot{\theta} - m\ell\cos\theta\,\ddot{x} + m\ell^2\ddot{\theta}.

Next, the partial derivative with respect to \theta is:

  • For the term -m\ell\cos\theta\,\dot{x}\dot{\theta}: \displaystyle\frac{\partial}{\partial \theta}(-m\ell\cos\theta\,\dot{x}\dot{\theta}) = m\ell\sin\theta\,\dot{x}\dot{\theta}
  • For the potential energy term -mg\ell\cos\theta: \displaystyle\frac{\partial}{\partial \theta}(-mg\ell\cos\theta) = mg\ell\sin\theta

So,

\frac{\partial L}{\partial \theta} = m\ell\sin\theta\,\dot{x}\dot{\theta} + mg\ell\sin\theta.

Therefore, from the Euler–Lagrange equation,

\begin{aligned} \frac{d}{dt}\frac{\partial L}{\partial \dot{\theta}} - \frac{\partial L}{\partial \theta} &= \Bigl[m\ell\sin\theta\,\dot{x}\,\dot{\theta} - m\ell\cos\theta\,\ddot{x} + m\ell^2\ddot{\theta}\Bigr] - \Bigl[m\ell\sin\theta\,\dot{x}\dot{\theta} + mg\ell\sin\theta\Bigr] \\ &= - m\ell\cos\theta\,\ddot{x} + m\ell^2\ddot{\theta} - mg\ell\sin\theta \\ &= 0. \end{aligned}

Dividing both sides by m\ell:

-\cos\theta\,\ddot{x} + \ell\ddot{\theta} - g\sin\theta = 0.

Rearranging yields:

\ell\ddot{\theta} - \cos\theta\,\ddot{x} - g\sin\theta = 0.

5. Final Equations of Motion

Based on the results above, the equations of motion for the cart-pole inverted pendulum when counter-clockwise is positive are:

\boxed{ \begin{aligned} (M+m)\ddot{x} + m\ell\sin\theta\,\dot{\theta}^2 - m\ell\cos\theta\,\ddot{\theta} &= F,\\ \ell\ddot{\theta} - \cos\theta\,\ddot{x} - g\sin\theta &= 0. \end{aligned} }

Dynamics Formulation Summary

  1. Coordinate Setup:
    The center of mass of the pendulum is defined as:
x_p = x - \ell\sin\theta,\quad y_p = \ell\cos\theta

with \theta=0 as unstable equilibrium (vertically upward).

  1. Energy Calculation:
    We determined the kinetic energy for both the cart and the pendulum, as well as the potential energy of the pendulum, and constructed the Lagrangian $ L = T - V $.

  2. Application of Euler–Lagrange Formulas:
    We derived equations of motion for each generalized coordinate $ x $ and \theta, and introduced the external force $ F $ into the $ x $ equation.

As a result, the equations of motion for the cart-pole system formulated with counter-clockwise as positive are obtained as shown above.

Further Simplification

By first solving for \ddot{\theta} from the second equation and substituting it into the first equation, we can explicitly determine \ddot{x} and \ddot{\theta} as follows.


Step 1: Solving for \ddot{\theta} from the second equation

The given second equation is:

\ell\,\ddot{\theta}-\cos\theta\,\ddot{x}-g\sin\theta=0.

Solving this for \ddot{\theta} gives:

\ddot{\theta}=\frac{\cos\theta\,\ddot{x}+g\sin\theta}{\ell}\,.

Step 2: Substituting the above expression into the first equation

The first equation is:

(M+m)\ddot{x}+m\ell\sin\theta\,\dot{\theta}^2-m\ell\cos\theta\,\ddot{\theta}=F\,.

Substituting the expression for \ddot{\theta} derived above:

(M+m)\ddot{x}+m\ell\sin\theta\,\dot{\theta}^2 - m\ell\cos\theta\left(\frac{\cos\theta\,\ddot{x}+g\sin\theta}{\ell}\right)=F\,.

First, the \ell terms cancel out:

(M+m)\ddot{x}+m\ell\sin\theta\,\dot{\theta}^2 - m\cos\theta\Bigl(\cos\theta\,\ddot{x}+g\sin\theta\Bigr)=F\,.

Expanding the terms:

(M+m)\ddot{x} - m\cos^2\theta\,\ddot{x} + m\ell\sin\theta\,\dot{\theta}^2 - m g\sin\theta\cos\theta = F\,.

Grouping the \ddot{x} terms:

\Bigl[(M+m)-m\cos^2\theta\Bigr]\ddot{x} + m\ell\sin\theta\,\dot{\theta}^2 - m g\sin\theta\cos\theta = F\,.

Therefore:

\ddot{x} = \frac{F + m g\sin\theta\cos\theta - m\ell\sin\theta\,\dot{\theta}^2}{(M+m)-m\cos^2\theta}\,.

Furthermore, since 1-\cos^2\theta=\sin^2\theta:

(M+m)-m\cos^2\theta=M+m(1-\cos^2\theta)=M+m\sin^2\theta\,.

Thus, finally:

\boxed{ \ddot{x}=\frac{F + m g\sin\theta\cos\theta - m\ell\sin\theta\,\dot{\theta}^2}{M+m\sin^2\theta}\,. }

Step 3: Simplifying the expression for \ddot{\theta} as well

By substituting the expression for \ddot{x} obtained above into:

\ddot{\theta}=\frac{\cos\theta\,\ddot{x}+g\sin\theta}{\ell}

We get:

\ddot{\theta}=\frac{1}{\ell}\left(\cos\theta\,\frac{F + m g\sin\theta\cos\theta - m\ell\sin\theta\,\dot{\theta}^2}{M+m\sin^2\theta}+g\sin\theta\right)\,.

To find a common denominator, we multiply g\sin\theta by M+m\sin^2\theta:

\ddot{\theta}=\frac{F\cos\theta + m g\,\sin\theta\cos^2\theta - m\ell\sin\theta\cos\theta\,\dot{\theta}^2 + g\sin\theta(M+m\sin^2\theta)}{\ell\,(M+m\sin^2\theta)}\,.

Considering the terms m g\,\sin\theta\cos^2\theta + g\sin\theta(M+m\sin^2\theta):

m g\,\sin\theta\cos^2\theta+g\sin\theta(M+m\sin^2\theta)=g\sin\theta\Bigl[M+m(\cos^2\theta+\sin^2\theta)\Bigr] =g\sin\theta(M+m)\,.

Thus, the simplified \ddot{\theta} is:

\boxed{ \ddot{\theta}=\frac{F\cos\theta - m\ell\sin\theta\cos\theta\,\dot{\theta}^2 + g\sin\theta(M+m)}{\ell\,(M+m\sin^2\theta)}\,. }

Final Simplified Results

In summary, the simultaneous differential equations are simplified as follows:

\boxed{ \begin{aligned} \ddot{x} &= \frac{F + m g\sin\theta\cos\theta - m\ell\sin\theta\,\dot{\theta}^2}{M+m\sin^2\theta},\\ \ddot{\theta} &= \frac{F\cos\theta - m\ell\sin\theta\cos\theta\,\dot{\theta}^2 + g\sin\theta(M+m)}{\ell\,(M+m\sin^2\theta)}\,. \end{aligned} }

Now, the original simultaneous differential equations have been solved explicitly for \ddot{x} and \ddot{\theta}.

Linearization, State-Space Representation, and Control System Design

The following is an example of describing the system in a state-space representation after linearizing the non-linear dynamics using small-angle approximation (\sin\theta\approx\theta, \cos\theta\approx1). The state variables are defined as follows:

X = \begin{pmatrix} x \\ v \\ \theta \\ \omega \end{pmatrix} \quad \text{(where } v = \dot{x},\ \omega = \dot{\theta} \text{)}

Control System Design

1. Linearization Procedure

The original system is:

\begin{aligned} &(M+m)\ddot{x} + m\ell\sin\theta\,\dot{\theta}^2 - m\ell\cos\theta\,\ddot{\theta} = F,\\ &\ell\ddot{\theta} - \cos\theta\,\ddot{x} - g\sin\theta = 0, \end{aligned}

but through small-angle approximation, it can be approximated as follows:

  1. Applying Small-Angle Approximation:
    Assuming \sin\theta\approx\theta and \cos\theta\approx 1:
  • Equation 1:
(M+m)\ddot{x} - m\ell\,\ddot{\theta} = F.
  • Equation 2:
\ell\,\ddot{\theta} - \ddot{x} - g\,\theta = 0,

meaning

\ddot{\theta} = \frac{\ddot{x}+g\,\theta}{\ell}\,.
  1. Deriving the Equation for \ddot{x}:
    Substituting \ddot{\theta} from Equation 2 into Equation 1:
(M+m)\ddot{x} - m\ell \left(rac{\ddot{x}+g\,\theta}{\ell}\right) = F,
(M+m)\ddot{x} - m\ddot{x} - m\,g\,\theta = F,
M\,\ddot{x} - m\,g\,\theta = F.

Therefore,

\ddot{x} = \frac{F}{M} + \frac{m\,g}{M}\theta.
  1. Deriving the Equation for \ddot{\theta}:
    From the result above and Equation 2:
\ddot{\theta} = \frac{1}{\ell}\Bigl(\ddot{x}+g\,\theta\Bigr) = \frac{1}{\ell}\left(\frac{F}{M} + \frac{m\,g}{M}\theta + g\,\theta\right) = \frac{F}{\ell\,M} + \frac{(M+m)g}{\ell\,M}\theta.

2. State-Space Representation

Based on the results above, the time evolution of each component of the state variables can be written as follows:

\begin{cases} \dot{x} = v,\\ \dot{v} = \dfrac{F}{M} + \dfrac{m\,g}{M}\,\theta,\\ \dot{\theta} = \omega,\\ \dot{\omega} = \dfrac{F}{\ell\,M} + \dfrac{(M+m)g}{\ell\,M}\,\theta. \end{cases}

This can be rewritten in the form:

\dot{X} = A\,X + B\,F,

where the state matrix A and the input matrix B are as follows:


3. Concrete Expressions for Matrices A and B

  • Matrix A:
A = \begin{pmatrix} 0 & 1 & 0 & 0 \\ 0 & 0 & \dfrac{m\,g}{M} & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & \dfrac{(M+m)g}{\ell\,M} & 0 \end{pmatrix}\,.
  • Input Matrix B:
B = \begin{pmatrix} 0 \\ \dfrac{1}{M} \\ 0 \\ \dfrac{1}{\ell\,M} \end{pmatrix}\,.

These matrices serve as the foundation for designing the closed-loop system:

\dot{X} = (A - BK)X

through state feedback control:

F = -K\,X = -\bigl[k_x x + k_v v + k_\theta \theta + k_\omega \omega\bigr]

Control System Design Summary

The linearized state-space representation is:

\dot{X} = \underbrace{\begin{pmatrix} 0 & 1 & 0 & 0 \\ 0 & 0 & \dfrac{m\,g}{M} & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & \dfrac{(M+m)g}{\ell\,M} & 0 \end{pmatrix}}_{A}\,X + \underbrace{\begin{pmatrix} 0 \\ \dfrac{1}{M} \\ 0 \\ \dfrac{1}{\ell\,M} \end{pmatrix}}_{B} F\,.

Based on these matrices A and B, it is possible to stabilize the system by designing state feedback gains K = [k_x \; k_v \; k_\theta \; k_\omega] using methods such as pole placement or LQR.

Performance Evaluation Prompt for AI Agents

By using the linearization, pole placement, and optimal control logic mentioned above, it is possible to design feedback gains that achieve stabilization in the linear region.

Here, I conducted an experiment to see if the system could actually be stabilized by having an AI agent execute the process of finding the optimal gains when given the non-linear dynamics and a goal.

Prompt

Below are the dynamics of a cart-pole inverted pendulum.

## Dynamics

$$
\boxed{
\begin{aligned}
\ddot{x} &= \frac{F + m g\sin\theta\cos\theta - m\ell\sin\theta\,\dot{\theta}^2}{M+m\sin^2\theta}\,,\\[1mm]
\ddot{\theta} &= \frac{F\cos\theta - m\ell\sin\theta\cos\theta\,\dot{\theta}^2 + g\sin\theta(M+m)}{\ell\,(M+m\sin^2\theta)}\,.
\end{aligned}
}
$$

For these dynamics, we aim for stabilization with the following feedback input.
The goal here is stabilization at the origin (x=v=θ=ω=0).

## Feedback Input

$$
F =-k_xx-k_vv-k_\theta-k_\omega\omega
$$

Here, $v = \dot{x}$ and $\omega=\dot{\theta}$.

## Goal

Find the gains $k_x,k_v,k_\theta,k_\omega$ to converge all four states to 0.

## Notes

- Basic parameters are as follows:

$$
M=1,m=0.5,l=2, g=9.81
$$

- Initial state: $x=0,v=0,\omega=0$
- The larger the initial angle, the higher the score (180 degrees for a perfect score).
- As an important constraint, the range of motion for x is [-4.75, 4.75]. Exceeding this results in a game over.

Cursor+Claude 3.5 Sonnet Output

Output

I understand the request. Let's design appropriate feedback gains for the cart-pole inverted pendulum control problem.

<Task Analysis>
Main Tasks:

  1. Linearization of the non-linear system
  2. Design of state feedback gains for the linearized system
  3. Verification through simulation
  4. Confirmation of constraints

Important Requirements and Constraints:

  • System parameters: M=1, m=0.5, l=2, g=9.81
  • Initial conditions: x=0, v=0, θ=5deg, ω=0
  • State constraints: |x| ≤ 4.75
  • Goal: Converge all states to 0

Potential Challenges:

  1. Accuracy of the linearization of the non-linear system
  2. Gain design that satisfies constraint conditions
  3. Control of transient response

Execution Steps:

  1. System linearization
  2. Derivation of state-space representation
  3. Control system design
  4. Implementation of simulation code
  5. Verification and adjustment of results
    </Task Analysis>

First, let's proceed with the implementation of the system. We will perform the simulation using Python.

cart_pole_control.py
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

# System parameters
M = 1.0    # Cart mass
m = 0.5    # Pendulum mass
l = 2.0    # Pendulum length
g = 9.81   # Gravity acceleration

# Control gains (to be tuned)
K = np.array([-100, -50, 800, 100])  # Initial guess for [kx, kv, ktheta, komega]

def dynamics(state, t):
    x, v, theta, omega = state

    # Control input (state feedback)
    F = -K[0]*x - K[1]*v - K[2]*theta - K[3]*omega

    # System dynamics
    sin_theta = np.sin(theta)
    cos_theta = np.cos(theta)

    x_ddot = (F + m*g*sin_theta*cos_theta - m*l*sin_theta*omega**2) / (M + m*sin_theta**2)
    theta_ddot = (F*cos_theta - m*l*sin_theta*cos_theta*omega**2 + g*sin_theta*(M+m)) / (l*(M + m*sin_theta**2))

    return [v, x_ddot, omega, theta_ddot]

# Initial conditions
theta_0 = np.deg2rad(5)  # 5 degrees in radians
x0 = [0, 0, theta_0, 0]  # [x, v, theta, omega]

# Time vector
t = np.linspace(0, 10, 1000)

# Solve ODE
solution = odeint(dynamics, x0, t)

# Plot results
plt.figure(figsize=(12, 8))

# Cart position
plt.subplot(2, 2, 1)
plt.plot(t, solution[:, 0])
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Cart Position [m]')
plt.title('Cart Position vs Time')

# Cart velocity
plt.subplot(2, 2, 2)
plt.plot(t, solution[:, 1])
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Cart Velocity [m/s]')
plt.title('Cart Velocity vs Time')

# Pendulum angle
plt.subplot(2, 2, 3)
plt.plot(t, np.rad2deg(solution[:, 2]))
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Angle [deg]')
plt.title('Pendulum Angle vs Time')

# Angular velocity
plt.subplot(2, 2, 4)
plt.plot(t, np.rad2deg(solution[:, 3]))
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Angular Velocity [deg/s]')
plt.title('Angular Velocity vs Time')

plt.tight_layout()
plt.show()

# Check if position constraint is violated
max_pos = np.max(np.abs(solution[:, 0]))
print(f"Maximum absolute cart position: {max_pos:.3f} m")
if max_pos > 4.75:
    print("Warning: Position constraint violated!")

Next, we will linearize the system and design appropriate gains. We will create code for analyzing the linearized system.

linear_analysis.py
import numpy as np
from scipy import linalg

# System parameters
M = 1.0    # Cart mass
m = 0.5    # Pendulum mass
l = 2.0    # Pendulum length
g = 9.81   # Gravity acceleration

# Linearized state-space matrices at the upright position
A = np.array([
    [0, 1, 0, 0],
    [0, 0, m*g/M, 0],
    [0, 0, 0, 1],
    [0, 0, g*(M+m)/(M*l), 0]
])

B = np.array([
    [0],
    [1/M],
    [0],
    [1/(M*l)]
])

# Desired pole locations
# We want relatively fast response but avoid oscillations
poles = np.array([-2, -2.1, -2.2, -2.3])

# Calculate feedback gains using pole placement
K = linalg.place_poles(A, B, poles).gain_matrix

print("Designed feedback gains:")
print(f"k_x = {K[0, 0]:.2f}")
print(f"k_v = {K[0, 1]:.2f}")
print(f"k_theta = {K[0, 2]:.2f}")
print(f"k_omega = {K[0, 3]:.2f}")

# Verify closed-loop eigenvalues
A_cl = A - B @ K
eig_vals = np.linalg.eigvals(A_cl)
print("\nClosed-loop eigenvalues:")
for i, eig in enumerate(eig_vals):
    print(f"λ_{i+1} = {eig:.3f}")

Now, let's run this system and check the results.

python linear_analysis.py

I apologize. We need to install the necessary packages.

uv init && uv add numpy scipy matplotlib

Now, let's run the linear analysis again.

uv run linear_analysis.py

I apologize. I will correct the code to use place instead of place_poles.

linear_analysis.py
import numpy as np
from scipy import linalg

# System parameters
M = 1.0    # Cart mass
m = 0.5    # Pendulum mass
l = 2.0    # Pendulum length
g = 9.81   # Gravity acceleration

# Linearized state-space matrices at the upright position
A = np.array([
    [0, 1, 0, 0],
    [0, 0, m*g/M, 0],
    [0, 0, 0, 1],
    [0, 0, g*(M+m)/(M*l), 0]
])

B = np.array([
    [0],
    [1/M],
    [0],
    [1/(M*l)]
])

# Desired pole locations
# We want relatively fast response but avoid oscillations
poles = np.array([-2, -2.1, -2.2, -2.3])

# Calculate feedback gains using pole placement
K = linalg.place(A, B, poles)

print("Designed feedback gains:")
print(f"k_x = {K[0, 0]:.2f}")
print(f"k_v = {K[0, 1]:.2f}")
print(f"k_theta = {K[0, 2]:.2f}")
print(f"k_omega = {K[0, 3]:.2f}")

# Verify closed-loop eigenvalues
A_cl = A - B @ K
eig_vals = np.linalg.eigvals(A_cl)
print("\nClosed-loop eigenvalues:")
for i, eig in enumerate(eig_vals):
    print(f"λ_{i+1} = {eig:.3f}")

Let's run it again.

uv run linear_analysis.py

I apologize. Let's design the control gains using LQR (Linear Quadratic Regulator) instead.

linear_analysis.py
import numpy as np
from scipy import linalg

# System parameters
M = 1.0    # Cart mass
m = 0.5    # Pendulum mass
l = 2.0    # Pendulum length
g = 9.81   # Gravity acceleration

# Linearized state-space matrices at the upright position
A = np.array([
    [0, 1, 0, 0],
    [0, 0, m*g/M, 0],
    [0, 0, 0, 1],
    [0, 0, g*(M+m)/(M*l), 0]
])

B = np.array([
    [0],
    [1/M],
    [0],
    [1/(M*l)]
])

# LQR weight matrices
Q = np.diag([1, 1, 10, 1])  # State cost matrix
R = np.array([[0.1]])       # Control cost

# Solve the Riccati equation
P = linalg.solve_continuous_are(A, B, Q, R)

# Calculate the optimal feedback gain
K = np.linalg.inv(R) @ B.T @ P

print("Designed feedback gains:")
print(f"k_x = {K[0, 0]:.2f}")
print(f"k_v = {K[0, 1]:.2f}")
print(f"k_theta = {K[0, 2]:.2f}")
print(f"k_omega = {K[0, 3]:.2f}")

# Verify closed-loop eigenvalues
A_cl = A - B @ K
eig_vals = np.linalg.eigvals(A_cl)
print("\nClosed-loop eigenvalues:")
for i, eig in enumerate(eig_vals):
    print(f"λ_{i+1} = {eig:.3f}")

Let's run it again.

uv run linear_analysis.py

Let's perform the non-linear simulation using the control gains obtained from LQR.

cart_pole_control.py
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

# System parameters
M = 1.0    # Cart mass
m = 0.5    # Pendulum mass
l = 2.0    # Pendulum length
g = 9.81   # Gravity acceleration

# Control gains from LQR design
K = np.array([-3.16, -7.10, 77.34, 32.47])

def dynamics(state, t):
    x, v, theta, omega = state

    # Control input (state feedback)
    F = -K[0]*x - K[1]*v - K[2]*theta - K[3]*omega

    # System dynamics
    sin_theta = np.sin(theta)
    cos_theta = np.cos(theta)

    x_ddot = (F + m*g*sin_theta*cos_theta - m*l*sin_theta*omega**2) / (M + m*sin_theta**2)
    theta_ddot = (F*cos_theta - m*l*sin_theta*cos_theta*omega**2 + g*sin_theta*(M+m)) / (l*(M + m*sin_theta**2))

    return [v, x_ddot, omega, theta_ddot]

# Initial conditions
theta_0 = np.deg2rad(5)  # 5 degrees in radians
x0 = [0, 0, theta_0, 0]  # [x, v, theta, omega]

# Time vector
t = np.linspace(0, 10, 1000)

# Solve ODE
solution = odeint(dynamics, x0, t)

# Plot results
plt.figure(figsize=(12, 8))

# Cart position
plt.subplot(2, 2, 1)
plt.plot(t, solution[:, 0])
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Cart Position [m]')
plt.title('Cart Position vs Time')
plt.axhline(y=4.75, color='r', linestyle='--', label='Position limit')
plt.axhline(y=-4.75, color='r', linestyle='--')
plt.legend()

# Cart velocity
plt.subplot(2, 2, 2)
plt.plot(t, solution[:, 1])
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Cart Velocity [m/s]')
plt.title('Cart Velocity vs Time')

# Pendulum angle
plt.subplot(2, 2, 3)
plt.plot(t, np.rad2deg(solution[:, 2]))
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Angle [deg]')
plt.title('Pendulum Angle vs Time')

# Angular velocity
plt.subplot(2, 2, 4)
plt.plot(t, np.rad2deg(solution[:, 3]))
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Angular Velocity [deg/s]')
plt.title('Angular Velocity vs Time')

plt.tight_layout()
plt.savefig('cart_pole_response.png')
plt.close()

# Check if position constraint is violated
max_pos = np.max(np.abs(solution[:, 0]))
print(f"Maximum absolute cart position: {max_pos:.3f} m")
if max_pos > 4.75:
    print("Warning: Position constraint violated!")

Now, let's run the simulation.

uv run cart_pole_control.py

Let's analyze the simulation results. Results using the control gains designed with LQR:

  1. Control Gains:

    • k_x = -3.16 (Position feedback)
    • k_v = -7.10 (Velocity feedback)
    • k_theta = 77.34 (Angle feedback)
    • k_omega = 32.47 (Angular velocity feedback)
  2. System Response:

    • Maximum absolute cart position: 0.398 m (within the limit of 4.75 m)
    • Closed-loop poles: All are in the left half-plane, and the system is stable
      • λ_1 = -4.201 (Real pole)
      • λ_2 = -2.701 (Real pole)
      • λ_3,4 = -1.118 ± 0.341j (Complex conjugate poles)
  3. Control Performance:

    • The cart position is well within the constraint range (±4.75 m)
    • Settling from an initial angle of 5 degrees is achieved
    • Due to the presence of complex poles, some oscillatory response is expected, but the damping is sufficient

This LQR controller has the following features:

  1. Uses state weight matrix Q = diag([1, 1, 10, 1]), prioritizing the control of angle θ in particular
  2. Control input weight R = 0.1, allowing for relatively large control inputs
  3. The resulting control gains emphasize the upright control of the pendulum, especially with a large angle feedback (77.34)

From the simulation results, we can judge that this control design meets the required specifications:

  • All states converge to the origin
  • Satisfies cart position constraint (±4.75 m)
  • Achieves stabilization from an initial angle of 5 degrees

I might have just been lucky since I only tried it once, but I succeeded in stabilization on the very first try! By the way, I've modified the commands for the Python virtual environment to use uv. It's just a difference in the execution environment, so the results shouldn't change even without the modification.

https://x.com/gosrum/status/1893830860727623696

By the way, the program was designed to also output a time-series graph of the simulation results.

I'd also like to try combining it with Cline or other LLMs. Furthermore, I want to save those results in a database and make them viewable from the web app. If I do that, although it is a niche area like control engineering, it could serve as a single benchmark.

I suspect that stabilization in the linear region can be achieved without much trouble in many cases, so eventually, I want to add a UI for non-linear control to increase the difficulty and evaluate the limits of LLMs and AI agents.

Supplement: Rules for AI

By the way, I have included the following in the Rules for AI.

Rules for AI
You are an AI assistant with advanced problem-solving skills. Please perform tasks efficiently and accurately according to the following instructions:

First, confirm the instructions received from the user:

<Instructions>
{{instructions}}
</Instructions>

Based on these instructions, please proceed with the work according to the following process. Note that all proposals and implementations must be made within the constraints of the stated technical stack:

1. Analysis and Planning of Instructions
<Task Analysis>
- Briefly summarize the main tasks.
- Review the listed technical stack and consider implementation methods within those constraints.
- Identify important requirements and constraints.
- List potential challenges.
- Enumerate specific steps for task execution in detail.
- Determine the optimal execution order for those steps.
- Consider potential tools or resources that may be required.

This section will guide the entire subsequent process, so take the time to conduct a sufficiently detailed and comprehensive analysis.
</Task Analysis>

2. Task Execution
- Execute the identified steps one by one.
- Report progress briefly after each step is completed.
- If problems or questions arise during execution, report them immediately and propose countermeasures.

3. Quality Control
- Rapidly verify the execution results of each task.
- If errors or inconsistencies are found, implement corrective actions immediately.
- When executing commands, always check the standard output and report the results.

4. Final Confirmation
- Once all tasks are completed, evaluate the overall deliverables.
- Confirm consistency with the original instructions and make adjustments as necessary.

Important Notes:
- If there are any uncertainties, be sure to seek clarification before starting work.
- If important decisions are required, report each time and obtain approval.
- If unexpected problems occur, report them immediately and propose countermeasures.

Please carry out the task efficiently and accurately according to this process.

Also, as an important fact, gpt-4o and gpt-4o-mini models exist within OpenAI.

This is adopted directly from what was described in Nike-chan-san's article. Apparently, it was originally released by Kinopy-san and then partially improved by Nike-chan-san.

https://note.com/nike_cha_n/n/nd0f7566019ae

To be honest, some parts are unrelated to this task, but since the stabilization was successful, it's all good.

Summary

This article ended up being quite packed, but I summarized the following:

  • About the development of the cart-pole inverted pendulum web app
  • About the dynamics and control system design in the linear region of the cart-pole inverted pendulum
  • About the prompts and output for control system design using Cursor + Claude 3.5 Sonnet

In the future, I would like to try stabilizing it with various models and explore extensions to non-linear control.

Thank you for reading until the end. I look forward to your continued support in the next one.

Bonus: A little side story

By the way, as some of you might have noticed, this app also features a manual control mode. I initially started building it with the concept that a human could clear it by stabilizing it through manual operation, but I gave up because it was too difficult 😇

After that, I added the feedback control mode, thinking that only those strong in the control field could clear it, and then I published the app and wrote this article as a challenge, thinking, "Wouldn't it be easy to clear using generative AI now?"

If you're thinking about trying something using generative AI, please give it a shot.

Discussion