Solution (source code)

= Solution

Stationarity of the action under variations with fixed endpoints gives the Euler-Lagrange equation. The <generalized momentum> is $p=\partial L/\partial\dot q$. The <Legendre transform in mechanics> is
$$
H(q,p,t)=p\dot q-L(q,\dot q,t),
$$
after solving $p(q,\dot q,t)$ for $\dot q$. This requires at least local invertibility, $\partial^2L/\partial\dot q^2\ne0$; global single-valuedness requires global invertibility.