This short chapter is a prerequisite for
Chapter 10 (Lagrange’s Equations & Fundamental Principles):
it works out, once and for all, the vector/matrix calculus identities that let Lagrange’s
equations be written directly in the matrix form used throughout the
rest of these notes (Chapter 5’s eigsort, Chapter 7’s Gershgorin bounds, Chapter 10’s own
2-DOF and double-pendulum examples). It is built from three source materials the reader
supplied: two short derivations of the underlying matrix calculus, and a sympy notebook
demonstrating a Hessian-based shortcut for recovering a matrix from a quadratic form — which
this chapter generalizes into a small, reusable tool for extracting , , directly from
a system’s energy expressions, instead of the manual coefficient-matching used in Chapter 10.
import numpy as np
import sympy as sp
from scipy.linalg import eigh
sp.init_printing()
np.set_printoptions(precision=4, suppress=True)9.1 Why this is worth a chapter of its own¶
Every energy-method vibration derivation in this book eventually produces two scalar expressions,
(plus, with damping, ), and the practical question is always the
same: given , (and ) written out as scalar sympy expressions, how do I get the
matrices back out? Chapter 10 answers this by hand — differentiate the Euler-Lagrange
residual with respect to each and read off the coefficients. That works, but it
doesn’t scale, and it obscures a much more direct route: the matrices are just Hessians of
the energy expressions. This chapter derives why, and then builds the corresponding
sympy helper.
9.2 Theory: the derivative of a quadratic form¶
9.2.1 A general bilinear identity¶
For independent vectors , and a constant matrix , the scalar has
— differentiating a sum that is linear in with respect to just strips away the and leaves the coefficient it multiplied, exactly as does in the scalar case. Componentwise: .
9.2.2 Quadratic forms: setting ¶
Now let (a single vector) and be square. The scalar is a quadratic form. It is no longer simply linear in on both sides, so the identity above cannot be applied naively — but it can be applied twice, once for each occurrence of , treating the other occurrence as if it were momentarily a constant vector (the “red/blue” bookkeeping trick: colour one copy of red, the other blue, differentiate each in turn using §9.2.1, then add the two contributions back together):
For the symmetric matrices that arise from physical energies (, , — inertia, stiffness and damping are always symmetric for a system derived from a single scalar energy function), and this collapses to the identity used throughout this book:
Let’s verify this symbolically for a small generic (non-symmetric, to see the general case) matrix, then again enforcing symmetry:
n = 3
x_syms = sp.symbols(f"x1:{n+1}")
x_vec = sp.Matrix(x_syms)
A_generic = sp.Matrix(n, n, lambda i, j: sp.Symbol(f"a{i}{j}"))
quad = (x_vec.T * A_generic * x_vec)[0]
grad = sp.Matrix([sp.diff(quad, xi) for xi in x_syms])
expected = (A_generic + A_generic.T) * x_vec
print("gradient - (A+A^T)x (should be the zero vector):")
sp.simplify(grad - expected)gradient - (A+A^T)x (should be the zero vector):
9.3 From the gradient to the Hessian: recovering automatically¶
This is exactly the trick used in the uploaded quadraticform.ipynb: differentiating the
gradient once more with respect to gives the (constant) Hessian matrix
— so can be read off a quadratic-form expression purely mechanically, with no
coefficient-matching by hand:
Reproducing that notebook’s own check here, with its exact numbers:
x1, x2, x3, x4 = sp.symbols("x1 x2 x3 x4")
A = sp.Matrix([
[3, 2, 0, 5],
[2, -1, 4, -3],
[0, 4, -2, -4],
[5, -3, -4, 7],
])
xv = sp.Matrix([x1, x2, x3, x4])
quad_expr = sp.expand((xv.T * A * xv)[0])
print("x^T A x =", quad_expr)
H = sp.hessian(quad_expr, [x1, x2, x3, x4])
A_recovered = H / 2
print("Recovered A =\n", A_recovered)
print("Matches original A:", A_recovered == A)x^T A x = 3*x1**2 + 4*x1*x2 + 10*x1*x4 - x2**2 + 8*x2*x3 - 6*x2*x4 - 2*x3**2 - 8*x3*x4 + 7*x4**2
Recovered A =
Matrix([[3, 2, 0, 5], [2, -1, 4, -3], [0, 4, -2, -4], [5, -3, -4, 7]])
Matches original A: True
9.4 The matrix form of Lagrange’s equations¶
Now apply the same idea to the physical energies rather than an abstract quadratic form. For a linear(ized) multi-DOF system,
with symmetric and the vector of external generalized forces. Substituting into the Euler-Lagrange equation with a Rayleigh dissipation function,
and using §9.2.2’s identity term by term — (so for constant ), (no explicit -dependence once is constant), , — gives exactly the matrix equation used everywhere in this book:
The table below (from the reference material) makes the term-by-term correspondence explicit — each physical ingredient contributes to exactly one matrix:
| Energy term | Contributes to | Via |
|---|---|---|
| Mass/inertia matrix | ||
| Damping matrix | ||
| Stiffness matrix | ||
| (part of ) | Force vector |
This is precisely why Chapter 10 could read and straight off the 2-DOF spring system’s : it was implicitly using this identity, just applying it by hand one coefficient at a time instead of via a Hessian.
9.5 Hands-on: automating extraction with sympy¶
Here is the reusable tool this chapter set out to build — a direct generalization of
quadraticform.ipynb’s Hessian trick to full Lagrangian mechanics:
def matrices_from_energies(T, V, q, qd, D=None):
"""Extract the (constant) mass, damping and stiffness matrices from scalar energy
expressions T(qd), V(q) and, optionally, a Rayleigh dissipation function D(qd).
Valid whenever T is an exact quadratic form in `qd` with q-independent coefficients (the
standard linear-vibration assumption used throughout this book); for a configuration-
dependent mass matrix M(q) (as in several of the ``lagrange_examples/`` notebooks), evaluate
T's Hessian at the configuration of interest instead (e.g. the equilibrium) before calling.
Parameters
----------
T, V, D : sympy expressions
Kinetic energy, potential energy, and (optional) Rayleigh dissipation function.
q, qd : sequences of sympy symbols/functions
Generalized coordinates and their (time) derivatives, in matching order.
Returns
-------
M, C, K : sympy Matrix
Mass, damping and stiffness matrices, with 2T=qd^T M qd, 2D=qd^T C qd, 2V=q^T K q
(up to any q-independent forcing terms already removed from V).
"""
M = sp.hessian(T, qd)
K = sp.hessian(V, q)
C = sp.hessian(D, qd) if D is not None else sp.zeros(len(q))
return sp.simplify(M), sp.simplify(C), sp.simplify(K)Validation 1 — Chapter 10’s 2-DOF mass-spring system¶
Re-deriving Chapter 10 §10.2’s example ( connected to a wall and to each other by
) with matrices_from_energies instead of manual coefficient-matching:
t = sp.symbols("t")
m1, m2, k1, k2, k3 = sp.symbols("m1 m2 k1 k2 k3", positive=True)
x1t = sp.Function("x1")(t)
x2t = sp.Function("x2")(t)
x1d, x2d = sp.diff(x1t, t), sp.diff(x2t, t)
T_spring = sp.Rational(1, 2) * m1 * x1d**2 + sp.Rational(1, 2) * m2 * x2d**2
V_spring = (sp.Rational(1, 2) * k1 * x1t**2 + sp.Rational(1, 2) * k2 * (x2t - x1t) ** 2
+ sp.Rational(1, 2) * k3 * x2t**2)
M_auto, C_auto, K_auto = matrices_from_energies(T_spring, V_spring, [x1t, x2t], [x1d, x2d])
print("M (Hessian-extracted) =\n", M_auto)
print("K (Hessian-extracted) =\n", K_auto)M (Hessian-extracted) =
Matrix([[m1, 0], [0, m2]])
K (Hessian-extracted) =
Matrix([[k1 + k2, -k2], [-k2, k2 + k3]])
This is exactly and — matching Chapter 10’s manually coefficient-matched result, with no manual algebra at all.
Validation 2 — the linearized double pendulum¶
Chapter 10 §10.3 linearizes the double pendulum via a formal -expansion of the
equations of motion. An equivalent (and often more direct) route is to expand the
Lagrangian itself to quadratic order in the small quantities and only then apply
matrices_from_energies — the two routes must agree, since Lagrange’s equations commute with
truncating a power series at a fixed order.
m, l, g, eps = sp.symbols("m l g epsilon", positive=True)
th1 = sp.Function("theta1")(t)
th2 = sp.Function("theta2")(t)
th1e, th2e = eps * th1, eps * th2
x1p = l * sp.sin(th1e)
y1p = -l * sp.cos(th1e)
x2p = x1p + l * sp.sin(th2e)
y2p = y1p - l * sp.cos(th2e)
T_full = (sp.Rational(1, 2) * m * (sp.diff(x1p, t) ** 2 + sp.diff(y1p, t) ** 2)
+ sp.Rational(1, 2) * m * (sp.diff(x2p, t) ** 2 + sp.diff(y2p, t) ** 2))
V_full = m * g * y1p + m * g * y2p
L_full = sp.expand(T_full - V_full)
L_series = sp.series(L_full, eps, 0, 3).removeO()
L2 = sp.expand(L_series.coeff(eps, 2)) # quadratic-order Lagrangian
th1d, th2d = sp.diff(th1, t), sp.diff(th2, t)
V2 = -L2.subs({th1d: 0, th2d: 0}) # at zero velocity, L2 = T2 - V2 = -V2
T2 = sp.expand(L2 + V2) # so T2 = L2 + V2
M_pend2, C_pend2, K_pend2 = matrices_from_energies(T2, V2, [th1, th2], [th1d, th2d])
print("M (from quadratic Lagrangian, Hessian) =\n", M_pend2)
print("K (from quadratic Lagrangian, Hessian) =\n", K_pend2)M (from quadratic Lagrangian, Hessian) =
Matrix([[2*l**2*m, l**2*m], [l**2*m, l**2*m]])
K (from quadratic Lagrangian, Hessian) =
Matrix([[2*g*l*m, 0], [0, g*l*m]])
subs_num = {m: 1.0, l: 1.0, g: 9.81}
M_num2 = np.array(M_pend2.subs(subs_num)).astype(float)
K_num2 = np.array(K_pend2.subs(subs_num)).astype(float)
lam2, _ = eigh(K_num2, M_num2)
wn2 = np.sqrt(lam2)
wn_exact = np.sqrt(np.array([2 - np.sqrt(2), 2 + np.sqrt(2)]) * 9.81 / 1.0)
print("Natural frequencies from Hessian-extracted M,K:", np.sort(wn2))
print("Exact closed form sqrt((2-/+sqrt2)*g/l): ", np.sort(wn_exact))Natural frequencies from Hessian-extracted M,K: [2.3972 5.7874]
Exact closed form sqrt((2-/+sqrt2)*g/l): [2.3972 5.7874]
The Hessian-extracted matrices reproduce Chapter 10’s natural frequencies exactly (both
routes — expanding the equations, or expanding the Lagrangian first — must agree, and they do).
This is the payoff of this prerequisite chapter: once and are written down, sympy’s
hessian() gets you straight to and , for a 2-DOF system or a 20-DOF one, without ever
hand-differentiating an Euler-Lagrange residual.
9.6 List of example notebooks¶
9.6.1 Kelly’s Lagrange_Mechanics_Derivations gallery — translated to Python/sympy¶
Matthew Kelly’s Lagrange_Mechanics_Derivations
is a MATLAB repository of worked Lagrangian-mechanics derivations (Symbolic Math Toolbox +
Newton-Euler cross-checks, one folder per system). As requested, every system in that repository
has been independently re-derived in Python/sympy — not machine-translated line-by-line
from the MATLAB source, but rebuilt from the same physical setup using the tools built in this
chapter and Chapter 10 — and lives in
advanced/lagrange_examples/:
| # | Notebook | System (original MATLAB folder) |
|---|---|---|
| 1 | Simple harmonic oscillator | simpleHarmonicOscillator/ |
| 2 | Single pendulum | singlePendulum/ |
| 3 | Double pendulum (nonlinear simulation) | doublePendulum/ |
| 4 | Double pendulum, actuated at the shoulder | doublePendulumForced/ |
| 5 | N-link pendulum (generalized) | nLinkPendulum/ |
| 6 | Point mass in polar coordinates / pumped pendulum | polarPointMass/ |
| 7 | Rolling disk with a pendulum | rollingCartPole/ |
| 8 | Cart-pole with a spring | springCartPole/ |
| 9 | Thrust-controlled point-mass “rocket” | simpleRocket/ (translated as a point-mass simplification — see the notebook’s note) |
Every notebook in the table follows the same pattern taught in this chapter: write and
(and , for actuated systems) as sympy expressions, derive the Euler-Lagrange equations
with a small reusable lagrange_equations() helper, solve the resulting linear-in-
system for the accelerations, and either extract (linear systems) or integrate the exact
nonlinear equations numerically with scipy.integrate.solve_ivp (nonlinear systems) — no
hand-written free-body diagrams anywhere.
9.6.2 Further practice: resonance (Python, Univ. of California Davis)¶
moorepants.github.io/resonance is an existing,
already-Python collection of interactive mechanical-vibration teaching notebooks (Jason Moore’s
ENG 122 course materials), listed here for further practice rather than translated (it is
already Python-based):
| Course offering | Selected notebooks |
|---|---|
| ENG 122, Winter 2020 (12 notebooks) | Book oscillating on a cylindrical cup · Bicycle wheel inertia · Curve fitting · Clock pendulum with air-drag / with friction damping · Compound pendulums & center of percussion · 1-DOF trifilar pendulum · 2-DOF “bouncy” pendulum · Ball-channel pendulum & its modes · Sinusoidal forcing · Vibrating building under forcing |
| ENG 122, Fall 2017 (14 notebooks) | Introduction to Jupyter · Book-on-cup & bicycle-wheel labs · Clock pendulum (air drag / joint friction) · Sinusoidal forcing · Vertical vibration of a quarter car · Drone swinging from a trifilar pendulum · Washing-machine model · Ball-channel pendulum & its modes · Modes of a vibrating building · Vibrating building under forcing · Bicycle dynamics |
Open the site directly for the notebooks themselves and their downloadable data packages — a good next step after this chapter’s gallery for more experimentally-flavoured (parameter identification from real measurements) vibration modeling.