Python scipy.fft() Examples
The following are 29
code examples of scipy.fft().
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
scipy
, or try the search function
.
Example #1
Source File: fft.py From cupy with MIT License | 7 votes |
def ihfft(x, n=None, axis=-1, norm=None, overwrite_x=False, *, plan=None): """Compute the FFT of a signal that has Hermitian symmetry. Args: a (cupy.ndarray): Array to be transform. n (None or int): Number of points along transformation axis in the input to use. If ``n`` is not given, the length of the input along the axis specified by ``axis`` is used. axis (int): Axis over which to compute the FFT. norm (None or ``"ortho"``): Keyword to specify the normalization mode. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (None): This argument is currently not supported. Returns: cupy.ndarray: The transformed array which shape is specified by ``n`` and type will convert to complex if the input is other. The length of the transformed axis is ``n//2+1``. .. seealso:: :func:`scipy.fft.ihfft` """ # TODO(leofang): support R2C & C2R plans if plan is not None: raise NotImplementedError('ihfft plan is currently not yet supported') return _ihfft(x, n, axis, norm)
Example #2
Source File: audio.py From pliers with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _stft(self, stim): x = stim.data framesamp = int(self.frame_size * stim.sampling_rate) hopsamp = int(self.hop_size * stim.sampling_rate) w = np.hanning(framesamp) X = np.array([fft(w * x[i:(i + framesamp)]) for i in range(0, len(x) - framesamp, hopsamp)]) nyquist_lim = int(X.shape[1] // 2) X = np.log(X[:, :nyquist_lim]) X = np.absolute(X) if self.spectrogram: import matplotlib.pyplot as plt bins = np.fft.fftfreq(framesamp, d=1. / stim.sampling_rate) bins = bins[:nyquist_lim] plt.imshow(X.T, origin='lower', aspect='auto', interpolation='nearest', cmap='RdYlBu_r', extent=[0, stim.duration, bins.min(), bins.max()]) plt.xlabel('Time') plt.ylabel('Frequency') plt.colorbar() plt.show() return X
Example #3
Source File: fft.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 5 votes |
def create_fft(fn): sample_rate, X = scipy.io.wavfile.read(fn) fft_features = abs(scipy.fft(X)[:1000]) write_fft(fft_features, fn)
Example #4
Source File: transform.py From DeepLearning_Wavelet-LSTM with MIT License | 5 votes |
def w_k(self): """Angular frequency as a function of Fourier index. See eq5 of TC. N.B the frequencies returned by numpy are adimensional, on the interval [-1/2, 1/2], so we multiply by 2 * pi. """ return 2 * np.pi * np.fft.fftfreq(self.N, self.dt)
Example #5
Source File: transform.py From DeepLearning_Wavelet-LSTM with MIT License | 5 votes |
def cwt_freq(data, wavelet, widths, dt, axis): # compute in frequency # next highest power of two for padding N = data.shape[axis] pN = int(2 ** np.ceil(np.log2(N))) # N.B. padding in fft adds zeros to the *end* of the array, # not equally either end. fft_data = scipy.fft(data, n=pN, axis=axis) # frequencies w_k = np.fft.fftfreq(pN, d=dt) * 2 * np.pi # sample wavelet and normalise norm = (2 * np.pi * widths / dt) ** .5 wavelet_data = norm[:, None] * wavelet(w_k, widths[:, None]) # Convert negative axis. Add one to account for # inclusion of widths axis above. axis = (axis % data.ndim) + 1 # perform the convolution in frequency space slices = [slice(None)] + [None for _ in data.shape] slices[axis] = slice(None) out = scipy.ifft(fft_data[None] * wavelet_data.conj()[slices], n=pN, axis=axis) # remove zero padding slices = [slice(None) for _ in out.shape] slices[axis] = slice(None, N) if data.ndim == 1: return out[slices].squeeze() else: return out[slices]
Example #6
Source File: transform.py From DeepLearning_Wavelet-LSTM with MIT License | 5 votes |
def w_k(self): """Angular frequency as a function of Fourier index. See eq5 of TC. N.B the frequencies returned by numpy are adimensional, on the interval [-1/2, 1/2], so we multiply by 2 * pi. """ return 2 * np.pi * np.fft.fftfreq(self.N, self.dt)
Example #7
Source File: transform.py From DeepLearning_Wavelet-LSTM with MIT License | 5 votes |
def cwt_freq(data, wavelet, widths, dt, axis): # compute in frequency # next highest power of two for padding N = data.shape[axis] pN = int(2 ** np.ceil(np.log2(N))) # N.B. padding in fft adds zeros to the *end* of the array, # not equally either end. fft_data = scipy.fft(data, n=pN, axis=axis) # frequencies w_k = np.fft.fftfreq(pN, d=dt) * 2 * np.pi # sample wavelet and normalise norm = (2 * np.pi * widths / dt) ** .5 wavelet_data = norm[:, None] * wavelet(w_k, widths[:, None]) # Convert negative axis. Add one to account for # inclusion of widths axis above. axis = (axis % data.ndim) + 1 # perform the convolution in frequency space slices = [slice(None)] + [None for _ in data.shape] slices[axis] = slice(None) out = scipy.ifft(fft_data[None] * wavelet_data.conj()[slices], n=pN, axis=axis) # remove zero padding slices = [slice(None) for _ in out.shape] slices[axis] = slice(None, N) if data.ndim == 1: return out[slices].squeeze() else: return out[slices]
Example #8
Source File: transform.py From DeepLearning_Wavelet-LSTM with MIT License | 5 votes |
def cwt_freq(data, wavelet, widths, dt, axis): # compute in frequency # next highest power of two for padding N = data.shape[axis] pN = int(2 ** np.ceil(np.log2(N))) # N.B. padding in fft adds zeros to the *end* of the array, # not equally either end. fft_data = scipy.fft(data, n=pN, axis=axis) # frequencies w_k = np.fft.fftfreq(pN, d=dt) * 2 * np.pi # sample wavelet and normalise norm = (2 * np.pi * widths / dt) ** .5 wavelet_data = norm[:, None] * wavelet(w_k, widths[:, None]) # Convert negative axis. Add one to account for # inclusion of widths axis above. axis = (axis % data.ndim) + 1 # perform the convolution in frequency space slices = [slice(None)] + [None for _ in data.shape] slices[axis] = slice(None) out = scipy.ifft(fft_data[None] * wavelet_data.conj()[slices], n=pN, axis=axis) # remove zero padding slices = [slice(None) for _ in out.shape] slices[axis] = slice(None, N) if data.ndim == 1: return out[slices].squeeze() else: return out[slices]
Example #9
Source File: transform.py From DeepLearning_Wavelet-LSTM with MIT License | 5 votes |
def w_k(self): """Angular frequency as a function of Fourier index. See eq5 of TC. N.B the frequencies returned by numpy are adimensional, on the interval [-1/2, 1/2], so we multiply by 2 * pi. """ return 2 * np.pi * np.fft.fftfreq(self.N, self.dt)
Example #10
Source File: transform.py From DeepLearning_Wavelet-LSTM with MIT License | 5 votes |
def cwt_freq(data, wavelet, widths, dt, axis): # compute in frequency # next highest power of two for padding N = data.shape[axis] pN = int(2 ** np.ceil(np.log2(N))) # N.B. padding in fft adds zeros to the *end* of the array, # not equally either end. fft_data = scipy.fft(data, n=pN, axis=axis) # frequencies w_k = np.fft.fftfreq(pN, d=dt) * 2 * np.pi # sample wavelet and normalise norm = (2 * np.pi * widths / dt) ** .5 wavelet_data = norm[:, None] * wavelet(w_k, widths[:, None]) # Convert negative axis. Add one to account for # inclusion of widths axis above. axis = (axis % data.ndim) + 1 # perform the convolution in frequency space slices = [slice(None)] + [None for _ in data.shape] slices[axis] = slice(None) out = scipy.ifft(fft_data[None] * wavelet_data.conj()[slices], n=pN, axis=axis) # remove zero padding slices = [slice(None) for _ in out.shape] slices[axis] = slice(None, N) if data.ndim == 1: return out[slices].squeeze() else: return out[slices]
Example #11
Source File: transform.py From DeepLearning_Wavelet-LSTM with MIT License | 5 votes |
def w_k(self): """Angular frequency as a function of Fourier index. See eq5 of TC. N.B the frequencies returned by numpy are adimensional, on the interval [-1/2, 1/2], so we multiply by 2 * pi. """ return 2 * np.pi * np.fft.fftfreq(self.N, self.dt)
Example #12
Source File: transform.py From DeepLearning_Wavelet-LSTM with MIT License | 5 votes |
def cwt_freq(data, wavelet, widths, dt, axis): # compute in frequency # next highest power of two for padding N = data.shape[axis] pN = int(2 ** np.ceil(np.log2(N))) # N.B. padding in fft adds zeros to the *end* of the array, # not equally either end. fft_data = scipy.fft(data, n=pN, axis=axis) # frequencies w_k = np.fft.fftfreq(pN, d=dt) * 2 * np.pi # sample wavelet and normalise norm = (2 * np.pi * widths / dt) ** .5 wavelet_data = norm[:, None] * wavelet(w_k, widths[:, None]) # Convert negative axis. Add one to account for # inclusion of widths axis above. axis = (axis % data.ndim) + 1 # perform the convolution in frequency space slices = [slice(None)] + [None for _ in data.shape] slices[axis] = slice(None) out = scipy.ifft(fft_data[None] * wavelet_data.conj()[slices], n=pN, axis=axis) # remove zero padding slices = [slice(None) for _ in out.shape] slices[axis] = slice(None, N) if data.ndim == 1: return out[slices].squeeze() else: return out[slices]
Example #13
Source File: signal_processing.py From bird-species-classification with MIT License | 5 votes |
def stft(x, fs, framesz, hop): framesamp = int(framesz*fs) hopsamp = int(hop*fs) w = scipy.hanning(framesamp) X = scipy.array([scipy.fft(w*x[i:i+framesamp]) for i in range(0, len(x)-framesamp, hopsamp)]) return X
Example #14
Source File: fft.py From cupy with MIT License | 5 votes |
def hfft(x, n=None, axis=-1, norm=None, overwrite_x=False, *, plan=None): """Compute the FFT of a signal that has Hermitian symmetry. Args: a (cupy.ndarray): Array to be transform. n (None or int): Length of the transformed axis of the output. For ``n`` output points, ``n//2+1`` input points are necessary. If ``n`` is not given, it is determined from the length of the input along the axis specified by ``axis``. axis (int): Axis over which to compute the FFT. norm (None or ``"ortho"``): Keyword to specify the normalization mode. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (None): This argument is currently not supported. Returns: cupy.ndarray: The transformed array which shape is specified by ``n`` and type will convert to complex if the input is other. If ``n`` is not given, the length of the transformed axis is ``2*(m-1)`` where `m` is the length of the transformed axis of the input. .. seealso:: :func:`scipy.fft.hfft` """ # TODO(leofang): support R2C & C2R plans if plan is not None: raise NotImplementedError('hfft plan is currently not yet supported') return _hfft(x, n, axis, norm)
Example #15
Source File: fft.py From cupy with MIT License | 5 votes |
def rfftn(x, s=None, axes=None, norm=None, overwrite_x=False, *, plan=None): """Compute the N-dimensional FFT for real input. Args: a (cupy.ndarray): Array to be transform. s (None or tuple of ints): Shape to use from the input. If ``s`` is not given, the lengths of the input along the axes specified by ``axes`` are used. axes (tuple of ints): Axes over which to compute the FFT. norm (None or ``"ortho"``): Keyword to specify the normalization mode. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (:class:`cupy.cuda.cufft.PlanNd` or ``None``): a cuFFT plan for transforming ``x`` over ``axes``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, s, axes, value_type='R2C') Note that ``plan`` is defaulted to ``None``, meaning CuPy will use an auto-generated plan behind the scene. Returns: cupy.ndarray: The transformed array which shape is specified by ``s`` and type will convert to complex if the input is other. The length of the last axis transformed will be ``s[-1]//2+1``. .. seealso:: :func:`scipy.fft.rfftn` """ s = _assequence(s) axes = _assequence(axes) func = _default_fft_func(x, s, axes, value_type='R2C') return func(x, s, axes, norm, cufft.CUFFT_FORWARD, 'R2C', overwrite_x=overwrite_x, plan=plan)
Example #16
Source File: fft.py From cupy with MIT License | 5 votes |
def irfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, *, plan=None): """Compute the two-dimensional inverse FFT for real input. Args: a (cupy.ndarray): Array to be transform. s (None or tuple of ints): Shape of the output. If ``s`` is not given, they are determined from the lengths of the input along the axes specified by ``axes``. axes (tuple of ints): Axes over which to compute the FFT. norm (None or ``"ortho"``): Keyword to specify the normalization mode. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (:class:`cupy.cuda.cufft.PlanNd` or ``None``): a cuFFT plan for transforming ``x`` over ``axes``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, s, axes, value_type='C2R') Note that ``plan`` is defaulted to ``None``, meaning CuPy will use an auto-generated plan behind the scene. Returns: cupy.ndarray: The transformed array which shape is specified by ``s`` and type will convert to complex if the input is other. If ``s`` is not given, the length of final transformed axis of output will be `2*(m-1)` where `m` is the length of the final transformed axis of the input. .. seealso:: :func:`scipy.fft.irfft2` """ return irfftn(x, s, axes, norm, overwrite_x, plan=plan)
Example #17
Source File: fft.py From cupy with MIT License | 5 votes |
def rfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, *, plan=None): """Compute the two-dimensional FFT for real input. Args: a (cupy.ndarray): Array to be transform. s (None or tuple of ints): Shape to use from the input. If ``s`` is not given, the lengths of the input along the axes specified by ``axes`` are used. axes (tuple of ints): Axes over which to compute the FFT. norm (None or ``"ortho"``): Keyword to specify the normalization mode. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (:class:`cupy.cuda.cufft.PlanNd` or ``None``): a cuFFT plan for transforming ``x`` over ``axes``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, s, axes, value_type='R2C') Note that ``plan`` is defaulted to ``None``, meaning CuPy will use an auto-generated plan behind the scene. Returns: cupy.ndarray: The transformed array which shape is specified by ``s`` and type will convert to complex if the input is other. The length of the last axis transformed will be ``s[-1]//2+1``. .. seealso:: :func:`scipy.fft.rfft2` """ return rfftn(x, s, axes, norm, overwrite_x, plan=plan)
Example #18
Source File: fft.py From cupy with MIT License | 5 votes |
def irfft(x, n=None, axis=-1, norm=None, overwrite_x=False, *, plan=None): """Compute the one-dimensional inverse FFT for real input. Args: x (cupy.ndarray): Array to be transformed. n (None or int): Length of the transformed axis of the output. If ``n`` is not given, the length of the input along the axis specified by ``axis`` is used. axis (int): Axis over which to compute the FFT. norm (None or ``'ortho'``): Normalization mode. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (:class:`cupy.cuda.cufft.Plan1d` or ``None``): a cuFFT plan for transforming ``x`` over ``axis``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, n, axis, value_type='C2R') Note that ``plan`` is defaulted to ``None``, meaning CuPy will use an auto-generated plan behind the scene. Returns: cupy.ndarray: The transformed array. .. seealso:: :func:`scipy.fft.irfft` """ return _fft(x, (n,), (axis,), norm, cufft.CUFFT_INVERSE, 'C2R', overwrite_x=overwrite_x, plan=plan)
Example #19
Source File: fft.py From cupy with MIT License | 5 votes |
def rfft(x, n=None, axis=-1, norm=None, overwrite_x=False, *, plan=None): """Compute the one-dimensional FFT for real input. The returned array contains the positive frequency components of the corresponding :func:`fft`, up to and including the Nyquist frequency. Args: x (cupy.ndarray): Array to be transformed. n (None or int): Length of the transformed axis of the output. If ``n`` is not given, the length of the input along the axis specified by ``axis`` is used. axis (int): Axis over which to compute the FFT. norm (None or ``'ortho'``): Normalization mode. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (:class:`cupy.cuda.cufft.Plan1d` or ``None``): a cuFFT plan for transforming ``x`` over ``axis``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, n, axis, value_type='R2C') Note that ``plan`` is defaulted to ``None``, meaning CuPy will use an auto-generated plan behind the scene. Returns: cupy.ndarray: The transformed array. .. seealso:: :func:`scipy.fft.rfft` """ return _fft(x, (n,), (axis,), norm, cufft.CUFFT_FORWARD, 'R2C', overwrite_x=overwrite_x, plan=plan)
Example #20
Source File: fft.py From cupy with MIT License | 5 votes |
def fftn(x, s=None, axes=None, norm=None, overwrite_x=False, *, plan=None): """Compute the N-dimensional FFT. Args: x (cupy.ndarray): Array to be transformed. s (None or tuple of ints): Shape of the transformed axes of the output. If ``s`` is not given, the lengths of the input along the axes specified by ``axes`` are used. axes (tuple of ints): Axes over which to compute the FFT. norm (None or ``'ortho'``): Normalization mode. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (:class:`cupy.cuda.cufft.PlanNd` or ``None``): a cuFFT plan for transforming ``x`` over ``axes``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, s, axes) Note that ``plan`` is defaulted to ``None``, meaning CuPy will use an auto-generated plan behind the scene. Returns: cupy.ndarray: The transformed array which shape is specified by ``s`` and type will convert to complex if that of the input is another. .. seealso:: :func:`scipy.fft.fftn` """ s = _assequence(s) axes = _assequence(axes) func = _default_fft_func(x, s, axes) return func(x, s, axes, norm, cufft.CUFFT_FORWARD, overwrite_x=overwrite_x, plan=plan)
Example #21
Source File: fft.py From cupy with MIT License | 5 votes |
def ifft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, *, plan=None): """Compute the two-dimensional inverse FFT. Args: x (cupy.ndarray): Array to be transformed. s (None or tuple of ints): Shape of the transformed axes of the output. If ``s`` is not given, the lengths of the input along the axes specified by ``axes`` are used. axes (tuple of ints): Axes over which to compute the FFT. norm (None or ``'ortho'``): Normalization mode. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (:class:`cupy.cuda.cufft.PlanNd` or ``None``): a cuFFT plan for transforming ``x`` over ``axes``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, s, axes) Note that ``plan`` is defaulted to ``None``, meaning CuPy will use an auto-generated plan behind the scene. Returns: cupy.ndarray: The transformed array which shape is specified by ``s`` and type will convert to complex if that of the input is another. .. seealso:: :func:`scipy.fft.ifft2` """ return ifftn(x, s, axes, norm, overwrite_x, plan=plan)
Example #22
Source File: fft.py From cupy with MIT License | 5 votes |
def fft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, *, plan=None): """Compute the two-dimensional FFT. Args: x (cupy.ndarray): Array to be transformed. s (None or tuple of ints): Shape of the transformed axes of the output. If ``s`` is not given, the lengths of the input along the axes specified by ``axes`` are used. axes (tuple of ints): Axes over which to compute the FFT. norm (None or ``'ortho'``): Normalization mode. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (:class:`cupy.cuda.cufft.PlanNd` or ``None``): a cuFFT plan for transforming ``x`` over ``axes``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, s, axes) Note that ``plan`` is defaulted to ``None``, meaning CuPy will use an auto-generated plan behind the scene. Returns: cupy.ndarray: The transformed array which shape is specified by ``s`` and type will convert to complex if that of the input is another. .. seealso:: :func:`scipy.fft.fft2` """ return fftn(x, s, axes, norm, overwrite_x, plan=plan)
Example #23
Source File: fft.py From cupy with MIT License | 5 votes |
def ifft(x, n=None, axis=-1, norm=None, overwrite_x=False, *, plan=None): """Compute the one-dimensional inverse FFT. Args: x (cupy.ndarray): Array to be transformed. n (None or int): Length of the transformed axis of the output. If ``n`` is not given, the length of the input along the axis specified by ``axis`` is used. axis (int): Axis over which to compute the FFT. norm (None or ``'ortho'``): Normalization mode. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (:class:`cupy.cuda.cufft.Plan1d` or ``None``): a cuFFT plan for transforming ``x`` over ``axis``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, n, axis) Note that ``plan`` is defaulted to ``None``, meaning CuPy will use an auto-generated plan behind the scene. Returns: cupy.ndarray: The transformed array which shape is specified by ``n`` and type will convert to complex if that of the input is another. .. seealso:: :func:`scipy.fft.ifft` """ return _fft(x, (n,), (axis,), norm, cufft.CUFFT_INVERSE, overwrite_x=overwrite_x, plan=plan)
Example #24
Source File: fft.py From cupy with MIT License | 5 votes |
def fft(x, n=None, axis=-1, norm=None, overwrite_x=False, *, plan=None): """Compute the one-dimensional FFT. Args: x (cupy.ndarray): Array to be transformed. n (None or int): Length of the transformed axis of the output. If ``n`` is not given, the length of the input along the axis specified by ``axis`` is used. axis (int): Axis over which to compute the FFT. norm (None or ``'ortho'``): Normalization mode. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (:class:`cupy.cuda.cufft.Plan1d` or ``None``): a cuFFT plan for transforming ``x`` over ``axis``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, n, axis) Note that ``plan`` is defaulted to ``None``, meaning CuPy will use an auto-generated plan behind the scene. Returns: cupy.ndarray: The transformed array which shape is specified by ``n`` and type will convert to complex if that of the input is another. .. seealso:: :func:`scipy.fft.fft` """ return _fft(x, (n,), (axis,), norm, cufft.CUFFT_FORWARD, overwrite_x=overwrite_x, plan=plan)
Example #25
Source File: dataset.py From deep_complex_networks with MIT License | 5 votes |
def aggregate_raw_batch(self, features, output): """Aggregate batch. All post processing goes here. Parameters: ----------- features : 3D float tensor Input tensor output : 2D integer tensor Output classes """ channels = 2 if self.complex_ else 1 features_out = numpy.zeros( [features.shape[0], self.window_size, channels]) if self.fourier: if self.complex_: data = fft(features, axis=1) features_out[:, :, 0] = numpy.real(data[:, :, 0]) features_out[:, :, 1] = numpy.imag(data[:, :, 0]) else: data = numpy.abs(fft(features, axis=1)) features_out = data elif self.stft: _, _, data = stft(features, nperseg=120, noverlap=60, axis=1) length = data.shape[1] n_feats = data.shape[3] if self.complex_: features_out = numpy.zeros( [len(self.train_data), length, n_feats * 2]) features_out[:, :, :n_feats] = numpy.real(data) features_out[:, :, n_feats:] = numpy.imag(data) else: features_out = numpy.abs(data[:, :, 0, :]) else: features_out = features return features_out, output
Example #26
Source File: fft.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 5 votes |
def plot_wav_fft(wav_filename, desc=None): plt.clf() plt.figure(num=None, figsize=(6, 4)) sample_rate, X = scipy.io.wavfile.read(wav_filename) spectrum = np.fft.fft(X) freq = np.fft.fftfreq(len(X), 1.0 / sample_rate) plt.subplot(211) num_samples = 200.0 plt.xlim(0, num_samples / sample_rate) plt.xlabel("time [s]") plt.title(desc or wav_filename) plt.plot(np.arange(num_samples) / sample_rate, X[:num_samples]) plt.grid(True) plt.subplot(212) plt.xlim(0, 5000) plt.xlabel("frequency [Hz]") plt.xticks(np.arange(5) * 1000) if desc: desc = desc.strip() fft_desc = desc[0].lower() + desc[1:] else: fft_desc = wav_filename plt.title("FFT of %s" % fft_desc) plt.plot(freq, abs(spectrum), linewidth=5) plt.grid(True) plt.tight_layout() rel_filename = os.path.split(wav_filename)[1] plt.savefig("%s_wav_fft.png" % os.path.splitext(rel_filename)[0], bbox_inches='tight') plt.show()
Example #27
Source File: fft.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 5 votes |
def read_fft(genre_list, base_dir=GENRE_DIR): X = [] y = [] for label, genre in enumerate(genre_list): genre_dir = os.path.join(base_dir, genre, "*.fft.npy") file_list = glob.glob(genre_dir) assert(file_list), genre_dir for fn in file_list: fft_features = np.load(fn) X.append(fft_features[:2000]) y.append(label) return np.array(X), np.array(y)
Example #28
Source File: fft.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 5 votes |
def write_fft(fft_features, fn): """ Write the FFT features to separate files to speed up processing. """ base_fn, ext = os.path.splitext(fn) data_fn = base_fn + ".fft" np.save(data_fn, fft_features) print("Written "%data_fn)
Example #29
Source File: peakdetect.py From py-findpeaks with MIT License | 4 votes |
def zero_crossings(y_axis, window = 11): """ Algorithm to find zero crossings. Smoothens the curve and finds the zero-crossings by looking for a sign change. keyword arguments: y_axis -- A list containg the signal over which to find zero-crossings window -- the dimension of the smoothing window; should be an odd integer (default: 11) return -- the index for each zero-crossing """ # smooth the curve length = len(y_axis) x_axis = np.asarray(range(length), int) # discard tail of smoothed signal y_axis = _smooth(y_axis, window)[:length] zero_crossings = np.where(np.diff(np.sign(y_axis)))[0] indices = [x_axis[index] for index in zero_crossings] # check if zero-crossings are valid diff = np.diff(indices) if diff.std() / diff.mean() > 0.2: print diff.std() / diff.mean() print np.diff(indices) raise(ValueError, "False zero-crossings found, indicates problem {0} or {1}".format( "with smoothing window", "problem with offset")) # check if any zero crossings were found if len(zero_crossings) < 1: raise(ValueError, "No zero crossings found") return indices # used this to test the fft function's sensitivity to spectral leakage #return indices + np.asarray(30 * np.random.randn(len(indices)), int) ############################Frequency calculation############################# # diff = np.diff(indices) # time_p_period = diff.mean() # # if diff.std() / time_p_period > 0.1: # raise ValueError, # "smoothing window too small, false zero-crossing found" # # #return frequency # return 1.0 / time_p_period ##############################################################################