Python numpy.fft.ifft() Examples
The following are 30
code examples of numpy.fft.ifft().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
numpy.fft
, or try the search function
.
Example #1
Source File: fir_filter_design.py From lambda-packs with MIT License | 8 votes |
def _dhtm(mag): """Compute the modified 1D discrete Hilbert transform Parameters ---------- mag : ndarray The magnitude spectrum. Should be 1D with an even length, and preferably a fast length for FFT/IFFT. """ # Adapted based on code by Niranjan Damera-Venkata, # Brian L. Evans and Shawn R. McCaslin (see refs for `minimum_phase`) sig = np.zeros(len(mag)) # Leave Nyquist and DC at 0, knowing np.abs(fftfreq(N)[midpt]) == 0.5 midpt = len(mag) // 2 sig[1:midpt] = 1 sig[midpt+1:] = -1 # eventually if we want to support complex filters, we will need a # np.abs() on the mag inside the log, and should remove the .real recon = ifft(mag * np.exp(fft(sig * ifft(np.log(mag))))).real return recon
Example #2
Source File: digitalcom.py From scikit-dsp-comm with BSD 2-Clause "Simplified" License | 6 votes |
def xcorr(x1,x2,Nlags): """ r12, k = xcorr(x1,x2,Nlags), r12 and k are ndarray's Compute the energy normalized cross correlation between the sequences x1 and x2. If x1 = x2 the cross correlation is the autocorrelation. The number of lags sets how many lags to return centered about zero """ K = 2*(int(np.floor(len(x1)/2))) X1 = fft.fft(x1[:K]) X2 = fft.fft(x2[:K]) E1 = sum(abs(x1[:K])**2) E2 = sum(abs(x2[:K])**2) r12 = np.fft.ifft(X1*np.conj(X2))/np.sqrt(E1*E2) k = np.arange(K) - int(np.floor(K/2)) r12 = np.fft.fftshift(r12) idx = np.nonzero(np.ravel(abs(k) <= Nlags)) return r12[idx], k[idx]
Example #3
Source File: util.py From scikit-kge with MIT License | 6 votes |
def cconv(a, b): """ Circular convolution of vectors Computes the circular convolution of two vectors a and b via their fast fourier transforms a \ast b = \mathcal{F}^{-1}(\mathcal{F}(a) \odot \mathcal{F}(b)) Parameter --------- a: real valued array (shape N) b: real valued array (shape N) Returns ------- c: real valued array (shape N), representing the circular convolution of a and b """ return ifft(fft(a) * fft(b)).real
Example #4
Source File: T1FFT.py From lie_learn with MIT License | 6 votes |
def synthesize(f_hat, axis=0): """ Compute the inverse / synthesis Fourier transform of the function f_hat : Z -> C. The function f_hat(n) is sampled at points in a limited range -floor(N/2) <= n <= ceil(N/2) - 1 This function returns f[k] = f(theta_k) = sum_{n=-floor(N/2)}^{ceil(N/2)-1} f_hat(n) exp(i n theta_k) where theta_k = 2 pi k / N for k = 0, ..., N - 1 :param f_hat: :param axis: :return: """ f_hat = ifftshift(f_hat * f_hat.shape[axis], axes=axis) f = ifft(f_hat, axis=axis) return f
Example #5
Source File: util.py From scikit-kge with MIT License | 6 votes |
def ccorr(a, b): """ Circular correlation of vectors Computes the circular correlation of two vectors a and b via their fast fourier transforms a \ast b = \mathcal{F}^{-1}(\overline{\mathcal{F}(a)} \odot \mathcal{F}(b)) Parameter --------- a: real valued array (shape N) b: real valued array (shape N) Returns ------- c: real valued array (shape N), representing the circular correlation of a and b """ return ifft(np.conj(fft(a)) * fft(b)).real
Example #6
Source File: util.py From cesi with Apache License 2.0 | 6 votes |
def cconv(a, b): """ Circular convolution of vectors Computes the circular convolution of two vectors a and b via their fast fourier transforms a \ast b = \mathcal{F}^{-1}(\mathcal{F}(a) \odot \mathcal{F}(b)) Parameter --------- a: real valued array (shape N) b: real valued array (shape N) Returns ------- c: real valued array (shape N), representing the circular convolution of a and b """ return ifft(fft(a) * fft(b)).real
Example #7
Source File: util.py From cesi with Apache License 2.0 | 6 votes |
def ccorr(a, b): """ Circular correlation of vectors Computes the circular correlation of two vectors a and b via their fast fourier transforms a \ast b = \mathcal{F}^{-1}(\overline{\mathcal{F}(a)} \odot \mathcal{F}(b)) Parameter --------- a: real valued array (shape N) b: real valued array (shape N) Returns ------- c: real valued array (shape N), representing the circular correlation of a and b """ return ifft(np.conj(fft(a)) * fft(b)).real
Example #8
Source File: frft.py From pyoptools with GNU General Public License v3.0 | 6 votes |
def _frft2(x, alpha): assert x.ndim == 2, "x must be a 2 dimensional array" m, n = x.shape # TODO please remove this confusing comment. Is it 'm' or 'm-1' ? # TODO If 'p = m', more code cleaning is easy to do. p = m # m-1 # deveria incrementarse el sigiente pow y = zeros((2 * p, n), dtype=complex) z = zeros((2 * p, n), dtype=complex) j = indices(z.shape)[0] y[(p - m) // 2 : (p + m) // 2, :] = x * exp( -1.0j * pi * (j[0:m] ** 2) * float(alpha) / m ) z[0:m, :] = exp(1.0j * pi * (j[0:m] ** 2) * float(alpha) / m) z[-m:, :] = exp(1.0j * pi * ((j[-m:] - 2 * p) ** 2) * float(alpha) / m) d = exp(-1.0j * pi * j ** 2 ** float(alpha) / m) * ifft( fft(y, axis=0) * fft(z, axis=0), axis=0 ) return d[0:m] # TODO better docstring
Example #9
Source File: fftarma.py From Splunking-Crime with GNU Affero General Public License v3.0 | 6 votes |
def filter(self, x): ''' filter a timeseries with the ARMA filter padding with zero is missing, in example I needed the padding to get initial conditions identical to direct filter Initial filtered observations differ from filter2 and signal.lfilter, but at end they are the same. See Also -------- tsa.filters.fftconvolve ''' n = x.shape[0] if n == self.fftarma: fftarma = self.fftarma else: fftarma = self.fftma(n) / self.fftar(n) tmpfft = fftarma * fft.fft(x) return fft.ifft(tmpfft)
Example #10
Source File: fftarma.py From Splunking-Crime with GNU Affero General Public License v3.0 | 6 votes |
def invpowerspd(self, n): '''autocovariance from spectral density scaling is correct, but n needs to be large for numerical accuracy maybe padding with zero in fft would be faster without slicing it returns 2-sided autocovariance with fftshift >>> ArmaFft([1, -0.5], [1., 0.4], 40).invpowerspd(2**8)[:10] array([ 2.08 , 1.44 , 0.72 , 0.36 , 0.18 , 0.09 , 0.045 , 0.0225 , 0.01125 , 0.005625]) >>> ArmaFft([1, -0.5], [1., 0.4], 40).acovf(10) array([ 2.08 , 1.44 , 0.72 , 0.36 , 0.18 , 0.09 , 0.045 , 0.0225 , 0.01125 , 0.005625]) ''' hw = self.fftarma(n) return np.real_if_close(fft.ifft(hw*hw.conj()), tol=200)[:n]
Example #11
Source File: fir_filter_design.py From Splunking-Crime with GNU Affero General Public License v3.0 | 6 votes |
def _dhtm(mag): """Compute the modified 1D discrete Hilbert transform Parameters ---------- mag : ndarray The magnitude spectrum. Should be 1D with an even length, and preferably a fast length for FFT/IFFT. """ # Adapted based on code by Niranjan Damera-Venkata, # Brian L. Evans and Shawn R. McCaslin (see refs for `minimum_phase`) sig = np.zeros(len(mag)) # Leave Nyquist and DC at 0, knowing np.abs(fftfreq(N)[midpt]) == 0.5 midpt = len(mag) // 2 sig[1:midpt] = 1 sig[midpt+1:] = -1 # eventually if we want to support complex filters, we will need a # np.abs() on the mag inside the log, and should remove the .real recon = ifft(mag * np.exp(fft(sig * ifft(np.log(mag))))).real return recon
Example #12
Source File: fir_filter_design.py From GraphicDesignPatternByPython with MIT License | 6 votes |
def _dhtm(mag): """Compute the modified 1D discrete Hilbert transform Parameters ---------- mag : ndarray The magnitude spectrum. Should be 1D with an even length, and preferably a fast length for FFT/IFFT. """ # Adapted based on code by Niranjan Damera-Venkata, # Brian L. Evans and Shawn R. McCaslin (see refs for `minimum_phase`) sig = np.zeros(len(mag)) # Leave Nyquist and DC at 0, knowing np.abs(fftfreq(N)[midpt]) == 0.5 midpt = len(mag) // 2 sig[1:midpt] = 1 sig[midpt+1:] = -1 # eventually if we want to support complex filters, we will need a # np.abs() on the mag inside the log, and should remove the .real recon = ifft(mag * np.exp(fft(sig * ifft(np.log(mag))))).real return recon
Example #13
Source File: core.py From kshape with MIT License | 6 votes |
def _ncc_c(x, y): """ >>> _ncc_c([1,2,3,4], [1,2,3,4]) array([ 0.13333333, 0.36666667, 0.66666667, 1. , 0.66666667, 0.36666667, 0.13333333]) >>> _ncc_c([1,1,1], [1,1,1]) array([ 0.33333333, 0.66666667, 1. , 0.66666667, 0.33333333]) >>> _ncc_c([1,2,3], [-1,-1,-1]) array([-0.15430335, -0.46291005, -0.9258201 , -0.77151675, -0.46291005]) """ den = np.array(norm(x) * norm(y)) den[den == 0] = np.Inf x_len = len(x) fft_size = 1 << (2*x_len-1).bit_length() cc = ifft(fft(x, fft_size) * np.conj(fft(y, fft_size))) cc = np.concatenate((cc[-(x_len-1):], cc[:x_len])) return np.real(cc) / den
Example #14
Source File: test_ndimage.py From Computable with MIT License | 6 votes |
def test_fourier_ellipsoid_real01(self): for shape in [(32, 16), (31, 15)]: for type in [numpy.float32, numpy.float64]: a = numpy.zeros(shape, type) a[0, 0] = 1.0 a = fft.rfft(a, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], shape[0], 0) a = fft.ifft(a, shape[1], 1) a = fft.irfft(a, shape[0], 0) assert_almost_equal(ndimage.sum(a), 1.0)
Example #15
Source File: test_ndimage.py From Computable with MIT License | 6 votes |
def test_fourier_shift_real01(self): for shape in [(32, 16), (31, 15)]: for dtype in [numpy.float32, numpy.float64]: expected = numpy.arange(shape[0] * shape[1], dtype=dtype) expected.shape = shape a = fft.rfft(expected, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_shift(a, [1, 1], shape[0], 0) a = fft.ifft(a, shape[1], 1) a = fft.irfft(a, shape[0], 0) assert_array_almost_equal(a[1:, 1:], expected[:-1, :-1]) assert_array_almost_equal(a.imag, numpy.zeros(shape))
Example #16
Source File: test_ndimage.py From Computable with MIT License | 6 votes |
def test_fourier_uniform_real01(self): for shape in [(32, 16), (31, 15)]: for type in [numpy.float32, numpy.float64]: a = numpy.zeros(shape, type) a[0, 0] = 1.0 a = fft.rfft(a, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_uniform(a, [5.0, 2.5], shape[0], 0) a = fft.ifft(a, shape[1], 1) a = fft.irfft(a, shape[0], 0) assert_almost_equal(ndimage.sum(a), 1.0)
Example #17
Source File: fftarma.py From vnpy_crypto with MIT License | 6 votes |
def invpowerspd(self, n): '''autocovariance from spectral density scaling is correct, but n needs to be large for numerical accuracy maybe padding with zero in fft would be faster without slicing it returns 2-sided autocovariance with fftshift >>> ArmaFft([1, -0.5], [1., 0.4], 40).invpowerspd(2**8)[:10] array([ 2.08 , 1.44 , 0.72 , 0.36 , 0.18 , 0.09 , 0.045 , 0.0225 , 0.01125 , 0.005625]) >>> ArmaFft([1, -0.5], [1., 0.4], 40).acovf(10) array([ 2.08 , 1.44 , 0.72 , 0.36 , 0.18 , 0.09 , 0.045 , 0.0225 , 0.01125 , 0.005625]) ''' hw = self.fftarma(n) return np.real_if_close(fft.ifft(hw*hw.conj()), tol=200)[:n]
Example #18
Source File: fftarma.py From vnpy_crypto with MIT License | 6 votes |
def filter(self, x): ''' filter a timeseries with the ARMA filter padding with zero is missing, in example I needed the padding to get initial conditions identical to direct filter Initial filtered observations differ from filter2 and signal.lfilter, but at end they are the same. See Also -------- tsa.filters.fftconvolve ''' n = x.shape[0] if n == self.fftarma: fftarma = self.fftarma else: fftarma = self.fftma(n) / self.fftar(n) tmpfft = fftarma * fft.fft(x) return fft.ifft(tmpfft)
Example #19
Source File: core.py From kshape with MIT License | 5 votes |
def _ncc_c_2dim(x, y): """ Variant of NCCc that operates with 2 dimensional X arrays and 1 dimensional y vector Returns a 2 dimensional array of normalized fourier transforms """ den = np.array(norm(x, axis=1) * norm(y)) den[den == 0] = np.Inf x_len = x.shape[-1] fft_size = 1 << (2*x_len-1).bit_length() cc = ifft(fft(x, fft_size) * np.conj(fft(y, fft_size))) cc = np.concatenate((cc[:,-(x_len-1):], cc[:,:x_len]), axis=1) return np.real(cc) / den[:, np.newaxis]
Example #20
Source File: core.py From kshape with MIT License | 5 votes |
def _ncc_c_3dim(x, y): """ Variant of NCCc that operates with 2 dimensional X arrays and 2 dimensional y vector Returns a 3 dimensional array of normalized fourier transforms """ den = norm(x, axis=1)[:, None] * norm(y, axis=1) den[den == 0] = np.Inf x_len = x.shape[-1] fft_size = 1 << (2*x_len-1).bit_length() cc = ifft(fft(x, fft_size) * np.conj(fft(y, fft_size))[:, None]) cc = np.concatenate((cc[:,:,-(x_len-1):], cc[:,:,:x_len]), axis=2) return np.real(cc) / den.T[:, :, None]
Example #21
Source File: scale_filter.py From pyCFTrackers with MIT License | 5 votes |
def track(self, im, pos, base_target_sz, current_scale_factor): """ track the scale using the scale filter """ # get scale filter features scales = current_scale_factor * self.scale_size_factors xs = self._extract_scale_sample(im, pos, base_target_sz, scales, self.scale_model_sz) # project xs = self.basis.dot(xs) * self.window # get scores xsf = fft(xs, axis=1) scale_responsef = np.sum(self.sf_num * xsf, 0) / (self.sf_den + self.config.lamBda) interp_scale_response = np.real(ifft(resize_dft(scale_responsef, self.config.number_of_interp_scales))) recovered_scale_index = np.argmax(interp_scale_response) if self.config.do_poly_interp: # fit a quadratic polynomial to get a refined scale estimate id1 = (recovered_scale_index - 1) % self.config.number_of_interp_scales id2 = (recovered_scale_index + 1) % self.config.number_of_interp_scales poly_x = np.array([self.interp_scale_factors[id1], self.interp_scale_factors[recovered_scale_index], self.interp_scale_factors[id2]]) poly_y = np.array([interp_scale_response[id1], interp_scale_response[recovered_scale_index], interp_scale_response[id2]]) poly_A = np.array([[poly_x[0]**2, poly_x[0], 1], [poly_x[1]**2, poly_x[1], 1], [poly_x[2]**2, poly_x[2], 1]], dtype=np.float32) poly = np.linalg.inv(poly_A).dot(poly_y.T) scale_change_factor = - poly[1] / (2 * poly[0]) else: scale_change_factor = self.interp_scale_factors[recovered_scale_index] return scale_change_factor
Example #22
Source File: simulate.py From wonambi with GNU General Public License v3.0 | 5 votes |
def _color_noise(x, s_freq, coef=0): """Add some color to the noise by changing the power spectrum. Parameters ---------- x : ndarray one vector of the original signal s_freq : int sampling frequency coef : float coefficient to apply (0 -> white noise, 1 -> pink, 2 -> brown, -1 -> blue) Returns ------- ndarray one vector of the colored noise. """ # convert to freq domain y = fft(x) ph = angle(y) m = abs(y) # frequencies for each fft value freq = linspace(0, s_freq / 2, int(len(m) / 2) + 1) freq = freq[1:-1] # create new power spectrum m1 = zeros(len(m)) # leave zero alone, and multiply the rest by the function m1[1:int(len(m) / 2)] = m[1:int(len(m) / 2)] * f(freq, coef) # simmetric around nyquist freq m1[int(len(m1) / 2 + 1):] = m1[1:int(len(m1) / 2)][::-1] # reconstruct the signal y1 = m1 * exp(1j * ph) return real(ifft(y1))
Example #23
Source File: utils.py From joie-kdd19 with MIT License | 5 votes |
def circular_correlation(h, t): return tf.real(tf.spectral.ifft(tf.multiply(tf.conj(tf.spectral.fft(tf.complex(h, 0.))), tf.spectral.fft(tf.complex(t, 0.)))))
Example #24
Source File: utils.py From joie-kdd19 with MIT License | 5 votes |
def np_ccorr(h, t): return ifft(np.conj(fft(h)) * fft(t)).real
Example #25
Source File: cooc.py From text_embedding with MIT License | 5 votes |
def circular_conv(cooc, w2v): for i, word in enumerate(cooc): vec = w2v.get(word) if vec is None: return 0.0 if i: output = output * fft(vec) else: output = fft(vec) return np.real(ifft(output))
Example #26
Source File: delayseq.py From piradar with GNU Affero General Public License v3.0 | 5 votes |
def delayseq(x, delay_sec: float, fs: int): """ x: input 1-D signal delay_sec: amount to shift signal [seconds] fs: sampling frequency [Hz] xs: time-shifted signal """ assert x.ndim == 1, "only 1-D signals for now" delay_samples = delay_sec * fs delay_int = round(delay_samples) nfft = nextpow2(x.size + delay_int) fbins = 2 * pi * ifftshift((arange(nfft) - nfft // 2)) / nfft X = fft(x, nfft) Xs = ifft(X * exp(-1j * delay_samples * fbins)) if isreal(x[0]): Xs = Xs.real xs = zeros_like(x) xs[delay_int:] = Xs[delay_int : x.size] return xs
Example #27
Source File: bidiphase.py From suite2p with GNU General Public License v3.0 | 5 votes |
def compute(frames): """ computes the bidirectional phase offset sometimes in line scanning there will be offsets between lines; if ops['do_bidiphase'], then bidiphase is computed and applied Parameters ---------- frames : int16 random subsample of frames in binary (frames x Ly x Lx) Returns ------- bidiphase : int bidirectional phase offset in pixels """ Ly = frames.shape[1] Lx = frames.shape[2] # lines scanned in 1 direction yr1 = np.arange(1, np.floor(Ly/2)*2, 2, int) # lines scanned in the other direction yr2 = np.arange(0, np.floor(Ly/2)*2, 2, int) # compute phase-correlation between lines in x-direction d1 = fft.fft(frames[:, yr1, :], axis=2) d2 = np.conj(fft.fft(frames[:, yr2, :], axis=2)) d1 = d1 / (np.abs(d1) + 1e-5) d2 = d2 / (np.abs(d2) + 1e-5) #fhg = gaussian_fft(1, int(np.floor(Ly/2)), Lx) cc = np.real(fft.ifft(d1 * d2 , axis=2))#* fhg[np.newaxis, :, :], axis=2)) cc = cc.mean(axis=1).mean(axis=0) cc = fft.fftshift(cc) ix = np.argmax(cc[(np.arange(-10,11,1) + np.floor(Lx/2)).astype(int)]) ix -= 10 bidiphase = -1*ix return bidiphase
Example #28
Source File: csr.py From ocelot with GNU General Public License v3.0 | 5 votes |
def csr_convolution(a, b): P = len(a) Q = len(b) L = P + Q - 1 K = 2 ** nextpow2(L) a_pad = np.pad(a, (0, K - P), 'constant', constant_values=(0)) b_pad = np.pad(b, (0, K - Q), 'constant', constant_values=(0)) c = ifft(fft(a_pad)*fft(b_pad)) c = c[0:L-1].real return c
Example #29
Source File: test_ndimage.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_fourier_gaussian_real01(self): for shape in [(32, 16), (31, 15)]: for type_, dec in zip([numpy.float32, numpy.float64], [6, 14]): a = numpy.zeros(shape, type_) a[0, 0] = 1.0 a = fft.rfft(a, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_gaussian(a, [5.0, 2.5], shape[0], 0) a = fft.ifft(a, shape[1], 1) a = fft.irfft(a, shape[0], 0) assert_almost_equal(ndimage.sum(a), 1, decimal=dec)
Example #30
Source File: bench_basic.py From Computable with MIT License | 5 votes |
def bench_random(self): from numpy.fft import ifft as numpy_ifft print() print(' Inverse Fast Fourier Transform') print('===============================================') print(' | real input | complex input ') print('-----------------------------------------------') print(' size | scipy | numpy | 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() for x in [random([size]).astype(double), random([size]).astype(cdouble)+random([size]).astype(cdouble)*1j ]: if size > 500: y = ifft(x) else: y = direct_idft(x) assert_array_almost_equal(ifft(x),y) print('|%8.2f' % measure('ifft(x)',repeat), end=' ') sys.stdout.flush() assert_array_almost_equal(numpy_ifft(x),y) print('|%8.2f' % measure('numpy_ifft(x)',repeat), end=' ') sys.stdout.flush() print(' (secs for %s calls)' % (repeat)) sys.stdout.flush()