Plotting a signal in Python - python

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()

Related

Solving differentioal equations with rapid oscillations using odeint

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")

A question about deconvolution of a signal using Python scipy

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'])

Minuit doesn't converge with log function?

Trying to fit some data with to a log curve however my output is not valid and I don't understand what is causing the error. IT's weird cause when omitting the b of the fit it converges and all fields are green.
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
def logis(x,a,b): #function to fit
return (1+x*np.log(b/x))*a
xlat=np.array([81.96100485, 64.96427609, 38.15520137, 45.75992993,
27.38344029, 23.41742996, 18.73586921, 18.07486749,
9.20589292, 4.83878931, 72.17070899, 71.08083681,
39.57647386, 31.63373626]) #xdata
lo=logis(xlat,92,30) #ydata
p=np.concatenate((np.array([92,30]),xlat,lo),axis=0) #all parameters
def chi(pa): #chisquare
chis=sum((92-pa[0:1])**2)+sum((30-p[1:2])**2)+sum((xlat-pa[2:16])**2)+sum((lo-pa[16:30])**2)
return chis
#minuit part
m = Minuit.from_array_func(chi,p,errordef=1)
fmin,para=m.migrad()
print(m.values)
print(fmin)
xn=[]
xtra=np.sort(xlat)
for i in range(2,16):
xn.append(m.values[i])
xr=np.array(xn)
#plot part
xp=np.linspace(min(xr),max(xr),14)
plt.figure(figsize=(14,8.5))
plt.plot(xp,logis(xp,m.values[0],m.values[1]))
plt.show
Here are some figures:
Nevermind I found the problem, had written sum((30-p[1:2])**2) instead of sum((30-pa[1:2])**2). Thank you for your time!

Why does numpy give correct least squares solution but not scipy?

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?

Function that computes rk method/no plotting

import math
import matplotlib
import numpy as np
from numpy import linspace
tmax=10.0
n=2000
G=4
D=-1
m=2
t=np.linspace (0,400,n+1)
phi=10
dphi=delta=phi_dot=np.linspace(0,400,n+1)
def f(delta_dot,t):
return ((G)*(D*delta+m))
def iterate (func,phi,delta,tmax,n):
dt=tmax/(n-1)
t=0.0
for i in range(n):
phi,delta = func (phi,delta,t,dt)
t += dt
return phi
def rk_iter(phi,delta,t,dt):
k1=f(t,phi)
k2=f(t+dt*0.5,phi+k1*0.5*dt)
k3=f(t+dt*0.5,phi*k2*0.5*dt)
k4=f(t*dt,phi*k3*dt)
delta +=dt*(k1+2*k2+2*k3+k4)/6
k1=k2=k3=k4=delta=phi_dot
phi += dt*(k1+2*k2+2*k3+k4)/6
return phi,delta
runge_kutta = lambda delta, phi,tmax,n:iterate(rk_iter,delta,phi,tmax,n)
def plot_result (delta,phi,tmax,n):
dt=tmax/(n-1)
error_rk=[]
r_rk=[]
t=0.0
phi=phi_rk=phi
delta=delta_rk=delta
for i in range(n):
phi_rk,delta_rk=rk_iter(phi_rk,delta_rk,t,dt=tmax/(n-1))
t+=dt
_plot("error.png","Error","time t", "error e",error_rk)
def _plot(title,xlabel,ylabel,rk):
import matplotlib.pyplot as plt
plt.title(title)
plt.ylabel(ylabel)
plt.xlabel(xlabel)
plt.plot(rk,"r--",label="Runge-Kutta")
plt.legend(loc=4)
plt.grid(True)
plt.plot(runge_kutta,t)
print "runge_kutta=", runge_kutta(phi,delta,tmax,n)
print "tmax=",t
I have no idea how to get the function plt.show() to work. What do I have to do to open a plot window?
You haven't defined f; instead, f is being imported from matplotlib by the statement from matplotlib import *:
In [10]: import matplotlib
In [11]: matplotlib.f
Out[11]: Forward: "a"
In [12]: matplotlib.f(1,1)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-5843007d7dbe> in <module>()
----> 1 matplotlib.f(1,1)
TypeError: __call__() takes at most 2 arguments (3 given)
You will save yourself many headaches like this in the future if you never use the * form of the import statement in your scripts. For example, instead of from math import *, use one of these two forms:
import math
# Now refer to math.sin, math.pi, etc.
or, explicilty import only the names that you will use:
from math import sin, pi
At no point do you call the plot_result procedure. And even if you called it, you do not fill the rk and error_rk lists. You could simply use the result from the runge_kutta call,...
As commented in the other, duplicate post, you define the system equation as f(y,t) but use it as f(t,y).
There is some confusion in the usage of delta, sometimes it is the integration variable, sometimes the rk4-step update.
In the rk4-step, there are some misplaced multiplications where there should be additions. And the line
k1=k2=k3=k4=delta=phi_dot
is complete nonsense and invalidates the previous computations and makes the rk4-update in the next step meaningless.
Remove the imports of math and linspace, neither is used in the code. Move the aliasing of plt to the top and merge it with the unnecessary import of matplotlib.

Categories