I’m trying to solve a n-Body problem using hamilton equations of motion; here is what I’v done:
1.) First I define random initial values for momentums and the vectors positions:
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate
n= 3 # of bodys
G = 1 # constant
m = np.random.random_sample((1,n)) # random values for masses
#----- Random Values for momentums and positions
P_0 = np.random.random_sample(size=(3,n)) # each column of the matrix represents one vector
R_0= np.random.random_sample(size=(3,n))
Y_0 = np.array([P_0,R_0])
2.) then I write the hamilton equations for a k-th particle:
# Hamilton equations:
p_kDot = lambda t,r_k,r_j,m_k,m_j: G*(m_k*m_j/np.linalg.norm(r_k-r_j)**3)*np.subtract(r_k-r_j) # Equation for the momentum
r_kDot = lambda t,p_k,m_k: (1/m_k)*p_k # Equation for the vectors positions.
3.)Then I sum over all the particles and define the function U, which is gonna be pass to scipy.integrate.solve_ivp:
def U(t,Y,m):
partial_Ham_r = np.array( [p_kDot(t,Y[1][k],Y[1][j],m[k],m[j]) for k in range(0,len(Y[1]))
for j in range(0,k)] )
partial_Ham_p = np.array( [r_kDot(t,Y[0][i],m[i]) for i in range(0,len(Y[0]))] )
return (partial_Ham_r,partial_Ham_p)
4.) Call the scipy integrator, but, as documentation say, Y_0 must be a vector, but i dont find a way to express my initial conditions as a n-dimensional vector!:
Sol = scipy.integrate.solve_ivp(U,t_span=
[0,10],y0=Y_0,args=m,dense_output=True,vectorized=True)
obviously outcomes the an error saying that Y_0 must be 1-Dimensional.
Is there a way to express Y_0 so that the code works? or should I express the position and moment vectors in 1 dimensional arrays?
U.reshape([2,3,-1])andU.flatten(). Even then you will get questionable results. There might be a minus missing in the force, check that the force will always be attracting. If you want something with sensible plots, you will have to transform to a barycentric frame first.