I am new to python, transiting from Matlab. I wrote the following code to solve a nonlinear equation system but somehow failed in python. It worked in matlab fsolve for many initial values unless I put an extremely large number. But it only works for python fsolve if the initial value is close enough to the solution. I don't always have good initial guess to the problem so I want it to work most of the time. Thank you very much! Solution is [0.003,0.0053] according to Matlab.
Python code
param = {'r': 0.04,
'mu': 0.112,
'delta': 0.02,
'alpha': 0.35,
'g': 0.0187 + 0.5*0.16*0.16,
'sigma': 0.20,
'xi0': 0.02,
'xi1':1.05,
'lambda0':0.02,
'lambda1':1.05};
param['sgsq'] = 0.5*param['sigma']**2;
param['g0'] = param['g'] - (param['mu'] - param['r']) - param['sgsq'];
#%% Polynomial
import numpy as np
import numpy.polynomial.polynomial as poly
import scipy.optimize as spyopt
param['coef'] = (- (param['r']+param['delta']), (param['g0']+param['delta']
-param['sgsq']), param['sgsq'])
charfun = poly.Polynomial(param['coef'])
param['psi'] = np.max(poly.polyroots(param['coef']))
param['halpha'] = poly.polyval(param['alpha'],param['coef'])
def lumpyfun(x0, param0):
xstar,B = x0
AIPx = - np.power(xstar,param0['alpha']) / param0['halpha']
BigA = ((1.0-param0['alpha'])*(B**param0['alpha'])/(1.0-param0['psi'])/param0['halpha']
+ (param0['lambda1']-param0['lambda0'])/(1.0-param0['psi']))
vprimex = param0['alpha']*AIPx/xstar + param0['psi']*np.power((xstar/B),(param0['psi']-1.0)) * BigA/B
vprimeB = (param0['psi']-param0['alpha'])*np.power(B,param0['alpha']-1.0)/(1.0-param0['psi'])/param0['halpha'] + param0['psi']*(param0['lambda1']-param0['lambda0'])/(1.0-param0['psi'])/B
diffy = (AIPx + np.power(xstar/B,param0['psi']) * BigA - xstar*vprimex - param0['lambda1'], vprimex - vprimeB)
return diffy`def lumpyfun(x0, param0):
#%% Solve the problem
#worked
x0 = np.multiply(np.sqrt(-param['halpha']),(1.0,2.0))/100.0
#lumpyfun(x0,param)
spyopt.fsolve(lumpyfun, x0, args=param)
# not worked
x0 = np.multiply(np.sqrt(-param['halpha']),(1.0,2.0))/10.0
spyopt.fsolve(lumpyfun, x0, args=param, maxfev = 5000000)
Matlab code:
r = 0.04;
mu = 0.112;
delta = 0.02;
alpha = 0.35;
g = 0.0187 + 0.5*0.16*0.16 ; % 0.0187 + 0.5*sigma*sigma;
sigma = 0.20; % 0.16 default;
a2 = 0.5*sigma*sigma;
g0 = g - (mu-r) - a2; % risk-neutral growth;
lambda0 = 0.02;
lambda1 = 1.05;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%h = #(x) sgsq05*x^2 + (mu+delta-sgsq05)*x - (r+delta);
coef = [a2, (g0+delta-a2), - (r+delta)];
halpha = polyval(coef,alpha);
phi = max(roots(coef))
x0 = realsqrt(-halpha)*[1;2]/10;
options = optimoptions('fsolve','Display','off','MaxFunEvals',2000);
sol = fsolve(#(x) diffinvestmentoption(x,phi,alpha,lambda1,lambda0,halpha), x0, options);
function [diffy,X] = diffinvestmentoption(xin,phi,alpha,lambda1,lambda0,halpha)
xstar = xin(1);
B = xin(2);
AIPx = -xstar.^alpha / halpha;
%AIPB = -B.^alpha / halpha;
BigA = (1-alpha)*(B^alpha)/(1-phi)/halpha + (lambda1-lambda0)/(1-phi);
vprimex = alpha*AIPx/xstar + phi*(xstar/B)^(phi-1) * BigA/B;
vprimeB = (phi-alpha)*(B^(alpha-1))/(1-phi)/halpha + phi*(lambda1-lambda0)/(1-phi)/B;
diffy = [AIPx + (xstar/B)^phi * BigA - xstar*vprimex - lambda1;
vprimex - vprimeB];
Related
I have been trying to simulate Two Temperature Model using fipy
the math of the model:
C_e(∂T_e)/∂t=∇[k_e∇T_e ]-G(T_e-T_ph )+ A(r,t)
C_ph(∂T_ph)/∂t=∇[k_ph∇T_ph] + G(T_e-T_ph)
the source supposed to heat the electrons T_e, then the heat transferred to phonons T_ph through G, when T_ph reach melting point for example 2700 K, some of heat (360000 J) goes as latent heat before melting.
here is my code:
from fipy.tools import numerix
import scipy
import fipy
import numpy as np
from fipy import CylindricalGrid1D
from fipy import Variable, CellVariable, TransientTerm, DiffusionTerm, Viewer, LinearLUSolver, LinearPCGSolver, \
LinearGMRESSolver, ImplicitDiffusionTerm, Grid1D, ImplicitSourceTerm
## Mesh
nr = 50
dr = 1e-7
# r = nr * dr
mesh = CylindricalGrid1D(nr=nr, dr=dr, origin=0)
x = mesh.cellCenters[0]
# Variables
T_e = CellVariable(name="electronTemp", mesh=mesh,hasOld=True)
T_e.setValue(300)
T_ph = CellVariable(name="phononTemp", mesh=mesh, hasOld=True)
T_ph.setValue(300)
G = CellVariable(name="EPC", mesh=mesh)
t = Variable()
# Material parameters
C_e = CellVariable(name="C_e", mesh=mesh)
k_e = CellVariable(name="k_e", mesh=mesh)
C_ph = CellVariable(name="C_ph", mesh=mesh)
k_ph = CellVariable(name="k_ph", mesh=mesh)
C_e = 4.15303 - (4.06897 * numerix.exp(T_e / -85120.8644))
C_ph = 4.10446 - 3.886 * numerix.exp(-T_ph / 373.8)
k_e = 0.1549 * T_e**-0.052
k_ph =1.24 + 16.29 * numerix.exp(-T_ph / 151.57)
G = numerix.exp(21.87 + 10.062 * numerix.log(numerix.log(T_e )- 5.4))
# Boundary conditions
T_e.constrain(300, where=mesh.facesRight)
T_ph.constrain(300, where=mesh.facesRight)
# Source 𝐴(𝑟,𝑡) = 𝑎𝐷(𝑟)𝜏−1 𝑒−𝑡/𝜏 , 𝐷(𝑟) = 𝑆𝑒 exp (−𝑟2/𝜎2)/√2𝜋𝜎2
sig = 1.0e-6
tau = 1e-15
S_e = 35
d_r = (S_e * 1.6e-9 * numerix.exp(-x**2 /sig**2)) / (numerix.sqrt(2. * 3.14 * sig**2))
A_t = numerix.exp(-t/tau)
a = (numerix.sqrt(2. * 3.14)) / (3.14 * sig)
A_r = a * d_r * tau**-1 * A_t
eq0 = (
TransientTerm(var=T_e, coeff=C_e) == \
DiffusionTerm(var=T_e, coeff=k_e) - \
ImplicitSourceTerm(coeff=G, var=T_e) + \
ImplicitSourceTerm(var=T_ph, coeff=G) + \
A_r)
eq1 = (TransientTerm(var=T_ph, coeff=C_ph) == DiffusionTerm(var=T_ph, coeff=k_ph) + ImplicitSourceTerm(var=T_e, coeff=G) - ImplicitSourceTerm(coeff=G, var=T_ph))
eq = eq0 & eq1
dt = 1e-18
steps = 7000
elapsed = 0.
vi = Viewer((T_e, T_ph), datamin=0., datamax=2e4)
for step in range(steps):
T_e.updateOld()
T_ph.updateOld()
vi.plot()
res = 1e100
dt *= 1.01
count = 0
while res > 1:
res = eq.sweep(dt=dt, underRelaxation=0.5)
print(t, res)
t.setValue(t + dt)
As I understood I can include the latent heat as source term as sink in eq1, or add a gaussian peak to C_ph and the peak center should be around melting point.
I have no idea which one is better and more stable, I have no idea how to implement any one of them .
please help me with that
Based on the comments (please edit that into the question), change eq1 to
eq1 = (TransientTerm(var=T_ph, coeff=C_ph)
== DiffusionTerm(var=T_ph, coeff=k_ph)
+ ImplicitSourceTerm(var=T_e, coeff=G)
- ImplicitSourceTerm(coeff=G, var=T_ph)
+ (1/numerix.sqrt(2*numerix.pi * sig2)) * numerix.exp(-(T_ph - 1850)**2 / 2 * sig2)))
It will be evaluated explicitly, but it will update whenever T_ph updates.
I have been trying to implement a model of unstable glacier flow in Python, solving the ODEs in scipy, with the RK45 method.
The original model publication can be found here.
Now, I think I understand what is going on with the error but I cannot find a way to fix it.
I don't know if it comes from my implementation or from the ODEs themselves.
I've been through the units several times, checking that all times were in seconds, all distances in meters and so on.
I've tried with different t_eval and even different values of certain constants, but not been able to solve my problem.
I started by creating a class with all constants.
import numpy as np
import scipy.integrate
import matplotlib.pyplot as plt
import astropy.units as u
SECONDS_PER_YEAR = 3600*24*365.15
class Cst:
#Glenn's flow Law
A = 2.4e-25
n = 3.
#Standard physical constants
g = 10.#*(u.m)*(u.second**-2)
rho = 916#*(u.kilogram*(u.m**-3))
#Thermodynamics
cp = 2000#**(u.Joule)*(u.kilogram**-1)*(u.Kelvin**-1)
L = 3.3e5#*(u.Joule)*(u.kilogram**-1)
k = 2.1 #*(u.Watt)*(u.m**-1)*'(u.Kelvin**-1)'
DDF = 0.1/SECONDS_PER_YEAR #*(u.m)*(u.yr**-1)*'(u.Kelvin**-1)
K = 2.3e-47#*((3600*24*365.15)**9)#*((u.kilogram**-5)*(u.m**2)*(u.second**9))
C = 9.2e13#*((u.Pascal)*(u.Joule)*(u.m**-2))
#Weertman friction law
q = 1
p = 1/3
R = 15.7#*((u.m**(-1/3))*(u.second**(1/3)))
d = 10#*u.m
sin_theta = 0.05
Tm = 0+273.15 #*u.Kelvin
T_offset = -10+273.15#*u.Kelvin
w = 0.6 #u.m
Wc = 1000.#*u.m
#Velocities
u1 = 0/SECONDS_PER_YEAR #m/s
u2 = 100/SECONDS_PER_YEAR # m/s
#Dimensionless parameters
alpha = 5.
Then I declared the problem-specific parameters specified in the paper:
#All values are from Table 1
a0 = 1./SECONDS_PER_YEAR#* m/s (u.meter*((u.second)**-1))
l0 = 10000#*(u.meter)
E0 = 1.8e8#(Cst.g*Cst.sin_theta*a0*(l0**2))/(Cst.L*Cst.K))**(1/Cst.alpha)#*(u.Joule/u.m**2)
T0 = 10#E0/(Cst.rho*Cst.cp*Cst.d)#*u.Kelvin
w0 = 0.6#E0/(Cst.rho*Cst.L)#*u.m
N0 = 0.5#Cst.C/E0#*u.Pascal
H0 = 200 #((Cst.R*(Cst.C**Cst.q)*(a0**Cst.p)*(l0**Cst.p))/(Cst.rho*Cst.g*Cst.sin_theta*(E0**Cst.q)))**(1/(Cst.p+1))
t0 = 200 #H0/a0
u0 = 50/SECONDS_PER_YEAR#((Cst.rho*Cst.g*Cst.sin_theta*(E0**Cst.q)*a0*l0)/(Cst.R*(Cst.C**Cst.q)))**(1/(Cst.p+1))
Q0 = (Cst.g*Cst.sin_theta*a0*(l0**2))/Cst.L
S0 = ((Cst.g*Cst.sin_theta*a0*(l0**2)*Cst.Wc)/(Cst.L*Cst.K*((Cst.rho*Cst.g*Cst.sin_theta)**(1/2))))**(3/4)
lamb = ((2.*Cst.A*(Cst.rho*Cst.g*Cst.sin_theta)**Cst.n)*(H0**(Cst.n+1)))/((Cst.n+2)*u0)
chi = N0/(Cst.rho*Cst.g*H0)
gamma = 0.41
kappa = 0.7
phi = 0.2
delta = 66
mu = 0.2
Define the model :
def model(t, x):
#Initial values
H_hat = x[0]
E_hat = x[1]
#Thickness
H = H_hat*H0
#Enthalpy
E_hat_plus = max(E_hat, 0)
E_hat_minus = min(E_hat, 0)
E_plus = E_hat_plus*E0
E_minus = E_hat_minus*E0
a_hat = 1.
theta_hat = Cst.sin_theta/Cst.sin_theta
l_hat =l0/l0
T_a = 0+273.15
T = -10+273.15
# Equation 3
m_hat = (Cst.DDF*(T_a-Cst.T_offset))/a0
S_hat = 0.
T_a_hat = T_a/T0
#Equation A7
if E_plus > 0:
N = min(H/chi, 1./E_plus)
else:
N = H/chi
phi = min(1., E_plus/(H/chi))
#Equation 8
inv_p = 1./Cst.p
u = (Cst.rho*Cst.g*Cst.sin_theta/Cst.R * H * (N**(-Cst.q)))**inv_p
#Equation A7
beta = min(max(0, (u-Cst.u1)/(Cst.u2-Cst.u1)), 1)
#Equation A4
dHdt_hat = (
a_hat - m_hat
+ 1./l_hat*(
theta_hat**inv_p
* H_hat**(1.+inv_p)
* N**(-Cst.q*inv_p)
+ lamb*(theta_hat**Cst.n)
)
)
#Equation A5
dEdt_hat = 1./mu*(
theta_hat**(1+inv_p) * H_hat**(1.+inv_p) * N**(-Cst.q*inv_p)
+ gamma
+ kappa*(E_hat_minus - T_a_hat)/H_hat
- 1./l_hat * (
theta_hat * E_hat_plus**Cst.alpha
+ phi * theta_hat**(1./2) * S_hat**(4/3.)
)
+ delta * beta * m_hat
)
return [dHdt_hat, dEdt_hat]
And finally call it :
tmax = 200*SECONDS_PER_YEAR# *u.years
t = np.linspace(0, tmax, 10000)
sol = scipy.integrate.solve_ivp(model, t_span=[t[0], t[-1]], y0=[1, 1], t_eval=t, method='RK23')
print(sol)
Which yields
message: 'Required step size is less than spacing between numbers.'
nfev: 539
njev: 0
nlu: 0
sol: None
status: -1
success: False
t: array([0.])
t_events: None
y: array([[1.],
[1.]])
y_events: None
So the purpose of my code is to use inputted data points to give a gaussian plot distribution. I figured out how to make it work with a double gaussian but I'm having a lot of trouble adding a third. Im not quite sure what I'm doing wrong. 1 of the errors I keep getting is an Index Error saying that the list index is out of range. I would appreciate any help with this.
Heres my code:
from pylab import *
import numpy as np
from numpy import loadtxt
from scipy.optimize import leastsq
from scipy.optimize import least_squares
from scipy.stats import iqr
import math
import matplotlib.pyplot as plt
import sys
matplotlib.rcParams['mathtext.default'] = 'regular'
fitfunc_triple = lambda p, x: np.abs(p[0]) * exp(-0.5 * ((x - p[1]) / p[2]) ** 2) + np.abs(p[3]) * exp(
-0.5 * ((x - p[4]) / p[5]) ** 2) + np.abs(p[6]) * exp(-0.5 * ((x - p[7])/ p[8] **2 ))
fitfunc_double = lambda p, x: np.abs(p[0]) * exp(-0.5 * ((x - p[1]) / p[2]) ** 2) + np.abs(p[3]) * exp(
-0.5 * ((x - p[4]) / p[5]) ** 2)
fitfunc_single = lambda p, x: np.abs(p[0]) * exp(-0.5 * ((x - p[1]) / p[2]) ** 2)
errfunc = lambda p, x, y: (y - fitfunc(p, x))
dataR = np.loadtxt("/Users/Safi/Library/Preferences/PyCharmCE2018.1/scratches/rspecial1385.a2261.dat5", skiprows=0)
RA = dataR[:, 0]
DEC = dataR[:, 1]
VELR = dataR[:, 2]
REDSH = dataR[:, 3]
RADD = dataR[:, 4]
sl = 3E5
zbar = np.mean(REDSH)
vc = zbar * sl
VEL = vc + sl * ((REDSH - zbar) / (1 + zbar))
wdith = 200
iters = 10
sig2 = 500
binN = int(math.ceil((np.max(VEL) - np.min(VEL)) / wdith))
sys.stdout = open(str(wdith) + "_1sigma_" + str(iters) + "_sig2_" + str(sig2) + ".txt", "w")
plt.figure(1)
y, x, _ = plt.hist(VEL, binN, alpha=0.5, label='data')
x = (x[1:] + x[:-1]) / 2 # for len(x)==len(y)
data = np.vstack((x, y)).T
xdata = data[:, 0]
ydata = data[:, 1]
yerr = ydata ** 0.5
init = [10, 69500, 1200, 5, 68000, sig2]
bds = ([0, 66000, 800, 0, 66000, sig2], [50, 70000, 1750, 20, 70000, sig2 + 0.01])
def index_outlier(data):
inter_quart = iqr(data) * 1.5
bd2 = np.percentile(data, 75) + inter_quart
bd1 = np.percentile(data, 25) - inter_quart
index = []
for i in [i for i, x in enumerate(data) if x < bd1 or x > bd2]:
index.append(i)
return (index)
#### Bootstrapping Estimation Function ####
def fit_bootstrap(fitfunc, datax, datay, init, bds, sigma, iterations=iters):
errfunc = lambda p, x, y: (y - fitfunc(p, x))
# Fit first time
pfit = least_squares(errfunc, init, bounds=bds, args=(datax, datay), max_nfev=10000)
model = fitfunc(pfit.x, datax)
residuals = pfit.fun
# Random data sets are generated and fitted
ps = []
for i in range(iterations):
randomdataY = []
for k in range(len(sigma)):
randomDelta = np.random.normal(0., sigma[k], 1)
randomdataY.append(datay[k] + randomDelta)
out = np.concatenate(randomdataY)
randomfit = least_squares(errfunc, init, bounds=bds, args=(datax, out))
ps.append(randomfit.x)
# Removing outliers
# Finding outliers and indexing them
master_list = []
indexed = []
for k in range(len(ps[0])): # 0-6
it = []
for i in range(len(ps)): # 0-1000
it.append(ps[i][k])
master_list.append(it)
# indexed.append(index_outlier(master_list[k]))
# # List of outlier indicies
# flat_list=[item for sublist in indexed for item in sublist]
# no_dups= list(set(flat_list))
# # Removing bad fits
# for k in range(len(master_list)):
# for i in sorted(no_dups,reverse=True):
# del master_list[k][i]
pfit_bootstrap = []
perr_bootstrap = []
for i in master_list:
pfit_bootstrap.append(np.median(i))
perr_pos = np.round(np.percentile(i, 84) - np.median(i), 4)
perr_neg = np.round(np.median(i) - np.percentile(i, 16), 4)
perr_bootstrap.append(str('[+') + str(perr_pos) + str(',-') + str(perr_neg) + str(']'))
return (pfit_bootstrap, perr_bootstrap, residuals, pfit.nfev, master_list)
pfit, perr, residuals, nfev, master_list = fit_bootstrap(fitfunc_double, xdata, ydata, init, bds, yerr)
pfit1, perr1, residuals1, nfev1, master_list1 = fit_bootstrap(fitfunc_single, xdata, ydata, init, bds, yerr)
more_data = np.linspace(np.min(xdata), np.max(xdata), 1000)
real_func = fitfunc_double(pfit, more_data)
real_func1 = fitfunc_single(pfit1, more_data)
######## Saving Coefficients #########
A1 = pfit[0]
m1 = pfit[1]
s1 = pfit[2]
A2 = pfit[3]
m2 = pfit[4]
s2 = pfit[5]
A3 = pfit[6]
m3 = pfit[7]
s3 = pfit[8]
pecp = VEL - vc
m1p = m1 - vc
m2p = m2 - vc
m3p = m3 - vc
xdatap = xdata - vc
plt.figure(6)
plt.hist(pecp, binN, alpha=.5, label='data', color='skyblue')
xhmax = np.amax(pecp + 1500)
xhmin = np.amin(pecp - 1500)
xh = np.linspace(xhmin, xhmax, 50)
# yh1=(mlab.normpdf(xh, c[1], c[2]))
yh1 = np.abs(A1) * exp(-0.5 * (((xh - m1p) / (s1)) ** 2))
yh2 = np.abs(A2) * exp(-0.5 * (((xh - m2p) / (s2)) ** 2))
yh3 = np.abs(A3) * exp(-0.5 * (((xh - m3p) / (s3)) ** 2))
plt.plot(xh, yh1, color='b', linewidth=2)
plt.plot(xh, yh2, color='r', linewidth=2)
plt.plot(xh, yh3, color='g', linewidth=2)
plt.plot(xh, yh1 + yh2 + yh3, color='purple', linewidth=3)
# plt.errorbar(xdatap,y,xerr=wdith/2,ls='none', yerr=yerr,color='k',linewidth=2)
# plt.plot(xdatap, ydata,'.',color='k')
plt.ylim(0, np.max(ydata) + 2)
plt.xlabel('Peculiar Velocity (km/s)')
plt.ylabel('N$_{gal}$')
plt.text(-4800, 15, '$\mu_{2}$-$\mu_{1}$ = ' + str(int(m2 - m1)) + ' km/s')
plt.savefig(str(wdith) + "_1sigma_" + str(iters) + "_sig2_" + str(sig2) + "_hist.ps")
divi = -1800
memlow = np.array([[0 for x in range(2)] for y in range(1)])
memhigh = np.array([[0 for x in range(2)] for y in range(1)])
j = 0
k = 0
plt.show()
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import time
MissionName = "Mars"
savename = "Mission"
start_time = time.time()
t = np.arange(0.0, 200.0, 0.01)
vE = np.where(t<50, 2580, 0)
M0 = 2970000
mps = 12857.1429
mT = (mps * t)
m = (M0 - mT)
G = (6.67 * (10**-11))
MAarde = ((5.972) * (10**24))
rAarde = 6371000
h1 = (vE * M0/mps)
h2 = (1-(m / M0))
h3 = (np.log(M0 / m) / np.log(2.718281828)) + 1
h = h1 * h2 * h3
Fz = ((m * G * MAarde) / ((rAarde + h)**2))
Fstuw = 35100000 # - Fz
a = Fstuw / m
v = vE * (np.log(M0 / m) / np.log(2.718281828))
plt.plot(t,v)
plt.xlabel('time (s)')
plt.ylabel('Velocity (m/s)')
plt.title('Model raketmissie ' + str(MissionName))
plt.grid(True)
plt.savefig(savename + ".png")
print("it cost %s seconds to execute" % float((time.time()) - float(start_time)))
plt.show()
so it's working fine, but say i'd want vE to be 5000 when t > 150, how would i go about that? since i know how to do it with 1 but not with 2... thanks!
You may can check if concatenate works for this.
t1 = np.arange(0.0, 150.0, 0.01)
t2 = np.arange(150.0, 200.0, 0.01)
t = np.concatenate((t1,t2))
vE1 = np.where(t1<50, 2580, 0)
vE2 = np.where(t2>150, 5000, 0)
vE = np.concatenate((vE1,vE2))
I have an ODE system. I'm looking for a solution of the system using PyDSTool. I try to put the integration step, but I get an error.
import PyDSTool as ds
from PyDSTool import Par, Var
import time
from PyDSTool import *
# Declare names and initial values for (symbolic) parameters
varepsilon = pow(10, -2)
j = 2.5*pow(10, -5)
e = 3.0
y8 = lambda y1,y5,y7: 1 / (1 - 2 / y1) * math.sqrt(y5 ** 2 + (1 - 2 / y1) * (1 + y1 ** 2 * y7 ** 2))
E0 = lambda y1,y8: (1 - 2 / y1) * y8
Phi0 = lambda y1,y7: y1 ** 2 * y7
# Compute nontrivial boundary equilibrium initial condition from parameters (see reference for derivation)
u0 = -math.sqrt(-1 + math.sqrt(varepsilon ** 2 + 12) / varepsilon) * math.sqrt(2) / 6
v0 = 1 / (1 - 2 / e) * math.sqrt(j ** 2 + (1 - 2 / e) * (e ** 2 * u0 ** 2 + 1))
y08 = y8(y1=e, y5=j, y7=u0);
E = E0(y1=e, y8=y08); Phi = Phi0(y1=e, y7=u0)
z01, z03, z04, z05, z07, z08 = e, 0.0, 0.0, j, u0, v0
# Declare symbolic variables
z1, z3, z4, z5, z7, z8 = Var('z1'), Var('z3'), Var('z4'), Var('z5'), Var('z7'), Var('z8')
# Create Symbolic Quantity objects for definitions
p1 = -z1*z5/(z1 - 2);
p3 = -z1**2 *z7;
p4 = z8*(1 - 2/z1);
Q1 = -z5**2/(z1*(z1 - 2)) + (z8**2/z1**3 - z7**2)*(z1 - 2);
Q3 = 2*z5*z7/z1;
Q4 = 2*z5*z8/(z1*(z1 - 2));
c1 = z1*z7*varepsilon;
c3 = -z1*z5*varepsilon;
C = z7*varepsilon/z1 - z8*(1 - 2/z1);
d1 = -z1*z8*varepsilon;
d3 = z1*z5*varepsilon;
B = z1**2*z7 - z8*varepsilon*(1 - 2/z1);
Omega = 1/(c1*d3*p3+c3*d1*p4-c3*d3*p1);
# differential equations
z1dot = z5;
z3dot = z7;
z4dot = z8;
z5dot = Omega*(-Q1*c1*d3*p3 - Q1*c3*d1*p4 + Q1*c3*d3*p1 + B*c3*p4 + C*d3*p3 + E*d3*p3 - Phi*c3*p4);
z7dot = -Omega*(Q3*c1*d3*p3 + Q3*c3*d1*p4 - Q3*c3*d3*p1 + B*c1*p4 - C*d1*p4 + C*d3*p1 - E*d1*p4 + E*d3*p1 - Phi*c1*p4);
z8dot = Omega*(-Q4*c1*d3*p3 - Q4*c3*d1*p4 + Q4*c3*d3*p1 + B*c1*p3 - B*c3*p1 - C*d1*p3 - E*d1*p3 - Phi*c1*p3 + Phi*c3*p1);
# Build Generator
DSargs = args(name='Sining particle')
#print(dir(DSargs))
#DSargs.pars = [varepsilon, j, e]
DSargs.MaxNumPoints = 450
DSargs.MaxStepSize = 2e-2
DSargs.MinStepSize = 1e-5
DSargs.StepSize = e-2
DSargs.tdata = [0.0, 0.1]
DSargs.varspecs = args(z1=z1dot, z3=z3dot, z4=z4dot, z5=z5dot, z7=z7dot, z8=z8dot)
# Use eval method to get a float value from the symbolic definitions given in
# terms of parameter values
DSargs.ics = args(z1=z01, z3=z03, z4=z04, z5=z05, z7=z07, z8=z08)
ode = Generator.Vode_ODEsystem(DSargs)
t = time.time()
result = ode.compute('test')
print("time for integration: %f" %(time.time() - t))
pts = result.sample()
plt.plot(pts['t'], pts['z7'], label='x')
plt.legend()
plt.xlabel('t')
plt.show()
Through the next lines I get an the error:
DSargs.MaxNumPoints = 450
DSargs.MaxStepSize = 2e-2
DSargs.MinStepSize = 1e-5
DSargs.StepSize = e-2
Traceback (most recent call last):
File "C:\Users\mykola\Downloads\pydstool.py", line 65, in <module>
ode = Generator.Vode_ODEsystem(DSargs)
File "C:\Users\mykola\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PyDSTool\Generator\Vode_ODEsystem.py", line 47, in __init__
ODEsystem.__init__(self, kw)
File "C:\Users\mykola\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PyDSTool\Generator\ODEsystem.py", line 61, in __init__
self.checkArgs(kw)
File "C:\Users\mykola\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PyDSTool\Generator\baseclasses.py", line 1069, in checkArgs
raise PyDSTool_KeyError('Invalid keyword arguments for this class')
PyDSTool.errors.PyDSTool_KeyError: 'Invalid keyword arguments for this class'
The library PyDSTool has very little training information in internet.
What I do wrong?. And how to correctly determine the step of integration?