Independently re-derived in Python/sympy, following the physical setup described in
springCartPole/ of
Kelly’s Lagrange_Mechanics_Derivations:
a cart of mass slides horizontally, tethered to a wall by a spring , and a pendulum of
mass and length hangs from the cart. This is the classic “cart-pole” of control theory,
with the free-sliding cart replaced by a spring-restrained one — genuinely a 2-DOF vibration
problem once linearized, tying this gallery back to the basics chapters’ MDOF machinery.
import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
from scipy.integrate import solve_ivp
from scipy.linalg import eigh
plt.rcParams["figure.figsize"] = (7, 4.0)
plt.rcParams["axes.grid"] = True
def lagrange_equations(L, qs, t, Q=None):
if Q is None:
Q = [0] * len(qs)
eqs = []
for qi, Qi in zip(qs, Q):
qid = sp.diff(qi, t)
eqs.append(sp.expand(sp.diff(sp.diff(L, qid), t) - sp.diff(L, qi) - Qi))
return eqs
def solve_for_accelerations(eqs, qs, t):
qdd = [sp.diff(qi, t, 2) for qi in qs]
M = sp.Matrix([[sp.diff(eq, a) for a in qdd] for eq in eqs])
f = sp.Matrix([eq.subs({a: 0 for a in qdd}) for eq in eqs])
sol = M.solve(-f)
return M, f, solSetup¶
Generalized coordinates: cart position , pendulum angle from vertical. Pendulum bob position: .
t = sp.symbols("t")
Mc, m, k, l, g = sp.symbols("M m k l g", positive=True)
x = sp.Function("x")(t)
th = sp.Function("theta")(t)
xp = x + l * sp.sin(th)
yp = -l * sp.cos(th)
T = (sp.Rational(1, 2) * Mc * sp.diff(x, t) ** 2
+ sp.Rational(1, 2) * m * (sp.diff(xp, t) ** 2 + sp.diff(yp, t) ** 2))
V = sp.Rational(1, 2) * k * x**2 + m * g * l * (1 - sp.cos(th))
L = sp.simplify(T - V)
eqs = [sp.simplify(e) for e in lagrange_equations(L, [x, th], t)]
M_sym, f_sym, qdd_sol = solve_for_accelerations(eqs, [x, th], t)
print("Mass matrix M(theta) =\n", M_sym)Mass matrix M(theta) =
Matrix([[M + m, l*m*cos(theta(t))], [l*m*cos(theta(t)), l**2*m]])
Linearized 2-DOF vibration problem¶
About the hanging equilibrium : using Chapter 9’s Hessian recipe directly on and (evaluated at , so the coupling term drops out of at equilibrium up to the order needed):
qs = [x, th]
qds = [sp.diff(q, t) for q in qs]
M_lin = sp.hessian(T, qds).subs(th, 0)
K_lin = sp.hessian(V, qs).subs(th, 0)
print("M_lin =\n", M_lin)
print("K_lin =\n", K_lin)
subs_num = {Mc: 3.0, m: 0.5, k: 40.0, l: 0.6, g: 9.81}
M_num = np.array(M_lin.subs(subs_num)).astype(float)
K_num = np.array(K_lin.subs(subs_num)).astype(float)
lam, vecs = eigh(K_num, M_num)
wn = np.sqrt(lam)
print("Natural frequencies (rad/s):", wn, " (Hz):", wn / (2 * np.pi))M_lin =
Matrix([[M + m, l*m], [l*m, l**2*m]])
K_lin =
Matrix([[k, 0], [0, g*l*m]])
Natural frequencies (rad/s): [3.08669957 4.78336901] (Hz): [0.49126349 0.76129682]
Both frequencies are strictly positive here (unlike the free-rolling cart-pole in notebook 7): the spring gives the cart its own restoring stiffness, so there is no rigid-body/zero-frequency mode left.
Nonlinear simulation¶
Release the pendulum from a moderate angle with the cart at its spring’s natural length, and integrate the exact (unlinearized) equations.
args = (x, th, sp.diff(x, t), sp.diff(th, t), Mc, m, k, l, g)
xdd_f = sp.lambdify(args, qdd_sol[0], "numpy")
thdd_f = sp.lambdify(args, qdd_sol[1], "numpy")
p = subs_num
def deriv(_t, y):
xx, aa, xd, wd = y
return [xd, wd,
xdd_f(xx, aa, xd, wd, p[Mc], p[m], p[k], p[l], p[g]),
thdd_f(xx, aa, xd, wd, p[Mc], p[m], p[k], p[l], p[g])]
tt = np.linspace(0, 10, 2000)
sol = solve_ivp(deriv, [tt[0], tt[-1]], [0.1, np.deg2rad(40), 0.0, 0.0], t_eval=tt,
max_step=0.005, rtol=1e-9, atol=1e-9)
fig, ax = plt.subplots()
ax.plot(tt, sol.y[0], label="cart position x(t) [m]")
ax.plot(tt, np.rad2deg(sol.y[1]) / 100, label=r"$\theta$(t)/100 [deg/100, rescaled]")
ax.set_xlabel("t [s]"); ax.legend()
ax.set_title("Spring cart-pole: coupled nonlinear response")
plt.show()