This is more like a coding question, but I thought I'll post it here because of its mathematical foundation.
Two ODEs first degree can describe a Hamiltonian System. The connection between the ODEs and the Hamiltonian System is given by the canonical equations which are:
$ \dot{x}=\frac{\partial H}{\partial x} $
$ \dot{y}=-\frac{\partial H}{\partial y} $
For example:
Two ODEs:
$ \dot{x}= 2y $
$ \dot{y}= -2x $
Results in the following Hamiltonian:
$ H(x,y)=x^2+y^2 $
Is there a way to create a code/algorithm, that can calculate the Hamiltonian from these ODE?
Given the differential equations $$ \eqalign{\dot{x} &= f(x,y)\cr \dot{y} &= g(x,y)\cr} $$ you want $H= H(x,y)$ such that $$\eqalign{\frac{\partial H}{\partial x} &= -g(x,y)\cr \frac{\partial H}{\partial y} &= f(x,y)\cr} $$ That is, $H$ is a scalar potential for the vector field $\langle -g(x,y), f(x,y) \rangle$. Of course you need this vector field to be conservative. If this is the case, first take an antiderivative of the first component with respect to $x$: $$ V(x,y) = \int -g(x,y)\; dx$$ Then we should have $\dfrac{\partial}{\partial x} (H - V) = 0$, so $H - V$ should be a function of $y$ alone. And $$\dfrac{\partial}{\partial y} (H - V) = f(x,y) - \dfrac{\partial V}{\partial y}$$ so $$ H - V = \int \left(f(x,y) - \frac{\partial V}{\partial y} \right) \; dy + constant$$ i.e. a Hamiltonian is $$H = V + \int \left( f(x,y) - \frac{\partial V}{\partial y} \right)\; dy $$