def run_i_periodogram(data_sets): ''' run the periodogram using a cubic spline ''' sampling_rate = 30 ds_none = list(data_sets.items())[0][1] ds_none_name = list(data_sets.items())[0][0] for i in range(1, len(data_sets)): ds_vibration = list(data_sets.items())[i][1] ds_vibration_name = list(data_sets.items())[i][0] fig = plt.figure("Cubic Periodogram " + ds_none_name + " (left), " +ds_vibration_name + " (right)") gs = fig.add_gridspec(len(ds_none), 2, hspace=1) axs = gs.subplots() for i in range(len(ds_none)): cs = CubicSpline(ds_none[i]["t"], ds_none[i]["ds"]) times = numpy.arange(ds_none[i]["t"][0],ds_none[i]["t"][-1],1000/sampling_rate) values = cs(times) p = spectrum.Periodogram(values, sampling=sampling_rate) p.run() x, y = p.frequencies(), 10 * spectrum.tools.log10(p.psd) axs[i][0].plot(x[2:], y[2:]) for i in range(len(ds_none)): cs = CubicSpline(ds_vibration[i]["t"], ds_vibration[i]["ds"]) times = numpy.arange(ds_vibration[i]["t"][0],ds_vibration[i]["t"][-1],1000/sampling_rate) values = cs(times) p = spectrum.Periodogram(values, sampling=sampling_rate) p.run() x, y = p.frequencies(), 10 * spectrum.tools.log10(p.psd) axs[i][1].plot(x[2:], y[2:]) plt.show()
def run_periodogram(data_sets): ''' Run a periodogram on the data sets ''' ds_none = list(data_sets.items())[0][1] ds_none_name = list(data_sets.items())[0][0] for i in range(1, len(data_sets)): ds_vibration = list(data_sets.items())[i][1] ds_vibration_name = list(data_sets.items())[i][0] fig = plt.figure("Uniform Periodogram " + ds_none_name + " (left), " +ds_vibration_name + " (right)") gs = fig.add_gridspec(len(ds_none), 2, hspace=1) axs = gs.subplots() for i in range(len(ds_none)): data = ds_none[i]["ds"] p = spectrum.Periodogram(data, sampling=(len(data)/30)) p.run() x, y = p.frequencies(), 10 * spectrum.tools.log10(p.psd) axs[i][0].plot(x[2:], y[2:]) for i in range(len(ds_none)): data = ds_vibration[i]["ds"] p = spectrum.Periodogram(data, sampling=(len(data)/30)) p.run() x, y = p.frequencies(), 10 * spectrum.tools.log10(p.psd) axs[i][1].plot(x[2:], y[2:]) plt.show()
def updateSpectrum(data): '''Power spectrum density''' if not update_data.update_data.rx_stop: p = spectrum.Periodogram(P.data, sampling=P.Params['sample_freq'], window='hann') p.run() if sum(p.psd) == 0: P.PSD = np.zeros(np.size(p.psd)) P.line_spec.set_ydata(P.PSD[P.Params['start']:P.Params['end']]) else: P.PSD = np.fft.fftshift(10 * np.log10(p.psd)) P.line_spec.set_ydata(P.PSD[P.Params['start']:P.Params['end']]) P.line_spec.set_xdata(P.Params['spec_idx']) y = np.array(P.PSD[:]) ymax = max(y) idx = np.where(y > ymax * 0.9) ave = np.mean(y[idx[0][0]:idx[0][-1]]) threshold = ave / np.sqrt(2) x = np.where(y > threshold) bw = (x[0][-1] - x[0][0] + 1) * P.Params['sample_freq'] / 1e3 / P.Params[ 'input_sample_len'] #unit: KHz bandwidth = 'Bandwidth: {:.2f}KHz'.format(bw) P.bwLabel['text'] = bandwidth updateCursor() return P.line_spec,
def timerEvent(self, e): # FFT global fftbuffersize if self.datastream == None: return if self.freeze == 1: return if SELECTEDCH == BOTH12: channel = 12 X, Y = self.datastream.read(channel, fftbuffersize, verbose) if X is None or not len(X): return data_CH1 = X[:fftbuffersize] data_CH2 = Y[:fftbuffersize] elif SELECTEDCH == CH1: channel = 1 X = self.datastream.read(channel, fftbuffersize, verbose) if X is None or not len(X): return data_CH1 = X[:fftbuffersize] data_CH2 = np.ones((fftbuffersize, )) elif SELECTEDCH == CH2: channel = 2 X = self.datastream.read(channel, fftbuffersize, verbose) if X is None or not len(X): return data_CH2 = X[:fftbuffersize] data_CH1 = np.ones((fftbuffersize, )) self.df = 1.0 / (fftbuffersize * self.dt) self.setAxisTitle(Qwt.QwtPlot.xBottom, 'Frequency [Hz] - Bin width %g Hz' % (self.df, )) self.f = np.arange(0.0, samplerate, self.df) if not SPECTRUM_MODULE: lenX = fftbuffersize window = np.blackman(lenX) sumw = np.sum(window * window) A = FFT.fft(data_CH1 * window) #lenX B = (A * np.conjugate(A)).real A = FFT.fft(data_CH2 * window) #lenX B2 = (A * np.conjugate(A)).real sumw *= 2.0 # sym about Nyquist (*4); use rms (/2) sumw /= self.dt # sample rate B /= sumw B2 /= sumw else: print "FFT buffer size: %d points" % (fftbuffersize, ) B = spectrum.Periodogram(np.array(data_CH1, dtype=float64), samplerate) B.sides = 'onesided' B.run() B = B.get_converted_psd('onesided') B2 = spectrum.Periodogram(np.array(data_CH2, dtype=float64), samplerate) B2.sides = 'onesided' B2.run() B2 = B2.get_converted_psd('onesided') if self.logy: P1 = np.log10(B) * 10.0 P2 = np.log10(B2) * 10.0 P1 -= P1.max() P2 -= P2.max() else: P1 = B P2 = B2 if not self.average: self.a1 = P1 self.a2 = P2 self.avcount = 0 else: self.avcount += 1 if self.avcount == 1: self.sumP1 = P1 self.sumP2 = P2 elif self.sumP1.shape != P1.shape or self.sumP1.shape != P1.shape: self.avcount = 1 self.sumP1 = P1 self.sumP2 = P2 else: self.sumP1 += P1 self.sumP2 += P2 self.a1 = self.sumP1 / self.avcount self.a2 = self.sumP2 / self.avcount self.setDisplay()
def create_all_psd(): f = pylab.linspace(0, 1, 4096) pylab.figure(figsize=(12, 8)) # MA model p = spectrum.pma(xx, 64, 128) p() p.plot() """ #ARMA 15 order a, b, rho = spectrum.arma_estimate(data, 15,15, 30) psd = spectrum.arma2psd(A=a,B=b, rho=rho) newpsd = tools.cshift(psd, len(psd)//2) # switch positive and negative freq pylab.plot(f, 10 * pylab.log10(newpsd/max(newpsd)), label='ARMA 15,15') """ # YULE WALKER p = spectrum.pyule(xx, 7, NFFT=4096, scale_by_freq=False) p.plot() # equivalent to # plot([x for x in p.frequencies()] , 10*log10(p.psd)); grid(True) #burg method p = spectrum.pburg(xx, 7, scale_by_freq=False) p.plot() #pcovar p = spectrum.pcovar(xx, 7, scale_by_freq=False) p.plot() #pmodcovar p = spectrum.pmodcovar(xx, 7, scale_by_freq=False) p.plot() # correlogram p = spectrum.pcorrelogram(xx, lag=60, NFFT=512, scale_by_freq=False) p.plot() # minvar p = spectrum.pminvar(xx, 7, NFFT=256, scale_by_freq=False) p.plot() # pmusic p = spectrum.pmusic(xx, 10, 4, scale_by_freq=False) p.plot() # pmusic p = spectrum.pev(xx, 10, 4, scale_by_freq=False) p.plot() # periodogram p = spectrum.Periodogram(xx, scale_by_freq=False) p.plot() # legend([ "MA 32", "pyule 7", "pburg 7", "pcovar", "pmodcovar", "correlogram", "minvar", "pmusic", "pev", "periodgram" ]) pylab.ylim([-80, 80])
N = 1000 # cantidad de muestras df = fs/N # resolución espectral eps = np.finfo(float).tiny # grilla de sampleo temporal tt = np.linspace(0, (N-1)/fs, N).flatten() dd = 0.5 # prestar atención que las tuplas dentro de los diccionarios también pueden direccionarse mediante "ii" #data = np.sin( 2*np.pi*(N/4+dd)*df*tt) + np.sqrt(0.1)*np.random.randn(N) data = np.sin( 2*np.pi*(N/4+dd)*df*tt) + np.sin( 2*np.pi*(N/4+10+dd)*df*tt) + np.sqrt(0.1)*np.random.randn(N) # No paramétricos pP = sp.Periodogram(data, sampling=fs, NFFT = N ) _, pW = sg.welch(data, fs=fs, nfft=N, window='hanning', nperseg=int(np.round(N/3)) ) pBT = sp.pcorrelogram(data, sampling=fs, NFFT = N, lag=int(np.round(N/5)), window='hamming') pMT = sp.MultiTapering(data, sampling=fs, NFFT = N, NW=2 ) # Paramétricos pEig = sp.pev(data, 30, NFFT=N ) pCov = sp.pmodcovar(data, 30, NFFT = N ) pARMA = sp.parma(data, 8, 8, 30, NFFT=N) sp.pma
hamming = Window(len(x), name='hamming') f, pxx = sci.periodogram(x, window=hamming.data, fs=Fs, nfft=len(x), scaling='spectrum') pwrest = pxx.max() idx = pxx.argmax() plt.subplot(312) plt.plot(f, pxx) plt.title('Periodograma') plt.xlabel('Frequência') plt.ylabel('Potência (W)') plt.grid() plt.axis([0, 2 * fc, 0, A**2]) print('A potência máxima ocorre em ', f[idx], ' Hz') print('A potência estimada é', pwrest) plt.subplot(313) #construindo todo o procedimento com as funções da spectrum import spectrum as spec data = spec.data_cosine(N=len(x), A=10, sampling=Fs, freq=fc) p = spec.Periodogram(x, sampling=Fs, window='hamming') p.run() #Recomputa a psd caso 'x' tenha sido alterado p.plot() plt.title("Periodograma (dB) da Spectrum") plt.tight_layout() plt.show()