def test_basic(self): assert_allclose(signal.flattop(6, sym=False), [-0.000421051, -0.051263156, 0.19821053, 1.0, 0.19821053, -0.051263156]) assert_allclose(signal.flattop(6), [-0.000421051, -0.0677142520762119, 0.6068721525762117, 0.6068721525762117, -0.0677142520762119, -0.000421051]) assert_allclose(signal.flattop(7, True), [-0.000421051, -0.051263156, 0.19821053, 1.0, 0.19821053, -0.051263156, -0.000421051])
def fft_spectrum(self, y , fs=1, nl=None, o=0.75, win='hann', nAverage=np.inf): n = len(y) if nl is None: nl = n i = 0. m = 0 done = False f = np.arange(0, nl)/nl*fs Y = np.zeros(nl) if win == 'rectangle': w = sig.boxcar(nl) elif win == 'flattop': w = sig.flattop(nl) else: w = sig.hann(nl) while not done: a = int(np.floor(i*nl)) b = int(a+nl) Y = np.abs(fft(y[a:b]*w/np.sum(w)))+Y i = i+1*(1-o) m+=1 done = b > (n-nl*(1-o)) or m == nAverage Y = Y/m*2 return (Y, f, m)
def test_basic(self): assert_allclose(signal.flattop(6, sym=False), [-0.000421051, -0.051263156, 0.19821053, 1.0, 0.19821053, -0.051263156]) assert_allclose(signal.flattop(7, sym=False), [-0.000421051, -0.03684078115492348, 0.01070371671615342, 0.7808739149387698, 0.7808739149387698, 0.01070371671615342, -0.03684078115492348]) assert_allclose(signal.flattop(6), [-0.000421051, -0.0677142520762119, 0.6068721525762117, 0.6068721525762117, -0.0677142520762119, -0.000421051]) assert_allclose(signal.flattop(7, True), [-0.000421051, -0.051263156, 0.19821053, 1.0, 0.19821053, -0.051263156, -0.000421051])
def blakmanTukey(signal, M=0, win="Bartlett", n1=0, n2=0, ax=0): if n1 == 0 and n2 == 0: # por defecto usa la selal completa n1 = 0 n2 = len(signal) N = n2 - n1 if M == 0: M = int(N / 5) M = 2 * M - 1 if M > N: raise ValueError('Window cannot be longer than data') if win == "Bartlett": w = np.bartlett(M) elif win == "Hanning": w = np.hanning(M) elif win == "Hamming": w = np.hamming(M) elif win == "Blackman": w = np.blackman(M) elif win == "Flattop": w = sg.flattop(M) else: w = sg.boxcar(M) r, lags = acorrBiased(signal) r = r[np.logical_and(lags >= 0, lags < M)] rw = r * w Px = 2 * fft(rw).real - rw[0] return Px
def get_f0(wfdata, lflim, uflim, nfft=1024, sr=44100): """ Uses the scipy.signal package to construct a flat top window function, which is multiplied with the waveform. Performs the real-input fft from the numpy.fft package, and finds the frequency peak and its estimated power in a range restricted by lflim ad uflim (in Hz). Input ----- wfdata : the waveform data array lflim, uflim : lower and upper frequency limits nfft : number of samples to use for windowing & fft (power of 2 recommended - defaults to 1024) Output ------ f0x, f0y : frequency and power of the harmonic peak detected between lflim and uflim """ window = sig.flattop(nfft) wfwind = [wf * wd for wf, wd in zip(wfdata, window)] spectrum = np.fft.rfft(wfwind, nfft) fvals = np.fft.rfftfreq(nfft, 1 / sr) power = 20 * np.log10(np.abs(spectrum)) lindex = int(np.floor((len(fvals) / fvals[-1]) * lflim)) uindex = int(np.ceil((len(fvals) / fvals[-1]) * uflim)) pslice = power[lindex:uindex] fslice = fvals[lindex:uindex] f0x = fslice[np.argmax(pslice)] f0y = np.amax(pslice) return f0x, f0y
def f(): window_type = display['window_type'] window_size = int(display['size']) p = float(display['param']) window = np.zeros(window_size) if window_type == 'square': window = np.ones(window_size) elif window_type == 'exponential': window = np.exp(np.arange(window_size) * p) elif window_type == 'hanning': window = np.hanning(window_size) elif window_type == 'blackman': window = np.blackman(window_size) elif window_type == 'ricker': window = ricker(window_size, p) elif window_type == 'gaussian': window = gaussian(window_size, p) elif window_type == 'barthann': window = barthann(window_size) elif window_type == 'flattop': window = flattop(window_size) elif window_type == 'cosine': window = cosine(window_size) elif window_type == 'triangle': window = triang(window_size) return window
def Flattop(N, x): ventana = signal.flattop(N) salida = np.multiply(x, ventana) return salida
def write_to_file(recv_buffer, fname, log, dec=10): print("writing to file %s" % (fname)) # w=lpf(dec=dec) # todo: read filter length from create_waveforms, where it is determined w = ss.flattop(52) fl = len(w) # filter, time shift, decimate, and cast to complex64 data type obuf = n.array(n.roll( n.fft.ifft(n.fft.fft(w, len(recv_buffer)) * n.fft.fft(recv_buffer)), -int(fl / 2))[0:len(recv_buffer):dec], dtype=n.complex64) # rectangular impulse response. better for range resolution, # but not very good for frequency selectivity. # obuf=stuffr.decimate(recv_buffer,dec=dec) obuf.tofile(fname)
def windowing(surv_ch, window_function): """ Description: ------------ Applies the specified window function on the surveillance channel. Using the appropriate window function the energy leakage of the reflected signal component in the Doppler domain can be avoided. To select the desired window function chose one from the followings: - "Rectangular" - "Flat top" - "Hamming" - "Hann" - "Tukey" - "Blackman" - "Blackman-Harris" Parameters: ----------- :param: surv_ch: Surveillance channel :param: window_function: (string) Name of the applied window function Return values: -------------- """ if window_function == "Rectangular": window = np.ones(surv_ch.size) elif window_function == "Flat top": window = signal.flattop(surv_ch.size) elif window_function == "Hamming": window = signal.hamming(surv_ch.size) elif window_function == "Hann": window = signal.hann(surv_ch.size) elif window_function == "Tukey": window = signal.tukey(surv_ch.size) elif window_function == "Blackman": window = signal.blackman(surv_ch.size) elif window_function == "Blackman-Harris": window = signal.blackmanharris(surv_ch.size) else: print("Window function is not identified") return surv_ch * window
def calcAvgPs(umtrx, rxStream, fftSize = 4096, numFFT = 10, numSkips=2): samps = numpy.array([0]*fftSize, numpy.complex64) avgFFT = numpy.array([0]*fftSize, numpy.complex64) while umtrx.readStream(rxStream, [samps], fftSize, 0, 1000).ret != SOAPY_SDR_TIMEOUT: pass #read until timeout umtrx.activateStream(rxStream, SOAPY_SDR_END_BURST, 0, fftSize*(numFFT+numSkips)) numActualFFTs = 0 for i in range(numFFT+numSkips): if umtrx.readStream(rxStream, [samps], fftSize).ret != fftSize: print 'D' return calcAvgPs(umtrx, rxStream, fftSize, numFFT, numSkips) if i < numSkips: continue #skip first for transients samps *= signal.flattop(fftSize) avgFFT += numpy.fft.fft(samps) numActualFFTs += 1 avgFFT /= numActualFFTs assert(len(avgFFT) == fftSize) ps = 10*numpy.log10(numpy.abs(avgFFT)) - 20*math.log10(fftSize) freqs = numpy.fft.fftfreq(fftSize, 1.0/SAMP_RATE) return ps, freqs
def mperiodogram(signal, win='Bartlett', n1=0, n2=0, exp=0, ax=0): if n1 == 0 and n2 == 0: # por defecto usa la selal completa n1 = 0 n2 = len(signal) N = n2 - n1 if win == "Bartlett": w = np.bartlett(N) elif win == "Hanning": w = np.hanning(N) elif win == "Hamming": w = np.hamming(N) elif win == "Blackman": w = np.blackman(N) elif win == "Flattop": w = sg.flattop(N) else: w = sg.boxcar(N) aux = signal[n1:n2] * w U = sum(np.abs(w)**2) / N return periodogram(aux, exp, ax=ax) / U
def plot(self, tab1, tab2, canal_1, canal_2, canal_3, win_var=1): num_datos = len(canal_1) X = range(0, num_datos, 1) # Scale the signal in g's for indice in X: canal_1[indice] *= g_scale canal_2[indice] *= g_scale canal_3[indice] *= g_scale # Calculates medium value for each channel. vdc_canal_1 = 0 vdc_canal_2 = 0 vdc_canal_3 = 0 for indice in X: vdc_canal_1 += canal_1[indice] vdc_canal_2 += canal_2[indice] vdc_canal_3 += canal_3[indice] vdc_canal_1 = vdc_canal_1 / num_datos vdc_canal_2 = vdc_canal_2 / num_datos vdc_canal_3 = vdc_canal_3 / num_datos #print("Vdc Channel 1: {0}, Vdc Channel 2: {1}".format(vdc_canal_1, vdc_canal_2)) # Substract DC offset for indice in X: canal_1[indice] -= vdc_canal_1 canal_2[indice] -= vdc_canal_2 canal_3[indice] -= vdc_canal_3 #----------------- Plotting ---------- X1 = np.linspace(0, num_datos/5, num=num_datos) # X axis, 5000 sps, 1/5 ms. # Figure 1. Sampled signals. #Channel X ax_11, ax_12, ax_13 = self.canvas2.figure.get_axes() ax_11.clear() ax_11.plot(X1,canal_1) ax_11.set_title("Channel X") ax_11.set_ylabel('g') ax_11.grid() #Shows grid. #Channel Y ax_12.clear() ax_12.plot(X1,canal_2) ax_12.set_title("Channel Y") #ax_12.set_xlabel('ms') ax_12.set_ylabel('g') ax_12.grid() #Shows grid. #Channel Z ax_13.clear() ax_13.plot(X1,canal_3) ax_13.set_title("Channel Z") ax_13.set_xlabel('ms') ax_13.set_ylabel('g') ax_13.grid() #Shows grid. # Figure 2. FFT from signals. #Channel X canal_fft = [] canal_fft = canal_1 N = len(canal_fft) # length of the signal #Window function if(win_var == 2): w = signal.hann(N, sym=False) #Hann (Hanning) window elif(win_var == 3): w = signal.flattop(N, sym=False) #Flattop window else: w = 1 #Rectangular window T = 1.0 / sample_rate y = canal_fft yf = fftpack.fft(y*w)*(2/N) yf = yf[:int(N/2)] xf = np.linspace(0.0, 1.0/(2.0*T), N/2) ax_21, ax_22, ax_23 = self.canvas1.figure.get_axes() ax_21.clear() #ax_21.plot(xf, 2.0/N * np.abs(yf[:N/2])) ax_21.plot(xf, np.abs(yf)) ax_21.grid() ax_21.set_title("Channel X") ax_21.set_ylabel('g') ax_21.set_xlim(xmax=max_freq) #Channel Y canal_fft = [] canal_fft = canal_2 N = len(canal_fft) # length of the signal T = 1.0 / sample_rate y = canal_fft yf = fftpack.fft(y*w)*(2/N) yf = yf[:int(N/2)] xf = np.linspace(0.0, 1.0/(2.0*T), N/2) ax_22.clear() #ax_22.plot(xf, 2.0/N * np.abs(yf[:N/2])) ax_22.plot(xf, np.abs(yf)) ax_22.grid() ax_22.set_title("Channel Y") #ax_22.set_xlabel('Hz') ax_22.set_xlim(xmax=max_freq) ax_22.set_ylabel('g') #Channel Z canal_fft = [] canal_fft = canal_3 N = len(canal_fft) # length of the signal T = 1.0 / sample_rate y = canal_fft yf = fftpack.fft(y*w)*(2/N) yf = yf[:int(N/2)] xf = np.linspace(0.0, 1.0/(2.0*T), N/2) ax_23.clear() #ax_23.plot(xf, 2.0/N * np.abs(yf[:N/2])) ax_23.plot(xf, np.abs(yf)) ax_23.grid() ax_23.set_title("Channel Z") ax_23.set_xlabel('Hz') #ax_23.set_xlim(xmax=max_freq) ax_23.set_xlim(xmax=max_freq_z) ax_23.set_ylabel('g') self.canvas1.draw() self.canvas2.draw()
def DoFFT(): # Fast Fourier transformation global SIGNAL1 global SAMPLEsize global TRACEmode global TRACEaverage global TRACEreset global ZEROpadding global FFTresult global fftsamples global SIGNALlevel global FFTwindow global NUMPYenabled global SMPfftlist global SMPfftindex global LONGfftsize #show what we are doing on the screen # FFT can take a long time! txt = "->FFT" x = X0L + 333 y = Y0T+GRH+32 IDtxt = ca.create_text (x, y, text=txt, anchor=W, fill=COLORred) root.update() # update screen T1 = time.time() # For time measurement of FFT routine # No FFT if empty or too short array of audio samples if len(SIGNAL1) >= 1<<24: # ensure only valid buffer sizes fftsamples = 1<<24 # can set this to be less than buffer size to make it faster elif len(SIGNAL1) >= 1<<23: # ensure only valid buffer sizes fftsamples = 1<<23 # can set this to be less than buffer size to make it faster elif len(SIGNAL1) >= 1<<22: # ensure only valid buffer sizes fftsamples = 1<<22 # can set this to be less than buffer size to make it faster elif len(SIGNAL1) >= 1<<21: # ensure only valid buffer sizes fftsamples = 1<<21 # can set this to be less than buffer size to make it faster elif len(SIGNAL1) >= 1<<20: # ensure only valid buffer sizes fftsamples = 1<<20 # can set this to be less than buffer size to make it faster elif len(SIGNAL1) >= 1<<19: # ensure only valid buffer sizes fftsamples = 1<<19 # can set this to be less than buffer size to make it faster elif len(SIGNAL1) >= 1<<18: # ensure only valid buffer sizes fftsamples = 1<<18 # can set this to be less than buffer size to make it faster elif len(SIGNAL1) >= 131072: # ensure only valid buffer sizes fftsamples = 131072 elif len(SIGNAL1) >= 65536: # ensure only valid buffer sizes fftsamples = 65536 elif len(SIGNAL1) >= 32768: # ensure only valid buffer sizes fftsamples = 32768 elif len(SIGNAL1) >= 16384: # ensure only valid buffer sizes fftsamples = 16384 elif len(SIGNAL1) >= 8192: # ensure only valid buffer sizes fftsamples = 8192 else: return # not a valid buffer size # print "Buffersize:" + str(len(SIGNAL1)) + " FFTsize: " + str(fftsamples) SAMPLEsize= fftsamples n = 0 SIGNALlevel = 0.0 v = 0.0 m = 0 # For calculation of correction factor SIGNAL1A = numpy.abs(SIGNAL1) SIGNALlevel = numpy.max(SIGNAL1A) # Cosine window function # medium-dynamic range B=1.24 if FFTwindow == 1: w = numpy.arange(fftsamples) w = numpy.multiply(w,math.pi) w = numpy.divide(w,fftsamples -1) w = numpy.sin(w) w = numpy.multiply(w,1.571) REX = numpy.multiply(SIGNAL1[:fftsamples],w) # Triangular non-zero endpoints # medium-dynamic range B=1.33 elif FFTwindow == 2: w = signal.triang(fftsamples) w = numpy.multiply(w,2.0) REX = numpy.multiply(SIGNAL1[:fftsamples],w) # Hann window function # medium-dynamic range B=1.5 elif FFTwindow == 3: w = signal.hann(fftsamples) w = numpy.multiply(w,2.0) REX = numpy.multiply(SIGNAL1[:fftsamples],w) # Blackman window, continuous first derivate function # medium-dynamic range B=1.73 elif FFTwindow == 4: w = signal.blackman(fftsamples) w = numpy.multiply(w,2.381) REX = numpy.multiply(SIGNAL1[:fftsamples],w) # Nuttall window, continuous first derivate function # high-dynamic range B=2.02 elif FFTwindow == 5: w = signal.nuttall(fftsamples) w = numpy.multiply(w,2.811) REX = numpy.multiply(SIGNAL1[:fftsamples],w) elif FFTwindow == 6: w = signal.flattop(fftsamples) # w = numpy.multiply(w,1.0) REX = numpy.multiply(SIGNAL1[:fftsamples],w) else: # no window (rectangular) REX = SIGNAL1[:fftsamples] # if m > 0: # For calculation of correction factor # print 1/m # For calculation of correction factor # Zero padding of array for better interpolation of peak level of signals ZEROpaddingvalue = int(math.pow(2,ZEROpadding) + 0.5) fftsamples = ZEROpaddingvalue * fftsamples # Add zero's to the arrays #fftsamples = ZEROpaddingvalue * fftsamples -1 # Add zero's to the arrays # The FFT calculation with NUMPY if NUMPYenabled == True or with the FFT calculation below # tbeg = time.time(); fftresult = numpy.fft.fft(REX, n=fftsamples)# Do FFT+zeropadding till n=fftsamples with NUMPY if NUMPYenabled == True # tend = time.time(); # print "fft.comp.done: " + str(tend -tbeg) REX=fftresult.real IMX=fftresult.imag # Make FFT result array Totalcorr = float(ZEROpaddingvalue)/ fftsamples # For VOLTAGE! Totalcorr = Totalcorr * Totalcorr # For POWER! FFTmemory = FFTresult FFTresult = [] #print len(FFTmemory) v = numpy.absolute(fftresult); v = numpy.square(v) v = numpy.multiply(v,Totalcorr) if TRACEmode == 2 and TRACEreset == False: # Max hold, change v to maximum value v = numpy.max(v,FFTmemory) elif TRACEmode == 3 and TRACEreset == False: # Average, add difference / TRACEaverage to v v = numpy.subtract(v,FFTmemory) v = numpy.divide(v,TRACEaverage) v = numpy.add(v,FFTmemory) FFTresult = v TRACEreset = False # Trace reset done T2 = time.time() print ("total fft" + str(T2 - T1)) # For time measurement of FFT routine
# SPDX-License-Identifier: MIT # Copyright (c) 2019-2021 Thomas Vanderbruggen <*****@*****.**> import numpy as np from scipy.signal import flattop if __name__ == "__main__": noise = np.random.randn(10000) print("Noise: mean = {}, std = {}".format(np.mean(noise), np.std(noise))) w = flattop(len(noise)) W = np.sum(w ** 2) fs = 1.0 psd = 2.0 * np.absolute(np.fft.rfft(noise * w)) ** 2 / (fs * W) # The expected PSD for a white noise is 2 * sigma ^ 2 print("PSD = {}".format(np.mean(psd)))
def spectrogram(self, filename, wavfile, framerate, msmode=False, hzmode=False, minX=None,maxX=None,minY=None,maxY=None): increment = 128 nwindow = 256 window = flattop(nwindow) nfft = nwindow # Convert wavfile into array wavfile_array = [] for i in wavfile: wavfile_array.append(i) numPoints = len(wavfile) spec = [] for i in range(0,len(wavfile_array)-nwindow,increment): buf = wavfile_array[i:i+nwindow] N = nwindow X = abs(fft.fft(window*buf, nfft)) f = linspace(0,framerate,N+1)[:N] Nout = N/2 + 1 spec.append(X[Nout:]) timescale = 1 if msmode: timescale = 1000 freqscale = 0.001 if hzmode: freqscale = 1 scale = 1 spec = transposed(spec) FILE = open(filename+'_SA_.z', 'w') FILE.write('! nx '+str(len(spec[0]))+' ny '+str(len(spec)/scale)+' xmin 0 xmax '+str(timescale*len(wavfile_array)/float(framerate))+' ymin 0 ymax '+str(freqscale*framerate/2.0)+"\n") maxval = -100 for y in range(0,len(spec),scale): for x in range(0,len(spec[y]),1): if spec[y][x] > maxval: maxval = spec[y][x] maxval = float(maxval) for y in range(0,len(spec),scale): for x in range(0,len(spec[y]),1): FILE.write(str(1-spec[len(spec)-y-1][x]/maxval)+" ") FILE.write("\n") FILE.close() if minX == None: minX = 0 if maxX == None: maxX = float(len(wavfile))/framerate if minY == None: minY = 0 if maxY == None: maxY = float(framerate)/2 s = ['size '+str(self.width)+' '+str(self.height)] s.append('include "color.gle"') s.append('set font psh') s.append('set hei 0.4') s.append('begin graph') s.append('nobox') s.append('x2axis off') s.append('y2axis off') if msmode: s.append('xtitle "Time (ms)"') else: s.append('xtitle "Time (s)"') if hzmode: s.append('ytitle "Frequency (Hz)"') else: s.append('ytitle "Frequency (kHz)"') s.append('xticks length -0.1') s.append('yticks length -0.1') s.append('title ""') s.append('xaxis min '+str(minX)+' max '+str(maxX)) s.append('yaxis min '+str(minY*freqscale)+' max '+str(maxY*freqscale)) s.append('colormap "'+filename.rsplit('/')[-1]+'_SA_.z" 300 200 color') s.append('end graph') FILE = open(filename+'_SA_.gle', 'w') FILE.writelines('\n'.join(s)) FILE.close() glecall = ['/usr/bin/gle', '-device', self.format, '-output', filename+'_SA_.'+self.format, filename+'_SA_.gle'] pid,stdin,stdout,stderr = spawn_async(glecall, flags=SPAWN_DO_NOT_REAP_CHILD) return pid
plt.ylabel('frequencia') plt.xlabel('valores') plt.title('Histograma Uniforme') plt.savefig("Histograma.png") plt.show() #%% generación de señales f1 = f0 + fa del fa ventanas = [ sg.boxcar(N), np.bartlett(N), np.hanning(N), np.blackman(N), sg.flattop(N) ] V = len(ventanas) ventana = ["Rectangular", 'Barlett', "Hanning", "Blackman", "Flattop"] sesgo = np.zeros((V)) a_est = np.zeros((Nexp, V)) a_mean = np.zeros((V)) varianza = np.zeros((V)) tt = np.linspace(0, (N - 1) / fs, N) for (ii, this_w) in zip(range(V), ventanas): signal = np.vstack( np.transpose([a0 * np.sin(2 * np.pi * j * tt) * this_w for j in f1])) mod_signal = np.vstack( np.transpose(
#import seaborn as sns os.system ("clear") # limpia la terminal de python plt.close("all") #cierra todos los graficos N = 1000 # muestras fs = 1000 # Hz df = fs / N a0 = 2 # Volts p0 = 0 # radianes f0 = fs / 4 M = 9*N ventanas = [np.bartlett(N), wds.triang(N), np.hanning(N), wds.hann(N), np.blackman(N), wds.blackamanHarris(N), sg.flattop(N), wds.flattop(N), sg.boxcar(N), sg.boxcar(N)] V = len(ventanas) ventana = ["Bartell", "my_Triang", "Hanning", "my_Hanning", "Blackman", "my_Blackman", "Flattop", "my_Flattop", "Rectangular", "my_Rectangular"] aux_padding = np.zeros(M, float) # creo las ventanas y obtengo el móduo de su dft signal = np.vstack(np.transpose([this_w for this_w in ventanas])) mod_signal = np.vstack(np.transpose([np.abs(np.fft.fft(signal[:,ii]))*2/N for ii in range(V)])) # creo las ventanas con zero padding y obtengo el móduo de su dft signal_padding = np.vstack(np.transpose([np.concatenate((this_w,aux_padding), axis=0) for this_w in ventanas])) mod_signal_padding = np.vstack(np.transpose([np.abs(np.fft.fft(signal_padding[:,ii]))*2/(N + M) for ii in range(V)])) # la paso en dB mod_signal = 20 *np.log10(mod_signal/mod_signal[0])
def flattop_filter1d(data, width, axis=0, mode='reflect'): window_size = round(width / 0.2327) window = signal.flattop(window_size) window = window / np.sum(window) result = ndimage.convolve1d(data, window, axis=axis, mode='reflect') return (result)
newAmp1 = analyticalTran1 * 1 newAmp2 = newAmp1 * analyticalTran2 if (assertion): return newAmp1 print("Analytical Transmission from region 1-2, new amplitude: ", newAmp1) print("Analytical Transmission from region 2-3, new amplitude: ", newAmp2) print("Free space dispersion: ", Decimal(freeSpaceVpinC0)) print("Material dispersion: ", Decimal(discrep)) print("matVpInC0: ", Decimal(matVpinC0)) print("actualVPinC0 : ", Decimal(actualVpinC0)) winHann = sign.hann(timeSteps) winBlack = sign.blackman(timeSteps) winHamm = sign.hamming(timeSteps) winFlat = sign.flattop(timeSteps) def smoothTurnOn(): ppw = c0 / (freq_in * dz) for timer in range(timeSteps): if (timer * dt < period): Ezs.append( float(Decimal(np.sin(2.0 * np.pi / ppw * (courantNo * timer))))) Hys.append( float( Decimal( np.sin(2.0 * np.pi / ppw * (courantNo * (timer + 1))))))
# Plot the window and its frequency response: from scipy import signal from scipy.fftpack import fft, fftshift import matplotlib.pyplot as plt window = signal.flattop(51) plt.plot(window) plt.title("Flat top window") plt.ylabel("Amplitude") plt.xlabel("Sample") plt.figure() A = fft(window, 2048) / (len(window) / 2.0) freq = np.linspace(-0.5, 0.5, len(A)) response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) plt.plot(freq, response) plt.axis([-0.5, 0.5, -120, 0]) plt.title("Frequency response of the flat top window") plt.ylabel("Normalized magnitude [dB]") plt.xlabel("Normalized frequency [cycles per sample]")
center = int(np.floor(N / 2)) modX = modX[center:N] modX = 20 * np.log10(modX) freq = np.linspace(0, 0.5, len(modX)) plt.plot(freq, modX) plt.title("blackman", fontsize=20) plt.xlim(0.2, 0.3) plt.xlabel("Frecuencia normalizada", fontsize=20) plt.ylabel("Amplitud en dB", fontsize=20) plt.grid() ######################### ###ventana flattop### ######################### plt.figure("flattop") rectWindow = sig.flattop(N) a2dB = -85 a2 = 10**(a2dB / 20) x1 = np.sin(2 * np.pi * f1 * tt) x2 = a2 * np.sin(2 * np.pi * f2 * tt) x = x1 + x2 x = x * rectWindow X = fft(x) modX = np.abs(fftshift(X)) * 2 / N center = int(np.floor(N / 2)) modX = modX[center:N] modX = 20 * np.log10(modX) freq = np.linspace(0, 0.5, len(modX)) plt.plot(freq, modX) plt.title("flattop", fontsize=20)
def flattop_filter1d(data,width, axis = 0, mode = 'reflect'): window_size = round(width/0.2327) window = signal.flattop(window_size) window = window/np.sum(window) result = ndimage.convolve1d(data, window, axis = axis, mode = 'reflect') return(result)
from scipy import signal from scipy.fftpack import fft, fftshift import matplotlib.pyplot as plt window = signal.flattop(51) plt.plot(window) plt.title("Flat top window") plt.ylabel("Amplitude") plt.xlabel("Sample") plt.figure() A = fft(window, 2048) / (len(window)/2.0) freq = np.linspace(-0.5, 0.5, len(A)) response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) plt.plot(freq, response) plt.axis([-0.5, 0.5, -120, 0]) plt.title("Frequency response of the flat top window") plt.ylabel("Normalized magnitude [dB]") plt.xlabel("Normalized frequency [cycles per sample]")
plt.xlim(0, 100) plt.xlabel('n') w = np.blackman(len(y)) y2 = y * w plt.subplot(3, 3, 5) plt.title('Okno Blackmana') plt.hlines(0, 0, 100, alpha=.2) plt.plot(y, color='black', alpha=.1) plt.plot(y, color='lightgray') plt.plot(y2) plt.plot(w) plt.xlim(0, 100) plt.xlabel('n') w = signal.flattop(len(y)) y2 = y * w plt.subplot(3, 3, 6) plt.title('Okno Flat-top') plt.hlines(0, 0, 100, alpha=.2) plt.plot(y, color='black', alpha=.1) plt.plot(y, color='lightgray') plt.plot(y2) plt.plot(w) plt.xlim(0, 100) plt.xlabel('n') w = np.kaiser(len(y), 20) y2 = y * w plt.subplot(3, 3, 7) plt.title(r'Okno Kaisera $\beta=20$')
# -*- coding: utf-8 -*- """ Created on Tue Oct 22 00:54:03 2019 @author: fede """ import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from numpy.fft import fft, fftshift import scipy.signal as sig N = 60 # muestras fftSize = 2048 ventanas = [sig.boxcar(N), sig.bartlett(N), sig.hann(N), sig.blackman(N), sig.flattop(N)] ventanas_names = ["rectangular", "bartlett", "hanning", "blackman", "flattop"] V = len(ventanas_names) plt.figure("Ventanas", figsize = (10,10)) for (vv, this_win) in zip(ventanas_names, ventanas): plt.plot(this_win, label=vv) plt.legend() plt.grid() plt.xlabel("Numero de muestra") plt.ylabel("Amplitud de la ventana") plt.title("Forma de ventanas") complexMat = np.transpose(np.vstack([fft(thisWin,fftSize, axis=0) for thisWin in ventanas])) #fft(signal, size) Si size > len(signal) la FFT le hace zero padding automaticamente :)
# Agrego cuantizador xQ = cuantizador(x, bits, "ROUND") xQ = xQ / (2**(bits - 1) - 1) #Normalizo la cuatizacion # Grafico señal #graficar(tt1,xQ,0,'x = x1+ x2','f(x)','t') # Obtengo el espectro ff, espectroX = analizadorEspectro(xQ) # Grafico el espectro graficarEspectro_dB(ff, espectroX, 1, "Espectro $X(k)$") # Genero ventaneando la señal ventana_blackmanharris = signal.blackmanharris(len(xQ)) my_bartlett = flatTop(len(xQ)) np_bartlett = signal.flattop(len(xQ)) xQ_blackmanharris = xQ * ventana_blackmanharris graficar(tt1, my_bartlett, 0, 'xQ_blackmanharris', 'x(t)', 't') graficar(tt1, np_bartlett, 0, 'xQ_blackmanharris', 'x(t)', 't') # Grafico la señal ventaneada graficar(tt1, xQ_blackmanharris, 0, 'xQ_blackmanharris', 'x(t)', 't') # Obtengo el espectro de la señal ventaneada ff, espectroX_blackmanharris = analizadorEspectro(xQ_blackmanharris) # Grafico el espectro graficarEspectro_dB(ff, espectroX_blackmanharris, 1, "Espectro $X(k)$")
import scipy.signal as sig from scipy.fftpack import fft, fftshift N = 1000 fs = 1000 Ts = 1 / fs tt = np.linspace(0, (N - 1) * Ts, N) ventanas = [ 1, sig.boxcar(N), sig.bartlett(N), sig.hann(N), sig.blackman(N), sig.flattop(N) ] ##Rect d = 2.8 f1 = fs / 4 + 0.5 * fs / N f2 = f1 + d * (fs / N) a2 = 1 x1 = np.sin(2 * np.pi * f1 * tt) x2 = a2 * np.sin(2 * np.pi * f2 * tt) x = x1 + x2 xw = x * sig.boxcar(N) X = fft(xw) modX = np.abs(fftshift(X)) * 2 / N center = int(np.floor(N / 2)) modX = modX[center:N]
data_buf = np.frombuffer(target_buffers[ch].contents, dtype=np.int16, count=samples_added[ch]) data_numpy[ch] = np.append(data_numpy[ch], data_buf) # If we have enough data to update the FFT plot, do it for ch in range(0,number_of_iqchannels): if len(data_numpy[2*ch]) >= fftlength and len(data_numpy[2*ch+1]) >= fftlength: # Calculate FFT from complex-valued data iqdata = np.zeros(fftlength, complex) iqdata.real = data_numpy[2*ch + 0][0:fftlength] iqdata.imag = data_numpy[2*ch + 1][0:fftlength] data_numpy[2*ch + 0] = data_numpy[2*ch + 0][fftlength:] data_numpy[2*ch + 1] = data_numpy[2*ch + 1][fftlength:] iqdata = np.multiply(iqdata,signal.flattop(fftlength)) iqfft = 20*np.log10(np.abs(np.fft.fft(iqdata))/iqdata.size/2**(target_bytes_per_sample*8-2)) iqfft = np.fft.fftshift(iqfft) # Update plot try: fftline[ch].set_ydata(iqfft) fig.canvas.draw() fig.canvas.flush_events() except: ADQAPI.DeleteADQControlUnit(adq_cu) sys.exit() if(ADQAPI.ADQ_GetStreamOverflow(adq_cu,adq_num)): print('Overflow detected, shutting down') overflow = 1
start = 0 end = 31 m_vals = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0] for i in range(12): daily_ave.append(np.mean(model_cut[start * 24:end * 24:8760])) start += m_vals[i] end += m_vals[i + 1] #daily_ave_e = daily_ave[19:24] + daily_ave[0:19] plt.plot(range(12), daily_ave) #annual_index = np.argmin(np.abs(model_periods - 1)) #print 'annual model phase= ', fft_phase[annual_index] #Divide output by sampling freq window = signal.flattop(len(model_cut)) #window = np.kaiser(len(model_cut),4) model_mean = np.mean(model_cut) model_cut = model_cut - model_mean model_cut = model_cut * window #model_cut = model_cut[:-2] #model_time = model_time[:-2] #fc, fd, model_amp, model_ph= lomb.fasper(model_time,model_cut) #fft_array = fft(model_cut) #fft_mag = np.abs(fft_array) #fft_phase = [phase(i) for i in fft_array] #fft_phase = np.array(fft_phase) #fft_freqs = fftfreq(len(model_cut),hourly_step) #valid = fft_freqs > 0
def test_flattop(self): size = randint(0, 1000) generated = windowing.flattop(size) reference = signal.flattop(size) np.testing.assert_array_almost_equal(reference, generated)
#%% generación de frecuencias aleatorias fa = np.random.uniform(a, b, size = (Nexp)) # genera aleatorios plt.figure("histograma de frecuencias aleatorias") plt.hist(fa, bins=20, alpha=1, edgecolor = 'black', linewidth=1) plt.ylabel('frequencia') plt.xlabel('valores') plt.title('Histograma Uniforme') plt.savefig("Histograma.png") plt.show() #%% generación de señales f1 = f0 + fa del fa ventanas = [sg.boxcar(N), np.bartlett(N), np.hanning(N), np.blackman(N), sg.flattop(N)] V = len(ventanas) ventana = ["Rectangular",'Barlett',"Hanning", "Blackman", "Flattop"] sesgo = np.zeros((V)) a_est = np.zeros((Nexp, V)) a_mean = np.zeros((V)) varianza = np.zeros((V)) tt = np.linspace(0, (N-1)/fs, N) for (ii, this_w) in zip(range(V), ventanas): signal = np.vstack(np.transpose([a0 * np.sin(2*np.pi*j*tt) * this_w for j in f1])) mod_signal = np.vstack(np.transpose([np.abs(np.fft.fft(signal[:,ii]))*2/N for ii in range(Nexp)])) mod_signal = mod_signal[0:int(N/2)]
a0 = 2 # Volts df = np.random.uniform(-2, 2, k) fn = f0 + df * fs / N Ts = 1 / fs tt = np.linspace(0, (N - 1) * Ts, N) x = np.transpose(np.vstack([a0 * np.sin(2 * np.pi * ff * tt) for ff in fn])) ventana = [ sig.boxcar(N), sig.bartlett(N), sig.hann(N), sig.blackman(N), sig.flattop(N) ] V = len(ventana) sesgo = np.zeros(V) var = np.zeros(V) prom = np.zeros(V) dist = np.zeros((k, V)) for (vv, this_win) in zip(range(V), ventana): X = np.transpose(np.vstack([x[:, kk] * this_win for kk in range(0, k)])) X = fft(X, axis=0) modX = np.abs(fftshift(X)) * 2 / N center = int(np.floor(N / 2)) modX = modX[center:N]
if radioConfig.cropPercentage > 0: cmdstring = cmdstring + " -x " + str(radioConfig.cropPercentage) cmdstring = cmdstring + " -e " + datagathduration cmdstring = cmdstring + " -q" if radioConfig.linearPower: cmdstring = cmdstring + " -l" if radioConfig.fftWindow != "": if radioConfig.fftWindow == "BlacHarr": window = signal.blackmanharris(freqbins) elif radioConfig.fftWindow == "DolpCheb": window = signal.chebwin(freqbins, at=80) elif radioConfig.fftWindow == "FlatTop": window = signal.flattop(freqbins) file = open("window.txt","w") for wparm in window: file.write('{0:.12f}\n'.format(wparm)) file.close() cmdstring = cmdstring + " -w window.txt" if radioConfig.sessionDurationMin == 0: loopForever = True else: loopForever = False numscans = radioConfig.sessionDurationMin / radioConfig.dataGatheringDurationMin scancnt = 1