def test_cheb_odd_low_attenuation(self): cheb_odd_low_at_true = array([ 1.000000, 0.519052, 0.586405, 0.610151, 0.586405, 0.519052, 1.000000 ]) cheb_odd = signal.chebwin(7, at=-10) assert_array_almost_equal(cheb_odd, cheb_odd_low_at_true, decimal=4)
def plot(data, fs, rate, w_ofs, nperseg=1024, at=180): plt.subplot(2, 3, 1 + w_ofs) plt.plot(data) plt.title('Waveform') plt.subplot(2, 3, 2 + w_ofs) plt.subplots_adjust(wspace=0.8, hspace=0.6) f, t, Zxx = sg.stft(data, fs / rate, nperseg=nperseg, window=sg.chebwin(nperseg, at)) spectrum = 20 * np.log10( 2 * np.abs(Zxx) + np.random.rand(Zxx.shape[0], Zxx.shape[1]) * 1e-12) mmax = np.max(spectrum) + 6 plt.pcolormesh(t, f, spectrum, cmap='jet') plt.clim(vmin=mmax - at, vmax=mmax) plt.colorbar() plt.title('STFT Magnitude') plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]') plt.subplot(2, 3, 3 + w_ofs) plt.plot(spectrum) plt.ylim(mmax - at, mmax) plt.title('STFT Magnitude')
def test_cheb_even_low_attenuation(self): cheb_even_low_at_true = array([ 1.000000, 0.451924, 0.51027, 0.541338, 0.541338, 0.51027, 0.451924, 1.000000 ]) cheb_even = signal.chebwin(8, at=-10) assert_array_almost_equal(cheb_even, cheb_even_low_at_true, decimal=4)
def spectral_contraction(X_mag): """Spectral Contraction measure. As suggested in _[1]. Parameters ---------- X_mag : ndarray Magnitude spectrum of a time frame. Returns ------- spectral_contraction : References ---------- .. [1] Bernhard Lehner, Gerhard Widmer, Reinhard Sonnleitner "ON THE REDUCTION OF FALSE POSITIVES IN SINGING VOICE DETECTION", ICASSP 2014 """ window = chebwin(X_mag.shape[0], 200) if X_mag.ndim > 1: window = np.tile(window, (X_mag.shape[1], 1)).T spectral_contraction = np.sum(X_mag * window, axis=0) / (np.sum(X_mag, axis=0) + np.finfo(float).eps) return spectral_contraction
def test_cheb_even_low_attenuation(self): cheb_even_low_at_true = array([1.000000, 0.451924, 0.51027, 0.541338, 0.541338, 0.51027, 0.451924, 1.000000]) with suppress_warnings() as sup: sup.filter(UserWarning, "This window is not suitable") cheb_even = signal.chebwin(8, at=-10) assert_array_almost_equal(cheb_even, cheb_even_low_at_true, decimal=4)
def test_cheb_odd_low_attenuation(self): cheb_odd_low_at_true = array([1.000000, 0.519052, 0.586405, 0.610151, 0.586405, 0.519052, 1.000000]) with suppress_warnings() as sup: sup.filter(UserWarning, "This window is not suitable") cheb_odd = signal.chebwin(7, at=10) assert_array_almost_equal(cheb_odd, cheb_odd_low_at_true, decimal=4)
def test_cheb_even_low_attenuation(self): cheb_even_low_at_true = array([1.000000, 0.451924, 0.51027, 0.541338, 0.541338, 0.51027, 0.451924, 1.000000]) with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) cheb_even = signal.chebwin(8, at=-10) assert_array_almost_equal(cheb_even, cheb_even_low_at_true, decimal=4)
def test_cheb_odd_low_attenuation(self): cheb_odd_low_at_true = array([1.000000, 0.519052, 0.586405, 0.610151, 0.586405, 0.519052, 1.000000]) with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) cheb_odd = signal.chebwin(7, at=-10) assert_array_almost_equal(cheb_odd, cheb_odd_low_at_true, decimal=4)
def fft_filter(ydata, window_function=None, cutoff=[50, 690], sample_rate=None): """ Fourier filter implementation. Takes signal data in the frequency domain, and transforms into the time domain where slices are taken off. Various window functions can be applied, including stock and custom filters that I have implemented. One in particular is the house filter, which is considered the "gold standard". """ stock_windows = [ "blackmanharris", "blackman", "boxcar", "gaussian", "hanning", "bartlett", ] custom_windows = ["lowpass", "highpass", "bandpass", "chebyshev", "house"] # If a window function is provided, apply it to the frequency-domain signal # before applying the Fourier transform. if window_function: if window_function not in stock_windows and window_function not in custom_windows: pass if window_function in stock_windows: ydata *= spsig.get_window(window_function, ydata.size) else: if window_function != "chebyshev" and window_function != "house": #raise InvalidBandPassError("No frequency cut off supplied.") ydata *= butter_filter(ydata, cutoff, sample_rate, window_function) elif window_function == "chebyshev": ydata *= spsig.chebwin(ydata.size, 200.) # FFT the frequency spectrum to time domain time_domain = fft(ydata) # If no range is specified, take a prespecified chunk if cutoff is None: cutoff = [50, 690] # Make sure values are sorted cutoff = sorted(cutoff) # Apply the house filter before performing the inverse # FT back to frequency domain. if window_function == "house": house_window = house_filter(time_domain.size, *cutoff) time_domain *= house_window time_domain[:min(cutoff)] = 0. time_domain[max(cutoff):] = 0. # Return the real part of the inverse FT filtered = np.real(ifft(time_domain)) return filtered
def chebyshev_window2(lobefrac, tolerance): w = int((1 / math.pi) * (1 / lobefrac) * math.acosh(1.0 / tolerance)) if ((w % 2) != 0): w -= 1 x0 = math.cosh(math.acosh(1.0 / tolerance) / (w - 1)) w0 = 2.0 * math.acos(1.0 / x0) at = -20 * math.log10(1.0 / tolerance) x = signal.chebwin(w, at) return x
def test_basic(self): assert_allclose(signal.chebwin(6, 100), [0.1046401879356917, 0.5075781475823447, 1.0, 1.0, 0.5075781475823447, 0.1046401879356917]) assert_allclose(signal.chebwin(7, 100), [0.05650405062850233, 0.316608530648474, 0.7601208123539079, 1.0, 0.7601208123539079, 0.316608530648474, 0.05650405062850233]) assert_allclose(signal.chebwin(6, 10), [1.0, 0.6071201674458373, 0.6808391469897297, 0.6808391469897297, 0.6071201674458373, 1.0]) assert_allclose(signal.chebwin(7, 10), [1.0, 0.5190521247588651, 0.5864059018130382, 0.6101519801307441, 0.5864059018130382, 0.5190521247588651, 1.0]) assert_allclose(signal.chebwin(6, 10, False), [1.0, 0.5190521247588651, 0.5864059018130382, 0.6101519801307441, 0.5864059018130382, 0.5190521247588651])
def PSD(matrix): N1 = np.size(matrix, 1) N2 = np.size(matrix, 0) #rxx=sig.convolve2d(matrix,matrix,mode='same') rxx = matrix rxx = rxx * (chebwin(N1, at=100).reshape(1, N1) * np.ones((N2, 1))) sxx = np.fft.fft(rxx, axis=1) mag_sxx = (np.abs(sxx[:, 0:N1 // 2]) * ts)**2 mag_sxx = 10 * np.log10(np.mean(mag_sxx, 0)) F = np.linspace(0, fs // 2, len(mag_sxx)) return F, mag_sxx
def test_basic(self): with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) assert_allclose(signal.chebwin(6, 100), [0.1046401879356917, 0.5075781475823447, 1.0, 1.0, 0.5075781475823447, 0.1046401879356917]) assert_allclose(signal.chebwin(7, 100), [0.05650405062850233, 0.316608530648474, 0.7601208123539079, 1.0, 0.7601208123539079, 0.316608530648474, 0.05650405062850233]) assert_allclose(signal.chebwin(6, 10), [1.0, 0.6071201674458373, 0.6808391469897297, 0.6808391469897297, 0.6071201674458373, 1.0]) assert_allclose(signal.chebwin(7, 10), [1.0, 0.5190521247588651, 0.5864059018130382, 0.6101519801307441, 0.5864059018130382, 0.5190521247588651, 1.0]) assert_allclose(signal.chebwin(6, 10, False), [1.0, 0.5190521247588651, 0.5864059018130382, 0.6101519801307441, 0.5864059018130382, 0.5190521247588651])
def test_basic(self): with suppress_warnings() as sup: sup.filter(UserWarning, "This window is not suitable") assert_allclose(signal.chebwin(6, 100), [0.1046401879356917, 0.5075781475823447, 1.0, 1.0, 0.5075781475823447, 0.1046401879356917]) assert_allclose(signal.chebwin(7, 100), [0.05650405062850233, 0.316608530648474, 0.7601208123539079, 1.0, 0.7601208123539079, 0.316608530648474, 0.05650405062850233]) assert_allclose(signal.chebwin(6, 10), [1.0, 0.6071201674458373, 0.6808391469897297, 0.6808391469897297, 0.6071201674458373, 1.0]) assert_allclose(signal.chebwin(7, 10), [1.0, 0.5190521247588651, 0.5864059018130382, 0.6101519801307441, 0.5864059018130382, 0.5190521247588651, 1.0]) assert_allclose(signal.chebwin(6, 10, False), [1.0, 0.5190521247588651, 0.5864059018130382, 0.6101519801307441, 0.5864059018130382, 0.5190521247588651])
def FFT(s): F = fft.fft(s) F = 20 * np.log10(np.abs(F)) N = F.shape[0] W = chebwin(N, at=100) Fw = fft.fft(s * W) Fw = 20 * np.log10(np.abs(Fw)) f = np.linspace(0, fs // 2, N // 2) plt.plot(f[0:N // 8], F[0:N // 8], label=lavel[j]) legend = plt.legend(loc='upper right', shadow=True, fontsize='small') legend.get_frame().set_facecolor('pink') plt.title(senal[i]) plt.grid()
def update_descriptors(self): if not self.kernel_type: raise ValueError("Integrator was passed kernel None") logger.debug( 'Updating WindowIntegrator "%s" descriptors based on input descriptor: %s.', self.name, self.sink.descriptor) record_length = self.sink.descriptor.axes[-1].num_points() time_pts = self.sink.descriptor.axes[-1].points time_step = time_pts[1] - time_pts[0] kernel = np.zeros(record_length, dtype=np.complex128) sample_start = int(self.box_car_start.value / time_step) sample_stop = int(self.box_car_stop.value / time_step) + 1 if self.kernel_type == 'boxcar': kernel[sample_start:sample_stop] = 1.0 elif self.kernel_type == 'chebwin': # create a Dolph-Chebyshev window with 100 dB attenuation kernel[sample_start:sample_stop] = \ chebwin(sample_start-sample_stop, at=100) elif self.kernel_type == 'blackman': kernel[sample_start:sample_stop] = \ blackman(sample_start-sample_stop) elif self.kernel_type == 'slepian': # create a Slepian window with 0.2 bandwidth kernel[sample_start:sample_stop] = \ slepian(sample_start-sample_stop, width=0.2) # add modulation kernel *= np.exp(2j * np.pi * self.frequency.value * time_step * time_pts) # pad or truncate the kernel to match the record length if kernel.size < record_length: self.aligned_kernel = np.append( kernel, np.zeros(record_length - kernel.size, dtype=np.complex128)) else: self.aligned_kernel = np.resize(kernel, record_length) # Integrator reduces and removes axis on output stream # update output descriptors output_descriptor = DataStreamDescriptor() # TODO: handle reduction to single point output_descriptor.axes = self.sink.descriptor.axes[:-1] output_descriptor._exp_src = self.sink.descriptor._exp_src output_descriptor.dtype = np.complex128 for os in self.source.output_streams: os.set_descriptor(output_descriptor) os.end_connector.update_descriptors()
def genCoeff(window, M): # CHEBWIN if window == "cheb-win": PFBCoeff = sp.chebwin(M, at=-30) # HANNING WINDOW elif window == "hanning": X = numpy.array([(float(i) / NFFT) - (float(NTaps) / 2) for i in range(M)]) PFBCoeff = numpy.sinc(X) * numpy.hanning(M) else: PFBCoeff = numpy.ones(M) return PFBCoeff
def test_cheb_even(self): cheb_even_true = array([ 0.203894, 0.107279, 0.133904, 0.163608, 0.196338, 0.231986, 0.270385, 0.311313, 0.354493, 0.399594, 0.446233, 0.493983, 0.542378, 0.590916, 0.639071, 0.686302, 0.732055, 0.775783, 0.816944, 0.855021, 0.889525, 0.920006, 0.946060, 0.967339, 0.983557, 0.994494, 1.000000, 1.000000, 0.994494, 0.983557, 0.967339, 0.946060, 0.920006, 0.889525, 0.855021, 0.816944, 0.775783, 0.732055, 0.686302, 0.639071, 0.590916, 0.542378, 0.493983, 0.446233, 0.399594, 0.354493, 0.311313, 0.270385, 0.231986, 0.196338, 0.163608, 0.133904, 0.107279, 0.203894 ]) cheb_even = signal.chebwin(54, at=-40) assert_array_almost_equal(cheb_even, cheb_even_true, decimal=4)
def test_cheb_odd(self): cheb_odd_true = array([ 0.200938, 0.107729, 0.134941, 0.165348, 0.198891, 0.235450, 0.274846, 0.316836, 0.361119, 0.407338, 0.455079, 0.503883, 0.553248, 0.602637, 0.651489, 0.699227, 0.745266, 0.789028, 0.829947, 0.867485, 0.901138, 0.930448, 0.955010, 0.974482, 0.988591, 0.997138, 1.000000, 0.997138, 0.988591, 0.974482, 0.955010, 0.930448, 0.901138, 0.867485, 0.829947, 0.789028, 0.745266, 0.699227, 0.651489, 0.602637, 0.553248, 0.503883, 0.455079, 0.407338, 0.361119, 0.316836, 0.274846, 0.235450, 0.198891, 0.165348, 0.134941, 0.107729, 0.200938 ]) cheb_odd = signal.chebwin(53, at=-40) assert_array_almost_equal(cheb_odd, cheb_odd_true, decimal=4)
def filter(self, f): ''' Beamforming filter coefficients Parameters ---------- f: frequency ''' filter = super(DelayAndSumChebyWin, self).filter(f) #multiply a chebwin window filter = filter * chebwin(self.M, at=self.attenuation_dB).reshape( self.M, 1) return filter
def dolph_chebyshev_coefficients(N, RoDb): Ro = pow(10, RoDb / 20) window = signal.chebwin(N, RoDb) coeffs_normalized = window[N // 2:] zo = math.cosh(cosh_inverse(Ro) / (N - 1)) normalization_factor = (zo**(N - 1)) / coeffs_normalized[-1] coeffs = [normalization_factor * i for i in coeffs_normalized] return coeffs
def test_cheb_odd(self): cheb_odd_true = array([0.200938, 0.107729, 0.134941, 0.165348, 0.198891, 0.235450, 0.274846, 0.316836, 0.361119, 0.407338, 0.455079, 0.503883, 0.553248, 0.602637, 0.651489, 0.699227, 0.745266, 0.789028, 0.829947, 0.867485, 0.901138, 0.930448, 0.955010, 0.974482, 0.988591, 0.997138, 1.000000, 0.997138, 0.988591, 0.974482, 0.955010, 0.930448, 0.901138, 0.867485, 0.829947, 0.789028, 0.745266, 0.699227, 0.651489, 0.602637, 0.553248, 0.503883, 0.455079, 0.407338, 0.361119, 0.316836, 0.274846, 0.235450, 0.198891, 0.165348, 0.134941, 0.107729, 0.200938]) cheb_odd = signal.chebwin(53, at=-40) assert_array_almost_equal(cheb_odd, cheb_odd_true, decimal=4)
def test_cheb_even(self): cheb_even_true = array([0.203894, 0.107279, 0.133904, 0.163608, 0.196338, 0.231986, 0.270385, 0.311313, 0.354493, 0.399594, 0.446233, 0.493983, 0.542378, 0.590916, 0.639071, 0.686302, 0.732055, 0.775783, 0.816944, 0.855021, 0.889525, 0.920006, 0.946060, 0.967339, 0.983557, 0.994494, 1.000000, 1.000000, 0.994494, 0.983557, 0.967339, 0.946060, 0.920006, 0.889525, 0.855021, 0.816944, 0.775783, 0.732055, 0.686302, 0.639071, 0.590916, 0.542378, 0.493983, 0.446233, 0.399594, 0.354493, 0.311313, 0.270385, 0.231986, 0.196338, 0.163608, 0.133904, 0.107279, 0.203894]) cheb_even = signal.chebwin(54, at=-40) assert_array_almost_equal(cheb_even, cheb_even_true, decimal=4)
def test_cheb_odd_high_attenuation(self): cheb_odd = signal.chebwin(53, at=-40) assert_array_almost_equal(cheb_odd, cheb_odd_true, decimal=4)
# Plot the window and its frequency response: from scipy import signal from scipy.fftpack import fft, fftshift import matplotlib.pyplot as plt window = signal.chebwin(51, at=100) plt.plot(window) plt.title("Dolph-Chebyshev window (100 dB)") 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 Dolph-Chebyshev window (100 dB)") plt.ylabel("Normalized magnitude [dB]") plt.xlabel("Normalized frequency [cycles per sample]")
def test_cheb_even_high_attenuation(self): with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) cheb_even = signal.chebwin(54, at=-40) assert_array_almost_equal(cheb_even, cheb_even_true, decimal=4)
fig=plt.figure(figsize=(10,10))#4 ax = plt.subplot(4,1,1)#5 ax.plot(time,y) #6 ax = plt.subplot(4,1,2) #7 windLength = 128; #8 overl = windLength-1; #9 freqBins = 250; #10 wind=np.kaiser(windLength,0) f, tt, Sxx =sg.spectrogram(y,fs,wind,len(wind),overl); #7 plt.pcolormesh(tt,f,Sxx); ax = plt.subplot(4,1,3) #12 wind=np.hanning(windLength); f, tt, Sxx =sg.spectrogram(y,fs,wind,len(wind),overl); #7 plt.pcolormesh(tt,f,Sxx) ax = plt.subplot(4,1,4); #14 wind=sg.chebwin(windLength, at=100); f, tt, Sxx =sg.spectrogram(y,fs,wind,len(wind)); #7 plt.pcolormesh(tt,f,Sxx); #%% b1_low, a1_low = sg.butter(5, .2, 'low', analog=True)#1 b2_low, a2_low = sg.butter(10, .2, 'low', analog=True)#2 b3_low, a3_low = sg.cheby1(5, .2, 100, 'low', analog=True)#3 b4_low, a4_low = sg.cheby1(5, .2, 100, 'low', analog=True)#4 w, k = sg.freqs(b3_low, a3_low) #5 plt.semilogx(w, 20 * np.log(abs(k))) #5 B_low,A_low = sg.butter(8,0.6,btype='low',analog=True) #1 B_high,A_high = sg.butter(8,0.4,btype='high',analog=True) #2 winds = {}
def test_cheb_even_high_attenuation(self): cheb_even = signal.chebwin(54, at=-40) assert_array_almost_equal(cheb_even, cheb_even_true, decimal=4)
def chebyshev_win(self, array_size, sll, *args, **kwargs): return signal.chebwin(array_size, at=-sll)
DIR = '/home/jernej/Desktop/ModelskaAn/MOJEDELLO/dvanajsta/' val = ["val2", "val3"] V = 1 SIG = loadtxt(DIR + val[V] + ".dat") # branje LS = len(SIG) # dolžina signala SIG_256 = SIG[0:LS // 2] SIG_128 = SIG[0:LS // 4] SIG_64 = SIG[0:LS // 8] STD = 7 windowGauss = signal.gaussian(LS, std=STD) windowBartt = signal.bartlett(LS) windowHann = signal.hann(LS) windowCH = signal.chebwin(LS, at=100) windowTuR = signal.tukey(LS) FTSIG = 2 * abs(np.fft.fft(SIG))**2 FTfreq = np.fft.fftfreq(LS, 1 / len(SIG)) FTSIG_G = 2 * abs(np.fft.fft(SIG * signal.gaussian(LS, std=STD)))**2 FTSIG_B = 2 * abs(np.fft.fft(SIG * signal.bartlett(LS)))**2 FTSIG_H = 2 * abs(np.fft.fft(SIG * signal.hann(LS)))**2 FTSIG_CH = 2 * abs(np.fft.fft(SIG * signal.chebwin(LS, at=100)))**2 FTSIG_T = 2 * abs(np.fft.fft(SIG * signal.tukey(LS)))**2 FTSIG_HCH = 2 * abs(np.fft.fft(SIG * signal.tukey(LS) * signal.hann(LS)))**2 FTSIG_256 = 2 * abs(np.fft.fft(SIG_256))**2 FTfreq_256 = np.fft.fftfreq(LS // 2, 1 / len(SIG_256)) FTSIG_G_256 = 2 * abs(np.fft.fft( SIG_256 * signal.gaussian(LS // 2, std=STD)))**2
def phase_channels(conf,d,i0,carrier_width=10.0,cphases=None,camps=None,use_cphases=False): """ simple calculation of phase differences between ch0 and other channels as well as channel amplitude. can be used to beamform all channels together. """ if use_cphases: print("Using calibrated phases") else: cphases=n.zeros(len(conf.ch)) camps=n.ones(len(conf.ch)) fvec=n.fft.fftshift(n.fft.fftfreq(conf.nfft,d=1.0/conf.sample_rate)) fidx=n.where( (fvec>conf.fmin)&(fvec<conf.fmax))[0] carrier_fidx=n.where( (fvec>-10.0)&(fvec<10.0))[0] n_freq=len(fidx) nfft=conf.nfft step_len=conf.step_len*conf.sample_rate t=n.arange(nfft,dtype=n.float32)/conf.sample_rate wfun=s.chebwin(nfft,150) n_chan=len(conf.ch) ch_pairs=[] n_pair=0 for i in range(1,n_chan): ch_pairs.append((0,i)) n_pair+=1 S=n.zeros([n_pair,conf.nsteps,n_freq],dtype=n.complex64) overlap=int(nfft/conf.overlap_fraction) nmax_avg=int(n.floor((conf.step_len*conf.sample_rate-nfft-conf.offset)/overlap)) n_avg=1 tvec=n.zeros(conf.nsteps) pwrs=n.zeros(len(conf.ch)) npwrs=n.zeros(len(conf.ch)) for step_idx in range(conf.nsteps): fnow = conf.f0 + step_idx*conf.fstep fshift = conf.center_freq-fnow dshift=n.exp(1j*2.0*n.pi*fshift*t) for pi,ci in enumerate(ch_pairs): for avg_i in range(n_avg): inow=i0+step_idx*step_len + avg_i*overlap print("%s n_avg %d/%d f0 %1.2f"%(stuffr.unix2datestr(inow/conf.sample_rate),n_avg,nmax_avg,fnow/1e6)) tvec[step_idx]=step_idx*step_len/conf.sample_rate z0=dshift*d.read_vector_c81d(inow,nfft,conf.ch[ci[0]])*camps[ci[0]]*n.exp(1j*cphases[ci[0]]) pwrs[ci[0]]+=n.mean(n.abs(z0)**2.0) npwrs[ci[0]]+=1.0 z1=dshift*d.read_vector_c81d(inow,nfft,conf.ch[ci[1]])*camps[ci[1]]*n.exp(1j*cphases[ci[1]]) pwrs[ci[1]]+=n.mean(n.abs(z1)**2.0) npwrs[ci[1]]+=1.0 X0=n.fft.fftshift(n.fft.fft(wfun*z0)) X1=n.fft.fftshift(n.fft.fft(wfun*z1)) S[pi,step_idx,:]+=X0[fidx]*n.conj(X1[fidx]) gfidx=n.where( n.abs((fvec[fidx])>carrier_width))[0] phase_diffs=[] for i in range(n_pair): xc=n.copy(S[i,:,gfidx]) xc=xc.flatten() xc_idx=n.argsort(xc) phase_diff=n.angle(n.sum(xc[xc_idx[int(len(xc_idx)*0.3):int(len(xc_idx)*0.9)]])) phase_diffs.append(phase_diff) if use_cphases: plt.pcolormesh(n.angle(S[i,:,:])) plt.colorbar() plt.show() plt.plot(n.angle(n.sum(S[i,:,:],axis=0))) plt.axhline(phase_diff) plt.show() ch_pwrs=pwrs/npwrs phases=n.zeros(n_chan) # simple phaseup with reference to channel 0 # ph0-ph1 # ph0-ph2 # ph0-ph3 # ph0-ph4 for i in range(n_pair): phases[i+1]=phase_diffs[i] # plt.plot(phases) # plt.show() # pha = 0 # pha - phb = mab # pha - phc = return(1.0/n.sqrt(ch_pwrs),phases)
def calculate_sweep_xc(conf,d,i0,use_cphases=False,cphases=None,camps=None): if use_cphases: print("Using calcibrated phases") else: cphases=n.zeros(len(conf.ch)) camps=n.ones(len(conf.ch)) fvec=n.fft.fftshift(n.fft.fftfreq(conf.nfft,d=1.0/conf.sample_rate)) fidx=n.where( (fvec>conf.fmin)&(fvec<conf.fmax))[0] carrier_fidx=n.where( (fvec>-10.0)&(fvec<10.0))[0] n_freq=len(fidx) nfft=conf.nfft step_len=conf.step_len*conf.sample_rate t=n.arange(nfft,dtype=n.float32)/conf.sample_rate wfun=s.chebwin(nfft,150) n_chan=len(conf.ch) cpix=ito.combinations(n.arange(n_chan,dtype=n.int),2) ch_pairs=[] for i in range(n_chan): ch_pairs.append((i,i)) for cpi in cpix: ch_pairs.append((cpi[0],cpi[1])) n_pairs=len(ch_pairs) S=n.zeros([n_pairs,conf.nsteps,n_freq],dtype=n.complex64) overlap=int(nfft/conf.overlap_fraction) nmax_avg=int(n.floor((conf.step_len*conf.sample_rate-nfft-conf.offset)/overlap))+1 if conf.fast: n_avg=n.min([conf.n_avg,nmax_avg]) else: n_avg=nmax_avg tvec=n.zeros(conf.nsteps) carrier = n.zeros(conf.nsteps,dtype=n.complex64) f0s=n.zeros(conf.nsteps) for step_idx in range(conf.nsteps): fnow = conf.f0 + step_idx*conf.fstep f0s[step_idx]=fnow fshift = conf.center_freq-fnow dshift=n.exp(1j*2.0*n.pi*fshift*t) tvec[step_idx]=step_idx*step_len/conf.sample_rate for avg_i in range(n_avg): inow=i0+step_idx*step_len + avg_i*overlap print("%s n_avg %d/%d f0 %1.2f"%(stuffr.unix2datestr(inow/conf.sample_rate),n_avg,nmax_avg,fnow/1e6)) for pi,chp_i in enumerate(ch_pairs): z0=dshift*d.read_vector_c81d(inow,nfft,conf.ch[chp_i[0]])*camps[chp_i[0]]*n.exp(1j*cphases[chp_i[0]]) z1=dshift*d.read_vector_c81d(inow,nfft,conf.ch[chp_i[1]])*camps[chp_i[1]]*n.exp(1j*cphases[chp_i[1]]) X0=n.fft.fftshift(n.fft.fft(wfun*z0)) X1=n.fft.fftshift(n.fft.fft(wfun*z1)) S[pi,step_idx,:]+=X0[fidx]*n.conj(X1[fidx]) if conf.fscale == "kHz": fvec=fvec/1e3 ho=h5py.File("img/%s_sweep_xc_%1.2f.h5"%(conf.prefix,i0/conf.sample_rate),"w") ho["S"]=S ho["ch_pairs"]=ch_pairs ho["phases"]=cphases ho["amps"]=camps ho["time_vec"]=tvec ho["freq_vec"]=fvec[fidx] ho["f0s"]=f0s ho["center_freq"]=conf.center_freq ho["t0"]=i0/conf.sample_rate ho["date"]=stuffr.unix2datestr(i0/conf.sample_rate) ho.close()
def calculate_sweep(conf,d,i0,use_cphases=False,cphases=None,camps=None): ofname="img/%s_sweep_%1.2f.h5"%(conf.prefix,i0/conf.sample_rate) if os.path.exists(ofname) and conf.overwrite == False: print("File %s already exists. Skipping."%(ofname)) if use_cphases: print("Using calcibrated phases") else: cphases=n.zeros(len(conf.ch)) camps=n.ones(len(conf.ch)) fvec=n.fft.fftshift(n.fft.fftfreq(conf.nfft,d=1.0/conf.sample_rate)) fidx=n.where( (fvec>conf.fmin)&(fvec<conf.fmax))[0] carrier_fidx=n.where( (fvec>-10.0)&(fvec<10.0))[0] n_freq=len(fidx) nfft=conf.nfft step_len=conf.step_len*conf.sample_rate t=n.arange(nfft,dtype=n.float32)/conf.sample_rate wfun=s.chebwin(nfft,150) S=n.zeros([conf.nsteps*conf.nsubsteps,n_freq]) N_avgd=n.zeros([conf.nsteps*conf.nsubsteps,n_freq]) overlap=int(nfft/conf.overlap_fraction) nmax_avg=int(n.floor((conf.step_len*conf.sample_rate-conf.trim_end)/overlap/conf.nsubsteps))+1 sub_len=int(n.floor((step_len-conf.trim_end)/conf.nsubsteps)) if conf.fast: n_avg=n.min([conf.n_avg,nmax_avg]) else: n_avg=nmax_avg tvec=n.zeros(conf.nsteps*conf.nsubsteps) carrier = n.zeros(conf.nsteps*conf.nsubsteps,dtype=n.complex64) f0s=n.zeros(conf.nsteps*conf.nsubsteps) for step_idx in range(conf.nsteps): fnow = conf.f0 + step_idx*conf.fstep fshift = conf.center_freq-fnow dshift=n.exp(1j*2.0*n.pi*fshift*t) step_i0=i0+step_idx*step_len for sub_idx in range(conf.nsubsteps): f0s[step_idx*conf.nsubsteps+sub_idx]=fnow tvec[step_idx*conf.nsubsteps+sub_idx]=(step_idx*step_len+sub_idx*sub_len)/conf.sample_rate for avg_i in range(n_avg): inow=i0 + step_idx*step_len + sub_idx*sub_len + avg_i*overlap # make sure this fits the step if (inow+nfft-step_i0+conf.trim_end) < step_len: print("%s n_avg %d/%d f0 %1.2f"%(stuffr.unix2datestr(inow/conf.sample_rate),avg_i,nmax_avg,fnow/1e6)) z=n.zeros(nfft,dtype=n.complex128) # beamform signals for ch_i in range(len(conf.ch)): try: z+=dshift*d.read_vector_c81d(inow,nfft,conf.ch[ch_i])*camps[ch_i]*n.exp(1j*cphases[ch_i]) except: print("missing data") X=n.fft.fftshift(n.fft.fft(wfun*z)) if conf.debug: plt.plot(fvec,10.0*n.log10(X)) plt.show() S[step_idx*conf.nsubsteps+sub_idx,:]+=n.abs(X[fidx])**2.0 N_avgd[step_idx*conf.nsubsteps+sub_idx,:]+=1.0 carrier[step_idx*conf.nsubsteps+sub_idx]+=n.sum(n.abs(X[carrier_fidx])**2.0) S=S/N_avgd # ofname="img/%s_sweep_%1.2f.h5"%(conf.prefix,i0/conf.sample_rate) print("Saving %s"%(ofname)) ho=h5py.File(ofname,"w") ho["S"]=S ho["phases"]=cphases ho["amps"]=camps ho["time_vec"]=tvec ho["freq_vec"]=fvec[fidx] ho["f0s"]=f0s ho["carrier_pwr"]=carrier ho["center_freq"]=conf.center_freq ho["fscale"]=str(conf.fscale) ho["t0"]=i0/conf.sample_rate ho["date"]=stuffr.unix2datestr(i0/conf.sample_rate) ho.close() clean_image.plot_file(ofname,show_plot=conf.show_plot,vmin=conf.vmin,vmax=conf.vmax)
def test_cheb_even_high_attenuation(self): with suppress_warnings() as sup: sup.filter(UserWarning, "This window is not suitable") cheb_even = signal.chebwin(54, at=40) assert_array_almost_equal(cheb_even, cheb_even_true, decimal=4)
def test_cheb_odd_low_attenuation(self): cheb_odd_low_at_true = array([1.000000, 0.519052, 0.586405, 0.610151, 0.586405, 0.519052, 1.000000]) cheb_odd = signal.chebwin(7, at=-10) assert_array_almost_equal(cheb_odd, cheb_odd_low_at_true, decimal=4)
def test_cheb_even_low_attenuation(self): cheb_even_low_at_true = array([1.000000, 0.451924, 0.51027, 0.541338, 0.541338, 0.51027, 0.451924, 1.000000]) cheb_even = signal.chebwin(8, at=-10) assert_array_almost_equal(cheb_even, cheb_even_low_at_true, decimal=4)
SIG2_256= SIG2[0:LS//2] SIG3_lin_302= SIG3_lin[0:LS3//2] SIG4_256= SIG4[0:LS4//2] SIG5_256= SIG5[0:LS5//2] SIG6_256= SIG6[0:LS6//2] ########### FOURIERE ############################ FTSIG = 2*abs(np.fft.fft(SIG))**2 FTSIG_CH = 2*abs(np.fft.fft(SIG*signal.chebwin(LS, at=100)))**2 FTSIG_256 = 2*abs(np.fft.fft(SIG_256))**2 FTSIG_CH_256 = 2*abs(np.fft.fft(SIG_256*signal.chebwin(LS//2, at=100)))**2 FTSIG2 = 2*abs(np.fft.fft(SIG2))**2 FTSIG2_CH = 2*abs(np.fft.fft(SIG2*signal.chebwin(LS, at=100)))**2 FTSIG2_256 = 2*abs(np.fft.fft(SIG2_256))**2 FTSIG2_CH_256 = 2*abs(np.fft.fft(SIG2_256*signal.chebwin(LS//2, at=100)))**2 FTSIG3_lin = 2*abs(np.fft.fft(SIG3_lin))**2 FTSIG3_lin_CH = 2*abs(np.fft.fft(SIG3_lin*signal.chebwin(LS3, at=100)))**2 FTSIG3_lin_302 = 2*abs(np.fft.fft(SIG3_lin_302))**2 FTSIG3_lin_CH_302 = 2*abs(np.fft.fft(SIG3_lin_302*signal.chebwin(LS3//2, at=100)))**2 FTSIG4 = 2*abs(np.fft.fft(SIG4))**2
cmdstring = cmdstring + " -p " + str(radioConfig.tunerOffsetPPM) 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