I am trying to implement the Legendre transform of a function in Mathematica with the purpose of calculating the Hamiltonian of a system starting from the Lagrangian.
I have found this page which explained how to perform the transform on a function of a single variable. But I need to evaluate the transform of a function of a vector in 3D.
Here it is my clumsy attempt at it:
Off[Solve::ifun];
Off[InverseFunction::ifun];
Clear[legendreTransform];
legendreTransform[f_, v_, p_] :=
Module[{d1 = D[f, v[[1]]], d2 = D[f, v[[2]]], d3 = D[f, v[[3]]],transform},
transform /; (transform = (-f + v[[1]]*d1 + v[[2]]*d2 + v[[3]]*d3)
/.Solve[{p[[1]] == d1 && p[[2]] == d2 && p[[3]] == d3}, v[[1]], v[[2]], v[[3]]}] // Last;
FreeQ[transform, Solve] && FreeQ[transform, InverseFunction])] /; ! (v === p);
vel = {vel1, vel2, vel3};
mom = {mom1, mom2, mom3};
legendreTransform[Exp[Total[vel]], vel, mom]
This piece of code is not working. I was not able to troubleshoot it also because I don't fully understand the code in the page I linked in the first place. I looked up every word in the documentation, but I still cannot understand code flow.
If you could give my any hint or suggestion about where to look I would be grateful.
EDIT (SOLUTION):
The VariationalMethods path seemed me more appealing at first and in fact I used it to do my calculations. But it produced slightly wrong results in my case. It took me some time to realize it but there was a problem with a relative sign.
Eventually I wrote this function that takes the best of the two approaches (the direct and the alternate answer) and it is working as intended in my case:
legendreTransform[l_, q_, p_] :=
Module[{mom = Flatten[{p}], pos = Flatten[{q}], h},
First[h /.Quiet[Solve[h == D[pos,t].VariationalD[l[pos], D[pos, t], t] - l[pos] &&
mom == VariationalD[l[pos], D[pos, t], t], Append[D[pos, t], h]],
{Solve::incnst, Solve::ifun}]]]
More insight on what I am doing:
I am doing calculations in primordial cosmology and, as you may know, in General Relativity the Hamiltonian is null in value (but not in form). This is sometimes called "frozen formalism" because with a null Hamiltonian is trickier to define the evolution of the system in time. Maybe that is the reason the standard methods in VariationalMethods are failing me. More precisely, there is the wrong sign between the kinetical term and the potential term (the spatial curvature term) in the Hamiltonian produced by Legendre transform of the Lagrangian (I am working in the ADM formalism). This at first was not a big issue since all I did was introducing the correct sign by hand.
