Exemple #1
0
    def mult2(self, uh, vh, out=None):
        N2 = self.N2

        ret = None
        if not isinstance(out, np.ndarray):
            out = self.zeros()
            ret = out

        wh1 = self._w[0]
        wh1[N2:] = 0.0
        wh1[:N2] = uh[:N2]
        wh2 = self._w[1]
        wh2[N2:] = 0.0
        wh2[:N2] = vh[:N2]
        wh3 = self._w[2]

        irfft(wh1, overwrite_x=True)
        irfft(wh2, overwrite_x=True)
        np.multiply(wh1, wh2, wh3)
        rfft(wh3, overwrite_x=True)

        out[:N2] = wh3[:N2]
        out[N2:] = 0.0

        return ret
Exemple #2
0
def extract_3d_fft_features(time_windows, feat_len, class_attr, n_comps=None):
    X_matrix = []
    if class_attr is not None:
        y_vect = []
    for w in time_windows:
	if w.shape[0] == feat_len:
		x = w['x'].values
		y = w['y'].values
		z = w['z'].values
		m = mag(x,y,z)
		dim = len(x)
		if n_comps is not None:
		    dim = n_comps
		
		fftx = np.real(np.fft.fft(x))
		ffty = np.real(np.fft.fft(y))
		fftz = np.real(np.fft.fft(z))  
		fftm = np.abs(np.real(np.fft.fft(m)))       
	  
		features = []               
		features.append(fftpack.irfft(fftx[:dim])) 
		features.append(fftpack.irfft(ffty[:dim]))
		features.append(fftpack.irfft(fftz[:dim]))      
		
		X_matrix.append(features)
		if y_vect is not None:
			y_vect.append(w['class'].iloc[0])

    X_matrix = np.array(X_matrix)

    if y_vect is None:
        return X_matrix
    else:
        return X_matrix, y_vect
Exemple #3
0
    def fft(self, data):
        # FFT
        W = fftfreq(len(data), 1.0 / RecordDetectAudio.RATE * 2.0)
        f_signal = rfft(data)

        # Doing some filter?
        f_signal[(W < 16)] = 0

        # Visualization
        self.li.set_xdata(W[1:len(W) / 2])
        self.li.set_ydata(np.abs(f_signal[1:len(W) / 2]))
        self.ax.relim()
        self.ax.autoscale_view(True, True, True)
        os.kill(os.getpid(), signal.SIGUSR2)

        m_signal = f_signal.copy()
        # print np.mean(np.abs(m_signal[16:96]))
        if np.mean(np.abs(m_signal[16:96])) > self.threshold2:
            self.detect_count += 1
        else:
            self.detect_count = 0

        if self.detect_count > 0:
            self.detect_count = 0
            return irfft(m_signal).astype(np.int32), False
        else:
            return irfft(m_signal).astype(np.int32), True
Exemple #4
0
def polar_fourier_filter(psi):
    #filter zonal wavenumbers in polar regions
    #south pole
    psi_trans_sp = rfft(psi[4:-4, 4:8, :], axis=0)
    psi_trans_sp[3:, 0, :] = 0.0
    psi_trans_sp[11:, 1, :] = 0.0
    psi_trans_sp[19:, 2, :] = 0.0
    psi_trans_sp[23:, 3, :] = 0.0
    #    psi_trans[12:,4,:] = 0.0
    #    psi_trans[15:,5,:] = 0.0
    #    psi_trans[18:,6,:] = 0.0
    #    psi_trans[20:,7,:] = 0.0
    #north pole
    psi_trans_np = rfft(psi[4:-4, -8:-4, :], axis=0)
    psi_trans_np[3:, -1, :] = 0.0
    psi_trans_np[11:, -2, :] = 0.0
    psi_trans_np[19:, -3, :] = 0.0
    psi_trans_np[23:, -4, :] = 0.0
    #    psi_trans[12:,nphi-5,:] = 0.0
    #    psi_trans[15:,nphi-6,:] = 0.0
    #    psi_trans[18:,nphi-7,:] = 0.0
    #    psi_trans[20:,nphi-8,:] = 0.0
    psi[4:-4, 4:8, :] = irfft(psi_trans_sp, axis=0)
    psi[4:-4, -8:-4, :] = irfft(psi_trans_np, axis=0)
    return psi
Exemple #5
0
def delay(data1, data2, q5):
    time_FFT_A = np.array([])
    time_FFT_B = np.array([])
    data1 = [(data1[i * 4410:(i + 1) * 4410])
             for i in range(int(len(data1) / 4410))]
    data2 = [(data2[i * 4410:(i + 1) * 4410])
             for i in range(int(len(data2) / 4410))]

    #for time, value in enumerate(data1):
    time_FFT_A = np.append(
        time_FFT_A, [irfft(data1[time]) for time, value in enumerate(data1)])
    time_FFT_B = np.append(
        time_FFT_B, [irfft(data2[time]) for time, value in enumerate(data2)])

    corr = np.correlate(time_FFT_A, time_FFT_B, "full")
    maks = np.argmax(np.absolute(corr))
    if maks < 20000:
        sample2kurtosis = corr[:maks + 20000]
    else:
        sample2kurtosis = corr[maks - 20000:maks + 20000]
    kurtosiss = kurtosis(sample2kurtosis)
    match_counter = 0
    for x, j in enumerate(corr[maks - 5000:maks + 5000]):
        if x < 4900 or x > 5100:
            if j > np.amax(corr) * 0.30:
                match_counter += 1
    # print('Peaks: ',match_counter)
    # print('Przesunięcie =', np.argmax(corr) - (len(time_FFT_B) - 1))
    q5.put([kurtosiss, match_counter])
 def newwindow(self):
     self.window = QtWidgets.QMainWindow()
     self.ui2 = Ui_otherwindow()
     self.ui2.setupUi(self.window)
     if self.loaded:
         self.ui2.original_sign.plot(self.original_sig)
         self.ui2.original_frequ.plot(abs(self.original_complex))
         if not (self.output_sig1.size == 0):
             self.ui2.output1_sig.plot(irfft(self.output_sig1),
                                       pen=pg.mkPen(color=(170, 0, 0)))
             self.ui2.output11.plot(abs(self.output_sig1),
                                    pen=pg.mkPen(color=(170, 0, 0)))
         if not (self.output_sig2.size == 0):
             self.ui2.output2_sig.plot(irfft(self.output_sig2),
                                       pen=pg.mkPen(color=(0, 250, 0)))
             self.ui2.output22.plot(abs(self.output_sig2),
                                    pen=pg.mkPen(color=(0, 250, 0)))
         if (not (self.output_sig2.size
                  == 0)) and (not (self.output_sig1.size == 0)):
             self.ui2.diff_sig.plot(np.subtract(irfft(self.output_sig1),
                                                irfft(self.output_sig2)),
                                    pen=pg.mkPen(color=(0, 25, 159)))
             self.ui2.diff_freq.plot(np.subtract(abs(self.output_sig1),
                                                 abs(self.output_sig2)),
                                     pen=pg.mkPen(color=(0, 25, 159)))
     else:
         pass
     self.window.show()
Exemple #7
0
 def test_random_real(self):
     for size in [1, 51, 111, 100, 200, 64, 128, 256, 1024]:
         x = random([size]).astype(self.rdt)
         y1 = irfft(rfft(x))
         y2 = rfft(irfft(x))
         assert_equal(y1.dtype, self.rdt)
         assert_equal(y2.dtype, self.rdt)
         assert_array_almost_equal(y1, x, decimal=self.ndec, err_msg="size=%d" % size)
         assert_array_almost_equal(y2, x, decimal=self.ndec, err_msg="size=%d" % size)
Exemple #8
0
def sanity(wavobj):
    transformed = wavobj['transformed']
    transformed_raw = wavobj['raw']
    rate = wavobj['rate']
    output = irfft(transformed)
    san_output = irfft(transformed) * transformed_raw.max(axis=0)

    write('sanity.wav', rate, np.array(san_output, dtype=np.int16))
    print("Sanity.wav written")
Exemple #9
0
def sanity(wavobj):
    transformed = wavobj['transformed']
    transformed_raw = wavobj['raw']
    rate = wavobj['rate']
    output = irfft(transformed)
    san_output = irfft(transformed)* transformed_raw.max(axis=0)

    write('sanity.wav', rate, np.array(san_output, dtype=np.int16))
    print("Sanity.wav written")
 def test_random_real(self):
     for size in [1,51,111,100,200,64,128,256,1024]:
         x = random([size]).astype(self.rdt)
         y1 = irfft(rfft(x))
         y2 = rfft(irfft(x))
         assert_equal(y1.dtype, self.rdt)
         assert_equal(y2.dtype, self.rdt)
         assert_array_almost_equal(y1, x, decimal=self.ndec,
                                    err_msg="size=%d" % size)
         assert_array_almost_equal(y2, x, decimal=self.ndec,
                                    err_msg="size=%d" % size)
 def test_random_real(self):
     for size in [1,51,111,100,200,64,128,256,1024]:
         x = random([size]).astype(self.rdt)
         y1 = irfft(rfft(x))
         y2 = rfft(irfft(x))
         self.failUnless(y1.dtype == self.rdt,
                 "Output dtype is %s, expected %s" % (y1.dtype, self.rdt))
         self.failUnless(y2.dtype == self.rdt,
                 "Output dtype is %s, expected %s" % (y2.dtype, self.rdt))
         assert_array_almost_equal (y1, x, decimal=self.ndec)
         assert_array_almost_equal (y2, x, decimal=self.ndec)
Exemple #12
0
 def test_definition(self):
     x = [1,2,3,4,1,2,3,4]
     x1 = [1,2+3j,4+1j,2+3j,4,2-3j,4-1j,2-3j]
     y = irfft(x)
     y1 = direct_irdft(x)
     assert_array_almost_equal(y,y1)
     assert_array_almost_equal(y,ifft(x1))
     x = [1,2,3,4,1,2,3,4,5]
     x1 = [1,2+3j,4+1j,2+3j,4+5j,4-5j,2-3j,4-1j,2-3j]
     y = irfft(x)
     y1 = direct_irdft(x)
     assert_array_almost_equal(y,y1)
     assert_array_almost_equal(y,ifft(x1))
 def test_random_real(self):
     for size in [1, 51, 111, 100, 200, 64, 128, 256, 1024]:
         x = random([size]).astype(self.rdt)
         y1 = irfft(rfft(x))
         y2 = rfft(irfft(x))
         self.failUnless(
             y1.dtype == self.rdt,
             "Output dtype is %s, expected %s" % (y1.dtype, self.rdt))
         self.failUnless(
             y2.dtype == self.rdt,
             "Output dtype is %s, expected %s" % (y2.dtype, self.rdt))
         assert_array_almost_equal(y1, x, decimal=self.ndec)
         assert_array_almost_equal(y2, x, decimal=self.ndec)
Exemple #14
0
def _test_slow_irfft_constants():

    assert np.allclose(irfft([1]), [1/1])
    assert np.allclose(irfft([1, 0]), [1/2, 1/2])
    assert np.allclose(irfft([1, 0, 0]), [1/3, 1/3, 1/3])
    assert np.allclose(irfft([1, 0, 0, 0]), [1/4, 1/4, 1/4, 1/4])
    assert np.allclose(irfft([1, 0, 0, 0, 0]), [1/5, 1/5, 1/5, 1/5, 1/5])

    # assert np.allclose(slow_irfft([1]), [1/1])
    # assert np.allclose(slow_irfft([1, 0]), [1/2, 1/2])
    assert np.allclose(slow_irfft([1, 0, 0]), [1/3, 1/3, 1/3])
    assert np.allclose(slow_irfft([1, 0, 0, 0]), [1/4, 1/4, 1/4, 1/4])
    assert np.allclose(slow_irfft([1, 0, 0, 0, 0]), [1/5, 1/5, 1/5, 1/5, 1/5])
Exemple #15
0
def _test_slow_irfft_additivity():

    for k in range(10):
        freqs = np.random.normal(size=k + 3)
        simultaneously = irfft(freqs)
        piecewise = np.sum([irfft(f) for f in np.diag(freqs)], axis=0)
        assert np.allclose(simultaneously, piecewise)

    for k in range(10):
        freqs = np.random.normal(size=k + 3)
        simultaneously = slow_irfft(freqs)
        piecewise = np.sum([slow_irfft(f) for f in np.diag(freqs)], axis=0)
        assert np.allclose(simultaneously, piecewise)
Exemple #16
0
    def test_size_accuracy(self):
        # Sanity check for the accuracy for prime and non-prime sized inputs
        if self.rdt == np.float32:
            rtol = 1e-5
        elif self.rdt == np.float64:
            rtol = 1e-10

        for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
            np.random.seed(1234)
            x = np.random.rand(size).astype(self.rdt)
            y = irfft(rfft(x))
            _assert_close_in_norm(x, y, rtol, size, self.rdt)
            y = rfft(irfft(x))
            _assert_close_in_norm(x, y, rtol, size, self.rdt)
Exemple #17
0
    def test_size_accuracy(self):
        # Sanity check for the accuracy for prime and non-prime sized inputs
        if self.rdt == np.float32:
            rtol = 1e-5
        elif self.rdt == np.float64:
            rtol = 1e-10

        for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
            np.random.seed(1234)
            x = np.random.rand(size).astype(self.rdt)
            y = irfft(rfft(x))
            _assert_close_in_norm(x, y, rtol, size, self.rdt)
            y = rfft(irfft(x))
            _assert_close_in_norm(x, y, rtol, size, self.rdt)
Exemple #18
0
def _test_slow_irfft_first_sine():

    tau = 2 * np.pi
    wave = lambda k: -2/k * np.sin(1 * tau * np.arange(k) / k)

    assert np.allclose(irfft([0, 0, 1]), wave(3))
    assert np.allclose(irfft([0, 0, 1, 0]), wave(4))
    assert np.allclose(irfft([0, 0, 1, 0, 0]), wave(5))
    assert np.allclose(irfft([0, 0, 1, 0, 0, 0]), wave(6))

    assert np.allclose(slow_irfft([0, 0, 1]), wave(3))
    assert np.allclose(slow_irfft([0, 0, 1, 0]), wave(4))
    assert np.allclose(slow_irfft([0, 0, 1, 0, 0]), wave(5))
    assert np.allclose(slow_irfft([0, 0, 1, 0, 0, 0]), wave(6))
Exemple #19
0
 def test_definition(self):
     x = [1, 2, 3, 4, 1, 2, 3, 4]
     x1 = [1, 2 + 3j, 4 + 1j, 2 + 3j, 4, 2 - 3j, 4 - 1j, 2 - 3j]
     y = irfft(x)
     y1 = direct_irdft(x)
     assert_array_almost_equal(y, y1)
     assert_array_almost_equal(y, ifft(x1))
     x = [1, 2, 3, 4, 1, 2, 3, 4, 5]
     x1 = [
         1, 2 + 3j, 4 + 1j, 2 + 3j, 4 + 5j, 4 - 5j, 2 - 3j, 4 - 1j, 2 - 3j
     ]
     y = irfft(x)
     y1 = direct_irdft(x)
     assert_array_almost_equal(y, y1)
     assert_array_almost_equal(y, ifft(x1))
Exemple #20
0
 def _test(x, xr):
     y = irfft(np.array(x, dtype=self.rdt))
     y1 = direct_irdft(x)
     self.assertTrue(y.dtype == self.rdt,
             "Output dtype is %s, expected %s" % (y.dtype, self.rdt))
     assert_array_almost_equal(y,y1, decimal=self.ndec)
     assert_array_almost_equal(y,ifft(xr), decimal=self.ndec)
Exemple #21
0
def fft_filter(x, fs, band=(9, 14)):
    w = fftfreq(x.shape[0], d=1. / fs * 2)
    f_signal = rfft(x)
    cut_f_signal = f_signal.copy()
    cut_f_signal[(w < band[0]) | (w > band[1])] = 0
    cut_signal = irfft(cut_f_signal)
    return cut_signal
Exemple #22
0
 def _test(x, xr):
     y = irfft(np.array(x, dtype=self.rdt))
     y1 = direct_irdft(x)
     self.assertTrue(y.dtype == self.rdt,
             "Output dtype is %s, expected %s" % (y.dtype, self.rdt))
     assert_array_almost_equal(y,y1, decimal=self.ndec)
     assert_array_almost_equal(y,ifft(xr), decimal=self.ndec)
Exemple #23
0
    def test_size_accuracy(self):
        # Sanity check for the accuracy for prime and non-prime sized inputs
        if self.rdt == np.float32:
            rtol = 1e-5
        elif self.rdt == np.float64:
            rtol = 1e-10

        for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
            np.random.seed(1234)
            x = np.random.rand(size).astype(self.rdt)
            y = irfft(rfft(x))
            self.failUnless(np.linalg.norm(x - y) < rtol*np.linalg.norm(x),
                            (size, self.rdt))
            y = rfft(irfft(x))
            self.failUnless(np.linalg.norm(x - y) < rtol*np.linalg.norm(x),
                            (size, self.rdt))
Exemple #24
0
def callback(in_data, frame_count, time_info, flag):
    global novoarray
    LOWPASS = filtrob  # Hz
    SAMPLE_RATE = 44100  # Hz
    FFT_LENGTH = 2048
    OVERLAP = 512
    HIGHPASS = filtroa  # Hz
    FFT_SAMPLE = FFT_LENGTH - OVERLAP
    NYQUIST_RATE = SAMPLE_RATE / 2.0
    LOWPASS /= (NYQUIST_RATE / (FFT_LENGTH / 2.0))
    HIGHPASS /= (NYQUIST_RATE / (FFT_LENGTH / 2.0))
    audio_data = np.fromstring(in_data, dtype=np.float32)

    novoarray1 = np.asarray(novoarray)
    freq = fftfreq(1024)

    l = len(audio_data)
    ff = 0
    fff = 0
    for ff in range(0, 1024):
        rampdown = 1.0
        if ff > LOWPASS:
            rampdown = 0.0
        elif ff < HIGHPASS:
            rampdown = 0.0
            mask.append(rampdown)
            fff += 1
    ff = 0

    print(len(mask))
    x = audio_data.astype(np.float32)
    y = rfft(x)
    print(y[512])
    #print (mask[len(mask)-1])
    for ff in range(fff):
        y[ff] *= mask[ff]

        ff += 1
    ff = 0

    i = 0

    yy = y.copy()

    yy[(freq < 0.001)] = 0
    N = len(yy)

    shifted_freq = np.zeros(N, yy.dtype)
    #aqui se altera a voz e cria o efeito distorção
    shift = efeito

    S = np.round(shift if shift > 0 else N + shift, 0)
    s = N - S
    shifted_freq[:S] = yy[s:]
    shifted_freq[S:] = yy[:s]
    z = irfft(shifted_freq)

    print(yy)

    return (z, pyaudio.paContinue)
def do_gen_random(peakAmpl, durationInMSec, samplingRate, fHigh, stereo=True):
    samples = durationInMSec * samplingRate / 1000
    result = np.zeros(samples * 2 if stereo else samples, dtype=np.int16)
    randomSignal = np.random.normal(scale = peakAmpl * 2 / 3, size=samples)
    fftData = fft.rfft(randomSignal)
    freqSamples = samples/2
    iHigh = freqSamples * fHigh * 2 / samplingRate + 1
    #print len(randomSignal), len(fftData), fLow, fHigh, iHigh
    if iHigh > freqSamples - 1:
        iHigh = freqSamples - 1
    fftData[0] = 0 # DC
    for i in range(iHigh, freqSamples - 1):
        fftData[ 2 * i + 1 ] = 0
        fftData[ 2 * i + 2 ] = 0
    if (samples - 2 *freqSamples) != 0:
        fftData[samples - 1] = 0

    filteredData = fft.irfft(fftData)
    #freq = np.linspace(0.0, samplingRate, num=len(fftData), endpoint=False)
    #plt.plot(freq, abs(fft.fft(filteredData)))
    #plt.plot(filteredData)
    #plt.show()
    if stereo:
        for i in range(len(filteredData)):
            result[2 * i] = filteredData[i]
            result[2 * i + 1] = filteredData[i]
    else:
        for i in range(len(filteredData)):
            result[i] = filteredData[i]
    return result
Exemple #26
0
def fft_filter(x, fs, band=(9, 14)):
    w = fftpack.rfftfreq(x.shape[0], d=1. / fs)
    f_signal = fftpack.rfft(x, axis=0)
    cut_f_signal = f_signal.copy()
    cut_f_signal[(w < band[0]) | (w > band[1])] = 0
    cut_signal = fftpack.irfft(cut_f_signal, axis=0)
    return cut_signal
Exemple #27
0
def fft_filter(x, fs, band=(9, 14)):
    w = fftpack.rfftfreq(x.shape[0], d=1. / fs)
    f_signal = fftpack.rfft(x, axis=0)
    cut_f_signal = f_signal.copy()
    cut_f_signal[(w < band[0]) | (w > band[1])] = 0
    cut_signal = fftpack.irfft(cut_f_signal, axis=0)
    return cut_signal
def ff_filt(x):
    W = fft.fftfreq(x.size, d=3000)
    f_x = fft.rfft(x)
    cut_f_x = f_x.copy()
    cut_f_x[(W > 1e-6)] = 0

    return fft.irfft(cut_f_x)
Exemple #29
0
def bandpass(x, sampling_rate, f_min, f_max, verbose=0):
	"""
	xf = bandpass(x, sampling_rate, f_min, f_max)

	Description
	--------------

	Phasen-treue mit der rueckwaerts-vorwaerts methode!
	Function bandpass-filters a signal without roleoff.  The cutoff frequencies,
	f_min and f_max, are sharp.

	Arguements
	--------------
		x: 			input timeseries
		sampling_rate: 			equidistant sampling with sampling frequency sampling_rate
		f_min, f_max:			filter constants for lower and higher frequency
	
	Returns
	--------------
		xf:		the filtered signal
	"""
	x, N = np.asarray(x, dtype=float), len(x)
	t = np.arange(N)/np.float(sampling_rate)
	xn = detrend_linear(x)
	del t

	yn = np.concatenate((xn[::-1], xn))		# backwards forwards array
	f = np.float(sampling_rate)*np.asarray(np.arange(2*N)/2, dtype=int)/float(2*N)
	s = rfft(yn)*(f>f_min)*(f<f_max)			# filtering

	yf = irfft(s)					# backtransformation
	xf = (yf[:N][::-1]+yf[N:])/2.			# phase average

	return xf
Exemple #30
0
def fftresample(S, npoints, reflect=False, axis=0):
    """
    Resample a signal using discrete fourier transform. The signal
    is transformed in the fourier domain and then padded or truncated
    to the correct sampling frequency.  This should be equivalent to
    a sinc resampling.
    """
    from scipy.fftpack import rfft, irfft
    from dlab.datautils import flipaxis

    # this may be considerably faster if we do the memory operations in C
    # reflect at the boundaries
    if reflect:
        S = nx.concatenate([flipaxis(S,axis), S, flipaxis(S,axis)],
                           axis=axis)
        npoints *= 3

    newshape = list(S.shape)
    newshape[axis] = int(npoints)

    Sf = rfft(S, axis=axis)
    Sr = (1. * npoints / S.shape[axis]) * irfft(Sf, npoints, axis=axis, overwrite_x=1)
    if reflect:
        return nx.split(Sr,3)[1]
    else:
        return Sr
Exemple #31
0
def fft_freq_filter(tdata, ydata, cutoff_freq, high_pass=True, show=False):
    """

    :param tdata: Time series data
    :param ydata: Y data
    :param cutoff_freq: cutoff frequency for filter, must be specified
    :param high_pass: If True filters high frequency if False filters low frequency
    :param show: Plots the before and after data

    :return: time data, filtered y data.
    """

    y_fft = fftpack.fftfreq(ydata.size, d=tdata[1] - tdata[0])
    f_signal = fftpack.rfft(ydata)

    # If our original signal time was in seconds, this is now in Hz
    cut_f_signal = f_signal.copy()

    if high_pass:
        cut_f_signal[(y_fft > cutoff_freq)] = 0
    else:
        cut_f_signal[(y_fft < cutoff_freq)] = 0

    cut_signal = fftpack.irfft(cut_f_signal)

    if show:
        plt.figure('fft filter')
        plt.plot(tdata, ydata, 'rx')
        plt.plot(tdata, cut_signal, 'b-')
        plt.title('Original data')
        plt.xlabel('tdata')
        plt.ylabel('ydata')
        plt.show()
    return tdata, cut_signal
Exemple #32
0
def band_pass_filter(signal, f1, f2, time="none", plot=False):
    signal = np.asarray(signal)
    if str(type(time)) == "<class 'int'>":
        time = np.linspace(0, time, len(signal))
    elif str(type(time)) == "<class 'numpy.ndarray'>":
        pass
    signal = np.asarray(signal)
    w = fftfreq(signal.size, d=time[1] - time[0])
    f_signal = rfft(signal)
    cut_f_signal = f_signal.copy()
    cut_f_signal[(w < f1)] = 0
    cut_f_signal[(w > f2)] = 0
    cut_f_signal[(w < -f1)] = f_signal[(w < -f1)]
    cut_f_signal[(w < -f2)] = 0
    cut_signal = irfft(cut_f_signal)
    if (plot == True):
        plt.subplot(221)
        plt.plot(time, signal)
        plt.subplot(222)
        plt.plot(w, f_signal)
        plt.subplot(223)
        plt.plot(time, cut_signal)
        plt.subplot(224)
        plt.plot(w, cut_f_signal)
        plt.show()
    return list(cut_signal)
Exemple #33
0
def ps(signal, time, plot=False):
    signal = np.asarray(signal)
    time = np.linspace(0, time, len(signal))
    w = fftfreq(signal.size, d=time[1] - time[0])
    f_signal = rfft(signal)
    cut_f_signal = f_signal.copy()
    mx = max(cut_f_signal)
    mn = min(cut_f_signal)
    f_loc = 0
    if mx > (mn * -1):
        f_loc = list(cut_f_signal).index(mx)
    else:
        f_loc = list(cut_f_signal).index(mn)
    cut_f_signal[(w < (f_loc - 15))] = 0
    cut_f_signal[(w > (f_loc + 15))] = 0
    cut_signal = irfft(cut_f_signal)
    if (plot == True):
        plt.subplot(221)
        plt.plot(time, signal)
        plt.subplot(222)
        plt.plot(w, f_signal)
        plt.subplot(223)
        plt.plot(time, cut_signal)
        plt.subplot(224)
        plt.plot(w, cut_f_signal)
        plt.show()
    return cut_signal
Exemple #34
0
def savefft(wavfile, wavobj, filtered):
    transformed = wavobj['transformed']
    transformed_raw = wavobj['raw']
    rate = wavobj['rate']
    data = filtered * transformed_raw.max(axis=0)
    output = irfft(data)
    write(wavfile, rate, np.array(output, dtype=np.int16))
Exemple #35
0
def main(raw_data):
    """ Performs FFT band pass filter 
    plots and saves filtered data

    Args:
         raw_data -> np.array((points, 2))

    """

    # Perform FFT /
    fft_signal = fftpack.rfft(raw_data[:, 1])
    points = len(raw_data[:, 0])
    dx = raw_data[1, 0] - raw_data[0, 0]
    freq = fftpack.rfftfreq(points, d=dx)

    # apply band pass filter
    filtered_signal = filter_signal(freq, fft_signal)

    # transform back
    filtered_data = fftpack.irfft(filtered_signal)

    plt.subplot(211)
    plt.plot(raw_data[:, 0], raw_data[:, 1], 'k.')
    plt.ylabel('Signal a.u.')

    plt.subplot(212)
    plt.plot(raw_data[:, 0], filtered_data, 'b-')
    plt.ylabel('Signal')
    plt.xlabel('Time')
    plt.show()
    np.savetxt('filtered_data.out',
               np.c_[raw_data[:, 0], filtered_data],
               header='{:22} {:22}'.format('Time', 'Filtered'))
Exemple #36
0
    def test_size_accuracy(self):
        # Sanity check for the accuracy for prime and non-prime sized inputs
        if self.rdt == np.float32:
            rtol = 1e-5
        elif self.rdt == np.float64:
            rtol = 1e-10

        for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
            np.random.seed(1234)
            x = np.random.rand(size).astype(self.rdt)
            y = irfft(rfft(x))
            self.failUnless(np.linalg.norm(x - y) < rtol*np.linalg.norm(x),
                            (size, self.rdt))
            y = rfft(irfft(x))
            self.failUnless(np.linalg.norm(x - y) < rtol*np.linalg.norm(x),
                            (size, self.rdt))
Exemple #37
0
 def filtering(self, fmin, fmax):
     """ This method applies a cut-band filter to the signal based on FFT
     analysis between fmin and fmax """
     timef = np.fft.fftfreq(len(self.df[self.parameter]),
                            d=1)  # Time range normalised
     signal = np.asarray(
         self.df[self.parameter])  # Convert the list in array
     W = fftfreq(
         signal.size, d=(timef[1] - timef[0])
     )  # convert in frequency adapted to the time range and frequential analysis
     f_signal = rfft(signal)  # Spectral analysis
     cut_f_signal1 = f_signal.copy(
     )  # Cut band filter in the following lines
     cut_f_signal2 = f_signal.copy()
     cut_f_signal = f_signal.copy()
     cut_f_signal1[(np.abs(W) >= float((2 * signal.size) / fmax))] = 0
     cut_f_signal2[(np.abs(W) <= float((2 * signal.size) / fmin))] = 0
     for i in range(0, signal.size - 1):
         if cut_f_signal[i] != cut_f_signal1[i] and cut_f_signal[
                 i] != cut_f_signal2[i]:
             cut_f_signal[i] = cut_f_signal1[i]
         else:
             cut_f_signal[i] = cut_f_signal[i]
     cut_signal = irfft(cut_f_signal)  # Inverse the signal
     filtered_list = np.array(
         cut_signal).tolist()  # Convert the array in list
     self.df.loc[:, self.parameter] = filtered_list
     return self.df
Exemple #38
0
    def addBandpassNoise(self, W, sigma_pass, sigma_out):
        """add gaussian colored noise with stddev sigma_pass in
        the 1kHz - 2Khz frequency range and stddev sigma_out
        outside the frequency range above"""
        lowerFreq = 1000 #1Khz
        higherFreq = 2000
        v = W.size
        v-=1
        v |= v >> 1;
        v |= v >> 2;
        v |= v >> 4;
        v |= v >> 8;
        v |= v >> 16;
        v+=1
        white_noise = np.random.normal(0, 1, v)

        freq = rfftfreq(white_noise.size, d = 1/self._comm.FS)
        f_wnoise = rfft(white_noise)

        # If our original signal time was in seconds, this is now in Hz
        in_band_mask = np.logical_or(
                np.logical_and(freq > lowerFreq, freq < higherFreq),
                np.logical_and(freq > -higherFreq,freq < -lowerFreq)
                )
        out_of_band_mask = np.logical_not(in_band_mask)
        f_wnoise[in_band_mask] *= sigma_pass
        f_wnoise[out_of_band_mask] *= sigma_out
        return W + irfft(f_wnoise)[:W.size]
Exemple #39
0
def fft_filter(x, fs, band=(9, 14)):
    w = fftfreq(x.shape[0], d=1. / fs * 2)
    f_signal = rfft(x)
    cut_f_signal = f_signal.copy()
    cut_f_signal[(w < band[0]) | (w > band[1])] = 0
    cut_signal = irfft(cut_f_signal)
    return cut_signal
Exemple #40
0
def do_gen_random(peakAmpl, durationInMSec, samplingRate, fHigh, stereo=True):
    samples = durationInMSec * samplingRate / 1000
    result = np.zeros(samples * 2 if stereo else samples, dtype=np.int16)
    randomSignal = np.random.normal(scale=peakAmpl * 2 / 3, size=samples)
    fftData = fft.rfft(randomSignal)
    freqSamples = samples / 2
    iHigh = freqSamples * fHigh * 2 / samplingRate + 1
    #print len(randomSignal), len(fftData), fLow, fHigh, iHigh
    if iHigh > freqSamples - 1:
        iHigh = freqSamples - 1
    fftData[0] = 0  # DC
    for i in range(iHigh, freqSamples - 1):
        fftData[2 * i + 1] = 0
        fftData[2 * i + 2] = 0
    if (samples - 2 * freqSamples) != 0:
        fftData[samples - 1] = 0

    filteredData = fft.irfft(fftData)
    #freq = np.linspace(0.0, samplingRate, num=len(fftData), endpoint=False)
    #plt.plot(freq, abs(fft.fft(filteredData)))
    #plt.plot(filteredData)
    #plt.show()
    if stereo:
        for i in range(len(filteredData)):
            result[2 * i] = filteredData[i]
            result[2 * i + 1] = filteredData[i]
    else:
        for i in range(len(filteredData)):
            result[i] = filteredData[i]
    return result
Exemple #41
0
    def fourier_filter_magnetic_potential(self):
        # Fourier Filtering
        self.nfourier = self.cfg['initial_data']['nfourier']

        if self.nfourier >= 0:
            (xs, xe), (ys, ye) = self.da1.getRanges()

            # obtain whole A vector everywhere
            scatter, Aglobal = PETSc.Scatter.toAll(self.A)

            scatter.begin(self.A, Aglobal, PETSc.InsertMode.INSERT,
                          PETSc.ScatterMode.FORWARD)
            scatter.end(self.A, Aglobal, PETSc.InsertMode.INSERT,
                        PETSc.ScatterMode.FORWARD)

            petsc_indices = self.da1.getAO().app2petsc(
                np.arange(self.nx * self.ny, dtype=np.int32))

            Ainit = Aglobal.getValues(petsc_indices).copy().reshape(
                (self.ny, self.nx))

            scatter.destroy()
            Aglobal.destroy()

            # compute FFT, cut, compute inverse FFT
            from scipy.fftpack import rfft, irfft

            Afft = rfft(Ainit, axis=1)

            #             Afft[:,0] = 0.
            Afft[:, self.nfourier + 1:] = 0.

            self.da1.getVecArray(self.A)[:, :] = irfft(Afft).T[xs:xe, ys:ye]
Exemple #42
0
def callback(fdb):
    global currblock, editedblock, y, y1, n, xf, off

    if editedblock > currblock + 10:
        return

    for j in range(20):
        block = y[(editedblock + 1 + j) * n:(editedblock + 2 + j) * n]
        filteredbf = np.asarray(rfft(block))
        for k in range(10):
            if not fdb.data[k]:
                filteredbf[np.argwhere((xf >= xf[int(2.0**(k)) - 1])
                                       & (xf < xf[int(2.0**(k + 1)) - 1]))] = 0
                off[k] = True
            else:
                off[k] = False
        filteredblock = irfft(filteredbf)
        filteredblock = [
            int(filteredblock[k]) for k in range(len(filteredblock))
        ]

        try:
            l = 0
            for k in range((editedblock + 1 + j) * n,
                           (editedblock + 2 + j) * n):
                y1[k] = [filteredblock[l], filteredblock[l]]
                # y[k] = filteredblock[l]
                l += 1
        except NameError:
            y[(editedblock + 1 + j) * n:(editedblock + 2 + j) *
              n] = filteredblock

    editedblock = editedblock + 20
Exemple #43
0
def new_polar_filter(psi, coeffs):
    psi_trans = rfft(psi[4:-4, 4:-4, :], axis=0)
    psi_trans_filtered = np.zeros(psi_trans.shape)
    for k in range(nP):
        psi_trans_filtered[:, :, k] = psi_trans[:, :, k] * coeffs
    psi[4:-4, 4:-4, :] = irfft(psi_trans_filtered, axis=0)
    return psi
 def subtract_original_signal_from_picked_signal(self, original_signal, picked_signal):
     # Note this function assumes that the signals are aligned for the starting point!
     fft_length = max(len(original_signal), len(picked_signal))
     original_f_domain = rfft(original_signal, n= fft_length)
     picked_f_domain = rfft(picked_signal, n= fft_length)
     assert len(original_f_domain) == len(picked_f_domain)
     difference_signal = picked_f_domain - original_f_domain
     return irfft(difference_signal)
 def testFFTComp(self):
     data = np.array([1, 0, 0, 1, 1, 0, 0, 1], dtype=np.float32)
     self.stft.performStft(data)
     dfts = self.stft.getDFTs()
     transformed = mat.to_numpy_format(dfts)
     ifftout = fftp.irfft(transformed[:, 0] / 2)
     print ifftout
     self.assertListFloatEqual(data, ifftout)
Exemple #46
0
    def irfft(self, X):
        """
        Apply real FFT to X

        Parameters
        ----------
        X     : list of lists or ndArrays
        """
        X = np.array([irfft(x) for x in X])
        return X
Exemple #47
0
    def applyParameter(self, data):
        
        #low pass filter
        fftdata = rfft(data)
        fftdata[int(float(self._variables["FREQUENCY"])*np.pi*2):] = 0

        ##removes negative values
        filtered_data = irfft(fftdata).clip(0)

        return filtered_data
Exemple #48
0
def bandpass(data_list, min_hz, max_hz):

    fft_list = rfft(data_list)

    # Filter
    for i in range(len(fft_list)):
        if not (min_hz < i/2+1 < max_hz): fft_list[i] = 0

    result_vals = irfft(fft_list)

    return result_vals
Exemple #49
0
def remove_freq_range(data_list, min_hz, max_hz):

    fft_list = rfft(data_list)

    # Filter
    for i in range(len(fft_list)):
        if (min_hz < i / 2 + 1 < max_hz): fft_list[i] = 0

    result_vals = irfft(fft_list)

    return result_vals
def ourFFT2(signal,ffTtime):
    W = fftfreq(len(signal), d=ffTtime[1]-ffTtime[0])
    f_signal = rfft(signal)

    # If our original signal time was in seconds, this is now in Hz    
    cut_f_signal = f_signal.copy()
    #cut_f_signal[(W>0.004)] = 0
    cut_f_signal[(W<=0)] = 0
    cut_f_signal[(W>0.001)] = 0

    cut_signal = irfft(cut_f_signal)
    return W, ffTtime, cut_signal, cut_f_signal, f_signal
Exemple #51
0
def filter_hum(array_to_clear):

    frame_fft = rfft(array_to_clear)
    frame_fft[freq_to_frame(110):] = 0

    # plt.semilogy(x_frequency, 2.0/frame*np.abs(frame_fft[:frame/2]), color='k')
    # plt.xlim([0, 250])
    # plt.show()

    refactored_array = irfft(frame_fft)
    refactored_array = np.real(refactored_array)

    return refactored_array
    def analytical_moments(self, eta):
        """
        Compute the analytical moments for the S1 (circle) Harmonic Density, also known as the generalized von-Mises.

        :param eta: the natural parameters of the distribution.
        :return:
        """
        negative_energy = irfft(np.hstack([[0], eta]), n=self.L_os) * (self.L_os / 2.)
        maximum = np.max(negative_energy)
        unnormalized_moments = rfft(np.exp(negative_energy - maximum)) / (self.L_os / 2.) * np.pi
        moments = unnormalized_moments[1:eta.size + 1] / unnormalized_moments[0]
        lnz = np.log(unnormalized_moments[0]) + maximum
        return moments, lnz
Exemple #53
0
def i_fft_window(grouped_data):  # inverse of fft_window
    ifft_grouped = []
    for i, group in enumerate(
            grouped_data):  # [[z1,z2,z3,...], [y1,y2,y3...], [x...]]
        ifft_grouped.append([])
        for dim in group:
            ifft_grouped[i].append(irfft(dim))
    # put into triplets, then flatten
    group_triplets = [np.rot90(i, 3) for i in ifft_grouped]
    triplets = []
    for i in group_triplets:
        triplets.extend(i)
    return triplets
def ourFFT(signal,ffTtime):
    W = fftfreq(len(signal), d=ffTtime[1]-ffTtime[0])
    print (ffTtime[1]-ffTtime[0])
    f_signal = rfft(signal)

    # If our original signal time was in seconds, this is now in Hz    
    cut_f_signal = f_signal.copy()
    #cut_f_signal[(W>0.004)] = 0 
    cut_f_signal[(W<0.1)] = 0
    cut_f_signal[(W>0.75)] = 0
    #cut_shift_signal = ifftshift(cut_f_signal)
    cut_signal = irfft(cut_f_signal)
    return W, ffTtime, cut_signal, cut_f_signal, f_signal
Exemple #55
0
def bandpass(input_iter):
    """
    filter extreme low and high only from a single channel
    """
    signal = np.array(list(input_iter))
    print signal.size
    time = np.linspace(0, 10, 20)
    w = fftfreq(signal.size, d=time[1] - time[0])
    f_signal = rfft(signal)
    cut_f_signal = f_signal.copy()
    cut_f_signal[(w < 6)] = 0
    cut_signal = irfft(cut_f_signal)
    print cut_signal.size
    return cut_signal
Exemple #56
0
def get_powers(x, fs, n_windows=10, band=(9, 14)):
    n_samples = x.shape[0] // n_windows
    print('n samples', n_samples)
    w = fftfreq(x.shape[0], d=1. / fs * 2)
    f_signal = rfft(x)
    cut_f_signal = f_signal.copy()
    cut_f_signal[(w < band[0]) | (w > band[1])] = 0
    cut_signal = irfft(cut_f_signal)
    plt.plot(cut_signal)
    plt.show()
    amps = np.zeros((n_windows, ))
    for k in range(n_windows):
        amps[k] = cut_signal[k*n_samples:(k+1)*n_samples].std()  # TODO: in one row
    return amps
def myIFFT(x):
	"""
	Return the IFFT for a real signal taking into account some normalization
	
	Parameters
	----------
	x : float 
	    Fourier coefficients
	
	Returns
	-------
	float : signal
	"""
	out = fft.irfft(x)
	return out * np.sqrt(len(out))
Exemple #58
0
def window_rms(signal, window_size):

    #calculates the RMS value for each 'window_size' values of the signal
    signal_squared = np.power(signal,2)
    window = np.ones(window_size)/float(window_size)
    indexes = np.s_[::window_size]
    data = np.sqrt(np.convolve(window, signal_squared, 'valid'))[indexes]

    #low pass filter
    fftdata = rfft(data)
    fftdata[int(filter_frequency_hz*np.pi*2):] = 0

    ##removes negative values
    filtered_data = irfft(fftdata).clip(0)

    return data, filtered_data
Exemple #59
0
def convolveGaussian(x, sigma, sigma_range=4, cache=None):
    """
    1D convolution of x with Gaussian of width sigma pixels
    x_max = int(sigma_range*sigma) the zero padding range at ends
    This uses periodic boundary conditions, and mode = 'same'
    This is the fastest fft version
    """
    fill = int(sigma_range * sigma)
    actual_size = x.size + 2 * fill
    if fill > 0:
        s = nearestFFTnumber(actual_size)
    else:
        s = actual_size
    gauss = None if cache is None else cache.get((fill, actual_size, sigma))
    if gauss is None:
        hnorm = sigma / float(s)
        ps = np.arange(1, s + 1) // 2
        gauss = np.exp(-(ps * (np.pi * hnorm)) ** 2 * 2)
        if cache is not None:
            cache[(fill, actual_size, sigma)] = gauss
    res = fftpack.irfft(fftpack.rfft(x, s) * gauss, s)
    return res[: x.size]
    def bench_random(self):
        from numpy.fft import irfft as numpy_irfft

        print()
        print('Inverse Fast Fourier Transform (real data)')
        print('==================================')
        print(' size |  scipy  |  numpy  ')
        print('----------------------------------')
        for size,repeat in [(100,7000),(1000,2000),
                            (256,10000),
                            (512,10000),
                            (1024,1000),
                            (2048,1000),
                            (2048*2,500),
                            (2048*4,500),
                            ]:
            print('%5s' % size, end=' ')
            sys.stdout.flush()

            x = random([size]).astype(double)
            x1 = zeros(size/2+1,dtype=cdouble)
            x1[0] = x[0]
            for i in range(1,size/2):
                x1[i] = x[2*i-1] + 1j * x[2*i]
            if not size%2:
                x1[-1] = x[-1]
            y = irfft(x)

            print('|%8.2f' % measure('irfft(x)',repeat), end=' ')
            sys.stdout.flush()

            assert_array_almost_equal(numpy_irfft(x1,size),y)
            print('|%8.2f' % measure('numpy_irfft(x1,size)',repeat), end=' ')
            sys.stdout.flush()

            print(' (secs for %s calls)' % (repeat))

        sys.stdout.flush()