Related
I'm trying solve a system of coupled ordinary differential equations, formed by 7 ODEs in python, using solve_ivp or either implement a fuction for RK4.
The general physical problem is as follows:
Cooling of photovoltaic modules with heat exchanger coupling to the module. In this way, the module generates electrical energy and thermal energy.
I have a polynomial function, G(t) = 9.8385e-13*t^4 - 1.82918e-8*t^3 + 5.991355e-05*t^2 + 2.312059e-1*t + 25, which works for an approximate range of 0 < t < 9000, which represents solar radiation as a function of time of day.
This function was obtained through a "polyfit" applied to real data (file upload here. Its a CSV - https://files.fm/u/9y4evkf6c).
This function is used as input for the ODEs, which represent an electrical and a thermal system as a function of time.
To solve the electrical model, I created some scripts that solve the diode equation for the photovoltaic module in question, and the output of this script is the photovoltaic power (called in the PPV thermal model) generated as a function of the module temperature and radiation. This script works great and solves part of my problem.
My difficulty lies in solving the equations of the thermal model, which receives as input parameters G(t) and PPV.
The equations result in this system:
System of EDOS
Labels:
Tvidro = Tglass = T1
Tcel = Tpv = T2
Ttedlar = T3
Tabs = Tabsorber = T4
Ttubo = Ttube = T5
Tfsai = Tfluid_out = T6
Tiso = Tinsulation = T7
Using method/function for RK4, the complete code is like this (you can go direct to part "#DEFINE MODEL EQUATIONS - ODES)" :
import numpy as np
import matplotlib.pyplot as plt
import csv
from numpy.polynomial.polynomial import polyval
############################################################
with open('directory of data called teste_dados_radiacao',"r") as i:
rawdata = list(csv.reader(i, delimiter = ";"))
exampledata = np.array(rawdata[1:], dtype=float)
xdata = exampledata[:,0]
ydata = exampledata[:,1]
curve = np.array(np.polyfit(xdata, ydata, 4))
rev_curve = np.array(list(reversed(curve)), dtype=float)
print(rev_curve)
#G_ajustado = polyval(xdata, rev_curve)
""" plt.plot(xdata, ydata, label = "dados experimentais")
plt.plot(xdata, model, label = "model")
plt.legend()
plt.show() """
#############################################################
#CONSTANTS
Tamb = 25 #°C #ambient temperatura
SIGMA = 5.67e-8 #W/m2K4
E_VIDRO = 0.90 #between 0.85 e 0.83 #nasrin2017 0.04
VENTO = 2 #m/s
T_GROUND = Tamb + 2 #°C
T_CEU = 0.00552*Tamb**1.5
Vf = 1 #m/s
Do = 10e-3 #m
Di = 8e-3 #m
NS = 6*10 #number of cells
T_F_ENT = 20 #°C
#INPUTS
Tcel = 25
Tv = 25
Tiso = 30
Av = 1.638*0.982
ALPHA_VIDRO = 0.9
L_VIDRO = 3e-3 #m
RHO_VIDRO = 2500 #kg/m3
M_VIDRO = Av*L_VIDRO*RHO_VIDRO #kg
CP_VIDRO = 500 #j/kgK
K_VIDRO = 2 #W/mK
TAU_VIDRO = 0.95
Pac = 0.85
H_CELL = 0.156 #m
A_CELL = NS*H_CELL**2
ALPHA_CELL = 0.9
L_CEL = 3e-3
RHO_CEL = 2330
M_CEL = A_CELL*L_CEL*RHO_CEL #kg - estimated
CP_CEL = 900 #J/kgK
K_CEL = 140 #W/mK
BETA_T = 0.43/100 # %/°C
N_ELE_REF = 0.1368 #13.68%
N_ELE = N_ELE_REF*(1 - BETA_T*(Tcel - 25)) #273 + 25 - tcel kelvin
A_tedlar = Av
L_TEDLAR = 0.33e-3
RHO_TEDLAR = 1500
M_TEDLAR = Av*L_TEDLAR*RHO_TEDLAR
CP_TEDLAR = 1090 #1090 OU 2090
K_TEDLAR = 0.35
ALPHA_TEDLAR = 0.34 #doc nasa ou zero
#parameters
RHO_ABS = 2700
A_ABS = Av
CP_ABS =900
L_ABS = 3e-3 #mm
M_ABS = A_ABS*RHO_ABS*L_ABS
K_ABS = 300
A_ABS_TUBO = 10*1.60*0.01+0.154*9*0.01
A_ABS_ISO = Av-A_ABS_TUBO
RHO_TUBO = 2700
CP_TUBO = 900
N_TUBOS = 10
L_TUBO = N_TUBOS*1.6
M_TUBO = RHO_TUBO*L_TUBO*(3.1415/4)*(Do**2 - Di**2)
K_TUBO = 300
A_TUBO_F = 0.387 #pi*Di*(L*10 VOLTAS + R(156MM)*9)
A_TUBO_ISO = 0.484 #pi*Do*(L*10 VOLTAS + R(156MM)*9)
A_ISO = Av
RHO_ISO = 50
L_ISO = 40e-3
M_ISO = A_ISO*RHO_ISO*L_ISO
CP_ISO = 670
K_ISO = 0.0375
E_ISO = 0.75 #ESTIMATED
RHO_FLUIDO = 997
M_FLUIDO = L_TUBO*(3.1415/4)*Di**2*RHO_FLUIDO
CP_FLUIDO = 4186 #j/kgK
MI_FLUIDO = 0.890e-3 #Pa*s ou N/m2 * s
K_FLUIDO = 0.607
M_PONTO = 0.05 #kg/s ou 0.5 kg/m3
#DIMENSIONLESS
Pr = CP_FLUIDO*MI_FLUIDO/K_FLUIDO #water 25°C
Re = RHO_FLUIDO*Vf*Di/MI_FLUIDO
if (Re<=2300):
Nuf = 4.364
else:
Nuf = 0.023*(Re**0.8)*(Pr*0.4)*Re
#COEFFICIENTS
h_rad_vidro_ceu = SIGMA*E_VIDRO*(Tv**2 - T_CEU)*(Tv + T_CEU)
h_conv_vidro_amb = 2.8 + 3*VENTO
h_conv_tubo_fluido = 0.5*30#Nuf
h_cond_vidro_cel = 1/((L_VIDRO/K_VIDRO) + (L_CEL/K_CEL))
h_cond_cel_tedlar = 1/((L_TEDLAR/K_TEDLAR) + (L_CEL/K_CEL))
h_cond_tedlar_abs = 1/((L_TEDLAR/K_TEDLAR) + (L_ABS/K_ABS))
h_cond_abs_tubo = 1/((L_TUBO/K_TUBO) + (L_ABS/K_ABS))
h_cond_abs_iso = 1/((L_ISO/K_ISO) + (L_ABS/K_ABS))
h_cond_tubo_iso = 1/((L_ISO/K_ISO) + (L_TUBO/K_TUBO))
h_conv_iso_amb = h_conv_vidro_amb
h_rad_iso_ground = SIGMA*E_ISO*(Tiso**2 - T_GROUND**2)*(Tiso + T_GROUND)
#GROUPS
A1 = (1/(M_VIDRO*CP_VIDRO))*(ALPHA_VIDRO*Av)#*G(t)) G_ajustado = polyval(dt,rev_curve)
A2 = (1/(M_VIDRO*CP_VIDRO))*(Av*(h_rad_vidro_ceu + h_conv_vidro_amb + h_cond_vidro_cel))
A3 = (1/(M_VIDRO*CP_VIDRO))*Av*h_cond_vidro_cel
A4 = (1/(M_VIDRO*CP_VIDRO))*Av*(h_conv_vidro_amb + h_rad_vidro_ceu)
A5 = (1/(M_CEL*CP_CEL))*(Pac*A_CELL*TAU_VIDRO*ALPHA_CELL) #*G(t)
A6 = -1*A5*N_ELE #*G(t)
A7 = (1/(M_CEL*CP_CEL))*A_CELL*h_cond_vidro_cel
A8 = (1/(M_CEL*CP_CEL))*A_CELL*(h_cond_vidro_cel + h_cond_cel_tedlar)
A9 = (1/(M_CEL*CP_CEL))*A_CELL*h_cond_cel_tedlar
A10 = (1/(M_TEDLAR*CP_TEDLAR))*A_tedlar*(1 - Pac)*TAU_VIDRO*ALPHA_TEDLAR#G(t)
A11 = (1/(M_TEDLAR*CP_TEDLAR))*A_tedlar*(h_cond_cel_tedlar + h_cond_tedlar_abs)
A12 = (1/(M_TEDLAR*CP_TEDLAR))*A_tedlar*h_cond_cel_tedlar
A13 = (1/(M_TEDLAR*CP_TEDLAR))*A_tedlar*h_cond_tedlar_abs
A14 = (1/(M_ABS*CP_ABS))*A_ABS*h_cond_tedlar_abs
A15 = (1/(M_ABS*CP_ABS))*(A_ABS*h_cond_tedlar_abs + A_ABS_TUBO*h_cond_abs_tubo + A_ABS_ISO*h_cond_abs_iso)
A16 = (1/(M_ABS*CP_ABS))*A_ABS_TUBO*h_cond_abs_tubo
A17 = (1/(M_ABS*CP_ABS))*A_ABS_ISO*h_cond_abs_iso
A18 = (1/(M_TUBO*CP_TUBO))*A_ABS_TUBO*h_cond_abs_tubo
A19 = (1/(M_TUBO*CP_TUBO))*(A_ABS_TUBO*h_cond_abs_tubo + A_TUBO_F*h_conv_tubo_fluido + A_TUBO_ISO*h_cond_tubo_iso)
A20 = (1/(M_TUBO*CP_TUBO))*A_TUBO_F*h_conv_tubo_fluido*0.5
A21 = (1/(M_TUBO*CP_TUBO))*A_TUBO_ISO*h_cond_tubo_iso
A22 = (1/(M_FLUIDO*CP_FLUIDO))*A_TUBO_F*h_conv_tubo_fluido
A23 = (1/(M_FLUIDO*CP_FLUIDO))*(A_TUBO_F*h_conv_tubo_fluido*0.5 + M_PONTO*CP_FLUIDO)
A24 = (1/(M_FLUIDO*CP_FLUIDO))*(T_F_ENT*(M_PONTO*CP_FLUIDO - h_conv_tubo_fluido*A_TUBO_F*0.5))
A25 = (1/(M_ISO*CP_ISO))*A_ABS_ISO*h_cond_abs_iso
A26 = (1/(M_ISO*CP_ISO))*(A_ABS_ISO*h_cond_abs_iso + A_TUBO_ISO*h_cond_tubo_iso + A_ISO*h_conv_iso_amb + A_ISO*h_rad_iso_ground)
A27 = (1/(M_ISO*CP_ISO))*A_TUBO_ISO*h_cond_tubo_iso
A28 = (1/(M_ISO*CP_ISO))*A_ISO*(h_conv_iso_amb*Tamb + h_rad_iso_ground*T_GROUND)
#DEFINE MODEL EQUATIONS - ODES - (GLASS, PV CELL, TEDLAR, ABSORBER, TUBE, FLUID, INSULATION) # dT1dt = A1*G_ajustado - A2*x[0] + A3*x[1] + A4 # dT2dt = A5*G_ajustado - A6*G_ajustado + A7*x[0] - A8*x[1] + A9*x[2]# dT3dt = A10*G_ajustado - A11*x[2] + A12*x[1] +A13*x[3]
def SysEdo(x, k):#tv-x[0] tcel-x[1] ttedlar-x[2] tabs-x[3] ttubo-x[4] tiso-x[5] tfs-x[6]
dT1dt = A1*polyval(k,rev_curve) - A2*x[0] + A3*x[1] + A4
dT2dt = A5*polyval(k,rev_curve) - A6*polyval(k,rev_curve) + A7*x[0] - A8*x[1] + A9*x[2]
dT3dt = A10*polyval(k,rev_curve) - A11*x[2] + A12*x[1] +A13*x[3]
dT4dt = A14*x[2] - A15*x[3] + A16*x[4] + A17*x[5]
dT5dt = A18*x[3] - A19*x[4] + A20*x[6] + A20*T_F_ENT + A21*x[5]
dT6dt = A22*x[4] - A23*x[6] + A24
dT7dt = A25*x[3] - A26*x[5] + A27*x[4] + A28
Tdot = np.array([dT1dt, dT2dt, dT3dt, dT4dt, dT5dt, dT6dt, dT7dt])
return Tdot
#RungeKutta4
def RK4(f, x0, t0, tf, dt):
t = np.arange(t0, tf, dt) #time vector
nt = t.size #lenght of time vector
nx = x0.size #length of state variables?
x = np.zeros((nx,nt)) #initialize 2D vector
x[:,0] = x0 #initial conditions
#RK4 constants
for k in range(nt-1):
k1 = dt*f(t[k], x[:,k],k)
k2 = dt*f(t[k] + dt/2, x[:,k] + k1/2, k)
k3 = dt*f(t[k] + dt/2, x[:,k] + k2/2, k)
k4 = dt*f(t[k] + dt, x[:,k] + k3, k)
dx = (k1 + 2*k2 + 2*k2 + k4)/6
x[:,k+1] = x[:,k] + dx
return x,t
#Define problems
f = lambda t, x, k : SysEdo(x, k)
#initial state - t0 is initial time - tf is final time - dt is time step
x0 = np.array([30, 30, 30, 30, 30, 30, 30])
t0 = 0
tf = 1000
dt = 1
#EDO SOLVE
x, t = RK4(f, x0, t0, tf, dt)
plt.figure()
plt.plot(t, x[0], '-', label='Tvidro')
"""
plt.plot(t, x[1], '-', label='Tpv')
plt.plot(t, x[2], '-', label='Ttedlar')
plt.plot(t, x[3], '-', label='Tabs')
plt.plot(t, x[4], '-', label='Tiso')
plt.plot(t, x[5], '-', label='Ttubo')
plt.plot(t, x[6], '-', label='Tfsai')"""
plt.title('Gráfico')
plt.legend(['Tvidro', 'Tpv', 'Ttedlar', 'Tabs', 'Tiso', 'Ttubo', 'Tfsai'], shadow=False)
plt.xlabel('t (s)')
plt.ylabel('Temperatura (°C)')
plt.xlim(0,20)
plt.ylim(0,150)
plt.grid('on')
plt.show()
Thank you in advance, I am also open to completely start the implementation from scratch if there is a better way to do this with python or matlab.
You can just replace
x, t = RK4(f, x0, t0, tf, dt)
with
t = arange(t0,tf+0.5*dt,dt)
res = solve_ivp(f,(t0,tf),x0,t_eval=t,args=(k,), method="DOP853", atol=1e-6,rtol=1e-8)
x = res.y[0]
Adapt the last 3 parameters to your liking.
I wrote a MPC with Python and it worked before. After a long time I want to use it again but I got this Error
f0 passed has more than 1 dimension.
But I didn't change anything on my code. It is some kind of strange.
Here is my code:
import numpy as np
import numpy.linalg as npl
import matplotlib.pyplot as plt
from scipy.optimize import minimize
def mpcAugment(Am, Bm, Cm ):
"Function for Augmented Model"
nx, nu = Bm.shape
ny = Cm.shape[0]
A = np.zeros((nx+ny,nx+ny))
A[0:nx,0:nx] = Am
A[nx:nx+ny,0:nx] = Cm#Am
A[nx:nx+ny,nx:nx+ny] = np.eye(ny)
B = np.zeros((nx+ny,nu))
B[0:nx,:nu] = Bm
B[nx:nx+ny,:nu] = Cm#Bm
C = np.zeros((ny,nx+ny))
C[:ny,nx:nx+ny] = np.eye(ny)
return A, B, C
'Define Parameters'
k = 0.4
AICB = 153.8
mcp = 8.8e4
vamb1 = 30
vamb2 = 45
a = -k*AICB/mcp
b = -1/mcp
Ts = 20
VICBref = -5.0
Am = np.array([[1+Ts*a]])
Bm = np.array([[Ts*b]])
Gm = np.array([[-Ts*a]])
Cm = np.array([[1]])
A, B, C = mpcAugment(Am,Bm,Cm)
A, G, C = mpcAugment(Am,Gm,Cm)
nx, nu = B.shape
ny = C.shape[0]
nd = G.shape[1]
Np = 20
Nu = 5
F = np.zeros((Np*ny,nx))
PHI = np.zeros((Np*ny,Nu*nu))
PHIw = np.zeros((Np*ny,Np*nd))
for i in range(0,Np):
Ai = npl.matrix_power(A, i+1)
F[i*ny:(i+1)*ny,:] = C#Ai
for j in range(0, Nu):
if j <= i:
Aij = np.linalg.matrix_power(A, i-j)
PHI[i*ny:(i+1)*ny, j*nu:(j+1)*nu] = C#Aij#B
for j in range(0, Np):
if j <= i:
Aij = np.linalg.matrix_power(A, i-j)
PHIw[i*ny:(i+1)*ny, j*nd:(j+1)*nd] = C#Aij#G
umax = 3100
umin = 0
Q = np.eye(Np*ny)
R = 1e-2*np.eye(Nu*nu)
Rs = VICBref*np.ones((Np*ny,1))
Ainq = np.zeros((2*Nu*nu,Nu*nu))
binq = np.zeros((2*Nu*nu,1))
cinq = np.zeros((2*Nu*nu,1))
for i in range(0,Nu):
binq[i*nu:(i+1)*nu] = umax
binq[(i+Nu)*nu:(Nu+i+1)*nu] = 1
cinq[i*nu:(i+1)*nu] = 1
cinq[(i+Nu)*nu:(Nu+i+1)*nu] = -1
for j in range(0,i+1):
Ainq[i*nu:(i+1)*nu,j*nu:(j+1)*nu] = np.eye(nu)
Ainq[(i+Nu)*nu:(Nu+i+1)*nu,j*nu:(j+1)*nu] = np.eye(nu)
u0 = 0
def objective(du):
dU = np.array(du).reshape((len(du),1))
Y = F#x + PHI#dU + PHIw#w
return np.transpose((Rs-Y))#(Rs-Y)+np.transpose(dU)#R#(dU)
def constraint1(du):
dU = np.array(du).reshape((len(du),1))
return (binq - Ainq#dU - cinq*u0)[0]
#print(objective([1,1,1]))
ulim = (umin, umax)
bnds = np.kron(np.ones((Nu,1)),ulim)
#print(bnds)
Um = np.ones((nu*Nu,1))
Tsim = 5e4
time = np.arange(0,Tsim,Ts)
Nt = len(time)
xm = np.zeros((Nt,1))
um = np.zeros((Nt,nu))
ym = np.zeros((Nt,ny))
xm[0] = 0
ym[0] = Cm.dot(xm[0])
w = np.zeros((Np*nd,1))
print('Am = ',Am)
print('Bm = ',Bm)
print('Cm = ',Cm)
x = np.zeros((nx,1))
x[1] = xm[0]
vamb = vamb1
Vamb = np.zeros((Nt,1))
Ns = int(np.floor(Nt/2))
Vamb[0:Ns] = vamb1*np.ones((Ns,1))
Vamb[Ns:Nt] = vamb2*np.ones((Nt-Ns,1))
Vref = VICBref*np.ones((Nt,1))
con = {'type':'ineq','fun':constraint1}
for i in range(0,Nt-1):
sol = minimize(objective, Um, method = 'SLSQP',constraints = con)
if sol.success == False:
print('Error Cant solve problem')
exit()
Um = sol.x
um[i+1] = um[i] + Um[0]
u0 = um[i+1]
xm[i+1] = Am.dot(xm[i])+Bm.dot(um[i+1])+Gm.dot(Vamb[i])
ym[i+1] = Cm.dot(xm[i+1])
for j in range(0,Np):
if i+j < Nt:
Rs[j] = Vref[i+j]
w[j] = Vamb[i+j]-Vamb[i+j-1]
else:
Rs[j] = Vref[Nt-1]
w[j] = 0
x[0] = xm[i+1] - xm[i]
x[1] = xm[i+1]
print('Q = ',um[i+1],' , VICB = ',xm[i+1], ' vamb = ', Vamb[i])
hour = 60*60
plt.figure()
plt.subplot(2,1,1)
plt.plot(time/hour,ym)
plt.plot(time/hour,Vref,'--')
plt.xlabel('time(hours)')
plt.xlim([0, Tsim/hour])
plt.subplot(2,1,2)
plt.plot(time/hour,um)
plt.xlim([0, Tsim/hour])
plt.show()
It about a controller, which control the temperature of a cool box.
Is that possible that anything changed in main simply code?
I think the problem is now in minimizations part.
I reinstalled all of my libraries and it worked
I have nested loops in the code attached. I want to optimise the interior most for loop (ks_div one).
from mpi4py import MPI
comm = MPI.COMM_WORLD
proc_id = comm.Get_rank()
n_procs = comm.Get_size()
import time
import numpy as np
from numpy.lib.scimath import sqrt
#import matplotlib.pyplot as plt
#from joblib import Parallel, delayed
delta = 10.0;
lund = 1e04;
alpha = 1e-7;
g = 10.0;
eta = 1.0;
VA = lund*eta/delta;
k0 = sqrt(6)/(1.0*delta);
Omega = VA*k0*50/(1.0*sqrt(2));
ratio = 500000.0;
beta = 1e05;#VA*VA*k0*k0/(g*alpha*ratio*ratio);
t0 = VA*VA/(1.0*g*alpha*beta*eta)
t_min = -8
t_max = 10
division =50
tym =np.logspace(t_min,t_max,division)
t11 = 4*Omega*Omega/(1.0*eta*VA**2*k0**4);
ks_max = 100.0/(1.0*delta);
kz_max = 100.0/(1.0*delta);
ks_min = 1e-10;
kz_min = 1e-10;
kz_div = 1000001
ks_div = 5001
div = ks_div*kz_div;
ks_inc = (ks_max-ks_min)/(1.0*ks_div)#increment in ks
kz_inc = (kz_max-kz_min)/(1.0*kz_div)#increment in kz
start = time.time()
work_size = (kz_div) // n_procs
extra_work = (kz_div) % n_procs
my_work = work_size + (1 if proc_id<extra_work else 0)
d_start = work_size * proc_id + (proc_id if proc_id<extra_work else extra_work)
d_end = d_start + my_work
for s in range(len(tym)):
norm = 0;
normk = 0;
normks = 0;
normkz = 0;
counter = 0;
for l in range(d_start, d_end):
for i in range(int(ks_div)):
ks1 = ks_min+i*ks_inc
kz1 = kz_min+l*kz_inc
ks = ks1 #np.ravel(ks1)
kz = kz1 #np.ravel(kz1) #, kz = np.meshgrid(ks_inc,kz_inc)
k = sqrt(ks**2+kz**2);
omgM = VA*kz;
omge = eta*k**2;
omgA = sqrt(g * alpha*beta)*ks/k;
omgO = Omega*kz/k;
a1 = 1j*1;
a2 = 2*omge;
a3 = -1j*(omgA**2+omge**2+2*omgM**2+4*omgO**2);
a4 = -2*omge*(omgA**2+omgM**2+4*omgO**2);
a5 = 1j*(omgM**4+omgA**2*(omge**2+omgM**2)+4*omge**2*omgO**2);
a6 = omgA**2*omge*omgM**2;
eqn =[a1,a2,a3,a4,a5,a6];
roots = np.roots(eqn);
l4 = roots[0];
l2 = roots[1];
l3 = roots[2];
l1 = roots[3];
l5 = roots[4];
t = tym[s]*t11
theta0hat = delta**3.0/(16.0*np.pi*(2*np.pi)**(1.0/2.0)) * np.exp(- (delta**2)*(ks**2 + kz**2)/8.0)
a11 = (alpha*g*ks/(1.0*k*k))*theta0hat;
a22 = 0;
a33 = -a11*(omgM*omgM+omgA*omgA+4*omgO*omgO);
a44 = a11*omgM*omgM*omge;
d1 = (l1-l2)*(l1-l3)*(l1-l4)*(l1-l5);
d2 = (l2-l1)*(l2-l3)*(l2-l4)*(l2-l5);
d3 = (l3-l1)*(l3-l2)*(l3-l4)*(l3-l5);
d4 = (l4-l1)*(l4-l3)*(l4-l2)*(l4-l5);
d5 = (l5-l1)*(l5-l3)*(l5-l2)*(l5-l4);
n11 = a44
n12 = -1j*a33*(l2+l3+l4+l5)
n13 = -a22*(l4*l5+l3*l4+l3*l5+l2*l3+l2*l4+l2*l5)
n14 = 1j*a11*(l2*l4*l5+l3*l4*l5+l2*l3*l4+l2*l3*l5)
n22 = -1j*a33*(l1+l3+l4+l5)
n23 = -a22*(l4*l5+l3*l4+l3*l5+l1*l3+l1*l4+l1*l5)
n24 = 1j*a11*(l1*l4*l5+l3*l4*l5+l1*l3*l4+l1*l3*l5)
n32 = -1j*a33*(l1+l2+l4+l5)
n33 = -a22*(l4*l5+l2*l4+l2*l5+l1*l2+l1*l4+l1*l5)
n34 = 1j*a11*(l1*l4*l5+l2*l4*l5+l1*l2*l4+l1*l2*l5)
n42 = -1j*a33*(l1+l3+l2+l5)
n43 = -a22*(l3*l5+l2*l3+l2*l5+l1*l2+l1*l3+l1*l5)
n44 = 1j*a11*(l1*l3*l5+l2*l3*l5+l1*l2*l3+l1*l2*l5)
n52 = -1j*a33*(l1+l3+l2+l4)
n53 = -a22*(l3*l4+l2*l3+l2*l4+l1*l2+l1*l3+l1*l4)
n54 = 1j*a11*(l1*l3*l4+l2*l3*l4+l1*l2*l3+l1*l2*l4)
D1 = (n11+n12+n13+n14)/(1.0*d1)
D2 = (n11+n22+n23+n24)/(1.0*d2)
D3 = (n11+n32+n33+n34)/(1.0*d3)
D4 = (n11+n42+n43+n44)/(1.0*d4)
D5 = (n11+n52+n53+n54)/(1.0*d5)
psihat = D5*np.exp(1j*l5*t)+D4*np.exp(1j*l4*t)+D2*np.exp(1j*l2*t)
#print(psihat)
func = psihat*sqrt(ks**2+kz**2)
func_ks = func*ks
func_kz = func*kz
func_k = func*sqrt(kz**2+ks**2)
norm += np.real(sqrt(func*np.conj(func)));
normk += np.real(sqrt(func_k*np.conj(func_k)));
normkz += np.real(sqrt(func_kz*np.conj(func_kz)));
normks += np.real(sqrt(func_ks*np.conj(func_ks)));
norm_reduced = comm.reduce(norm, op=MPI.SUM, root=0)
normk_reduced = comm.reduce(normk, op=MPI.SUM, root=0)
normks_reduced = comm.reduce(normks, op=MPI.SUM, root=0)
normkz_reduced = comm.reduce(normkz, op=MPI.SUM, root=0)
if proc_id == 0:
ksn = normks_reduced/norm_reduced
kzn = normkz_reduced/norm_reduced
kn = normk_reduced/norm_reduced
en = eta*(kn**2)
Mn = VA * kzn
An = sqrt(g* alpha * beta* ksn**2/(1.0*kn**2))
On = Omega*kzn/(1.0*kn)
aa1 = 1j*1;
aa2 = 2*en;
aa3 = -1j*(An**2+en**2+2*Mn**2+4*On**2);
aa4 = -2*en*(An**2+Mn**2+4*On**2);
aa5 = 1j*(Mn**4+An**2*(en**2+Mn**2)+4*en**2*On**2);
aa6 = An**2*en*Mn**2;
eqn1 =[aa1,aa2,aa3,aa4,aa5,aa6];
roots1 = np.roots(eqn1);
L1 = 2*On+1j*en*Mn**2/(4*On**2);
L3 = Mn*Mn/(2.0*On)+1j*en;
L2 = -2*On+1j*en*Mn*Mn/(4*On*On);
L4 = -Mn**2/(2.0*On)+1j*en;
L5 = 1j*An*An*en/(Mn*Mn);
ll4 = roots1[0];
ll2 = roots1[1];
ll3 = roots1[2];
ll1 = roots1[3];
ll5 = roots1[4];
f = open("rot_norm_OMEGA_m.txt","a")
f.write("%.12g %.12g %.12g %.12g %.12g\n"%(tym[s],On,Mn,An,en))
f.close()
p = open("rot_norm_imlambda_approx_m.txt","a")
p.write("%.12g %.12g %.12g %.12g %.12g\n"%(np.imag(L1),np.imag(L2),np.imag(L3),np.imag(L4),np.imag(L5)))
p.close()
s = open("rot_norm_relambda_approx_m.txt","a")
s.write("%.12g %.12g %.12g %.12g %.12g\n"%(np.real(L1),np.real(L2),np.real(L3),np.real(L4),np.real(L5)))
s.close()
q = open("rot_norm_imlambda_num_m.txt","a")
q.write("%.12g %.12g %.12g %.12g %.12g\n"%(np.imag(ll2),np.imag(ll4),np.imag(ll1),np.imag(ll3),np.imag(ll5)))
q.close()
q = open("rot_norm_relambda_num_m.txt","a")
q.write("%.12g %.12g %.12g %.12g %.12g\n"%(np.real(ll2),np.real(ll4),np.real(ll1),np.real(ll3),np.real(ll5)))
q.close()
print ('Completion Time: {:2f}'.format(time.time()-start))
I can't vectorise it since the number of points are quite large. I am using np.roots which also makes it difficult to use a vectorise form. Please have a look and help me out here. I am basically calculating a L2 norm. It is taking a quite lot of time. I had given this code on a machine with 1440 cores and it took about 20 hours to print just one time step.
Thank you.
I'm looking to animate my graph (below) and I'm not sure where or how to start since I have no experience animating. I'm not sure how it works or what the structure of the code should be, so if someone can offer a pseudo-code or an algorithm, I would greatly appreciate it. I have provided the code I used to graph the plot below, too.
enter code here
from scipy.integrate import odeint
import scipy as sci
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as ani
# Universal Gravitational Const.
G = 6.674e-11
# Defining Mass
m1 = 2
m2 = 3.5
m3 = 2.3
# Init positions in graph (array)
pos1 = [-5,0,1]
pos2 = [5,0,10]
pos3 = [0,1,3]
p01 = np.array(pos1)
p02 = np.array(pos2)
p03 = np.array(pos3)
# Init velocities (array)
vi1 = [1,0.01,0]
vi2 = [-5,0,1]
vi3 = [0,-1,0]
v01 = np.array(vi1)
v02 = np.array(vi2)
v03 = np.array(vi3)
#Function
def derivs_func(y,t,G,m1,m2,m3):
d1 = y[:3]
d2 = y[3:6]
d3 = y[6:9]
v1 = y[9:12]
v2 = y[12:15]
v3 = y[15:18]
dist12 = np.sqrt((pos2[0]-pos1[0])**2 + (pos2[1]-pos1[1])**2 + (pos2[2]-pos1[2])**2)
dist13 = np.sqrt((pos3[0]-pos1[0])**2 + (pos3[1]-pos1[1])**2 + (pos3[2]-pos1[2])**2)
dist23 = np.sqrt((pos3[0]-pos2[0])**2 + (pos3[1]-pos2[1])**2 + (pos3[2]-pos2[2])**2)
dv1dt = m2 * (d2-d1)/dist12**3 + m3 * (d3-d1)/dist13**3
dv2dt = m1 * (d1-d2)/dist12**3 + m3 * (d3-d2)/dist23**3
dv3dt = m1 * (d1-d3)/dist13**3 + m2 * (d2-d3)/dist23**3
dd1dt = v1
dd2dt = v2
dd3dt = v3
derivs = np.array([dd1dt,dd2dt,dd3dt,dv1dt,dv2dt,dv3dt])
derivs3 = derivs.flatten()
return derivs3
yo = np.array([p01, p02, p03, v01, v02, v03])
y0 = yo.flatten()
time = np.linspace(0,200,500)
sol = odeint(derivs_func, y0, time, args = (G,m1,m2,m3))
x1 = sol[:,:3]
x2 = sol[:,3:6]
x3 = sol[:,6:9]
fig = plt.figure(figsize = (15,15))
ax = fig.add_subplot(111,projection = '3d')
ax.plot(x1[:,0],x1[:,1],x1[:,2],color = 'b')
ax.plot(x2[:,0],x2[:,1],x2[:,2],color = 'm')
ax.plot(x3[:,0],x3[:,1],x3[:,2],color = 'g')
ax.scatter(x1[-1,0],x1[-1,1],x1[-1,2],color = 'b', marker = 'o', s=30, label = 'Mass 1')
ax.scatter(x2[-1,0],x2[-1,1],x2[-1,2],color = 'm', marker = 'o',s=90, label = 'Mass 2')
ax.scatter(x3[-1,0],x3[-1,1],x3[-1,2],color = 'g', marker = 'o',s=60, label = 'Mass 3')
ax.legend()
Doing a project for physics class. vPython documentation is not very good I think and it's a bit confusing. I need to move a ball, which currently is being moved by mouse, but I need to make this work with 2 players, so I need to use keyboard events.
Currently this is the code:
#GlowScript 2.7 VPython
scene.range = 30
scene.forward = vec(0,-0.25,-1)
#red side of the field
redField = box()
redField.size = vec(40,1,60)
redField.pos= vec(-20,0,0)
redField.color = color.red
#blue side of the field
redField = box()
redField.size = vec(40,1,60)
redField.pos= vec(20,0,0)
redField.color = color.blue
cueBall = sphere()
cueBall.radius = 1.5
cueBall.pos = vec(0,2,0)
cueBall.vel = vec(3,0,0) # velocity in m/s
cueBall.mass = 2.0
blueBall = sphere()
blueBall.radius = 1.5
blueBall.pos = vec(4,2,0)
blueBall.color = color.blue
blueBall.mass = 1.5
blueBall.vel = vec(0,0,0)
blueBall.force = arrow(axis = vec(0,0,0), color = color.blue)
rail1 = box()
rail1.texture = {'file': "https://i.imgur.com/ss5OcnL.jpg"}
rail1.size = vec(3,3,55)
rail1.pos = vec(-39,1,0)
rail2 = box()
rail2.texture = {'file': "https://i.imgur.com/ss5OcnL.jpg"}
rail2.size = vec(3,3,55)
rail2.pos = vec(39,1,0)
rail3 = box()
rail3.texture = {'file': "https://i.imgur.com/ss5OcnL.jpg"}
rail3.size = vec(80,3,3)
rail3.pos = vec(0,1,29)
rail4 = box()
rail4.texture = {'file': "https://i.imgur.com/ss5OcnL.jpg"}
rail4.size = vec(80,3,3)
rail4.pos = vec(0,1,-29)
redBall = sphere()
redBall.radius = 1.5
redBall.pos = vec(-3,2,0)
redBall.color = color.red
redBall.force = arrow(axis = vec(0,0,0), color = color.red)
redBall.vel = vec(0,0,0)
redBall.mass = 1.5
yBall = sphere()
yBall.radius = 1.5
yBall.pos = vec(-9,2,0)
yBall.color = color.yellow
yBall.vel = vec(0,0,0)
yBall.mass = 1.5
yBall.force = arrow(axis = vec(0,0,0), color = color.yellow)
rail = []
rail.append(rail1, rail2, rail3, rail4)
ball = []
ball.append(cueBall, blueBall, redBall, yBall)
ball[0].force = arrow(axis = vec(0,0,0), color = color.white)
drag = False
chosenObject = None
scene.bind("mousedown", down)
scene.bind("mousemove", move)
scene.bind("mouseup", up)
def down():
nonlocal drag, chosenObject
chosenObject = scene.mouse.pick()
drag = True
def move():
nonlocal drag, chosenObject
if (drag == True):
chosenObject.force.axis = scene.mouse.pos - chosenObject.pos
chosenObject.force.pos = chosenObject.pos
chosenObject.force.axis.y = 0
def up():
nonlocal drag, chosenObject
chosenObject.force.axis = vec(0,0,0)
chosenObject = None
drag = False
elasticConst = 500
dt = 0.01
time = 0
while (True):
rate(1/dt)
for i in range(len(ball)):
ball[i].vel = ball[i].vel + ( ball[i].force.axis * dt / ball[i].mass )
ball[i].force.pos = ball[i].pos
for i in range(len(ball)):
for j in range(len(ball)):
if (i == j): continue
separation = ball[i].pos - ball[j].pos
contactSeparation = separation.norm() * (ball[i].radius + ball[j].radius)
if (separation.mag < contactSeparation.mag):
elasticForce = - elasticConst * (separation - contactSeparation)
ball[i].vel = ball[i].vel + (elasticForce / ball[i].mass) * dt
for i in range(len(ball)):
if ( ball[i].pos.x < rail1.pos.x + 2):
ball[i].pos.x = rail1.pos.x + 2
ball[i].vel.x = - ball[i].vel.x
if ( ball[i].pos.x > rail2.pos.x - 2):
ball[i].pos.x = rail2.pos.x - 2
ball[i].vel.x = - ball[i].vel.x
if ( ball[i].pos.z > rail3.pos.z - 2):
ball[i].pos.z = rail3.pos.z - 2
ball[i].vel.z = - ball[i].vel.z
if ( ball[i].pos.z < rail4.pos.z + 2):
ball[i].pos.z = rail4.pos.z + 2
ball[i].vel.z = - ball[i].vel.z
## for i in range(len(ball)):
# for j in range(len(hole)):
# if ((ball[i].pos - hole[j].pos).mag < ball[i].radius + hole[j].radius):
# ball[i].visible = False
for i in range(len(ball)):
ball[i].pos = ball[i].pos + ball[i].vel * dt
If you could help me understand how I could increment the position variables on keyboard.