I am trying to compute a definite integral of a 2*10 matrix. I need to compute its definite integral from zero to t as we know the results must coincide to the sinus table.
Here is the code before reaching the goal gives error. The error probably is for the last lines.
I would be so thankful if you guide me please.
import numpy as np
import math
import matplotlib.pyplot as plt
from scipy import integrate
from scipy.integrate import quad
from numpy import linalg as LA
from numpy.linalg import matrix_power
from scipy import linalg
from sympy import *
import scipy.integrate as it
from numpy import vectorize
############
from numba import vectorize, float64
##############################
# Constants
tmax = 20
t = np.arange(0.0, tmax, 1)
t0=0
m=len(t)
#print(t)
etest=np.matrix([[np.sqrt(0),np.sqrt(1),np.sqrt(2) ,np.sqrt(3),np.sqrt(4),np.sqrt(5),np.sqrt(6),np.sqrt(7),np.sqrt(8),np.sqrt(9)],
[np.sqrt(10),np.sqrt(11),np.sqrt(12), np.sqrt(13),np.sqrt(14),np.sqrt(15),np.sqrt(16),np.sqrt(17),np.sqrt(18),np.sqrt (19)]])
pow = np.power( etest, 2 )
pow0=pow[0]
pow1=pow[1]
def norm2etest(xx):
sum= pow0+pow1
return sum
ans2=norm2etest(etest)
print(ans2)
def outerfun(norm2etest):
return np.cos(norm2etest)
def integrandtest(xx):
return outerfun(norm2etest(xx))
ttt=outerfun(norm2etest(etest))
#print(ttt)
for tnow in np.arange(0.0, tmax, 1):
numnow=1*tnow
num=np.array(numnow,dtype=int)
#np.vectorize
def integratetest(i):
def integrandtest(t):
return outerfun(norm2etest(t))[i]
I, ff = quad(integrandtest, t0,tnow)
return I
###########################
INTERVALtest=np.arange(0,10)
ANS1=integratetest(INTERVALtest)
print(INTERVALtest)
#print(ANS1.size)
gives this error
Traceback (most recent call last):
File "C:\Users\user\OneDrive\Desktop\44integral.py", line 58, in <module>
ANS1=integratetest(INTERVALtest)
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\numpy\lib\function_base.py", line 2163, in __call__
return self._vectorize_call(func=func, args=vargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\numpy\lib\function_base.py", line 2241, in _vectorize_call
ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args)
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\numpy\lib\function_base.py", line 2201, in _get_ufunc_and_otypes
outputs = func(*inputs)
File "C:\Users\user\OneDrive\Desktop\44integral.py", line 54, in integratetest
I, ff = quad(integrandtest, t0,tnow)
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\integrate\quadpack.py", line 352, in quad
points)
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\integrate\quadpack.py", line 463, in _quad
return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
TypeError: only size-1 arrays can be converted to Python scalars
Related
I'm trying to solve a system of stiff odes which describes a catalytic heterogeneous reaction. I want to solve this equations for different temperatures, so I'm using a for loop.
import scipy as sc
from scipy.integrate import odeint, solve_ivp
import numpy as np
import matplotlib.pyplot as plt
T=np.array([250,300,350,400,450,500])
for y in T:
y=T
def f(t,x,T=y,tfirst=True):
FA,FB,FC,FD,FE,FF=x
e=2.711828
R=8.314
Tm=723.15
A1=5.5
A2=0.686
A3=1.58
A4=2.6
A5=0.787
E1=90500
E2=165000
E3=150000
E4=139000
E5=132000
SB=-215
HB=-45600
SD=-42
HD=-128000
DH1=-105000
DH2=-1428000
DH3=-862000
DH4=-1323000
DH5=-757000
k1=e**(A1-(E1/R)*((1/T)-(1/Tm)))
k2=e**(A2-(E2/R)*((1/T)-(1/Tm)))
k3=e**(A3-(E3/R)*((1/T)-(1/Tm)))
k4=e**(A4-(E4/R)*((1/T)-(1/Tm)))
k5=e**(A5-(E5/R)*((1/T)-(1/Tm)))
KB=6.54e-12
KD=1.19
m2=0.922
m3=0.906
m4=1.23
m5=0.905
Patm=0.8*101325
FT=178.47
PA=(FA/FT)*Patm
PB=(FB/FT)*Patm
PC=(FC/FT)*Patm
PD=(FD/FT)*Patm
PE=(FE/FT)*Patm
PF=(FF/FT)*Patm
Tast=1/(1+((KB*PB)**0.5)+(KD*PD))
TB=((KB*PB)**0.5)*Tast
TD=KD*PD*Tast
r1=(k1/1000)*TB*PA #mol
r2=(k2/1000)*(TB**m2)*PA
r3=(k3/1000)*(TB**m3)*PA
r4=(k4/1000)*(TB**m4)*PC
r5=(k5/1000)*(TB**m5)*PC
rA=-r1-r2-r3
rB=-r1-7*r2-5*r3-6*r4-4*r5
rC=r1-r4-r5
rD=r1+3*r2+3*r3+2*r4+2*r5
rE=2*r2+2*r4
rF=2*r3+2*r5
FAdot=rA
FBdot=rB
FCdot=rC
FDdot=rD
FEdot=rE
FFdot=rF
return [FAdot,FBdot,FCdot,FDdot,FEdot,FFdot]
x0=(5,5,0,0,0,0)
t0=0
t1=40
soln=solve_ivp(f,(t0,t1),x0,method="Radau",args=(T,))
print(soln.y)
I get the following error:
c:\Users\Axel Flores\Documents\Escuela\Proyectos\Python\import scipy as sc.py:51: RuntimeWarning: invalid value encountered in sqrt
Tast=1/(1+((KB*PB)**0.5)+(KD*PD))
c:\Users\Axel Flores\Documents\Escuela\Proyectos\Python\import scipy as sc.py:52: RuntimeWarning: invalid value encountered in sqrt
TB=((KB*PB)**0.5)*Tast
Traceback (most recent call last):
File "c:\Users\Axel Flores\Documents\Escuela\Proyectos\Python\import scipy as sc.py", line 75, in <module>
soln=solve_ivp(f,(t0,t1),x0,method="Radau",args=(T,))
File "C:\Users\Axel Flores\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy\integrate\_ivp\ivp.py", line 546, in solve_ivp
solver = method(fun, t0, y0, tf, vectorized=vectorized, **options)
File "C:\Users\Axel Flores\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy\integrate\_ivp\radau.py", line 310, in __init__
self.jac, self.J = self._validate_jac(jac, jac_sparsity)
File "C:\Users\Axel Flores\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy\integrate\_ivp\radau.py", line 356, in _validate_jac
J = jac_wrapped(t0, y0, self.f)
File "C:\Users\Axel Flores\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy\integrate\_ivp\radau.py", line 352, in jac_wrapped
J, self.jac_factor = num_jac(self.fun_vectorized, t, y, f,
File "C:\Users\Axel Flores\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy\integrate\_ivp\common.py", line 316, in num_jac
return _dense_num_jac(fun, t, y, f, h, factor, y_scale)
File "C:\Users\Axel Flores\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy\integrate\_ivp\common.py", line 326, in _dense_num_jac
f_new = fun(t, y[:, None] + h_vecs)
File "C:\Users\Axel Flores\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy\integrate\_ivp\base.py", line 133, in fun_vectorized
f[:, i] = self._fun(t, yi)
ValueError: could not broadcast input array from shape (6,6) into shape (6,)
PS C:\Users\Axel Flores>
Anyone could help?
I believe the error is related to the for loop. But everything that I've tried hasn't worked.
Take a hard look on the effect of
for y in T:
y=T
def f(t,x,T=y,tfirst=True):
and how that introduces the extra dimension of size 6.
The function evaluates if I input a pair of arguments. But when I try to evaluate the function at grid points, it fails, saying "ValueError: dimension mismatch". I paste the code below. Could anyone help with the problem?
import numpy as np
from qutip import*
import pylab as plt
from numpy import eye,pi,kron,random,vdot,absolute,power,sqrt,matmul
from numpy import exp,arange
from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show
j0= tensor(sigmaz(),identity(2),identity(2))
def otoc(k0,n):
u0=(-1j*k0/6 *(tensor(sigmaz(),sigmaz(),identity(2)))).expm()
jn= u0.inv()**n*j0*u0**n
return ((commutator(jn,j0)* commutator(j0,jn)).tr()/8)
k0 = np.arange(0,4,0.1)
n = np.linspace(0,50,50)
X,Y = meshgrid(k0, n)
Z = otoc(X, Y)
The error showing is the following
Traceback (most recent call last):
File "/Users/sreerampg/Dropbox/myself/programs/levy's lemma/untitled8.py", line 27, in <module>
Z = otoc(X, Y)
File "/Users/sreerampg/Dropbox/myself/programs/levy's lemma/untitled8.py", line 20, in otoc
u0=(-1j*k0/6 *(tensor(sigmaz(),sigmaz(),identity(2)))).expm()
File "/Applications/anaconda3/lib/python3.7/site-packages/qutip/qobj.py", line 599, in __rmul__
return other * self.data
File "/Applications/anaconda3/lib/python3.7/site-packages/scipy/sparse/base.py", line 550, in __rmul__
return (self.transpose() * tr).transpose()
File "/Applications/anaconda3/lib/python3.7/site-packages/cvxpy/interface/scipy_wrapper.py", line 31, in new_method
return method(self, other)
File "/Applications/anaconda3/lib/python3.7/site-packages/scipy/sparse/base.py", line 516, in __mul__
raise ValueError('dimension mismatch')
ValueError: dimension mismatch
This is my code to plot a Power spectral density signal. I need some help as im having error coding in python.
import math
import numpy as np
import matplotlib.pyplot as plt
from numpy.fft import fft, ifft
from scipy import signal
t=np.linspace(0,1,106)
Fs=1000
y=np.sin(2*math.pi*15*t) + np.sin(2*math.pi*30*t)
Y=fft(y,512)
f = np.arange(0,len(Y)-1)*(Fs-1)/len(Y)
P = abs(Y)*2/len(Y)
plt.plot(f,P)
plt.show()
This is the error i have when i try to run it.
Traceback (most recent call last):
File "C:\Users\keehu\Desktop\trial.py", line 13, in <module>
plt.plot(f,P)
File "C:\Users\keehu\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\pyplot.py", line 2761, in plot
return gca().plot(
File "C:\Users\keehu\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\axes\_axes.py", line 1646, in plot
lines = [*self._get_lines(*args, data=data, **kwargs)]
File "C:\Users\keehu\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\axes\_base.py", line 216, in __call__
yield from self._plot_args(this, kwargs)
File "C:\Users\keehu\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\axes\_base.py", line 342, in _plot_args
raise ValueError(f"x and y must have same first dimension, but "
ValueError: x and y must have same first dimension, but have shapes (511,) and (512,)
>>>
Your f is of size len(Y)-1 as you requested, but P has size len(Y).
The size of f is 511 and Y is 512. I have changed the code to solve that.
import math
import numpy as np
import matplotlib.pyplot as plt
from numpy.fft import fft, ifft
from scipy import signal
t=np.linspace(0,1,106)
Fs=1000
y=np.sin(2*math.pi*15*t) + np.sin(2*math.pi*30*t)
Y=fft(y,512)
f = np.arange(0,len(Y))*(Fs-1)/len(Y) #changed here
P = abs(Y)*2/len(Y)
plt.plot(f,P)
plt.show()
"ValueError: x and y must have same first dimension, but have shapes (511,) and (512,)" means that your arrays, f and P don't have the same size. f is one element to small. Use:
f = np.arange(0,len(Y))*(Fs-1)/len(Y)
I have a problem when i'm trying to minimize my complex function using scipy.optimize fmin or scipy.optimize minimize. Indeed it seems like the minimization don't want to take into account the fact that i have a complex function.
I divide my code into two part, the first is a Class and the second is my main program which call the class and solve the minimization.
Here is my Class :
import sys,os
import numpy as np
import random, math
import matplotlib.pyplot as plt
import cmath
class real :
def __init__(self):
self.nmodes = 4
self.L_ch = 1
self.w = 2
def minim(self,eps):
self.T=np.array([[0.0,0.0],[0.00645-0.0012364j,0.0]])
self.Id=np.array([[1,0],[0,1]])
self.disp=np.linalg.det(self.T-self.Id)
return self.disp
Here is my main programm:
import sys,os
import numpy as np
import random, math, cmath
from math import exp
import scipy
from scipy.optimize import fmin
from Carlo import *
#################################
# Call the Class and the function
#################################
A=real()
eps=0.003+0.0042j
C=A.minim(eps)
#################################
# Declare some parameters and list
#################################
Cp=0
track=2
variable=np.arange(track,6,1)
Save=[]
Tau=4.1
Freal=12
Fimag=14j
#################################
# Loop for minimize
#################################
for track in variable:
Cp+=1
print Cp
if Cp==1:
part_real=0.0
part_imag=0.0
else:
part_real=Save[leng-1]/2*3.14*track
part_imag=Save[leng]/2*3.14*track
R_0 = fmin(C,[part_real,part_imag])
print 'La valeur de R_0',R_0
Save.append(Tau)
Save.append(Freal+1)
Save.append(Fimag+1)
leng = len(Save) -1
But i got this error :
Traceback (most recent call last):
File "Main.py", line 40, in <module>
R_0 = fmin(C,[part_real,part_imag])
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/optimize/optimize.py", line 360, in fmin
res = _minimize_neldermead(func, x0, args, callback=callback, **opts)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/optimize/optimize.py", line 424, in _minimize_neldermead
fsim[0] = func(x0)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/optimize/optimize.py", line 268, in function_wrapper
return function(x, *args)
TypeError: 'numpy.complex128' object is not callable
Someone have an idea on what is it happening exactly ?
Thank you.
In the call: R_0 = fmin(C,[part_real,part_imag]) you should send a function as the first argument and it appears that C is not a function (which is why you get the error "object is not callable"):
scipy.linalg.det returns a float or complex Determinant of a matrix, see:
http://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.det.html
I have an issu when i'm trying to minimize my (complex matrix) function using fsolve or scipy.optimize.newton but both of them didn't worked. Indeed, my function is 2*2 matrix with complex value. First, I defined my function in a Class i called real() and it is called by my main program MAin.py:
import sys,os
import numpy as np
import random, math
from scipy.optimize import fsolve
from scipy import optimize
class real :
def __init__(self):
self.w = 2
def func1(self,eps):
self.k_ch=2.5*np.exp(eps)
f=np.array([[0,eps*3*self.k_ch+0.032],[0,self.w]])
return f
And my Main program is:
import sys,os
import numpy as np
import random, math, cmath
from scipy.optimize import fsolve
from Carlo import *
A=real()
eps=0.003+0.0042j
C=A.func1(eps)
Cp=0
track=1e-03
variable=np.arange(track,0.1,1)
for track in variable:
Cp=Cp+1
if Cp==1:
eps_real=0
elif Cp==1:
fray=np.array([Cp-1,2])
eps_real=fray/2*3.14*track
R_0= fsolve(C,eps.real)
print R_0
if xtol<=1e-04:
value_stock= np.array([Cp-1,2])
print 'R_0 value is', R_0
But I got this error:
Traceback (most recent call last):
File "Main.py", line 29, in <module>
R_0= fsolve(C,eps.real)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/optimize/minpack.py", line 127, in fsolve
res = _root_hybr(func, x0, args, jac=fprime, **options)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/optimize/minpack.py", line 183, in _root_hybr
_check_func('fsolve', 'func', func, x0, args, n, (n,))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/optimize/minpack.py", line 14, in _check_func
res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
TypeError: 'numpy.ndarray' object is not callable
Since i'm a new beginner with python, I don't know how to deal with it. Can you help me please if you have any idea. It seems like maybe fsolve does not like complex value but I got the same error using scipy.optimize.newton.
Thank you.
fsolve needs a function in the first argument. You provided C which is a numpy.ndarray, not a function.
I wonder why you use fsolve while you state you want to minimize a function? In case minimization is what you want, this example straight from the scipy.optimize tutorial might set you on track:
import numpy as np
from scipy.optimize import minimize
def rosen(x):
"""The Rosenbrock function"""
return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)
x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])
res = minimize(rosen, x0, method='nelder-mead',
options={'xtol': 1e-8, 'disp': True})
print(res.x)
[ 1. 1. 1. 1. 1.]