I have wrote this code to solve an equation , I know the behavior of this function has very rapid oscillations, when I RUN it gives bogus values for some "m[x]" and some "t"'s, with this error:
C:\Users\dani\anaconda3\lib\site-packages\scipy\integrate\odepack.py:247: ODEintWarning: Excess work done on this call (perhaps wrong Dfun type). Run with full_output = 1 to get quantitative information.
warnings.warn(warning_msg, ODEintWarning)
I don't know what is the problem.
how can I get correct results? or at least as accurate as possible? or maybe I should rewrite the code in another form?
thank you.
import scipy as sio
import numpy as np
import mpmath as mp
import scipy.integrate as spi
import matplotlib.pyplot as plt
import time
from scipy.integrate import quad
initial_value=np.logspace(24,27,100)
t=np.logspace(-20,6,100)
m=np.logspace(0,6,100)
start_time=time.perf_counter()
phi_m={}
phi_m_prime={}
phi=[]
phi_prime=[]
j=0
i=np.pi*2.435*initial_value[0]
while i<(np.pi*(2.435*10**(27))):
i=np.pi*2.435*initial_value[j]
phi=[]
phi_prime=[]
for x in range (len(m)):
def dzdt(z,T):
return [z[1], -3*1.4441*(10**(-6))*m[x]*np.sqrt(0.69)*(mp.coth(1.5*np.sqrt(0.69)*(10**(-6))*1.4441*m[x]*T))*z[1] - z[0]]
z0 = [i,0]
ts = t/m[x]
zs = spi.odeint(dzdt, z0, ts)
phi.append(zs[99,0])
phi_prime.append(zs[99,1])
phi_m[j]=phi
phi_m_prime[j]=phi_prime
j+=1
end_time=time.perf_counter()
print(end_time-start_time,"seconds")
Related
I am trying to learn a bit of signal processing , specifically using Python. Here's a sample code I wrote.
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import deconvolve
a = np.linspace(-1,1,50)
b = np.linspace(-1,1,50)**2
c = np.convolve(a,b,mode='same')
quotient,remainder = deconvolve(c,b);
plt.plot(a/max(a),"g")
plt.plot(b/max(b),"r")
plt.plot(c/max(c),"b")
plt.plot(remainder/max(remainder),"k")
#plt.plot(quotient/max(quotient),"k")
plt.legend(['a_original','b_original','convolution_a_b','deconvolution_a_b'])
In my understanding, the deconvolution of the convoluted array should return exactly the same array 'a' since I am using 'b' as the filter. This is clearly not the case as seen from the plots below.
I am not really sure if my mathematical understanding of deconvolution is wrong or if there is something wrong with the code. Any help is greatly appreciated!
You are using mode='same', and this seems not to be compatible with scipy deconvolve. Try with mode='full', it should work much better.
Here the corrected code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import deconvolve
a = np.linspace(-1,1,50)
b = np.linspace(-1,1,50)**2
c = np.convolve(a,b,mode='full')
quotient,remainder = deconvolve(c,b)
plt.plot(a,"g")
plt.plot(b,"r")
plt.plot(c,"b")
plt.plot(quotient,"k")
plt.xlim(0,50)
plt.ylim(-6,2)
plt.legend(['a_original','b_original','convolution_a_b','deconvolution_c_b'])
I am supposed to use python to solve a Matrix A^1000. I have tried numpy's built in matrix_power function to compute the output, but when I try to compute the result step by step according to the formula P*(D^1000) *P^-1 , I get an incomplete result. I am trying to figure out if my precision options are just too tight or if I am doing something else wrong completely
I have tried the matrix_power function to definitely get the result I want. But I need to be able to show how the calculation is done, and when I do so, I get an incomplete result
import numpy as np
np.set_printoptions(precision=6) # set the precision of the output
np.set_printoptions(suppress=True) # suppress the use of scientific notation
from numpy import diag, allclose, corrcoef
from numpy.random import randint, randn
from numpy.linalg import eig, matrix_rank, inv, cholesky, qr, norm, matrix_power
from sympy import Matrix, init_printing, matrix2numpy
A = np.array([[0.9,0.15,0.25],[0.075,0.8,0.25],[0.025,0.05,0.5]])
A
#python way
A_1000 = matrix_power(A,1000)
A_1000
D , P = eig(A)
P * np.diag(D**1000) * np.linalg.inv(p)
I am scratching my head over this very simple problem. Given this toy data:
randgen = np.random.RandomState(9)
npoints = 1000
noise = randgen.randn(npoints)
x = np.linspace(0, 1, npoints)
y = 5 + 10*x + noise
Solving this using numpy's least squares:
# design matrix::
X = np.ones((npoints, 2))
X[:,0] = np.copy(x)
p, res, rnk, s = np.linalg.lstsq(X, y)
p
gives a reasonable answer: array([ 9.94406755, 5.05954009]) for p. However, solving using scipy's least squares gives wildly different answer (which changes on each invocation of the function):
p, res, rnk, s = scipy.linalg.lstsq(X, y)
p
An example solution is array([ 1.16328381e+08, -2.26560583e+06]). I don't understand what I am missing. I encountered this problem when using Scikit-learn's LinearRegression which internally uses scipy's lstsq. That was giving me weird answers.
Edit:
Numpy version: 1.11.2
Scipy version: 0.18.1
Python: 3.5
Edit 2:
I have realized that loading a particular library before loading scipy is causing this problem. The following order of loading libraries causes problem:
import numpy as np
from numpy.ma import MaskedArray
from matplotlib import pyplot as plt
from netCDF4 import Dataset
import matplotlib as mpl
from mpl_toolkits.basemap import Basemap
from pyeemd import ceemdan
from scipy.sparse.linalg import svds
from sklearn.utils.extmath import svd_flip
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
from scipy.signal import convolve, boxcar
If I removed the from pyeemd import ceemdan line then the problem is solved! This raises the following question: why could this be happening?
Here is my first steps within the NumPy world.
As a matter of fact the target is plotting below 2-D function as a 3-D mesh:
N = \frac{n}{2\sigma\sqrt{\pi}}\exp^{-\frac{n^{2}x^{2}}{4\sigma^{2}}}
That could been done as a piece a cake in Matlab with below snippet:
[x,n] = meshgrid(0:0.1:20, 1:1:100);
mu = 0;
sigma = sqrt(2)./n;
f = normcdf(x,mu,sigma);
mesh(x,n,f);
But the bloody result is ugly enough to drive me trying Python capabilities to generate scientific plots.
I searched something and found that the primary steps to hit above mark in Pyhton might be acquired by below snippet:
from matplotlib.patches import Polygon
import numpy as np
from scipy.integrate import quad
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
sigma = 1
def integrand(x,n):
return (n/(2*sigma*np.sqrt(np.pi)))*np.exp(-(n**2*x**2)/(4*sigma**2))
t = np.linespace(0, 20, 0.01)
n = np.linespace(1, 100, 1)
lower_bound = -100000000000000000000 #-inf
upper_bound = t
tt, nn = np.meshgrid(t,n)
real_integral = quad(integrand(tt,nn), lower_bound, upper_bound)
Axes3D.plot_trisurf(real_integral, tt,nn)
Edit: With due attention to more investigations on Greg's advices, above code is the most updated snippet.
Here is the generated exception:
RuntimeError: infinity comparisons don't work for you
It is seemingly referring to the quad call...
Would you please helping me to handle this integrating-plotting problem?!...
Best
Just a few hints to get you in the right direction.
numpy.meshgrid can do the same as MatLABs function:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html
When you have x and n you can do math just like in matlab:
sigma = numpy.sqrt(2)/n
(in python multiplication/division is default index by index - no dot needed)
scipy has a lot more advanced functions, see for example How to calculate cumulative normal distribution in Python for a 1D case.
For plotting you can use matplotlibs pcolormesh:
import matplotlib.pyplot as plt
plt.pcolormesh(x,n,real_integral)
Hope this helps until someone can give you a more detailed answer.
I'm trying to plot a simple signal in python, and when i run this it doesn't show any error only 'Restart' and a blank space
from pymatlab import*
import numpy as np
from numpy import sqrt
import matplotlib.pyplot as plt
import scipy as sp
import math
(hashtags) n, coef, freq, phase
def sinyal(N,c,f,p):
y=np.zeros(N)
t=np.linspace(0,2*pi,N)
Nf=len(c)
for i in range(Nf):
y+=c[i]*np.sin(f[i]*t)
return y;
# Signal Generator
c=[2,5,10]
f=[50, 150, 300]
p=[0,0]
N=2000
x=np.linspace(0,2.0*math.pi,N)
y=sinyal(N,c,f,p)
plt.plot(x[:100],y[:100])
plt.show()
The code you posted has a logical indentation error. The call to sinyal is indented one level, placing it inside the definition of sinyal itself. So although sinyal gets defined, it never gets called.
Using 4 spaces for indentation may help you avoid this error in the future.
Your code basically works (apart from some formatting errors and other oddities). I don't have pymatlab but it isn't necessary for this.
import numpy as np
from numpy import sqrt
import matplotlib.pyplot as plt
import scipy as sp
import math
def sinyal(N,c,f,p):
y=np.zeros(N)
t=np.linspace(0,2*np.pi,N)
Nf=len(c)
for i in range(Nf):
y+=c[i]*np.sin(f[i]*t)
return y;
# Signal Generator
c=[2,5,10]
f=[50, 150, 300]
p=[0,0]
N=2000
x=np.linspace(0,2.0*math.pi,N)
y=sinyal(N,c,f,p)
plt.plot(x[:100],y[:100])
plt.show()