Limit to Infinity - python

So I tried to get the limits to infinity of an expression which has a function argument through this code and I got this. Help.
import numpy as np
import sympy as sp
import matplotlib.pyplot as plt
from scipy import integrate
T=2
t=sp.symbols('t')
x=sp.Piecewise((1,t%T<=T/2),(0,t%T>T/2))
n=sp.symbols('n')
xnum=sp.lambdify(t,x)
def realintegrand(t,f):
w0=2*np.pi/T
trig=np.cos(n*w0*t)
return f(t)*trig/T
def imagintegrand(t,f):
w0=2*np.pi/T
trig=np.sin(n*w0*t)
return f(t)*trig/T
def limitfunc(f):
realans, errreal = integrate.quad(realintegrand, 0, T,args=(f,))
imagans, errimag = integrate.quad(imagintegrand, 0, T,args=(f,))
return sp.limit(realans-1.0j*imagans,n,float('inf'),'+')
k=limitfunc(xnum)
TypeError:
loop of ufunc does not support argument 0 of type Mul which has no callable cos method

Related

ValueError: Residuals are not finite in the initial point. with scipy least square

import originpro as op
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def circle(ReZ,R1,R2):
nImZ=(ReZ-R1)*np.sqrt(R2/(ReZ-R1)-1)
return nImZ
def Fit(func,used_x,used_y,bound,yerror):
fit_para,fit_cov=curve_fit(func,used_x,used_y,bounds=bound,sigma=yerror,absolute_sigma=True)
print(fit_para)
return fit_para
def yerror(ydata, p):
output=[]
for i in ydata:
data=i*p
output.append(data)
return output
def PrePlot(exp_x,exp_y,fit_x,fit_y):
fig,ax=plt.subplots()
fitline=ax.plot(fit_x,fit_y,marker='.',color='blue')
expline=ax.scatter(exp_x,exp_y,s=20,marker='.',color='red')
ax.legend(['Experimental','Fitted line'])
plt.show()
wkslist=range(83,109)
for wksnum in wkslist:
wks=op.find_sheet('w','Book'+str(wksnum))
xdata=wks.to_list(1)
ydata=wks.to_list(2)
bound=([3000,1*10**8],[6000,1*10**9])
error=yerror(ydata, 0.1)
fitRes=Fit(circle,xdata,ydata,bound,error)
fit_x=xdata
fit_y=[circle(x,fitRes[0],fitRes[1]) for x in fit_x]
PrePlot(xdata,ydata,fit_x,fit_y)
I get the error for the second worksheet(wks)
for the function used (circle), the condition is: when ReZ>R1, R1+R2>=ReZ; when ReZ<R1, R1+R2<=ReZ
The maximum ReZ in the xdata is 1.35e8, the minimum is 4353, which fits that condition with the given boundary.
So I'm really confused here

How to transform a np.array into a function?

I have the following np.array which describes a rectangular wave. I would like to transform it into a callable function with a continuous argument. The np.array is:
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import seed
from numpy.random import rand
def piecewise_control( off_times,amp_inj, period_inj ):
def select(T):
return lambda t: (-T/2 <= t) & (t < T/2)
def pulse_train(t, at, shape):
return np.sum(shape(t - at[:,np.newaxis]), axis=0)
for i in range(1,len(off_times)):
off_times[i] += off_times[i-1] + period_inj
return amp_inj*pulse_train(t,off_times,shape=select(period_inj))
t=np.linspace(0,100,10000)
off_times = 10*rand(10)
period_inj = 1
amp_inj = 1
control = piecewise_control( off_times,amp_inj, period_inj )
plt.plot(t,control)
plt.show()
This answer inspired me.
The plot is the following:
The question is: can we transform the array control into a function with a continuous argument?
Of course if we did:
def ccontrol(t, control):
return control[t]
unfortunately we would get a function which only depends on integers.
You can subclass numpy.ndarray and implement the __call__ method:
import numpy as np
class MyArray(np.ndarray):
def __call__(self, idx):
return self[idx]
control = np.random.rand(100)
control_view = control.view(MyArray)
print(control_view(5), control[5])
For interpolation you can use scipy.interpolate. In fact, interpolation routines can return functions that you can call with any input, not necessarily integers.

Explicitly calculate convolution in Python

I want to calculate a convolution in Python by explicitly evaluating the integral
and comparing the result with what I get from fftconvolve. The integral would be calculated using quad:
import numpy as np
from scipy.integrate import quad
from scipy.signal import fftconvolve
import matplotlib.pyplot as plt
from sympy import symbols
def f(x,a,b):
return np.exp(-(x-a)**2/b)
def g(x,a,b):
return np.exp(-(x-np.pi*a)**2/(2.9*b))
x = symbols('x')
a = 1.2
b = 4.7
t = np.linspace(-100,100,int(1e4))
dt = t[1] - t[0]
h1 = fftconvolve(f(t,a,b),g(t,a,b),mode='same')*dt
h2,_ = quad(f(t,a,b)*g(x-t,a,b),-np.inf,np.inf,epsabs=0,epsrel=1e-6,args=(a,b))
x = np.linspace(-100,100,int(1e4))
plt.figure()
plt.plot(t,h1,label='fftconvolve')
plt.plot(x,h2,label='brute force')
plt.legend()
plt.show()
I keep getting the error AttributeError: 'Mul' object has no attribute 'exp' which refers to the line h2,_ = quad(... when it is called by quad.
What does this error mean and is this an appropriate way to use quad to evaluate the integral?

Python's random module made inaccessible

When I call random.sample(arr,length) an error returns random_sample() takes at most 1 positional argument (2 given).I've tried importing numpy under a different name, which doesn't fix the problem.Any thoughts? Thanks
import numpy.random
import random
import numpy as np
from numpy import *
points = [[1,1],[1.5,2],[3,4],[5,7],[3.5,5],[4.5,5], [3.5,4]]
def cluster(X,center):
clusters = {}
for x in X:
z= min([(i[0], np.linalg.norm(x-center[i[0]])) for i in enumerate(center)], key=lambda t:t[1])
try:
clusters[z].append(x)
except KeyError:
clusters[z]=[x]
return clusters
def update(oldcenter,clusters):
d=[]
r=[]
newcenter=[]
for k in clusters:
if k[0]==0:
d.append(clusters[(k[0],k[1])])
else:
r.append(clusters[(k[0],k[1])])
c=np.mean(d, axis=0)
u=np.mean(r,axis=0)
newcenter.append(c)
newcenter.append(u)
return newcenter
def shouldStop(oldcenter,center, iterations):
MAX_ITERATIONS=0
if iterations > MAX_ITERATIONS: return True
u=np.array_equal(center,oldcenter)
return u
def init_board(N):
X = np.array([(random.uniform(1,4), random.uniform(1, 4)) for i in range(4)])
return X
def kmeans(X,k):
clusters={}
iterations = 0
oldcenter=([[],[]])
center = random.sample(X,k)
while not shouldStop(oldcenter, center, iterations):
# Save old centroids for convergence test. Book keeping.
oldcenter=center
iterations += 1
clusters=cluster(X,center)
center=update(oldcenter,clusters)
return (center,clusters)
X=init_board(4)
(center,clusters)=kmeans(X,2)
print "center:",center
#print "clusters:", clusters
When you use from numpy import * you import all items that are in the numpy namespace into your scripts namespace. When you do this any functions/variables/etc that have the same name will be overwritten by the items from the numpy namespace.
numpy has a subpackage called numpy.random which then overwrote your random import as the code below shows:
import random
# Here random is the Python stdlib random package.
from numpy import *
# As numpy has a random package, numpy.random,
# random is now the numpy.random package as it has been overwritten.
In this case you should instead use import numpy as np which will allow you to access both:
import random
# random now contains the stdlib random package
import numpy as np
# np.random now contains the numpy.random package
Your points is List type, so you should convert it to an array
points = np.asarray(point)
Also, you should use import random

solve an integral equation by python

I need to solve an integral equation by python 3.2 in win7.
I want to find an initial guess solution first and then use "fsolve()" to solve it in python.
This is the code:
import numpy as np
from scipy.optimize.minpack import fsolve
from cmath import cos, exp
from scipy.integrate.quadpack import quad
def integrand2(x, b):
return exp(-x)/b
def intergralFunc2(b):
integral,err = quad(integrand2, 0, 10, args=(b)) // **error here**
return 0.01 - integral
import matplotlib.pyplot as plt
def findGuess():
vfunc = np.vectorize(intergralFunc2)
f = np.linspace(-20, 20,10)
plt.plot(f, vfunc(f))
plt.xlabel('guess value')
plt.show()
def solveFunction():
y= fsolve(intergralFunc2, 10)
return y
if __name__ == '__main__':
findGuess()
solution = solveFunction()
print("solution is ", solution)
I got error:
quadpack.error: Supplied function does not return a valid float.
Any help would be appreciated.
Just made the following change and it should work (it worked for me).
remove:
from cmath import exp, cos
include:
from numpy import exp, cos
as explained in the comments, the cmath functions accept only float inputs, not arrays.

Categories

Resources