I have setup a function that iterates over combinations of chars to form strings.
It is recursive to itself, the recursive call looks like that:
testG(charNum - 1, arr2)
But when i call the entire function, I get this error:
>>> testSpeedGPU()
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
testSpeedGPU()
File "F:\Script Projects#\HASHFinder.py", line 90, in testSpeedGPU
testG(4, [''])
File "D:\Python\lib\site-packages\numba\cuda\dispatcher.py", line 40, in __call__
return self.compiled(*args, **kws)
File "D:\Python\lib\site-packages\numba\cuda\compiler.py", line 758, in __call__
kernel = self.specialize(*args)
File "D:\Python\lib\site-packages\numba\cuda\compiler.py", line 769, in specialize
kernel = self.compile(argtypes)
File "D:\Python\lib\site-packages\numba\cuda\compiler.py", line 784, in compile
kernel = compile_kernel(self.py_func, argtypes,
File "D:\Python\lib\site-packages\numba\core\compiler_lock.py", line 32, in _acquire_compile_lock
return func(*args, **kwargs)
TypeError: compile_kernel() got an unexpected keyword argument 'boundscheck'
Here is the function's body:
#jit(target ="cuda")
def testG(charNum, inpArray) -> null:
if charNum == 1:
arr2 = []
for s in range(len(inpArray)):
for i in range(len(alp)):
arr2.append(alp[i] + inpArray[s])
return
else:
print("more than 1")
arr2 = []
for s in range(len(inpArray)):
for i in range(len(alp)):
arr2.append(alp[i] + inpArray[s])
testG(charNum - 1, arr2)
I think it does have to do with the recursion but I really dont know.
Thanks for your help!
PS: The function works when not marked with #jit(target="cuda")
import numpy as np
from scipy.optimize import fsolve
from scipy.integrate import quad
import matplotlib.pyplot as plt
Rgas = 8.31446261815324 #Pa*m**3/mol*K
def Peng_Robinson_EOS(P,V,T,Tc,Pc,ω):
a = (1+(0.37464+1.54226*ω-0.26992*ω**2)*(1-(T/Tc)**(1/2)))**2*Rgas**2*Tc**2/Pc #Pa*m**3
b = 0.07780 * Rgas*Tc/Pc
return P + a/((V+(1-np.sqrt(2))*b)*(V+(1+np.sqrt(2)))) - Rgas*T/(V-b)
def PR_Psat(T,Tc,Pc,ω,V,Pguess = 100000):
def integral_diff (Pguess,T,Tc,Pc,ω,V):
def Psat_integrand (V,Pguess,T,Tc,Pc,ω):
integrand1 = fsolve(Peng_Robinson_EOS(Pguess,V,T,Tc,Pc,ω),Pguess)
integrand2 = Pguess
integrand = integrand1-integrand2
return integrand
Vl = fsolve(Psat_integrand(V,Pguess,T,Tc,Pc,ω),0)
Vv_guess = Rgas*T/Pguess
Vv = fsolve(Psat_integrand(V,Pguess,T,Tc,Pc,ω),Vv_guess)
Vinf_guess = (Vl + Vv)/2
Vinf = fsolve(Psat_integrand(V,Pguess,T,Tc,Pc,ω),Vinf_guess)
left = quad(Psat_integrand(V,Pguess,T,Tc,Pc,ω),Vl,Vinf)[0]
right = quad(Psat_integrand(V,Pguess,T,Tc,Pc,ω),Vinf,Vv)[0]
diff = left + right
return diff
Psat = fsolve(integral_diff(Pguess,T,Tc,Pc,ω,V),Pguess)
return Psat
There are two issues with this code.
1: in theory, PR_Psat should not depend on V, since all values of V used in calculation are found via fsolve. However, because Peng_Robinson_EOS depends on V, it Python won't let it be ignored in enclosing functions. Is there a way to eliminate the need to "specify" V?
from an earlier version (before V was a parameter of all functions), to demonstrate:
runfile('...', wdir='...')
Traceback (most recent call last):
File "<ipython-input-4-0875bc6411e8>", line 1, in <module>
runfile('...', wdir='...')
File "...\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "...\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "...", line 40, in <module>
print(PR_Psat(300,647.1,22055000,0.345))
File "...", line 37, in PR_Psat
Psat = fsolve(integral_diff(Pguess,T,Tc,Pc,ω),Pguess)
File "...", line 25, in integral_diff
Vl = fsolve(Psat_integrand(V,Pguess,T,Tc,Pc,ω),0)
NameError: name 'V' is not defined
2: It seems that Peng_Robinson is not being treated as a callable function, but rather as a float. I'm not sure what is causing this.
runfile('...', wdir='...')
Traceback (most recent call last):
File "<ipython-input-13-0875bc6411e8>", line 1, in <module>
runfile('...', wdir='...')
File "C:\Users\Spencer\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "...\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "...", line 42, in <module>
print(PR_Psat(300,647.1,22055000,0.345,1))
File "...", line 39, in PR_Psat
Psat = fsolve(integral_diff(Pguess,T,Tc,Pc,ω,V),Pguess)
File "...", line 27, in integral_diff
Vl = fsolve(Psat_integrand(V,Pguess,T,Tc,Pc,ω),0)
File "...", line 23, in Psat_integrand
integrand1 = fsolve(Peng_Robinson_EOS(Pguess,V,T,Tc,Pc,ω),Pguess)
File "...\lib\site-packages\scipy\optimize\minpack.py", line 148, in fsolve
res = _root_hybr(func, x0, args, jac=fprime, **options)
File "...\lib\site-packages\scipy\optimize\minpack.py", line 214, in _root_hybr
shape, dtype = _check_func('fsolve', 'func', func, x0, args, n, (n,))
File "...\lib\site-packages\scipy\optimize\minpack.py", line 27, in _check_func
res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
TypeError: 'numpy.float64' object is not callable
In theory, Peng_Robinson_EOS should, if plotted as P(V) with constant T, produce a cubic regression. The goal of PR_Psat is to find the value of P for which the integrals between P and the cubic regression cancel. (Hence, integral_diff being plugged into fsolve)
To summarize the questions,
1) Is there a way to eliminate the need for V in PR_Psat?
2) Why is Peng_Robinson_EOS being flagged as an un-callable numpy.float64 object?
The problem was a syntax error. Arguments for fsolve and quad were placed wrong. To fix both problems, I moved the args to the back. For example,
incorrect:
Vv = fsolve(Psat_integrand(V,Pguess,T,Tc,Pc,ω),Vv_guess)
correct:
Vv = fsolve(Psat_integrand,Vv_guess,args=(Pguess,T,Tc,Pc,ω))
The reason Peng_Robinson_EOS is being called a numpy.float64 is because with the syntax of the code in the question the program is evaluated before being passed to the solver.
Also, with proper syntax, V is no longer an issue.
def PR_Psat(T,Tc,Pc,ω,Pguess = 1000):
def integral_diff (Pguess,T,Tc,Pc,ω):
def Psat_integrand (V,Pguess,T,Tc,Pc,ω):
integrand1 = fsolve(Peng_Robinson_EOS,Pguess,args=(V,T,Tc,Pc,ω))
integrand2 = Pguess
integrand = integrand1-integrand2
return integrand
Vl = fsolve(Psat_integrand,0,args=(Pguess,T,Tc,Pc,ω))
Vv_guess = Rgas*T/Pguess
Vv = fsolve(Psat_integrand,Vv_guess,args=(Pguess,T,Tc,Pc,ω))
Vinf_guess = (Vl + Vv)/2
Vinf = fsolve(Psat_integrand,Vinf_guess,args=(Pguess,T,Tc,Pc,ω))
left = quad(Psat_integrand,Vl,Vinf,args=(Pguess,T,Tc,Pc,ω))[0]
right = quad(Psat_integrand,Vinf,Vv,args=(Pguess,T,Tc,Pc,ω))[0]
diff = left + right
return diff
Psat = fsolve(integral_diff,Pguess,args=(T,Tc,Pc,ω))
return Psat
I want to estimate parameters 'k,ru,sigma' that maximumize the function 'func'
('ru' means r upperba)
The'func'formula is compex, so I want to upload the image to show this fomula, but i have no enough reputation.
import numpy as np
sigma,k,ru=0.01,0.001,5
p0=np.array([[0.01,0.01,6]])
p=np.array([[sigma,k,ru]])
def func(p,r):
T=91/365
y=1/(np.sqrt(2*(np.pi)*p[0]**2/(2*p[1])*(1-np.exp(-(2*p[1]*T)))))*np.exp((r-p[2]-np.exp(-(p[1]*T))*(r-p[2]))**2/(p[0]**2/((-4)*p[1])*(1-np.exp(-(2*p[1]*T)))))
return -y
from scipy.optimize import minimize
r=np.array([[1.45,2.5,2.6,1.67,1.2]])
# r has 1350 datas like this
res=minimize(func,p0,args=(r))
Traceback (most recent call last):
File "<ipython-input-9-b94a05d2ede8>", line 1, in <module>
res=minimize(func,p0,args=(r))
File "C:\Users\hyun su\Anaconda3\lib\site-packages\scipy\optimize\_minimize.py", line 419, in minimize
return _minimize_bfgs(fun, x0, args, jac, callback, **options)
File "C:\Users\hyun su\Anaconda3\lib\site-packages\scipy\optimize\optimize.py", line 837, in _minimize_bfgs
gfk = myfprime(x0)
File "C:\Users\hyun su\Anaconda3\lib\site-packages\scipy\optimize\optimize.py", line 282, in function_wrapper
return function(*(wrapper_args + args))
File "C:\Users\hyun su\Anaconda3\lib\site-packages\scipy\optimize\optimize.py", line 616, in approx_fprime
return _approx_fprime_helper(xk, f, epsilon, args=args)
File "C:\Users\hyun su\Anaconda3\lib\site-packages\scipy\optimize\optimize.py", line 556, in _approx_fprime_helper
grad[k] = (f(*((xk + d,) + args)) - f0) / d[k]
ValueError: setting an array element with a sequence.
How can i solve this?
func here takes in a vector but it must be a scalar function of one or more variables as indicated in the scipy.optimize.minimize doc
Hi I am trying to use scipy for optimization. The minimize function with method as 'COBYLA' is working fine for small array size but errors out for larger sized arrays. I tried with 'COBYLA' and 'SLSQP' methods since I have a constrained optimization problem for non-linear functions.
Code snippet:
import scipy as sp
import random
def mytest7obj(x, x_d, y_d, z_d, power):
for x_i in x:
if x_i < 0:
return 0.
sum = 0.
for i in range(x_d):
for j in range(z_d):
term = 1.
for k in range(y_d):
term *= (x[i*(y_d*z_d)+j*(y_d)+k] ** power[k])
sum += term
return 0. - sum
def mytest7():
x_d = 30
y_d = 10
z_d = 100
goal = 1000000.
constraints = []
power = []
for i in range(y_d):
power.append(random.uniform(0.,0.3))
constraints.append({'type':'ineq', 'fun': lambda x: goal - sum(x)})
print 'power: %s\n' % (power,)
result = sp.optimize.minimize(fun = mytest7obj, x0 = [30.] * (x_d*y_d*z_d), method = 'COBYLA', args = (x_d, y_d, z_d, power), jac=False, constraints=constraints, options={'disp':True, 'rhobeg':3., 'maxiter': 10000})
print 'goal attained: %s'% (sum(result.x),)
if __name__ == “__main__”:
mytest7()
The traceback of the error with method 'COBYLA' is:
Traceback (most recent call last):
File "opt_test.py", line 584, in <module>
print 'mytest7'; mytest7()
File "opt_test.py", line 571, in mytest7
result = sp.optimize.minimize(fun = mytest7obj, x0 = [30.] * (x_d*y_d*z_d), method = 'COBYLA', args = (x_d, y_d, z_d, power), jac=False, constraints=constraints, options={'disp':True, 'rhobeg':3., 'maxiter': 10000})
File "/usr/lib64/python2.7/site-packages/scipy/optimize/_minimize.py", line 385, in minimize
return _minimize_cobyla(fun, x0, args, constraints, **options)
File "/usr/lib64/python2.7/site-packages/scipy/optimize/cobyla.py", line 238, in _minimize_cobyla
dinfo=info)
ValueError: failed to create intent(cache|hide)|optional array-- must have defined dimensions but got (-1594577286,)
With 'SLSQP', the error is:
File "opt_test.py", line 586, in <module>
print 'test'; test()
File "opt_test.py", line 454, in test
x = get_optimal(base, budget, initial_values, x_elas, y_elas, x_history, y_history, constraint_coeffs, opt_method = 'SLSQP')
File "opt_test.py", line 355, in get_optimal
constraints=constraints, options=opts)
File "/usr/lib64/python2.7/site-packages/scipy/optimize/_minimize.py", line 388, in minimize
constraints, **options)
File "/usr/lib64/python2.7/site-packages/scipy/optimize/slsqp.py", line 316, in _minimize_slsqp
w = zeros(len_w)
MemoryError
I am using python 2.7.5,
scipy version: 0.14.0rc1,
numpy version: 1.8.1
Playing around a lot with sympy lately, I came up with the problem of calculating divergence and gradient for scalar and vector fields. What I want to do for now is solving the heat equation, i.e.
d/dt u(x,t) - a * lap(u(x,t)) = 0, with lap(x) = (div(grad(x))
on a scalar field. Since I could not find lap, div and grad in sympy.physics.mechanics, I tried to implement them by myself
from sympy import *
from sympy.physics.mechanics import *
o = ReferenceFrame('o')
x,y,z = symbols('x y z')
class div(Function):
#classmethod
def eval(cls, F):
return F.diff(x, o).dot(o.x)+F.diff(y, o).dot(o.y)+F.diff(z, o).dot(o.z)
class grad(Function):
#classmethod
def eval(cls, F):
return o.x * F.diff(x) + o.y * F.diff(y) + o.z * F.diff(z)
f = x**2 + y**3 + z*0.5
print grad(f)
print type(grad(f))
print div(grad(f))
unluckily, this gives
2*x*o.x + 3*y**2*o.y + 0.500000000000000*o.z
Traceback (most recent call last):
File "/home/fortmeier/Desktop/autokernel/autokernel/tools/GenerateCode.py", line 24, in <module>
print div(grad(f))
File "/usr/local/lib/python2.7/dist-packages/sympy/core/cache.py", line 93, in wrapper
r = func(*args, **kw_args)
File "/usr/local/lib/python2.7/dist-packages/sympy/core/function.py", line 368, in __new__
result = super(Function, cls).__new__(cls, *args, **options)
File "/usr/local/lib/python2.7/dist-packages/sympy/core/cache.py", line 93, in wrapper
r = func(*args, **kw_args)
File "/usr/local/lib/python2.7/dist-packages/sympy/core/function.py", line 188, in __new__
args = list(map(sympify, args))
File "/usr/local/lib/python2.7/dist-packages/sympy/core/sympify.py", line 313, in sympify
expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)
File "/usr/local/lib/python2.7/dist-packages/sympy/parsing/sympy_parser.py", line 757, in parse_expr
return eval_expr(code, local_dict, global_dict)
File "/usr/local/lib/python2.7/dist-packages/sympy/parsing/sympy_parser.py", line 691, in eval_expr
code, global_dict, local_dict) # take local objects in preference
File "<string>", line 1, in <module>
AttributeError: 'Symbol' object has no attribute 'x'
[Finished in 0.3s with exit code 1]
I know that I could do something with the galgebra module, but first I'd like to understand more whats going on here. The question thus is what am I missing?
This looks like a bug in SymPy. sympify(ReferenceFrame('o').x) does not work.