Need help in ploting PSD(Power spectral density) on python - python

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)

Related

PyKrige Memory error of numpy.core._exceptions._ArrayMemoryError

I am trying to use the PyKrige module for the first time and ran the following script
import numpy as np
import pandas as pd
import glob
from pykrige.ok import OrdinaryKriging
from pykrige.kriging_tools import write_asc_grid
import pykrige.kriging_tools as kt
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.patches import Path, PathPatch
datafile='C:/myfile.xyz'
df=pd.read_csv(datafile,delimiter='\t')
print(df)
lons=np.array(df['x'])
lats=np.array(df['y'])
data=np.array(df['z'])
grid_space = 0.5
grid_lon = np.arange(np.amin(lons), np.amax(lons), grid_space) #grid_space is the desired delta/step of the output array
grid_lat = np.arange(np.amin(lats), np.amax(lats), grid_space)
OK = OrdinaryKriging(lons, lats, data, variogram_model='gaussian', verbose=True, enable_plotting=False,nlags=20)
z1, ss1 = OK.execute('grid', grid_lon, grid_lat)
kt.write_asc_grid(grid_lon, grid_lat, z1, filename="C:/users/public/output.asc")
print('job complete')
This runs for about a minute and then I get this error
Traceback (most recent call last):
File "c:\Users\anonymous\Documents\pykrige_kriginginterpolation.py", line 25, in <module>
z1, ss1 = OK.execute('grid', grid_lon, grid_lat)
File "C:\Python10\lib\site-packages\pykrige\ok.py", line 847, in execute
a = self._get_kriging_matrix(n)
File "C:\Python10\lib\site-packages\pykrige\ok.py", line 642, in _get_kriging_matrix
a[:n, :n] = -self.variogram_function(self.variogram_model_parameters, d)
File "C:\Python10\lib\site-packages\pykrige\variogram_models.py", line 45, in gaussian_variogram_model
return psill * (1.0 - np.exp(-(d**2.0) / (range_ * 4.0 / 7.0) ** 2.0)) + nugget
numpy.core._exceptions._ArrayMemoryError: Unable to allocate 10.2 GiB for an array with shape (36935, 36935) and data type float64
My computer has enough memory, so I'm not sure how to bypass this as i want to check that the results are as expected?
Please also note, as I've said this is a first attempt at using PyKrige to see if I can get it working - if anyone notices any obvious errors, please let me know!

strange error python code for definite integral of a matrix

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

Dimension mismatch error in python while evaluating a function of two arguments

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

ValueError when using lmfit LognormalModel

I have been using lmfit for about a day now and needless to say I know very little about the library. I have been using several built-in models for curve fitting and all of them work flawlessly with the data except the Lognormal Model.
Here is my code:
from numpy import *
from lmfit.models import LognormalModel
import pandas as pd
import scipy.integrate as integrate
import matplotlib.pyplot as plt
data = pd.read_csv('./data.csv', delimiter = ",")
x = data.ix[:, 0]
y = data.ix[:, 1]
print (x)
print (y)
mod = LognormalModel()
pars = mod.guess(y, x=x)
out = mod.fit(y, pars , x=x)
print(out.best_values)
print(out.fit_report(min_correl=0.25))
out.plot()
plt.plot(x, y, 'bo')
plt.plot(x, out.init_fit, 'k--')
plt.plot(x, out.best_fit, 'r-')
plt.show()
and the error output is:
Traceback (most recent call last):
File "Cs_curve_fit.py", line 17, in <module>
pvout = pvmod.fit(y, amplitude= 1, center = 1, sigma =1 , x=x)
File "C:\Users\NAME\Anaconda3\lib\site-packages\lmfit\model.py", line 731, in fit
output.fit(data=data, weights=weights)
File "C:\Users\NAME\Anaconda3\lib\site-packages\lmfit\model.py", line 944, in fit
self.init_fit = self.model.eval(params=self.params, **self.userkws)
File "C:\Users\NAME\Anaconda3\lib\site-packages\lmfit\model.py", line 569, in eval
return self.func(**self.make_funcargs(params, kwargs))
File "C:\Users\NAME\Anaconda3\lib\site-packages\lmfit\lineshapes.py", line 162, in lognormal
x[where(x <= 1.e-19)] = 1.e-19
File "C:\Users\NAME\Anaconda3\lib\site-packages\pandas\core\series.py", line 773, in __setitem__
setitem(key, value)
File "C:\Users\NAME\Anaconda3\lib\site-packages\pandas\core\series.py", line 755, in setitem
raise ValueError("Can only tuple-index with a MultiIndex")
ValueError: Can only tuple-index with a MultiIndex
First, the error message you show cannot have come from the code you post. The error message says that line 17 of the file "Cs_curve_fit.py" reads
pvout = pvmod.fit(y, amplitude= 1, center = 1, sigma =1 , x=x)
but that is not anywhere in your code. Please post the actual code and the actual output.
Second, the problem appears to happening because the data for x is cannot be turned into a 1D numpy array. Not being able to trust your code or output, I would just suggest converting the data to 1D numpy arrays yourself as a first test. Lmfit should be able to handle Pandas series, but it just does a simple coercion to 1D numpy arrays.

Interpolate a discontinuous function with Scipy

I am having problems interpolating some data points using Scipy. I guess that it might depend on the fact that the function I'm trying to interpolate is discontinuous at x roughly 4.
Here is the code I'm using to interpolate:
from scipy import *
y_interpolated = interp1d(x,y,buonds_error=False,fill_value=0.,kind='cubic')
new_x_array = arange(min(x),max(x),0.05)
plot(new_x_array,x_interpolated(new_x_array),'r-')
The error I get is
File "<stdin>", line 2, in <module>
File "/Library/Frameworks/EPD64.framework/Versions/7.1/lib/python2.7/site-packages/scipy/interpolate/interpolate.py", line 357, in __call__
out_of_bounds = self._check_bounds(x_new)
File "/Library/Frameworks/EPD64.framework/Versions/7.1/lib/python2.7/site-packages/scipy/interpolate/interpolate.py", line 415, in _check_bounds
raise ValueError("A value in x_new is above the interpolation "
ValueError: A value in x_new is above the interpolation range.
These are my data points:
1.56916432074 -27.9998263169
1.76773750527 -27.6198430485
1.98360238449 -27.2397962268
2.25133982943 -26.8596491107
2.49319293195 -26.5518194791
2.77823462692 -26.1896935372
3.07201297519 -25.9540514619
3.46090507092 -25.7362456112
3.65968688527 -25.6453922172
3.84116464506 -25.53652509
3.97070419447 -25.3374215879
4.03087127145 -24.8493356465
4.08217147954 -24.0540196233
4.12470899596 -23.0960856364
4.17612639206 -22.4634289328
4.19318305992 -22.1380894034
4.2708234589 -21.902951035
4.3745696768 -21.9027079759
4.52158254627 -21.9565591238
4.65985875536 -21.8839570732
4.80666329863 -21.6486676004
4.91026629192 -21.4496126386
5.05709528961 -21.2685401725
5.29054655428 -21.2860476871
5.54129211534 -21.3215908912
5.73174988353 -21.6645019816
6.06035782465 -21.772138994
6.30243916407 -21.7715483093
6.59656410998 -22.0238656166
6.86481948673 -22.3665921479
7.01182409559 -22.4385289076
7.17609125906 -22.4200564296
7.37494987052 -22.4376476472
7.60844044988 -22.5093814451
7.79869207061 -22.5812017094
8.00616642549 -22.5445612485
8.17903446593 -22.4899243886
8.29141325457 -22.4715846981
What version of scipy are you using?
The script you posted has some syntax errors (I assume due to wrong copy and paste).
This script works, with scipy.__version__ == 0.9.0. .
import sys
from scipy import *
from scipy.interpolate import *
from pylab import plot
x = []
y = []
for line in sys.stdin:
a, b = line.split()
x.append(float(a))
y.append(float(b))
y_interpolated = interp1d(x,y,bounds_error=False,fill_value=0.,kind='cubic')
new_x_array = arange(min(x),max(x),0.05)
plot(new_x_array,y_interpolated(new_x_array),'r-')

Categories