Problems using fsolve to find two unknowns in Python - python

I've been having problems trying to estimate two variables while using fsolve. Below is the code
def f(variables):
#Ideal
n=0 #this is passed as an argument but given in this example for simplicity
P1 = 101325; T1 = 300
q = 'H2:2,O2:1,N2:{}'.format(molno[n])
mech = 'H2O2sandan.cti'
cj_speed,R2,plot_data = CJspeed(P1,T1,q,mech,fullOutput=True)
gas = PostShock_fr(cj_speed, P1, T1, q, mech)
Ta = gas.T; Ps = gas.P;
CVout1 = cvsolve(gas)
taua = CVout1['ind_time']
Tb = Ta*1.01
gas.TPX = Tb,Ps,q
CVout2 = cvsolve(gas)
taub = CVout2['ind_time']
#Constant Volume
k,Ea = variables
T_0_1= Tvn_mg_d[n]
T_vn_1 = Tvn_mg_d[n]
den = rhovn_mg_d[n]
t = np.linspace(0,0.0001,100000000)
qr = Q_mg[n]
perfect_var = T_vn_1,den,Ea,k,qr
sol_t= odeint(ode,T_0_1,t=t,args=(perfect_var,))
index = np.argmax(np.gradient(sol_t[:,0]))
tau_cv_1 = t[index]
T_0_2= Tvn_mg_d[n]*1.01
T_vn_2 = Tvn_mg_d[n]*1.01
den = rhovn_mg_d[n]
t = np.linspace(0,0.0001,100000000)
qr = Q_mg[n]
perfect_var = T_vn_2,den,Ea,k,qr
sol_t= odeint(ode,T_0_2,t=t,args=(perfect_var,))
index = np.argmax(np.gradient(sol_t[:,0]))
tau_cv_2 = t[index]
root1 = taua - t_cv_1
root2 = taub - t_cv_2
return[root1,root2]
import scipy.optimize as opt
k_guess = 95000
Ea_guess = 28*300
solution = opt.fsolve(f,(k_guess,Ea_guess))
print(solution)
I want to find values of k_guess and Ea_guess such that roo1 and roo2 are 0 (i.e. taua = t_cv_1 and taub = t_cv_2). However I don't know if I've used fsolve the right way as the values returned seem to be way off. Am I returning the right thing? I also get the below error:
lsoda-- warning..internal t (=r1) and h (=r2) are
such that in the machine, t + h = t on the next step
(h = step size). solver will continue anyway
What am I doing wrong here?

Related

Nothing Happens When Running Script in Spyder

I am running this code and oddly, nothing happens. There is no error nor does it freeze. It simply just runs the code without storing variables, nothing is printed out and it doesn't open the window that is supposed to show the plot. So it simply does nothing. It is very odd. This worked only a few minutes ago and I did not change anything about it previously. I did make sure that the variable explorer is displaying all the definitions in the script. I intentionally removed the plotting section at the end since it just made the code set longer and the same issue persists here without it.
Code:
#Import libraries
import numpy as np
from scipy.integrate import odeint
#from scipy.integrate import solve_ivp
from time import time
import matplotlib.pyplot as plt
from matplotlib.pyplot import grid
from mpl_toolkits.mplot3d import Axes3D
import numpy, scipy.io
from matplotlib.patches import Circle
'''
import sympy as sy
import random as rand
from scipy import interpolate
'''
'''
Initiate Timer
'''
TimeStart = time()
'''
#User defined inputs
'''
TStep = (17.8E-13)
TFinal = (17.8E-10)
R0 = 0.02
V0X = 1E7
ParticleCount = 1 #No. of particles to generate energies for energy generation
BInput = 0.64 #Magnitude of B field near pole of magnet in experiment
ScaleV0Z = 1
'''
#Defining constants based on user input and nature (Cleared of all errors!)
'''
#Defining Space and Particle Density based on Pressure PV = NkT
k = 1.38E-23 #Boltzman Constant
#Natural Constants
Q_e = -1.602E-19 #Charge of electron
M_e = 9.11E-31 #Mass of electron
JToEv = 6.24E+18 #Joules to eV conversion
EpNaut = 8.854187E-12
u0 = 1.256E-6
k = 1/(4*np.pi*EpNaut)
QeMe = Q_e/M_e
'''
Create zeros matrices to populate later (Cannot create TimeIndex array!)
'''
TimeSpan = np.linspace(0,TFinal,num=round((TFinal/TStep)))
TimeIndex = np.linspace(0,TimeSpan.size,num=TimeSpan.size)
ParticleTrajectoryMat = np.zeros([91,TimeSpan.size,6])
BFieldTracking = np.zeros([TimeSpan.size,3])
InputAngle = np.array([np.linspace(0,90,91)])
OutputAngle = np.zeros([InputAngle.size,1])
OutputRadial = np.zeros([InputAngle.size,1])
'''
Define B-Field
'''
def BField(x,y,z):
InputCoord = np.array([x,y,z])
VolMag = 3.218E-6 #Volume of magnet in experiment in m^3
BR = np.sqrt(InputCoord[0]**2 + InputCoord[1]**2 + InputCoord[2]**2)
MagMoment = np.array([0,0,(BInput*VolMag)/u0])
BDipole = (u0/(4*np.pi))*(((3*InputCoord*np.dot(MagMoment,InputCoord))/BR**5)-(MagMoment/BR**3))
#BVec = np.array([BDipole[0],BDipole[1],BDipole[2]])
#print(BDipole[0],BDipole[1],BDipole[2])
return (BDipole[0],BDipole[1],BDipole[2])
'''
Lorentz Force Differential Equations Definition
'''
def LorentzForce(PosVel,t,Constants):
X,Y,Z,VX,VY,VZ = PosVel
Bx,By,Bz,QeMe = Constants
BFInput = np.array([Bx,By,Bz])
VelInput = np.array([VX,VY,VZ])
Accel = QeMe * (np.cross(VelInput, BFInput))
LFEqs = np.concatenate((VelInput, Accel), axis = 0)
return LFEqs
'''
Cartesean to Spherical coordinates converter function. Returns: [Radius (m), Theta (rad), Phi (rad)]
'''
def Cart2Sphere(xIn,yIn,zIn):
P = np.sqrt(xIn**2 + yIn**2 + zIn**2)
if xIn == 0:
Theta = np.pi/2
else:
Theta = np.arctan(yIn/xIn)
Phi = np.arccos(zIn/np.sqrt(xIn**2 + yIn**2 + zIn**2))
SphereVector = np.array([P,Theta,Phi])
return SphereVector
'''
Main Loop
'''
for angletrack in range(0,InputAngle.size):
MirrorAngle = InputAngle[0,angletrack]
MirrorAngleRad = MirrorAngle*(np.pi/180)
V0Z = np.abs(V0X/np.sin(MirrorAngleRad))*np.sqrt(1-(np.sin(MirrorAngleRad))**2)
V0Z = V0Z*ScaleV0Z
#Define initial conditions
V0 = np.array([[V0X,0,V0Z]])
S0 = np.array([[0,R0,0]])
ParticleTrajectoryMat[0,:] = np.concatenate((S0,V0),axis=None)
for timeplace in range(0,TimeIndex.size-1):
ICs = np.concatenate((S0,V0),axis=None)
Bx,By,Bz = BField(S0[0,0],S0[0,1],S0[0,2])
BFieldTracking[timeplace,:] = np.array([Bx,By,Bz])
AllConstantInputs = [Bx,By,Bz,QeMe]
t = np.array([TimeSpan[timeplace],TimeSpan[timeplace+1]])
ODESolution = odeint(LorentzForce,ICs,t,args=(AllConstantInputs,))
ParticleTrajectoryMat[angletrack,timeplace+1,:] = ODESolution[1,:]
S0[0,0:3] = ODESolution[1,0:3]
V0[0,0:3] = ODESolution[1,3:6]
MatSize = np.array([ParticleTrajectoryMat.shape])
RowNum = MatSize[0,1]
SphereMat = np.zeros([RowNum,3])
SphereMatDeg = np.zeros([RowNum,3])
for cart2sphereplace in range(0,RowNum):
SphereMat[cart2sphereplace,:] = Cart2Sphere(ParticleTrajectoryMat[angletrack,cart2sphereplace,0],ParticleTrajectoryMat[angletrack,cart2sphereplace,1],ParticleTrajectoryMat[angletrack,cart2sphereplace,2])
for rad2deg in range(0,RowNum):
SphereMatDeg[rad2deg,:] = np.array([SphereMat[rad2deg,0],(180/np.pi)*SphereMat[rad2deg,1],(180/np.pi)*SphereMat[rad2deg,2]])
PhiDegVec = np.array([SphereMatDeg[:,2]])
RVec = np.array([SphereMatDeg[:,0]])
MinPhi = np.amin(PhiDegVec)
MinPhiLocationTuple = np.where(PhiDegVec == np.amin(PhiDegVec))
MinPhiLocation = int(MinPhiLocationTuple[1])
RAtMinPhi = RVec[0,MinPhiLocation]
OutputAngle[angletrack,0] = MinPhi
OutputRadial[angletrack,0] = RAtMinPhi
print('Mirror Angle Input (In deg): ',InputAngle[0,angletrack])
print('Mirror Angle Output (In deg): ',MinPhi)
print('R Value at minimum Phi (m): ',RAtMinPhi)
InputAngleTrans = np.matrix.transpose(InputAngle)
CompareMat = np.concatenate((InputAngleTrans,OutputAngle),axis=1)

How to fix ''int' object has no attribute 'triu_indices'

I'm using a double for loop, to calculate a value. This for loop gets the i element of a vector and the i+1 element of the same vector, then it does some calculation. But when the second iteration of the second for loop starts, I get the error 'int' object has no attribute 'triu_indices'
I have three matrixes, and some functions. Also I use a double for (I don't think this is the pythonic way to do that, however I'm learning)
I have this:
import numpy as np
#The three matrixes
flowMatrixSymNoCeros = np.array([[0,4,6,2,4,4],
[4,0,4,2,2,8],
[6,4,0,2,2,6],
[2,2,2,0,6,2],
[4,2,2,6,0,10],
[4,8,6,2,10,0]])
flowMatrixSymCeros = np.array([[0,0,6,2,4,0],
[0,0,4,2,2,8],
[6,4,0,2,2,6],
[2,2,2,0,6,2],
[4,2,2,6,0,0],
[0,8,6,2,0,0]])
closenessRatingSymNoceros = np.array([[0,5,3,2,6,4],
[5,0,5,2,6,2],
[3,5,0,1,2,1],
[2,2,1,0,2,2],
[6,6,2,2,0,6],
[4,2,1,2,6,0]])
matrices = np.array([flowMatrixSymNoCeros,
flowMatrixSymCeros,
closenessRatingSymNoceros])
def normalMatrixesAsym(matrices):
matrixes = np.copy(matrices)
matrixes = np.absolute(matrixes)
normalMatrixes = []
for matriz in matrixes:
s = np.sum(matriz)
normalMatrixes.append(matriz / s)
return np.asarray(normalMatrixes)
def sdwm(symetria, normalMatrix):
SD= 0
normalizedMatrix = np.copy(normalMatrix)
m = normalizedMatrix.shape[0]
sd = lambda num,den : (num/den)**(1/2)
# maskUpper = np.mask_indices(m, np.triu, 1)
# maskLower = np.mask_indices(m, np.tril, -1)
upper = normalizedMatrix[np.triu_indices(m,1)]
lower = normalizedMatrix[np.tril_indices(m,-1)]
upperAbs = np.abs(upper)
if(symetria):
media = np.absolute(np.mean(upper))
num = np.sum((upperAbs - np.mean(media))**2)
den = ((m * (m-1))/2)-1
SD = sd(num,den) #calculo del SD
else:
# lower = np.tril(normalizedMatrix,-1)
matrixNoDiag = np.append(upper,lower)
matrixNoDiagAbs = np.abs(matrixNoDiag)
mean = np.absolute(np.mean(matrixNoDiag))
num = np.sum((matrixNoDiagAbs - mean)**2)
den = (m*(m-1))-1 #calcula el denominador
SD = sd(num,den) #calcula el SD
return SD
def calcularCriticalValues(funcion, symetria, normalMatrixes):
normalMatrices = np.copy(normalMatrixes)
criticalValules = []
for normalMatriz in normalMatrices:
criticalValules.append(funcion(symetria,normalMatriz))
return np.asarray(criticalValules)
normalizedMatrices = normalMatrixesAsym(matrices)
SD = calcularCriticalValues(nm.sdwm,False,normalizedMatrices)
m=len(matrices)
R= np.zeros((m,m))
n = len(normalizedMatrices[0])
for i,matrix in enumerate(normalizedMatrices):
upperI = matrix[np.triu_indices(n,1)]
lowerI = matrix[np.tril_indices(n,-1)]
matrixNoDiagI = np.append(upperI,lowerI)
meanI = np.absolute(np.mean(matrixNoDiagI))
matrixNoDiagIAbs = np.abs(matrixNoDiagI)
for j in range(i+1,m):
matrixJ =normalizedMatrices[j]
upperJ = matrixJ[np.triu_indices(n,1)] #the problem is here
lowerJ = matrixJ[np.tril_indices(n,-1)]
matrixNoDiagJ = np.append(upperJ,lowerJ)
meanJ = np.absolute(np.mean(matrixNoDiagJ))
matrixNoDiagJAbs = np.abs(matrixNoDiagJ)
num = np.sum((matrixNoDiagIAbs - meanI)*(matrixNoDiagJAbs -
meanJ))
np = (n*(n-1))-1 #n''
den = np*SD[i]*SD[j]
r = num/den
R[i][j] = r
print(R)
What I expect is a matrix named R, with the calculations that the algorithm do.
This is
>>>R
>>>[[0. 0.456510 0.987845]
[0. 0.156457 0.987845]
[0. 0. 0. ]]
The error I get is:
AttributeError Traceback (most recent call last)
in ()
204 # print(i,j)
205 matrixJ =normalizedMatrices[j]
--> 206 upperJ = matrixJ[np.triu_indices(n,1)] # Obtiene elementos diagonal superior
207 lowerJ = matrixJ[np.tril_indices(n,-1)] # Obtiene elementos diagonal superior
208 matrixNoDiagJ = np.append(upperJ,lowerJ)
AttributeError: 'int' object has no attribute 'triu_indices'
The problem is that you use np as a variable in that loop: np = (n*(n-1))-1 #n''. You are assigning it to an int value, which is shadowing the imported np. You need to rename that variable.

Pyomo parameter estimation with time-varying input signals

I want to try Pyomo for parameter estimation problems and this is what I have so far. First the parameters and variables are created. The unknows to the parameter estimation problem are p1 to p6. The time-varying inputs are TVL, mdot and TU.
model = pyo.ConcreteModel()
model.t = dae.ContinuousSet(initialize=time)
model.p1 = pyo.Var(domain=pyo.NonNegativeReals, initialize=5.993867814123688)
model.p2 = pyo.Var(domain=pyo.NonNegativeReals, initialize=0.5254928953213035)
model.p3 = pyo.Var(domain=pyo.NonNegativeReals, initialize=50.507139006670045)
model.p4 = pyo.Var(domain=pyo.NonNegativeReals, initialize=50.349545087852945)
model.p5 = pyo.Var(domain=pyo.NonNegativeReals, initialize=0.03248392142362977)
model.p6 = pyo.Var(domain=pyo.NonNegativeReals, initialize=0.10106006227941483)
model.TU = pyo.Param(model.t, default=273.15)
model.TVL = pyo.Param(model.t, default=333.15)
model.mdot = pyo.Param(model.t, default=0.01)
model.TR = pyo.Var(model.t)
model.TRL = pyo.Var(model.t)
model.TW = pyo.Var(model.t)
model.dTRdt = dae.DerivativeVar(model.TR, wrt=model.t)
model.dTRLdt = dae.DerivativeVar(model.TRL, wrt=model.t)
model.dTWdt = dae.DerivativeVar(model.TW, wrt=model.t)
model.t_meas = pyo.Set(within=model.t, initialize=time)
model.TR_meas = pyo.Param(model.t_meas, initialize=TR_dict)
The system consists of three ODEs.
def _diffeq1(model, t):
return model.dTRdt[t] == model.p1 * (model.TRL[t] - model.TR[t]) - model.p2 * (model.TR[t] - model.TW[t])
def _diffeq2(model, t):
return model.dTRLdt[t] == model.p3 * model.mdot[t] * (model.TVL[t] - model.TRL[t]) - model.p4 * (model.TRL[t] - model.TR[t])
def _diffeq3(model, t):
return model.dTWdt[t] == model.p5 * (model.TR[t] - model.TW[t]) - model.p6 * (model.TW[t] - model.TU[t])
model.diffeq1 = pyo.Constraint(model.t, rule=_diffeq1)
model.diffeq2 = pyo.Constraint(model.t, rule=_diffeq2)
model.diffeq3 = pyo.Constraint(model.t, rule=_diffeq3)
This is the objective function.
def _obj(model):
return sum((model.TR[i] - model.TR_meas[i])**2 for i in model.t_meas)
Simulation works fine according to the documentation
model.var_input = pyo.Suffix(direction=pyo.Suffix.LOCAL)
model.var_input[model.TU] = TU_dict
model.var_input[model.TVL] = TVL_dict
model.var_input[model.mdot] = mdot_dict
sim = dae.Simulator(model, package="casadi")
tsim, profiles = sim.simulate(numpoints=3600, integrator="cvodes", varying_inputs=model.var_input)
but I am having a hard time getting this to work with the optimization. Is there a recommended way to perform the optimization with time-varying inputs?
EDIT:
This is the code, I use for the optimization.
discretizer = pyo.TransformationFactory("dae.finite_difference")
discretizer.apply_to(model, wrt=model.t, nfe=200, scheme="BACKWARD")
solver = pyo.SolverFactory("ipopt")
results = solver.solve(model, tee=True)
I changed the above code from model.TU = pyo.Var(model.t) to model.TU = pyo.Param(model.t, default=273.15) (also for TVL and mdot). Otherwise ipopt tried to also find optimal trajectories for TU, TVL and mdot. With this new implementation only the default values are used for the optimization. I added the following figure showing TU to illustrate my point.

TypeError: 'int' object is not callable Modeling in python

I am getting the following error in python, and I am not sure why. I am trying to model how meth affects mice.
Here is my code, and the functions that are created in my code:
from scipy import array, linspace
from scipy import integrate
from matplotlib.pyplot import *
def Temp2(z, t, Ta, Te, wexc, yexc, winhib, yinhib, whd, yhd, wexctoinhib, winhibtomdl, whdtospn, yspn, Tt):
# Dependence of Meth Concentration
# dx
# -- = -x/Ta
# dt
#
# dy
# -- = x/Ta - y/Te
# dt
# x = interperitoneal
# y = blood
# Ta is the time constant of Meth in the absorbtion
# Te is the time constant of Meth in elimination
x = z[0] # Rabbits density
y = z[1] # Sheep density
T = z[2]
D = int(x=1)
yt = D(Ta/Te -1)**-1 * (e**-t/Ta - e**-t/Te)
Pexc = (1+tanhx)*[wexc*yt*yexc]
Pinhib = (1+tanhx)*[winhib*yt*yinhib]
Phd = (1+tanhx)*[whd*yt*yhd]
Pmdl = wexctoinghib*Pexc-winhibtomdl*Pinhib
Pspn = Pmdl + whdtospn*Phd+yspn
V = array([-x/Ta, x/Ta - y/Te, (Pspn-(T-T0))/Tt])
return V
def main():
# set up our initial conditions
IC0 = 1
BC0 = 0
T0 = 37
z0 = array([IC0, BC0, T0])
# Parameters
Ta = 8.25
Te = 57.5
wexc = 1.225
yexc = -0.357
winhib = 1.335
yinhib = 1.463
whd = 0.872
yhd = -3.69
wexctoinhib = 7.47
winhibtomdl = 6.38
whdtospn = 5.66
yspn = -3.35
Tt = 89.2
# choose the time's we'd like to know the approximate solution
t = linspace(0., 1., 60)
# and solve
xode= integrate.odeint(Temp2, z0, t, args=(Ta, Te, wexc, yexc, winhib, yinhib, whd, yhd, wexctoinhib, winhibtomdl, whdtospn, yspn, Tt))
print (xode)
main()
Ignore the #s as they do not relate to what the code is saying. Here is the error I am getting:
yt = D(Ta/Te -1)**-1 * (e**-t/Ta - e**-t/Te)
TypeError: 'int' object is not callable
I am not sure what is wrong, and how I can fix this? Can anyone help me?
The issue is here
yt = D(Ta/Te -1)**-1 * (e**-t/Ta - e**-t/Te)
There is no implicit multiplication in python, so when you attempt to do D(Ta/Te - 1) it is being interpreted as a function call rather than D multiplied by what is in the bracket.
Rewrite it like this
yt = D*(Ta/Te -1)**-1 * (e**-t/Ta - e**-t/Te)

Earth&Moon orbit system. My data is wrong

There is my code. I fixed it like this:
# Take 3 digits for significant figures in this code
import numpy as np
from math import *
from astropy.constants import *
import matplotlib.pyplot as plt
import time
start_time = time.time()
"""
G = Gravitational constant
g0 = Standard acceleration of gravity ( 9.8 m/s2)
M_sun = Solar mass
M_earth = Earth mass
R_sun = Solar darius
R_earth = Earth equatorial radius
au = Astronomical unit
Astropy.constants doesn't have any parameter of moon.
So I bring the data from wikipedia(https://en.wikipedia.org/wiki/Moon)
"""
M_moon = 7.342E22
R_moon = 1.737E6
M_earth = M_earth.value
R_earth = R_earth.value
G = G.value
perigee, apogee = 3.626E8, 4.054E8
position_E = np.array([0,0])
position_M = np.array([(perigee+apogee)/2.,0])
position_com = (M_earth*position_E+M_moon*position_M)/(M_earth+M_moon)
rel_pE = position_E - position_com
rel_pM = position_M - position_com
F = G*M_moon*M_earth/(position_M[0]**2)
p_E = {"x":rel_pE[0], "y":rel_pE[1],"v_x":0, "v_y":(float(F*rel_pE[0])/M_earth)**.5}
p_M = {"x":rel_pM[0], "y":rel_pM[1],"v_x":0, "v_y":(float(F*rel_pM[0])/M_moon)**.5}
print(p_E, p_M)
t = range(0,365)
data_E , data_M = [], []
def s(initial_velocity, acceleration, time):
result = initial_velocity*time + 0.5*acceleration*time**2
return result
def v(initial_velocity, acceleration, time):
result = initial_velocity + acceleration*time
return result
dist = float(sqrt((p_E["x"]-p_M['x'])**2 + (p_E["y"]-p_M["y"])**2))
xE=[]
yE=[]
xM=[]
yM=[]
data_E, data_M = [None]*len(t), [None]*len(t)
for i in range(1,366):
data_E[i-1] = p_E
data_M[i-1] = p_M
dist = ((p_E["x"]-p_M["x"])**2 + (p_E["y"]-p_M["y"])**2)**0.5
Fg = G*M_moon*M_earth/(dist**2)
theta_E = np.arctan(p_E["y"]/p_E["x"])
theta_M = theta_E + np.pi #np.arctan(data_M[i-1]["y"]/data_M[i-1]["x"])
Fx_E = Fg*np.cos(theta_E)
Fy_E = Fg*np.sin(theta_E)
Fx_M = Fg*np.cos(theta_M)
Fy_M = Fg*np.sin(theta_M)
a_E = Fg/M_earth
a_M = Fg/M_moon
v_E = (p_E["v_x"]**2+p_E["v_y"]**2)**.5
v_M = (p_M["v_x"]**2+p_M["v_y"]**2)**.5
p_E["v_x"] = v(p_E["v_x"], Fx_E/M_earth, 24*3600)
p_E["v_y"] = v(p_E["v_y"], Fy_E/M_earth, 24*3600)
p_E["x"] += s(p_E['v_x'], Fx_E/M_earth, 24*3600)
p_E["y"] += s(p_E['v_y'], Fy_E/M_earth, 24*3600)
p_M["v_x"] = v(p_M["v_x"], Fx_M/M_moon, 24*3600)
p_M["v_y"] = v(p_M["v_y"], Fy_M/M_moon, 24*3600)
p_M["x"] += s(p_M['v_x'], Fx_M/M_moon, 24*3600)
p_M["y"] += s(p_M['v_y'], Fy_M/M_moon, 24*3600)
for i in range(0,len(t)):
xE += data_E[i]["x"]
yE += data_E[i]["y"]
xM += data_M[i]["x"]
yM += data_M[i]["y"]
print("\n Run time \n --- %d seconds ---" %(time.time()-start_time))
after run this code i tried to print data_E and data_M.
Then I can get data but there is no difference. All of the data is the same.
But when I printed data step by step, it totally different.
I have wrong data problem and increase distance problem. Please help me this problem..
The code exits near line 45, where you are trying to assign p_E by pulling the square root of a negative number on the right hand side (as you've moved the [0] coordinate of the Earth to negative values while shifting Earth and Moon into the coordinate system of their center of mass). In line 45, the value of F*rel_pE[0]/M_earth is negative. So the code never reaches the end of the program using python 2.7.14. That bug needs to be solved before trying to discuss any further aspects.

Categories