def _raw_fftnd(a, s=None, axes=None, function=fft, norm=None): a = asarray(a) s, axes = _cook_nd_args(a, s, axes) itl = list(range(len(axes))) itl.reverse() for ii in itl: a = function(a, n=s[ii], axis=axes[ii], norm=norm) return a
def fftshift(x, axes=None): """ Shift the zero-frequency component to the center of the spectrum. This function swaps half-spaces for all axes listed (defaults to all). Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even. Parameters ---------- x : array_like Input array. axes : int or shape tuple, optional Axes over which to shift. Default is None, which shifts all axes. Returns ------- y : ndarray The shifted array. See Also -------- ifftshift : The inverse of `fftshift`. Examples -------- >>> freqs = np.fft.fftfreq(10, 0.1) >>> freqs array([ 0., 1., 2., 3., 4., -5., -4., -3., -2., -1.]) >>> np.fft.fftshift(freqs) array([-5., -4., -3., -2., -1., 0., 1., 2., 3., 4.]) Shift the zero-frequency component only along the second axis: >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3) >>> freqs array([[ 0., 1., 2.], [ 3., 4., -4.], [-3., -2., -1.]]) >>> np.fft.fftshift(freqs, axes=(1,)) array([[ 2., 0., 1.], [-4., 3., 4.], [-1., -3., -2.]]) """ x = asarray(x) if axes is None: axes = tuple(range(x.ndim)) shift = [dim // 2 for dim in x.shape] elif isinstance(axes, integer_types): shift = x.shape[axes] // 2 else: shift = [x.shape[ax] // 2 for ax in axes] return roll(x, shift, axes)
def byte_bounds(a): """ Returns pointers to the end-points of an array. Parameters ---------- a : ndarray Input array. It must conform to the Python-side of the array interface. Returns ------- (low, high) : tuple of 2 integers The first integer is the first byte of the array, the second integer is just past the last byte of the array. If `a` is not contiguous it will not use every byte between the (`low`, `high`) values. Examples -------- >>> I = np.eye(2, dtype='f'); I.dtype dtype('float32') >>> low, high = np.byte_bounds(I) >>> high - low == I.size*I.itemsize True >>> I = np.eye(2, dtype='G'); I.dtype dtype('complex192') >>> low, high = np.byte_bounds(I) >>> high - low == I.size*I.itemsize True """ ai = a.__array_interface__ a_data = ai['data'][0] astrides = ai['strides'] ashape = ai['shape'] bytes_a = asarray(a).dtype.itemsize a_low = a_high = a_data if astrides is None: # contiguous case a_high += a.size * bytes_a else: for shape, stride in zip(ashape, astrides): if stride < 0: a_low += (shape - 1) * stride else: a_high += (shape - 1) * stride a_high += bytes_a return a_low, a_high
def _raw_fft(a, n=None, axis=-1, init_function=fftpack.cffti, work_function=fftpack.cfftf, fft_cache=_fft_cache): a = asarray(a) if n is None: n = a.shape[axis] if n < 1: raise ValueError("Invalid number of FFT data points (%d) specified." % n) # We have to ensure that only a single thread can access a wsave array # at any given time. Thus we remove it from the cache and insert it # again after it has been used. Multiple threads might create multiple # copies of the wsave array. This is intentional and a limitation of # the current C code. wsave = fft_cache.pop_twiddle_factors(n) if wsave is None: wsave = init_function(n) if a.shape[axis] != n: s = list(a.shape) if s[axis] > n: index = [slice(None)]*len(s) index[axis] = slice(0, n) a = a[tuple(index)] else: index = [slice(None)]*len(s) index[axis] = slice(0, s[axis]) s[axis] = n z = zeros(s, a.dtype.char) z[tuple(index)] = a a = z if axis != -1: a = swapaxes(a, axis, -1) r = work_function(a, wsave) if axis != -1: r = swapaxes(r, axis, -1) # As soon as we put wsave back into the cache, another thread could pick it # up and start using it, so we must not do this until after we're # completely done using it ourselves. fft_cache.put_twiddle_factors(n, wsave) return r
def ifftshift(x, axes=None): """ The inverse of `fftshift`. Although identical for even-length `x`, the functions differ by one sample for odd-length `x`. Parameters ---------- x : array_like Input array. axes : int or shape tuple, optional Axes over which to calculate. Defaults to None, which shifts all axes. Returns ------- y : ndarray The shifted array. See Also -------- fftshift : Shift zero-frequency component to the center of the spectrum. Examples -------- >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3) >>> freqs array([[ 0., 1., 2.], [ 3., 4., -4.], [-3., -2., -1.]]) >>> np.fft.ifftshift(np.fft.fftshift(freqs)) array([[ 0., 1., 2.], [ 3., 4., -4.], [-3., -2., -1.]]) """ x = asarray(x) if axes is None: axes = tuple(range(x.ndim)) shift = [-(dim // 2) for dim in x.shape] elif isinstance(axes, integer_types): shift = -(x.shape[axes] // 2) else: shift = [-(x.shape[ax] // 2) for ax in axes] return roll(x, shift, axes)
def fft(a, n=None, axis=-1, norm=None): """ Compute the one-dimensional discrete Fourier Transform. This function computes the one-dimensional *n*-point discrete Fourier Transform (DFT) with the efficient Fast Fourier Transform (FFT) algorithm [CT]. Parameters ---------- a : array_like Input array, can be complex. n : int, optional Length of the transformed axis of the output. If `n` is smaller than the length of the input, the input is cropped. If it is larger, the input is padded with zeros. If `n` is not given, the length of the input along the axis specified by `axis` is used. axis : int, optional Axis over which to compute the FFT. If not given, the last axis is used. norm : {None, "ortho"}, optional .. versionadded:: 1.10.0 Normalization mode (see `numpy.fft`). Default is None. Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axis indicated by `axis`, or the last one if `axis` is not specified. Raises ------ IndexError if `axes` is larger than the last axis of `a`. See Also -------- numpy.fft : for definition of the DFT and conventions used. ifft : The inverse of `fft`. fft2 : The two-dimensional FFT. fftn : The *n*-dimensional FFT. rfftn : The *n*-dimensional FFT of real input. fftfreq : Frequency bins for given FFT parameters. Notes ----- FFT (Fast Fourier Transform) refers to a way the discrete Fourier Transform (DFT) can be calculated efficiently, by using symmetries in the calculated terms. The symmetry is highest when `n` is a power of 2, and the transform is therefore most efficient for these sizes. The DFT is defined, with the conventions used in this implementation, in the documentation for the `numpy.fft` module. References ---------- .. [CT] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the machine calculation of complex Fourier series," *Math. Comput.* 19: 297-301. Examples -------- >>> np.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8)) array([ -3.44505240e-16 +1.14383329e-17j, 8.00000000e+00 -5.71092652e-15j, 2.33482938e-16 +1.22460635e-16j, 1.64863782e-15 +1.77635684e-15j, 9.95839695e-17 +2.33482938e-16j, 0.00000000e+00 +1.66837030e-15j, 1.14383329e-17 +1.22460635e-16j, -1.64863782e-15 +1.77635684e-15j]) In this example, real input has an FFT which is Hermitian, i.e., symmetric in the real part and anti-symmetric in the imaginary part, as described in the `numpy.fft` documentation: >>> import matplotlib.pyplot as plt >>> t = np.arange(256) >>> sp = np.fft.fft(np.sin(t)) >>> freq = np.fft.fftfreq(t.shape[-1]) >>> plt.plot(freq, sp.real, freq, sp.imag) [<matplotlib.lines.Line2D object at 0x...>, <matplotlib.lines.Line2D object at 0x...>] >>> plt.show() """ a = asarray(a).astype(complex, copy=False) if n is None: n = a.shape[axis] output = _raw_fft(a, n, axis, fftpack.cffti, fftpack.cfftf, _fft_cache) if _unitary(norm): output *= 1 / sqrt(n) return output
def __div__(self, other): return self._rc(divide(self.array, asarray(other)))
def __rdiv__(self, other): return self._rc(divide(asarray(other), self.array))
def __rsub__(self, other): return self._rc(asarray(other) - self.array)
def __mul__(self, other): return self._rc(multiply(self.array, asarray(other)))
def __sub__(self, other): return self._rc(self.array - asarray(other))
def __add__(self, other): return self._rc(self.array + asarray(other))
def __setitem__(self, index, value): self.array[index] = asarray(value, self.dtype)
def __rpow__(self, other): return self._rc(power(asarray(other), self.array))
def __pow__(self, other): return self._rc(power(self.array, asarray(other)))