def test_basic(self): assert_allclose(signal.nuttall(6, sym=False), [0.0003628, 0.0613345, 0.5292298, 1.0, 0.5292298, 0.0613345]) assert_allclose(signal.nuttall(6), [0.0003628, 0.1105152530498718, 0.7982580969501282, 0.7982580969501283, 0.1105152530498719, 0.0003628]) assert_allclose(signal.nuttall(7, True), [0.0003628, 0.0613345, 0.5292298, 1.0, 0.5292298, 0.0613345, 0.0003628])
def test_basic(self): assert_allclose(signal.nuttall(6, sym=False), [0.0003628, 0.0613345, 0.5292298, 1.0, 0.5292298, 0.0613345]) assert_allclose(signal.nuttall(7, sym=False), [0.0003628, 0.03777576895352025, 0.3427276199688195, 0.8918518610776603, 0.8918518610776603, 0.3427276199688196, 0.0377757689535203]) assert_allclose(signal.nuttall(6), [0.0003628, 0.1105152530498718, 0.7982580969501282, 0.7982580969501283, 0.1105152530498719, 0.0003628]) assert_allclose(signal.nuttall(7, True), [0.0003628, 0.0613345, 0.5292298, 1.0, 0.5292298, 0.0613345, 0.0003628])
def fft_proc(self, data): self.send_coor(data) h_len = self.data_len window = sp.nuttall(h_len) x_fft = np.fft.rfft((data[:h_len] - np.mean(data[:h_len])) * window, len(data[:h_len]), norm='ortho') z_fft = np.fft.rfft( (data[h_len:len(data)] - np.mean(data[h_len:len(data)])) * window, len(data[h_len:len(data)]), norm='ortho') freq = np.fft.rfftfreq(h_len, 1) self.send_fft(np.concatenate([freq, np.abs(x_fft), np.abs(z_fft)])) # searching of working DR point try: x_arr = freq[np.where((freq < self.x_bound[1]) & (freq > self.x_bound[0]))] z_arr = freq[np.where((freq < self.z_bound[1]) & (freq > self.z_bound[0]))] x_index = np.argmax( np.abs(x_fft)[np.where((freq < self.x_bound[1]) & (freq > self.x_bound[0]))]) z_index = np.argmax( np.abs(z_fft)[np.where((freq < self.z_bound[1]) & (freq > self.z_bound[0]))]) x_tune = round(x_arr[x_index], 6) z_tune = round((1 - z_arr[z_index]), 6) self.collect_tunes(np.array([x_tune, z_tune])) except ValueError: pass
def calc_rfft(cube): cube = np.array(cube) nfreq, ny, nx = cube.shape data = cube.reshape((nfreq, ny*nx)) data = np.swapaxes(data, 0, 1) # [npix, nfreq] window = signal.nuttall(nfreq, sym=False) data *= window[np.newaxis, :] return np.fft.rfft(data, axis=1)
def recompute_window(self): zoom = int(self.width * (self.get_eff_sample_rate()) / self.zoom_fac) if self.filter == 'kaiser': self.window = signal.kaiser( freqshow.SDR_SAMPLE_SIZE, self.kaiser_beta, False, )[0:zoom + 2] # for every bin there is a window the same exact size as the read samples. elif self.filter == 'boxcar': self.window = signal.boxcar( freqshow.SDR_SAMPLE_SIZE, False, )[0:zoom + 2] elif self.filter == 'hann': self.window = signal.hann( freqshow.SDR_SAMPLE_SIZE, False, )[0:zoom + 2] elif self.filter == 'hamming': self.window = signal.hamming( freqshow.SDR_SAMPLE_SIZE, False, )[0:zoom + 2] elif self.filter == 'blackman': self.window = signal.blackman( freqshow.SDR_SAMPLE_SIZE, False, )[0:zoom + 2] elif self.filter == 'blackmanharris': self.window = signal.blackmanharris( freqshow.SDR_SAMPLE_SIZE, False, )[0:zoom + 2] elif self.filter == 'bartlett': self.window = signal.bartlett( freqshow.SDR_SAMPLE_SIZE, False, )[0:zoom + 2] elif self.filter == 'barthann': self.window = signal.barthann( freqshow.SDR_SAMPLE_SIZE, False, )[0:zoom + 2] elif self.filter == 'nuttall': self.window = signal.nuttall( freqshow.SDR_SAMPLE_SIZE, False, )[0:zoom + 2] else: self.window = 1
def getFreq(data, framesNumber, frameRate): time = float(framesNumber) / frameRate data = data * signal.nuttall(framesNumber) dataFFT = fft(data) absFFT = abs(dataFFT) logAbsFFT = np.log(absFFT) hps = copy(logAbsFFT) for h in np.arange(2, 6): decim = signal.decimate(logAbsFFT, int(h)) hps[:len(decim)] += decim start = 150 peak = np.argmax(hps[start::]) fundamental = ((start + peak) / time) return fundamental
def getFreq(data,framesNumber,frameRate): time = float(framesNumber) / frameRate data = data * signal.nuttall(framesNumber) dataFFT = fft(data) absFFT = abs(dataFFT) logAbsFFT = np.log(absFFT) hps = copy(logAbsFFT) for h in np.arange(2, 6): decim = signal.decimate(logAbsFFT, int(h)) hps[:len(decim)] += decim start = 150 peak = np.argmax(hps[start::]) fundamental = ((start+peak)/time) return fundamental
def get_data(self): """Get spectrogram data from the tuner. Will return width number of values which are the intensities of each frequency bucket (i.e. FFT of radio samples). """ # Get width number of raw samples so the number of frequency bins is # the same as the display width. Add two because there will be mean/DC # values in the results which are ignored. Increase by 1/self.zoom_fac if needed if self.zoom_fac < (self.sdr.sample_rate / 1000000): zoom = int(self.width * ((self.sdr.sample_rate / 1000000) / self.zoom_fac)) else: zoom = self.width self.zoom_fac = self.get_sample_rate() if zoom < freqshow.SDR_SAMPLE_SIZE: freqbins = self.sdr.read_samples(freqshow.SDR_SAMPLE_SIZE)[0:zoom + 2] else: zoom = self.width self.zoom_fac = self.get_sample_rate() freqbins = self.sdr.read_samples(freqshow.SDR_SAMPLE_SIZE)[0:zoom + 2] # Apply a window function to the sample to remove power in sample sidebands before the fft. if self.filter == 'kaiser': window = signal.kaiser( freqshow.SDR_SAMPLE_SIZE, self.kaiser_beta, False, )[0:zoom + 2] # for every bin there is a window the same exact size as the read samples. elif self.filter == 'boxcar': window = signal.boxcar( freqshow.SDR_SAMPLE_SIZE, False, )[0:zoom + 2] elif self.filter == 'hann': window = signal.hann( freqshow.SDR_SAMPLE_SIZE, False, )[0:zoom + 2] elif self.filter == 'hamming': window = signal.hamming( freqshow.SDR_SAMPLE_SIZE, False, )[0:zoom + 2] elif self.filter == 'blackman': window = signal.blackman( freqshow.SDR_SAMPLE_SIZE, False, )[0:zoom + 2] elif self.filter == 'blackmanharris': window = signal.blackmanharris( freqshow.SDR_SAMPLE_SIZE, False, )[0:zoom + 2] elif self.filter == 'bartlett': window = signal.bartlett( freqshow.SDR_SAMPLE_SIZE, False, )[0:zoom + 2] elif self.filter == 'barthann': window = signal.barthann( freqshow.SDR_SAMPLE_SIZE, False, )[0:zoom + 2] elif self.filter == 'nuttall': window = signal.nuttall( freqshow.SDR_SAMPLE_SIZE, False, )[0:zoom + 2] else: window = 1 samples = freqbins * window # Run an FFT and take the absolute value to get frequency magnitudes. freqs = np.absolute(fft(samples)) # Ignore the mean/DC values at the ends. freqs = freqs[1:-1] # Reverse the order of the freqs array if swaping I and Q if self.swap_iq == True: freqs = freqs[::-1] # Shift FFT result positions to put center frequency in center. freqs = np.fft.fftshift(freqs) # Truncate the freqs array to the width of the screen if neccesary. if freqs.size > self.width: freq_step = self.get_freq_step( ) # Get the frequency step in Hz between pixels. shiftsweep = int(self.get_lo_offset() * 1000000 / freq_step) # LO offset in pixels. extra_samples = int( (freqs.size - self.width) / 2 ) # The excess samples either side of the display width in pixels. if extra_samples > abs( shiftsweep ): # check if there is room to shift the array by the LO offset. if self.get_swap_iq() == True: lextra = extra_samples + shiftsweep elif self.get_swap_iq() == False: lextra = extra_samples - shiftsweep else: lextra = extra_samples rextra = freqs.size - (lextra + self.width) freqs = freqs[lextra:-rextra] # Convert to decibels. freqs = 20.0 * np.log10(freqs) # Get signal strength of the center frequency. # for i in range ( 1, 11): # self.sig_strength = (self.get_sig_strength() + freqs[((zoom+2)/2)+i-5]) # self.sig_strength = self.get_sig_strength()/10 # Update model's min and max intensities when auto scaling each value. if self.min_auto_scale: min_intensity = np.min(freqs) self.min_intensity = min_intensity if self.min_intensity is None \ else min(min_intensity, self.min_intensity) if self.max_auto_scale: max_intensity = np.max(freqs) self.max_intensity = max_intensity if self.max_intensity is None \ else max(max_intensity, self.max_intensity) # Update intensity range (length between min and max intensity). self.range = self.max_intensity - self.min_intensity # Return frequency intensities. return freqs
def test_blackman_nuttall(self): size = randint(0, 1000) generated = windowing.blackman_nutall(size) reference = signal.nuttall(size) np.testing.assert_array_almost_equal(reference, generated)
# Plot the window and its frequency response: from scipy import signal from scipy.fftpack import fft, fftshift import matplotlib.pyplot as plt window = signal.nuttall(51) plt.plot(window) plt.title("Nuttall 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 Nuttall window") plt.ylabel("Normalized magnitude [dB]") plt.xlabel("Normalized frequency [cycles per sample]")
if nois_type not in {"MAVD", "ESC50"}: print("Possible values for noise_type parameter are: {\"MAVD\", \"ESC50\"}") exit(1) n_samp = int(sys.argv[5]) SND = sys.argv[6] try: if SND == "None": SND = None elif SND[0] == "[" and SND[-1] == "]": SND = [float(a) for a in SND.strip("][").split(",")] if len(SND) != 2: raise ValueError("Error: wrong number os elements in SND") else: SND = float(SND) except ValueError: print("Possible values for SND are None, float number or a list of two float numbers") exit(1) with cp.cuda.Device(0): N = 512 W = np.zeros((3, N)) W[0] = scisig.nuttall(N, sym=False) W[1] = scisig.gaussian(N, N / 8, sym=False) W[2] = scisig.blackmanharris(N, sym=False) generate_spectrograms(N=N, windows=W, targetDir=out_fold, sourceDir=sig_fold, sourceDirNoise=nois_fold, NSAMP=n_samp, debug=False, signalLevel=SND, noiseType=nois_type)
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
def __init__(self, OFfile): self.OFfile = OFfile OFfilePath = os.getcwd() + '/postProcessing/probes/' + OFfile with open(OFfilePath, 'r') as f: data_raw = f.read() self.data_raw = data_raw ## Separa header com comentarios data2 = self.data_raw.split("Time\n")[1] ## Divide linhas data2 = data2.split('\n') data = [] ## Divide todos dados em uma matriz for i in data2: lines = i.strip() lines = lines.split() if lines != []: lines = map(float, lines) data.append(lines) else: print( '\nWarning: Possible space between lines or at the EOF.\n') data = np.asarray(data) self.probes = np.transpose(data[:, 1:]) self.time = data[:, 0] self.mean = np.mean(self.probes, axis=1) fluct = np.zeros_like(self.probes) self.corr = [] self.pad = [] self.fft = [] self.freq = [] self.psd = [] ## faz calculo para cada probe na forma de listas for i, col in enumerate(self.mean): fluct[i] = self.probes[i] - col nutall1 = signal.nuttall(fluct[i].size) cor = np.correlate(fluct[i] * nutall1, fluct[i] * nutall1, mode='full') self.corr.append(cor / max(cor)) ## Windows signal processing #window = np.hanning(self.corr[i].size) nutall = signal.nuttall(self.corr[i].size) ## Anti aliasing self.corr[i] = self.corr[i] * nutall ## zero padding self.pad.append( np.pad(self.corr[i], 2 * self.corr[i].size, mode='constant')) ## Fourrier Transform self.fft.append(np.fft.rfft(self.pad[i])) self.freq = (np.fft.rfftfreq(self.pad[i].size)) self.psd.append(np.abs(self.fft[i])) self.meanPSD = np.mean(self.psd, axis=0) self.fluct = fluct
slc_fg = cube_fg2[50, :, :] ft_fg = np.fft.fftshift(np.fft.fft2(slc_fg)) fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(12, 6)) ax0.imshow(slc_fg) ax1.imshow(np.log10(np.abs(ft_fg)**2)) fig.tight_layout() plt.show() # In[26]: nfreq0 = cube_fg2.shape[0] window = signal.nuttall(nfreq0, sym=False) cw_fg2 = cube_fg2 * window[:, np.newaxis, np.newaxis] rft_fg2 = np.fft.rfft(cw_fg2, axis=0) rft_fg2[:nex, :, :] = 0 cw2_fg2 = np.fft.irfft(rft_fg2, n=nfreq0, axis=0) slc_fg2 = cw2_fg2[50, :, :] ft_fg2 = np.fft.fftshift(np.fft.fft2(slc_fg2)) fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(12, 6)) ax0.imshow(slc_fg2) ax1.imshow(np.log10(np.abs(ft_fg2)**2)) fig.tight_layout() plt.show()
import matplotlib.pyplot as plt import coe_wavetable_4096 as coe import functions from functions import plot_freq_db as plot_freq from functions import PulseCompr, normalize from numpy.fft import fftshift from scipy import signal freq = (coe.freq / 1e6) distance = (coe.distance) N = coe.N mean = 0 std = 0.001 noise1 = np.random.normal(mean, std, size=N) delay = 1000 win = signal.nuttall(N) #np.blackman(N) win1 = np.hamming(N) win2 = np.hanning(N) #x = signal.hilbert(win) x = win x_delay = np.roll(x, delay) x_win = np.multiply(x, win) x_win1 = np.multiply(x, win1) x_win2 = np.multiply(x, win2) x_win_delay = np.multiply(np.roll(x_win, delay), 1) plot_freq(freq, x, 'b') plot_freq(freq, x_win, 'k') plot_freq(freq, x_win1, 'm') plot_freq(freq, x_win2, 'g')
# Plot the window and its frequency response: from scipy import signal from scipy.fftpack import fft, fftshift import matplotlib.pyplot as plt window = signal.nuttall(51) plt.plot(window) plt.title("Nuttall 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 Nuttall window") plt.ylabel("Normalized magnitude [dB]") plt.xlabel("Normalized frequency [cycles per sample]")
def charex(sigdata, samplerate, offset_ms, bfo_offset_hz, debug=False): """ Actually calculate characteristics of the signal record and return the result. """ from scipy import signal # np.set_printoptions(edgeitems=100) if debug: eprint(samplerate, offset_ms, bfo_offset_hz) n_samples = samplerate * len_input_sec # Generating an LPF # Not sure if we can apply Nuttall window and also Hamming window which # firwin() automatically applies. But as same as Beacon Monitor-1 code. if 'lpf' not in dir(charex): charex.lpf = signal.nuttall(n_filter_order + 1) \ * signal.firwin(n_filter_order + 1, lpf_cutoff) # Generating an complex tone (f = samplerate / 4) # XXX There are errors in latter elements but ignorable... if 'tone_f_4' not in dir(charex): charex.tone_f_4 = \ np.exp(1j * np.deg2rad(np.arange(0, 90 * n_samples, 90))) if len(sigdata) != n_samples * n_channels * np.dtype(dtype).itemsize: eprint('Length of sigdata (%d) is illegal' % (len(sigdata))) return character1(-float('Inf'), 0, 0, 0, 0.0) # Convert the sigdata (raw stream) to input complex vector # It is okay that each I/Q value is 16-bit signed integer and as same as # the original Beacon Monitor-1 libexec/proc.m (MATLAB implementation). iq_matrix = np.frombuffer(sigdata, dtype=dtype).reshape((n_samples, 2)) input_vec = iq_matrix[..., 0] + 1j * iq_matrix[..., 1] # input_vec is like this. # [ 88.-30.j 87.-29.j 88.-27.j ..., -2. +4.j -2. +0.j -2. -1.j] # print input_vec, len(input_vec) # Apply LPF to narrow band width to half, and remove preceding samples # as same as Monitor-1 sig = signal.lfilter(charex.lpf, 1, np.append(input_vec, np.zeros(n_filter_order / 2))) sig = sig[n_filter_order / 2 : ] # Applying tone (f = samplerate / 4) to shift signal upward on freq. domain sig *= charex.tone_f_4 # Drop imaginary parts as same as Monitor-1 sig = np.real(sig) # print sig, len(sig) # Background noise estimation bg, bg_smooth = bg_est(sig, samplerate, offset_ms) # Now, start analysis in signal parts of time domain max_sn = -np.inf best_pos = 0 ct_pos = np.zeros(wid_freq_detect, dtype=np.int16) for n in range(sec_sg_from, sec_sg_until): start = n * samplerate - offset_ms / 1000 * samplerate lvl, pos, sn = \ sg_est(sig, bg_smooth, start, samplerate, offset_ms, canceling=True) ct_pos[pos] += 1 if sn > max_sn: max_sn = sn best_pos = pos # Calculating values in the no-signal part (beginning part) bg_len = get_bg_len(offset_ms, samplerate) bg_lvl, bg_pos, bg_sn = \ sg_est(sig, bg_smooth, 0, bg_len, offset_ms, canceling=False) # print 'bg_pos', bg_pos # print 'bg_len', bg_len lower_pos, upper_pos, dummy = get_sig_bins(best_pos) # print lower_pos, upper_pos, ct_pos # print ct_pos[lower_pos : upper_pos + 1] total_ct = sum(ct_pos[lower_pos : upper_pos + 1]) if debug: print 'SN: %4.1f Bias: %4d Ct: %d IF: %4d %4.1f Z: -1 -1.0' % \ (max_sn, bin_to_freq(best_pos), total_ct, bin_to_freq(bg_pos), bg_sn) return character1(max_sn, bin_to_freq(best_pos), total_ct, bin_to_freq(bg_pos), bg_sn)
def __init__(self,OFfile): self.OFfile = OFfile OFfilePath = os.getcwd() + '/postProcessing/probes/' + OFfile with open(OFfilePath,'r') as f: data_raw = f.read() self.data_raw = data_raw ## Separa header com comentarios data2 = self.data_raw.split("Time\n")[1] ## Divide linhas data2 = data2.split('\n') data = [] ## Divide todos dados em uma matriz for i in data2: lines = i.strip() lines = lines.split() if lines!=[]: lines = map(float,lines) data.append(lines) else: print('\nWarning: Possible space between lines or at the EOF.\n') data = np.asarray(data) self.probes = np.transpose(data[:,1:]) self.time = data[:,0] self.mean = np.mean(self.probes,axis=1) fluct = np.zeros_like(self.probes) self.corr = [] self.pad = [] self.fft = [] self.freq = [] self.psd = [] ## faz calculo para cada probe na forma de listas for i,col in enumerate(self.mean): fluct[i] = self.probes[i] - col nutall1 = signal.nuttall(fluct[i].size) cor = np.correlate(fluct[i]*nutall1,fluct[i]*nutall1,mode='full') self.corr.append(cor/max(cor)) ## Windows signal processing #window = np.hanning(self.corr[i].size) nutall = signal.nuttall(self.corr[i].size) ## Anti aliasing self.corr[i] = self.corr[i]*nutall ## zero padding self.pad.append(np.pad(self.corr[i],2*self.corr[i].size,mode='constant')) ## Fourrier Transform self.fft.append(np.fft.rfft(self.pad[i])) self.freq = (np.fft.rfftfreq(self.pad[i].size)) self.psd.append(np.abs(self.fft[i])) self.meanPSD = np.mean(self.psd,axis=0) self.fluct = fluct
def test_blackman_nuttall(self): size = randint(0, 1000) generated = windowing.blackman_nutall(size) reference = signal.nuttall(size) for g, r in zip(generated, reference): self.assertAlmostEqual(g, r)