nsolve constantly throwing ValueError - python

I'm currently trying to run this block of code.
# %% Imports
import numpy as np
import sympy as sy
import scipy as sc
alpha = sy.Symbol('alpha', real=True)
beta = sy.Symbol('beta', real=True)
s_0 = sy.Symbol('s_0', real=True)
s_1 = sy.Symbol('s_1', real=True)
s_2 = sy.Symbol('s_2', real=True)
t = sy.Symbol('t', real=True)
#run checks on S(t) whether S(t) > S0 for current iteration
def main():
# A. Defining equations to constant variables to be called later
#S(t) > S0, (S(t) + β/α)*S(t) > 0
MODEL_1_1 = ((beta/alpha) * (1/sy.Abs((s_0 + beta/alpha)/s_0)) * sy.exp(beta*t)) / (1 - (1/sy.Abs((s_0 + beta/alpha)/s_0) * sy.exp(beta*t)))
#S(t) > S0, (S(t) + β/α)*S(t) < 0
MODEL_1_2 = -((beta/alpha) * (1/sy.Abs((s_0 + beta/alpha)/s_0)) * sy.exp(beta*t)) / (1 + (1/sy.Abs((s_0 + beta/alpha)/s_0) * sy.exp(beta*t)))
#S(t) < S0, (S(t) + β/α)*S(t) > 0
MODEL_1_3 = ((beta/alpha) * (1/sy.Abs((s_0 + beta/alpha)/s_0)) * sy.exp(-sy.Abs(beta)*t)) / (1 - (1/sy.Abs((s_0 + beta/alpha)/s_0) * sy.exp(-sy.Abs(beta)*t)))
#S(t) < S0, (S(t) + β/α)*S(t) > 0
MODEL_1_4 = -((beta/alpha) * (1/sy.Abs((s_0 + beta/alpha)/s_0)) * sy.exp(-sy.Abs(beta)*t)) / (1 + (1/sy.Abs((s_0 + beta/alpha)/s_0) * sy.exp(-sy.Abs(beta)*t)))
#---------------------------------------------------------------
# B. Initializing values
stock_price = [25725, 25600, 24600]
#---------------------------------------------------------------
# C. Get 2 functions for every t = 1 and t = 2
## C.1. processing t1
if (stock_price[1] > stock_price[0]):
eq1 = MODEL_1_1.subs([(t,1),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) > 0
eq2 = MODEL_1_2.subs([(t,1),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) < 0
else:
eq1 = MODEL_1_3.subs([(t,1),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) > 0
eq2 = MODEL_1_4.subs([(t,1),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) < 0
#print(eq1)
#print(eq2)
## C.2. processing t2
if (stock_price[2] > stock_price[0]):
eq3 = MODEL_1_1.subs([(t,2),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) > 0
eq4 = MODEL_1_2.subs([(t,2),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) < 0
else:
eq3 = MODEL_1_3.subs([(t,2),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) > 0
eq4 = MODEL_1_4.subs([(t,2),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) < 0
#print(eq3)
#print(eq4)
#------------------------------------------------
# D. Run 4 different solution, get 4 sets of possible (α,β) pair
## D.1. eq1 vs. eq3 -- (S(1) + β/α)*S(1) > 0, (S(2) + β/α)*S(2) > 0
print(eq1)
print(eq3)
sol1 = sy.solvers.nsolve([sy.Eq(eq1,stock_price[1]), sy.Eq(eq3,stock_price[2])],[alpha,beta],[-1,1])
print(sol1)
## D.2. eq2 vs. eq3 -- (S(1) + β/α)*S(1) < 0, (S(2) + β/α)*S(2) > 0
## D.3. eq1 vs. eq4 -- (S(1) + β/α)*S(1) > 0, (S(2) + β/α)*S(2) < 0
## D.4. eq2 vs. eq4 -- (S(1) + β/α)*S(1) < 0, (S(2) + β/α)*S(2) < 0
#check for contradictions against initial condition
#return values that satisfies all condition
#run t = 3 based on the iteration
#repeat
main()
However it keeps throwing
Could not find root within given tolerance. (655317900.776688019361 >
2.16840434497100886801e-19) Try another starting point or tweak arguments.
or
matrix is numerically singular
whenever I try to tweak around the initial starting point.
Could anyone help / suggest alternatives to nsolve for this particular function?
Edit 1:
adding tracebacks
Traceback (most recent call last):
File "D:\SKRIPSI ANDREE\Code\model1.py", line 76, in <module>
main()
File "D:\SKRIPSI ANDREE\Code\model1.py", line 64, in main
sol1 = sy.solvers.nsolve([sy.Eq(eq1,stock_price[1]), sy.Eq(eq3,stock_price[2])],[alpha,beta],[-1,1])
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\utilities\decorator.py", line 88, in func_wrapper
return func(*args, **kwargs)
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\solvers\solvers.py", line 2954, in nsolve
x = findroot(f, x0, J=J, **kwargs)
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\mpmath\calculus\optimization.py", line 969, in findroot
for x, error in iterations:
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\mpmath\calculus\optimization.py", line 660, in __iter__
s = self.ctx.lu_solve(Jx, fxn)
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\mpmath\matrices\linalg.py", line 226, in lu_solve
A, p = ctx.LU_decomp(A)
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\mpmath\matrices\linalg.py", line 136, in LU_decomp
raise ZeroDivisionError('matrix is numerically singular')
ZeroDivisionError: matrix is numerically singular

Related

Is there a way to create a sign function in python?

import re
import math
from random
import randint
import hashlib
P = (-0.15, 2.645)
Q = (0.7, 2.71)
max_mod = 1.158 * 10 ** 77
def SHA256_INT(text):
return int(f'0x{hashlib.sha256(text.encode("ascii")).hexdigest()}', 0)
def ecc_double_slope(P):
slope = (3 * P[0] ** 2) / (2 * P[1])
return slope
def ecc_add(P, Q, slope):
xr = slope ** 2 - P[0] - Q[0]
yr = slope * (P[0] - xr) - P[1]
return (xr, yr)
def ecc_double(P):
slope = ecc_double_slope(P)
sum0 = ecc_add(P, P, slope)
return sum0
def ecc_double_for(P, limit):
lis = []
for i in range(limit):
b = ecc_double(P)
P = b
lis.append((2 ** i, b))
return lis
def greedy2(number):
x = 0
dub_lis = []
add_lis = []
while 2 ** x < number:
dub_lis.append(2 ** x)
x += 1
x -= 1
n = 2 ** x
while n != number:
y = x
while n + (2 ** y) > number:
y -= 1
n += (2 ** y)
x += 1
add_lis.append(2 ** y)
return len(dub_lis), add_lis
def ecc_main_add(P, Q):
x1 = P[0]
y1 = P[1]
x2 = Q[0]
y2 = Q[1]
slope = (y2 - y1) / (x2 - y1)
xr = slope ** 2 - x1 - x2
yr = slope * (x1 - xr) - y1
return xr, yr
def gen_points(gen, points):
if gen == 1:
return points
elif gen > 1:
if type(points) == int:
point_curve = (points, math.sqrt(points ** 3 + 7))
elif type(points) == tuple:
point_curve = points
point_steps = greedy2(gen)
point_dub = point_steps[0]
point_add = point_steps[1]
dub_list = ecc_double_for(point_curve, point_dub)
for i in point_add:
b = ecc_main_add(dub_list[int(math.log(i, 2))][1], dub_list[-1][1])
return b, gen
elif gen == 0:
return 0
def sign(messsage, private_key, public_key, G):
global max_mod
msg_hash = SHA256_INT(messsage)
randnum = randint(2, max_mod)
r = gen_points(randnum, G)[0]
r_x = r[0]
msg_hash = SHA256_INT(messsage)
s = (r_x * private_key + msg_hash) / randnum
p1 = gen_points(msg_hash/s, G)
p2 = gen_points(r_x/s, public_key)
p3 = ecc_main_add(p1, p2)
return p3
pub, priv = gen_points(9756, P)
print(sign('hello', priv, pub, P))
Hello, I'm trying to implement a way to sign messages using this tutorial:
https://learnmeabitcoin.com/beginners/digital_signatures_signing_verifying
I've tried to follow the tutorial before, but it's either my key generation is wrong, I didn't follow the tutorial correctly, or both.
My current code generates an error, I've already debugged it and it generates the error: TypeError: 'NoneType' object is not subscriptable.
Does anyone know how to solve this?

Python: Write-Length Control

I am trying to create a specific output pattern for a textfile I wanted to later load into C++.
I wrote a file in Python that creates random coordinates and movement values in a circle.
The output is supposed to have the output:
Place_1 Place_2 Place_3 Movement_1 Movement_2 Movement_3\n
Place_1 Place_2 Place_3 Movement_1 Movement_2 Movement_3\n
Place_1 Place_2 Place_3 Movement_1 Movement_2 Movement_3
The Code is use is
import numpy as np
file = open('log.txt', 'a')
def f(n, center, radius, ecc):
pos = np.zeros((n,6))
r = ecc * radius
for i in range(n):
while 1:
x_1 = -1 + 2 * np.random.rand(1)
x_2 = -1 + 2 * np.random.rand(1)
if (x_1*x_1 + x_2*x_2)<1 :
pos[i,0] = center[0] + r * 2 * x_1 * np.sqrt(1 - x_1*x_1 - x_2*x_2)
pos[i,1] = center[1] + r * 2 * x_2 * np.sqrt(1 - x_1*x_1 - x_2*x_2)
pos[i,2] = center[2] + r * (1 - 2 * (x_1*x_1 + x_2*x_2))
pos[i,3] = (-1 + 2 * np.random.rand(1))
pos[i,4] = (-1 + 2 * np.random.rand(1))
pos[i,5] = (-1 + 2 * np.random.rand(1))
break
string = str(pos[i,:]).strip('[]').rstrip('\n')
file.write(string)
return
f(10000, np.array((127,127,127)), 92, 0.9)
file.close()
The log I create is however very badly formated. How can I get the required format?
You're going to a lot of trouble here that you don't need. This seems to solve the problem, simply.
import numpy as np
file = open('log.txt', 'a')
def f(n, center, radius, ecc):
r = ecc * radius
for i in range(n):
while 1:
pos = [0]*6
x_1 = -1 + 2 * np.random.rand(1)[0]
x_2 = -1 + 2 * np.random.rand(1)[0]
if (x_1*x_1 + x_2*x_2) < 1:
pos[0] = center[0] + r * 2 * x_1 * np.sqrt(1 - x_1*x_1 - x_2*x_2)
pos[1] = center[1] + r * 2 * x_2 * np.sqrt(1 - x_1*x_1 - x_2*x_2)
pos[2] = center[2] + r * (1 - 2 * (x_1*x_1 + x_2*x_2))
pos[3] = (-1 + 2 * np.random.rand(1)[0])
pos[4] = (-1 + 2 * np.random.rand(1)[0])
pos[5] = (-1 + 2 * np.random.rand(1)[0])
break
print(*pos, file=file)
f(10000, np.array((127,127,127)), 92, 0.9)
file.close()
A solution without numpy:
import math
import random
file = open('log.txt', 'a')
def f(n, center, radius, ecc):
r = ecc * radius
for _ in range(n):
pos = [0]*6
while 1:
x_1 = 2 * random.random() - 1
x_2 = 2 * random.random() - 1
vector = x_1*x_1 + x_2*x_2
if vector < 1:
break
pos[0] = center[0] + r * 2 * x_1 * math.sqrt(1 - vector)
pos[1] = center[1] + r * 2 * x_2 * math.sqrt(1 - vector)
pos[2] = center[2] + r * (1 - 2 * vector)
pos[3] = 2 * random.random() -1
pos[4] = 2 * random.random() -1
pos[5] = 2 * random.random() -1
print(*pos, file=file)
f(10000, (127,127,127), 92, 0.9)
file.close()
Use np.savetxt:
import numpy as np
def f(n, center, radius, ecc):
pos = np.zeros((n,6))
r = ecc * radius
for i in range(n):
while 1:
x_1 = -1 + 2 * np.random.rand(1)
x_2 = -1 + 2 * np.random.rand(1)
if (x_1*x_1 + x_2*x_2)<1 :
pos[i,0] = center[0] + r * 2 * x_1 * np.sqrt(1 - x_1*x_1 - x_2*x_2)
pos[i,1] = center[1] + r * 2 * x_2 * np.sqrt(1 - x_1*x_1 - x_2*x_2)
pos[i,2] = center[2] + r * (1 - 2 * (x_1*x_1 + x_2*x_2))
pos[i,3] = (-1 + 2 * np.random.rand(1))
pos[i,4] = (-1 + 2 * np.random.rand(1))
pos[i,5] = (-1 + 2 * np.random.rand(1))
break
np.savetxt('file.txt',pos,delimiter=';')
return
f(100, np.array((127,127,127)), 92, 0.9)
For the formatting issue you can make the coordinates into characters (What I mean is that turn coordinates into a character that would be printed like _ or / something like that) Also you can put empty space in a print like print(" Hello.") also to go to a different line in the console do print("\n Hello."). This probably was not what you were looking for but I hope this somewhat helps.

python - TypeError: only integer scalar arrays can be converted to scalar index, why?

I am running scipy.optimize.minimize to minimize the following function,
def gas_midas_ll(params, low_freq, hi_freq, lag='beta', dist='normal', outer=False):
T = low_freq[0]
nx = hi_freq[1]
omega = params[0]
A1 = params[1]
A2 = params[2]
B = params[3]
phi1 = params[4]
phi2= params[5]
f = np.ones((T+1,1)) ## <--- this is where I think the Traceback ends
s1 = np.ones((T+1,1))
s2 = np.ones((nx,T+1))
f[0] = omega/(1-B)
low_freq = np.append(0,low_freq).reshape((T+1,1))
hi_freq = np.c_[np.zeros((nx,1)),hi_freq]
s2[:,0:1] = hi_freq[:,0:1]**2 - f[0]
if dist == 'normal':
s1[0] = low_freq[0]**2 - f[0]
if lag == 'beta':
for t in range(1,T+1):
f[t] = omega + A1*s1[t-1] + A2*np.sum(beta_lag(phi1,phi2,hi_freq)*s2[:,t-1:t]) + B*f[t-1]
s1[t] = low_freq[t]**2 - f[t]
s2[:,t:t+1] = hi_freq[:,t:t+1]**2 - f[t]
elif lag == 'almon':
phi = np.array((phi1,phi2)).reshape((2,1))
for t in range(1,T+1):
f[t] = omega + A1*s1[t-1] + A2*np.sum(almon_q(phi,hi_freq)*s2[:,t-1:t]) + B*f[t-1]
s1[t] = low_freq[t]**2 - f[t]
s2[:,t:t+1] = hi_freq[:,t:t+1]**2 - f[t]
f = f[1:]
s1 = s1[1:]
s2 = s2[:,1:]
low_freq = low_freq[1:]
hi_freq = hi_freq[:,1:]
constants = (1/2)*np.log(2*np.pi)
ll = -((low_freq**2)/(2*f)) - constants - (1/2)*np.log(f)
elif dist == 't':
v = params[6]
s1[0] = ((v+1)*low_freq[0]**2)/((v-2)+(low_freq[0]**2)/f[0]) - f[0]
if lag == 'beta':
for t in range(1,T+1):
f[t] = omega + B*f[t-1] + A1*s1[t-1] + A2*np.sum(beta_lag(phi1,phi2,hi_freq)*s2[:,t-1:t])
s1[t] = ((v+1)*low_freq[t]**2)/((v-2)+(low_freq[t]**2)/f[t]) - f[t]
s2[:,t:t+1] = hi_freq[:,t:t+1]**2 - f[t]
elif lag == 'almon':
phi = np.array((phi1,phi2)).reshape((2,1))
for t in range(1,T+1):
f[t] = omega + B*f[t-1] + A1*s1[t-1] + A2*np.sum(almon_q(phi,hi_freq)*s2[:,t-1:t])
s1[t] = ((v+1)*low_freq[t]**2)/((v-2)+(low_freq[t]**2)/f[t]) - f[t]
s2[:,t:t+1] = hi_freq[:,t:t+1]**2 - f[t]
f = f[1:]
s1 = s1[1:]
s2 = s2[:,1:]
low_freq = low_freq[1:]
hi_freq = hi_freq[:,1:]
delta = (1/2)*(np.log(v-2)+np.log(np.pi))
G1 = np.log(special.gamma((v+1)/2))
G2 = np.log(special.gamma(v/2))
constants = G1 - G2 - delta
ll = constants - (1/2)*np.log(f) - ((v+1)/2)*np.log(1+(low_freq**2)/(f*(v-2)))
if outer == True:
return -ll
else:
return -np.sum(ll)
I get the error message,
Traceback (most recent call last):
File "C:\Users\***\SpyderProjects\SeminarW1920\draft5.py", line 320, in <module>
bounds=gas_midas_nbounds_beta)
File "C:\Users\***\Anaconda3\lib\site-packages\scipy\optimize\_minimize.py", line 618, in minimize
constraints, callback=callback, **options)
File "C:\Users\***\Anaconda3\lib\site-packages\scipy\optimize\slsqp.py", line 399, in _minimize_slsqp
fx = func(x)
File "C:\Users\***\Anaconda3\lib\site-packages\scipy\optimize\optimize.py", line 327, in function_wrapper
return function(*(wrapper_args + args))
File "C:\Users\***\SpyderProjects\SeminarW1920\likelihoodFunctions2.py", line 153, in gas_midas_ll
f = np.ones((T+1,1))
File "C:\Users\***\Anaconda3\lib\site-packages\numpy\core\numeric.py", line 207, in ones
a = empty(shape, dtype, order)
TypeError: only integer scalar arrays can be converted to a scalar index
Which to me it says, there is an error when calling np.ones()? But I don't understand why? I have similar functions, which I also minimize with scipy.optimize.minimize and none of them throw errors like these. Maybe the error is somewhere else and the erros message is not pointing in the right direction?

error while writing an L-BFGS minimizing function in python using numpy

I am trying to create an L-BFGS minimizing function for a initial guess of a symmetric matrix (to simplify taking the first hessian). The language I am using is python, and the library we are allowed to use is numpy. While there may be other errors I am as yet unaware of, I would like help solving a specific error where my random matrix A (nxn) is being interpreted as a 'str'. Thank you!
I have the following code:
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 23 16:33:22 2020
#author: 12064
"""
n = input("input the dimension of the function : ")
x_row = np.array(x)
x_column = np.transpose(x_row)
A = np.random.randn(n,n)
B = np.transpose(A)
f = np.matmul(B, A)
m = 5
k = 0
alpha = 1
epsilon = 10 ** -4
#define var's
gradf = np.gradient(f)
gradf_at_x = gradf.dot(x)
hessian_0 = np.gradient(gradf)
g[k] = gradf.dot(x[k])
condition_1 = g[k].dot(g[k])
p_T[k] = np.array(n)
p[k] = np.transpose(p_T)
#index an array
memory1 = np.linspace(change_g[k-m], change_g[k])#
memory2 = np.linspace(change_x[k-m], change_x[k])
memory3 = np.linspace(alpha[k-m], alpha[k])
memory4 = np.linspace(p[k-m], p[k])
memory5 = np.linspace(x[k-m], x[k+1])
memory6 = np.linspace(g[k-m], g[k])
def myminimizer(x, f):
if np.sqrt(condition_1) < epsilon:
#magnitude of the gradient (square root of dot product of grad f at x'k) <= epsilon (10^-4)
return x, k
else:
if k < 1:
p[k] = -1 * (hessian_0 * gradf_at_x)
else:
p = -1 * r
omega = f.dot(x[k] + alpha[k]*p[k])
while 1:
alpha = r * alpha
x[k+1] = x[k] + alpha[k] * p[k]
change_x = x[k+1] - x[k]
change_g = g[k+1] - g[k]
q[k] = g[k]
for i in range(k-m, k):
alpha[i] = p[i] * change_x_transpose * q[i]
q = q - alpha[i] * change_g[i]
r = H[k] * q
for i in range (k-m, k):
Beta[i] = p[i] * change_g_transpose[i] * r[i]
r = r + change_x * (alpha[i] - Beta[i]) #check that its Beta[i]
k += 1
if np.sqrt(condition_1) < epsilon:
#magnitude of the gradient (square root of dot product of grad f at x'k) <= epsilon (10^-4)
print ("x, k")
print ("x is your omtimizer of f")
else:
if k < 1:
p[k] = -1 * (hessian_0 * gradf_at_x)
else:
p = -1 * r
omega = f.dot(x[k] + alpha[k]*p[k])
while 1:
alpha = r * alpha
x[k+1] = x[k] + alpha[k] * p[k]
change_x = x[k+1] - x[k]
change_g = g[k+1] - g[k]
q[k] = g[k]
for i in range(k-m, k):
alpha[i] = p[i] * change_x_transpose * q[i]
q = q - alpha[i] * change_g[i]
r = H[k] * q
for i in range (k-m, k):
Beta[i] = p[i] * change_g_transpose[i] * r[i]
r = r + change_x * (alpha[i] - Beta[i]) #check that its Beta[i]
k += 1
#END CODE#
My error message is:
runfile('C:/Users/12064/Desktop/Duncan/assignments/ass 4 4realsies.py', wdir='C:/Users/12064/Desktop/Duncan/assignments')
input the dimension of the function : 10
Traceback (most recent call last):
File "<ipython-input-41-e748654944e8>", line 1, in <module>
runfile('C:/Users/12064/Desktop/Duncan/assignments/ass 4 4realsies.py', wdir='C:/Users/12064/Desktop/Duncan/assignments')
File "C:\Users\12064\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "C:\Users\12064\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/12064/Desktop/Duncan/assignments/ass 4 4realsies.py", line 11, in <module>
A = np.random.randn(n,n)
File "mtrand.pyx", line 1425, in mtrand.RandomState.randn
File "mtrand.pyx", line 1555, in mtrand.RandomState.standard_normal
File "mtrand.pyx", line 167, in mtrand.cont0_array
TypeError: 'str' object cannot be interpreted as an integer
Any directions on why the matrix I'm trying to create is causing this error would be greatly appreciated!
convert input string into integer:
n = int(input("input the dimension of the function : "))

PyDSTool step of integration

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?

Categories

Resources