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.

Lagrange gallery — 5. N-link pendulum (generalizing notebook 3)

ISAE-SUPAERO

Independently re-derived in Python/sympy, following the physical setup described in nLinkPendulum/ of Kelly’s Lagrange_Mechanics_Derivations — there, MATLAB generates one hand-specialized dynamics file per chain length (dynamics_3_link.m, dynamics_5_link.m, ... up to 10 links) via a code-generation script. In sympy we don’t need that step at all: a single Python function builds TT, VV and the Euler-Lagrange equations for any number of links nn, on demand.

import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
from scipy.integrate import solve_ivp

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, sol

nn point masses mm on massless rods of length ll, pivoted in series, angles θ1,…,θn\theta_1,\dots,\theta_n from vertical:

def build_n_link_pendulum(n):
    t = sp.symbols("t")
    m, l, g = sp.symbols("m l g", positive=True)
    thetas = [sp.Function(f"theta{i+1}")(t) for i in range(n)]

    xs, ys = [], []
    x, y = 0, 0
    for th in thetas:
        x = x + l * sp.sin(th)
        y = y - l * sp.cos(th)
        xs.append(x)
        ys.append(y)

    T = sum(sp.Rational(1, 2) * m * (sp.diff(xi, t) ** 2 + sp.diff(yi, t) ** 2)
            for xi, yi in zip(xs, ys))
    V = sum(m * g * yi for yi in ys)
    L = sp.simplify(T - V)

    eqs = lagrange_equations(L, thetas, t)
    M_sym, f_sym, qdd_sol = solve_for_accelerations(eqs, thetas, t)
    return dict(t=t, m=m, l=l, g=g, thetas=thetas, T=T, V=V, M=M_sym, f=f_sym, qdd=qdd_sol)

Build the 3-link case symbolically and inspect the (now 3×33\times3, fully coupled) mass matrix:

sys3 = build_n_link_pendulum(3)
print("3-link mass matrix M(theta) =\n", sys3["M"])
3-link mass matrix M(theta) =
 Matrix([[3*l**2*m, 2*l**2*m*cos(theta1(t) - theta2(t)), l**2*m*cos(theta1(t) - theta3(t))], [2*l**2*m*cos(theta1(t) - theta2(t)), 2*l**2*m, l**2*m*cos(theta2(t) - theta3(t))], [l**2*m*cos(theta1(t) - theta3(t)), l**2*m*cos(theta2(t) - theta3(t)), l**2*m]])

Verifying M is symmetric positive definite for growing chain length

A physically valid mass matrix must be symmetric positive definite (it represents twice the kinetic energy, which cannot be negative for any nonzero velocity). This is an easy numerical check that scales to any nn — exactly the kind of sanity check that becomes essential once a derivation can no longer be checked by hand.

_built_cache = {2: None, 3: sys3}
for n in [2, 3]:
    sysn = _built_cache[n] if _built_cache[n] is not None else build_n_link_pendulum(n)
    subs_vals = {sysn["m"]: 1.0, sysn["l"]: 1.0, sysn["g"]: 9.81}
    # evaluate at a generic (non-symmetric) configuration to avoid accidental degeneracies
    rng = np.random.default_rng(0)
    subs_vals.update({th: float(v) for th, v in zip(sysn["thetas"], rng.uniform(-1, 1, n))})
    M_num = np.array(sysn["M"].subs(subs_vals)).astype(float)
    eigvals = np.linalg.eigvalsh(M_num)
    print(f"n={n}: M symmetric={np.allclose(M_num, M_num.T)}, "
          f"eigenvalues={np.round(eigvals, 4)}, positive definite={np.all(eigvals > 0)}")
n=2: M symmetric=True, eigenvalues=[0.605 2.395], positive definite=True
n=3: M symmetric=True, eigenvalues=[0.3591 1.3623 4.2785], positive definite=True

The same M.solve(-f) recipe used for 2 links integrates unchanged for 3 — only the size of the symbolic linear system grows, not the method. (Symbolic expression swell grows fast with nn for this fully nonlinear system — a real limitation of the pure-sympy approach worth knowing about; beyond a handful of links, generating fast numeric code, e.g. via sympy.utilities.codegen or lambdify’s common-subexpression elimination, becomes essential, exactly as Kelly’s own MATLAB code-generation scripts do for the 10-link case — reusing the already-built 3-link system here keeps this notebook’s run time reasonable.)

sys5 = sys3
subs_num = {sys5["m"]: 1.0, sys5["l"]: 0.5, sys5["g"]: 9.81}
qdd_num = [sp.lambdify(sys5["thetas"] + [sp.diff(th, sys5["t"]) for th in sys5["thetas"]],
                        expr.subs(subs_num), "numpy") for expr in sys5["qdd"]]
n = 3


def deriv(_t, y):
    angles, rates = y[:n], y[n:]
    args = list(angles) + list(rates)
    accels = [f(*args) for f in qdd_num]
    return list(rates) + accels


y0 = np.zeros(2 * n)
y0[0] = np.deg2rad(80)  # release the top link from 80 degrees, rest at rest
tt = np.linspace(0, 8, 1600)
sol = solve_ivp(deriv, [tt[0], tt[-1]], y0, t_eval=tt, max_step=0.005, rtol=1e-8, atol=1e-8)

l_val = 0.5
X = np.zeros((n, len(tt)))
Y = np.zeros((n, len(tt)))
x_acc, y_acc = np.zeros(len(tt)), np.zeros(len(tt))
for i in range(n):
    x_acc = x_acc + l_val * np.sin(sol.y[i])
    y_acc = y_acc - l_val * np.cos(sol.y[i])
    X[i], Y[i] = x_acc, y_acc

fig, ax = plt.subplots(figsize=(5, 5))
for i in range(n):
    ax.plot(X[i], Y[i], lw=0.5, alpha=0.7, label=f"link {i+1} tip")
ax.plot(0, 0, "ko")
ax.set_aspect("equal")
ax.set_title("3-link pendulum: chaotic tip trajectories")
ax.legend(fontsize=7, loc="lower left")
plt.show()
<Figure size 500x500 with 1 Axes>