예제 #1
0
 def test_stft_linearity(self):
     """Test the linearity property of the Fourier transform."""
     x = fmlin(128, 0.0, 0.2)[0]
     y = fmlin(128, 0.3, 0.5)[0]
     h = x + y
     tfr, _, _ = linear.ShortTimeFourierTransform(h).run()
     tfrx, _, _ = linear.ShortTimeFourierTransform(x).run()
     tfry, _, _ = linear.ShortTimeFourierTransform(y).run()
     np.testing.assert_allclose(tfr, tfrx + tfry)
예제 #2
0
 def test_stft_linearity(self):
     """Test the linearity property of the Fourier transform."""
     x = fmlin(128, 0.0, 0.2)[0]
     y = fmlin(128, 0.3, 0.5)[0]
     h = x + y
     tfr, _, _ = linear.ShortTimeFourierTransform(h).run()
     tfrx, _, _ = linear.ShortTimeFourierTransform(x).run()
     tfry, _, _ = linear.ShortTimeFourierTransform(y).run()
     np.testing.assert_allclose(tfr, tfrx + tfry)
예제 #3
0
 def test_ideal_tfr(self):
     """Test if the ideal TFR can be found using the instantaneous frequency
     laws."""
     _, iflaw1 = fmlin(128, 0.0, 0.2)
     _, iflaw2 = fmlin(128, 0.3, 0.5)
     iflaws = np.c_[iflaw1, iflaw2].T
     tfr, _, _ = pproc.ideal_tfr(iflaws)
     tfr[tfr == 1] = 255
     tfr = tfr.astype(np.uint8)
     hspace, angles, dists = hough_line(tfr)
     for x in hough_line_peaks(hspace, angles, dists):
         self.assertEqual(len(x), 2)
예제 #4
0
 def test_ideal_tfr(self):
     """Test if the ideal TFR can be found using the instantaneous frequency
     laws."""
     _, iflaw1 = fmlin(128, 0.0, 0.2)
     _, iflaw2 = fmlin(128, 0.3, 0.5)
     iflaws = np.c_[iflaw1, iflaw2].T
     tfr, _, _ = pproc.ideal_tfr(iflaws)
     tfr[tfr == 1] = 255
     tfr = tfr.astype(np.uint8)
     hspace, angles, dists = hough_line(tfr)
     for x in hough_line_peaks(hspace, angles, dists):
         self.assertEqual(len(x), 2)
예제 #5
0
 def test_spectrogram_energy_conservation(self):
     """Test the energy conservation property of the spectrogram."""
     signal, _ = fmlin(128, 0.1, 0.4)
     window = kaiser(17, 3 * np.pi)
     tfr, ts, freqs = cohen.Spectrogram(signal, n_fbins=64, fwindow=window).run()
     e_sig = (np.abs(signal) ** 2).sum()
     self.assertAlmostEqual(tfr.sum().sum() / 64, e_sig)
예제 #6
0
 def test_stft_conjugation(self):
     x = fmlin(128, 0, 0.2)[0]
     h = np.conjugate(x)
     lhs, _, _ = linear.ShortTimeFourierTransform(h).run()
     rhs, _, _ = linear.ShortTimeFourierTransform(x[::-1]).run()
     rhs = np.conjugate(rhs)
     np.testing.assert_allclose(lhs, rhs)
예제 #7
0
 def test_stft_conjugation(self):
     x = fmlin(128, 0, 0.2)[0]
     h = np.conjugate(x)
     lhs, _, _ = linear.ShortTimeFourierTransform(h).run()
     rhs, _, _ = linear.ShortTimeFourierTransform(x[::-1]).run()
     rhs = np.conjugate(rhs)
     np.testing.assert_allclose(lhs, rhs)
예제 #8
0
 def test_spectrogram_energy_conservation(self):
     """Test the energy conservation property of the spectrogram."""
     signal, _ = fmlin(128, 0.1, 0.4)
     window = kaiser(17, 3 * np.pi)
     tfr, ts, freqs = cohen.Spectrogram(signal, n_fbins=64, fwindow=window).run()
     e_sig = (np.abs(signal) ** 2).sum()
     self.assertAlmostEqual(tfr.sum().sum() / 64, e_sig)
예제 #9
0
파일: test_cohen.py 프로젝트: dafx/pytftb
 def test_spectrogram_linearity(self):
     signal, _ = fmlin(128, 0.1, 0.4)
     window = kaiser(17, 3 * np.pi)
     tfr1, _, _ = cohen.spectrogram(signal, n_fbins=64, window=window)
     tfr2, _, _ = cohen.spectrogram(signal * 2, n_fbins=64, window=window)
     x = np.sum(np.sum(tfr2))
     y = np.sum(np.sum(tfr1))
     self.assertEqual(x / y, 4)
예제 #10
0
 def test_spectrogram_linearity(self):
     signal, _ = fmlin(128, 0.1, 0.4)
     window = kaiser(17, 3 * np.pi)
     tfr1, _, _ = cohen.spectrogram(signal, n_fbins=64, window=window)
     tfr2, _, _ = cohen.spectrogram(signal * 2, n_fbins=64, window=window)
     x = np.sum(np.sum(tfr2))
     y = np.sum(np.sum(tfr1))
     self.assertEqual(x / y, 4)
예제 #11
0
 def test_stft_translation(self):
     """Test the time-shift property of the Fourier transform."""
     x = fmlin(128, 0.0, 0.2)[0]
     tfrx, _, freqs = linear.ShortTimeFourierTransform(x).run()
     x_shifted = np.roll(x, 64)
     tfrxs, _, _ = linear.ShortTimeFourierTransform(x_shifted).run()
     f_mul = np.exp(-1j * 2 * np.pi * 64 * freqs)
     np.testing.assert_allclose(tfrxs, f_mul * tfrx)
예제 #12
0
 def test_stft_translation(self):
     """Test the time-shift property of the Fourier transform."""
     x = fmlin(128, 0.0, 0.2)[0]
     tfrx, _, freqs = linear.ShortTimeFourierTransform(x).run()
     x_shifted = np.roll(x, 64)
     tfrxs, _, _ = linear.ShortTimeFourierTransform(x_shifted).run()
     f_mul = np.exp(-1j * 2 * np.pi * 64 * freqs)
     np.testing.assert_allclose(tfrxs, f_mul * tfrx)
예제 #13
0
 def test_sigmerge(self):
     """Test merging of signals with a given SNR."""
     signal = fmlin(128)[0]
     noise = np.random.randn(128,)
     gamma = 0.1
     x = utils.sigmerge(signal, noise, gamma)
     h_est = np.linalg.norm(signal) / np.linalg.norm(noise) * 10 ** (-gamma / 20)
     x_hat = signal + h_est * noise
     np.testing.assert_allclose(x, x_hat)
예제 #14
0
 def test_stft_modulation(self):
     """Test the modulation / frequency shifting property of STFT."""
     x = fmlin(128, 0.0, 0.2)[0]
     tfrx, _, _ = linear.ShortTimeFourierTransform(x).run()
     f_0 = 0.3
     h = np.exp(1j * 2 * np.pi * f_0 * np.arange(128)) * x
     tfrh, _, _ = linear.ShortTimeFourierTransform(h).run()
     tfrx_shifted = np.roll(tfrx, int(np.ceil(128 * 0.3)), axis=0)
     self.assert_tfr_equal(tfrx_shifted, tfrh, tol=0.95)
예제 #15
0
 def test_stft_modulation(self):
     """Test the modulation / frequency shifting property of STFT."""
     x = fmlin(128, 0.0, 0.2)[0]
     tfrx, _, _ = linear.ShortTimeFourierTransform(x).run()
     f_0 = 0.3
     h = np.exp(1j * 2 * np.pi * f_0 * np.arange(128)) * x
     tfrh, _, _ = linear.ShortTimeFourierTransform(h).run()
     tfrx_shifted = np.roll(tfrx, int(np.ceil(128 * 0.3)), axis=0)
     self.assert_tfr_equal(tfrx_shifted, tfrh, tol=0.95)
예제 #16
0
 def test_sigmerge(self):
     """Test merging of signals with a given SNR."""
     signal = fmlin(128)[0]
     noise = np.random.randn(128,)
     noisy_signal = utils.sigmerge(signal, noise)
     gamma_estimate = np.sqrt(signal.var() / noise.var())
     np.testing.assert_allclose(noisy_signal,
                                signal + gamma_estimate * noise, rtol=1e-2,
                                atol=1e-2)
예제 #17
0
 def test_sigmerge(self):
     """Test merging of signals with a given SNR."""
     signal = fmlin(128)[0]
     noise = np.random.randn(128, )
     gamma = 0.1
     x = utils.sigmerge(signal, noise, gamma)
     h_est = np.linalg.norm(signal) / np.linalg.norm(noise) * 10**(-gamma /
                                                                   20)
     x_hat = signal + h_est * noise
     np.testing.assert_allclose(x, x_hat)
예제 #18
0
 def test_spectrogram_linearity(self):
     """Test the linearity property of the spectrogram."""
     signal, _ = fmlin(128, 0.1, 0.4)
     window = kaiser(17, 3 * np.pi)
     tfr1, _, _ = cohen.Spectrogram(signal, n_fbins=64,
                                    fwindow=window).run()
     tfr2, _, _ = cohen.Spectrogram(signal * 2, n_fbins=64,
                                    fwindow=window).run()
     x = np.sum(np.sum(tfr2))
     y = np.sum(np.sum(tfr1))
     self.assertEqual(x / y, 4)
예제 #19
0
 def test_spectrogram_linearity(self):
     """Test the linearity property of the spectrogram."""
     signal, _ = fmlin(128, 0.1, 0.4)
     window = kaiser(17, 3 * np.pi)
     tfr1, _, _ = cohen.Spectrogram(signal, n_fbins=64,
                                    fwindow=window).run()
     tfr2, _, _ = cohen.Spectrogram(signal * 2, n_fbins=64,
                                    fwindow=window).run()
     x = np.sum(np.sum(tfr2))
     y = np.sum(np.sum(tfr1))
     self.assertEqual(x / y, 4)
예제 #20
0
 def test_spectrogram_time_invariance(self):
     """Test the time invariance property of the spectrogram."""
     signal, _ = fmlin(128, 0.1, 0.4)
     window = kaiser(17, 3 * np.pi)
     tfr, ts, freqs = cohen.Spectrogram(signal, n_fbins=64, fwindow=window).run()
     shift = 64
     timeshifted_signal = np.roll(signal, shift)
     timeshifted_tfr, _, _ = cohen.Spectrogram(timeshifted_signal, n_fbins=64,
                                         fwindow=window).run()
     rolled_tfr = np.roll(tfr, shift, axis=1)
     # the time invariance property holds mostly qualitatively. The shifted
     # TFR is not numerically indentical to the rolled TFR, having
     # differences at the edges; so clip with two TFRs where there are
     # discontinuities in the TFR.
     edge = 10
     xx = np.c_[timeshifted_tfr[:, edge:(shift - edge)],
                timeshifted_tfr[:, (shift + edge):-edge]]
     yy = np.c_[rolled_tfr[:, edge:(shift - edge)],
                rolled_tfr[:, (shift + edge):-edge]]
     np.testing.assert_allclose(xx, yy)
예제 #21
0
 def test_spectrogram_time_invariance(self):
     """Test the time invariance property of the spectrogram."""
     signal, _ = fmlin(128, 0.1, 0.4)
     window = kaiser(17, 3 * np.pi)
     tfr, ts, freqs = cohen.Spectrogram(signal, n_fbins=64, fwindow=window).run()
     shift = 64
     timeshifted_signal = np.roll(signal, shift)
     timeshifted_tfr, _, _ = cohen.Spectrogram(timeshifted_signal, n_fbins=64,
                                               fwindow=window).run()
     rolled_tfr = np.roll(tfr, shift, axis=1)
     # the time invariance property holds mostly qualitatively. The shifted
     # TFR is not numerically indentical to the rolled TFR, having
     # differences at the edges; so clip with two TFRs where there are
     # discontinuities in the TFR.
     edge = 10
     xx = np.c_[timeshifted_tfr[:, edge:(shift - edge)],
                timeshifted_tfr[:, (shift + edge):-edge]]
     yy = np.c_[rolled_tfr[:, edge:(shift - edge)],
                rolled_tfr[:, (shift + edge):-edge]]
     np.testing.assert_allclose(xx, yy)
예제 #22
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2015 jaidev <jaidev@newton>
#
# Distributed under terms of the MIT license.
"""
Example from section 3.1.4 of the tutorial.
"""

import numpy as np
from tftb.processing.linear import ShortTimeFourierTransform
from tftb.generators import fmlin, amgauss
from matplotlib.pyplot import cm

x = np.real(amgauss(128) * fmlin(128)[0])
window = np.array([1])
stft = ShortTimeFourierTransform(x, n_fbins=128, fwindow=window)
tfr, _, _ = stft.run()

stft.plot(show_tf=True, cmap=cm.gray)
예제 #23
0
            points = np.arange(-min([lg, signal.shape[0] - ti - tau]),
                               min([lg, ti - 1 - tau]) + 1)
            g2 = twindow[lg + points]
            g2 = g2 / np.sum(g2)
            R = np.sum(g2 * signal[ti + tau - points - 1] * np.conj(signal[ti - tau - points - 1]))
            tfr[1 + tau, icol] = fwindow[lh + tau + 1] * R
            R = np.sum(g2 * signal[ti - tau - points - 1] * np.conj(signal[ti + tau - points - 1]))
            tfr[freq_bins - tau - 1, icol] = fwindow[lh - tau + 1] * R
        tau = np.round(freq_bins / 2.0)
        if (ti <= signal.shape[0] - tau) and (ti >= tau + 1) and (tau <= lh):
            points = np.arange(-min([lg, signal.shape[0] - ti - tau]),
                               min([lg, ti - 1 - tau]) + 1)
            g2 = twindow[lg + 1 + points]
            g2 = g2 / np.sum(g2)
            _x = np.sum(g2 * signal[ti + tau - points] * np.conj(signal[ti - tau - points]))
            _x *= fwindow[lh + tau + 1]
            _y = np.sum(g2 * signal[ti - tau - points] * np.conj(signal[ti + tau - points]))
            _y *= fwindow[lh - tau + 1]
            tfr[tau, icol] = (_x + _y) * 0.5
    tfr = np.fft.fft(tfr, axis=0)
    return np.real(tfr)


if __name__ == '__main__':
    from tftb.generators import fmlin
    sig = fmlin(128, 0.1, 0.4)[0]
    spec = PseudoWignerVilleDistribution(sig)
    tfr, _, _ = spec.run()
    from scipy.io import savemat
    savemat("/tmp/foo.mat", dict(tfr2=tfr))
Instantaneous frequency and group delay are very closely related. The former is
the frequency of a signal at a given instant, and the latter is the time delay
of frequency components. As this example shows, they coincide with each other
for a given signal when the time bandwidth product of the signal is
sufficiently high.

"""

import numpy as np
import matplotlib.pyplot as plt
from tftb.generators import amgauss, fmlin
from tftb.processing import loctime, locfreq, inst_freq, group_delay

time_instants = np.arange(2, 256)
sig1 = amgauss(256, 128, 90) * fmlin(256)[0]
tm, T1 = loctime(sig1)
fm, B1 = locfreq(sig1)
ifr1 = inst_freq(sig1, time_instants)[0]
f1 = np.linspace(0, 0.5 - 1.0 / 256, 256)
gd1 = group_delay(sig1, f1)

plt.subplot(211)
plt.plot(time_instants, ifr1, '*', label='inst_freq')
plt.plot(gd1, f1, '-', label='group delay')
plt.xlim(0, 256)
plt.grid(True)
plt.legend()
plt.title("Time-Bandwidth product: {0}".format(T1 * B1))
plt.xlabel('Time')
plt.ylabel('Normalized Frequency')
"""
Comparison of the Wigner Ville distribution with its smoothed and reassinged
counterparts.

Figure 4.35 from the tutorial.
"""

import numpy as np
import matplotlib.pyplot as plt
from tftb.generators import fmsin, fmlin, fmconst
from tftb.processing import (ideal_tfr, WignerVilleDistribution,
                             smoothed_pseudo_wigner_ville,
                             reassigned_smoothed_pseudo_wigner_ville)

sig1, if1 = fmsin(60, 0.16, 0.35, 50, 1, 0.35, 1)
sig2, if2 = fmlin(60, 0.3, 0.1)
sig3, if3 = fmconst(60, 0.4)

sig = np.hstack((sig1, np.zeros((8, )), sig2 + sig3))
iflaw = np.zeros((2, 128))
iflaw[0, :] = np.hstack((if1, np.nan * np.ones((8, )), if2))
iflaw[1, :] = np.hstack((np.nan * np.ones((68, )), if3))

tfr, t, f = ideal_tfr(iflaw)

plt.figure(figsize=(10, 8))
plt.subplot(221)
plt.contour(t, f, tfr, 1)
plt.gca().set_xticklabels([])
plt.grid(True)
plt.title("Ideal instantaneous frequencies")
예제 #26
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2015 jaidev <jaidev@newton>
#
# Distributed under terms of the MIT license.
"""
Example in section 2.4 of the tutorial.
"""

from tftb.generators import fmlin
from tftb.processing import group_delay
import numpy as np
import matplotlib.pyplot as plt

signal, _ = fmlin(256)
fnorm = np.linspace(0, .5, 10)
gd = group_delay(signal, fnorm)
plt.plot(gd, fnorm)
plt.grid(True)
plt.xlim(0, 256)
plt.xlabel('Time')
plt.ylabel('Normalized Frequency')
plt.title('Group Delay Estimation')
plt.show()
예제 #27
0
from tftb.generators import fmlin, amgauss
import numpy as np
import matplotlib.pyplot as plt

y_nonstat, _ = fmlin(2048)  # Already analytic, no need of Hilbert transorm
y_nonstat *= amgauss(2048)
plt.plot(np.real(y_nonstat), np.imag(y_nonstat))
plt.xlabel("Real part")
plt.ylabel("Imaginary part")
plt.show()
예제 #28
0
 def test_spectrogram_reality(self):
     """Test the reality property of the spectrogram."""
     signal, _ = fmlin(128, 0.1, 0.4)
     window = kaiser(17, 3 * np.pi)
     tfr, _, _ = cohen.Spectrogram(signal, n_fbins=64, fwindow=window).run()
     self.assertTrue(np.all(np.isreal(tfr)))
예제 #29
0
 def test_spectrogram_non_negativity(self):
     """Test that the spectrogram is non negative."""
     signal, _ = fmlin(128, 0.1, 0.4)
     window = kaiser(17, 3 * np.pi)
     tfr, _, _ = cohen.Spectrogram(signal, n_fbins=64, fwindow=window).run()
     self.assertTrue(np.all(tfr >= 0))
예제 #30
0
 def test_spectrogram_reality(self):
     """Test the reality property of the spectrogram."""
     signal, _ = fmlin(128, 0.1, 0.4)
     window = kaiser(17, 3 * np.pi)
     tfr, _, _ = cohen.Spectrogram(signal, n_fbins=64, fwindow=window).run()
     self.assertTrue(np.all(np.isreal(tfr)))
예제 #31
0
파일: group_delay.py 프로젝트: dafx/pytftb
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2015 jaidev <jaidev@newton>
#
# Distributed under terms of the MIT license.

"""

"""

import numpy as np
import matplotlib.pyplot as plt
from tftb.generators import amgauss, fmlin
from tftb.processing import group_delay

x = amgauss(128, 64.0, 30) * fmlin(128, 0.1, 0.4)[0]
fnorm = np.arange(0.1, 0.38, step=0.04)
gd = group_delay(x, fnorm)
plt.plot(gd, fnorm)
plt.xlim(0, 128)
plt.grid()
plt.title('Group delay estimation of linear chirp')
plt.xlabel('Group delay')
plt.ylabel('Normalized frequency')
plt.show()
예제 #32
0
 def test_spectrogram_reality(self):
     signal, _ = fmlin(128, 0.1, 0.4)
     window = kaiser(17, 3 * np.pi)
     tfr, _, _ = cohen.spectrogram(signal, n_fbins=64, window=window)
     self.assertTrue(np.all(np.isreal(tfr)))
예제 #33
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2015 jaidev <jaidev@newton>
#
# Distributed under terms of the MIT license.
"""
Examples from section 3.4.1 of the tutorial.
"""

from tftb.generators import fmlin
from tftb.processing.cohen import Spectrogram
import numpy as np
import matplotlib.pyplot as plt

sig = fmlin(128, 0, 0.3)[0] + fmlin(128, 0.2, 0.5)[0]
window = np.exp(np.log(0.005) * np.linspace(-1, 1, 63)**2)
spec = Spectrogram(sig, fwindow=window, n_fbins=128)
spec.run()
spec.plot(show_tf=True, cmap=plt.cm.gray)
#
# Copyright © 2015 jaidev <jaidev@newton>
#
# Distributed under terms of the MIT license.

"""
==================================================
Linear Frequency and Gaussian Amplitude Modulation
==================================================

Generate a mono-component nonstationary signal with linear frequency
modulation and Gaussian amplitude modulation.

"""

from tftb.generators import fmlin, amgauss
from numpy import real
import matplotlib.pyplot as plt


fm, _ = fmlin(256)
am = amgauss(256)
signal = fm * am
plt.plot(real(signal))
plt.xlabel("Time")
plt.ylabel("Real part")
plt.title("Linear Frequency, Gaussian Amplitude")
plt.xlim(0, 256)
plt.grid()
plt.show()
예제 #35
0
#
# Copyright © 2015 jaidev <jaidev@newton>
#
# Distributed under terms of the MIT license.

"""
=================================
Group Delay Estimation of a Chirp
=================================

Constuct a chirp and estimates its `group delay
<https://en.wikipedia.org/wiki/Group_delay_and_phase_delay>`_.

"""

from tftb.generators import fmlin
from tftb.processing import group_delay
import numpy as np
import matplotlib.pyplot as plt

signal, _ = fmlin(256)
fnorm = np.linspace(0, .5, 10)
gd = group_delay(signal, fnorm)
plt.plot(gd, fnorm)
plt.grid(True)
plt.xlim(0, 256)
plt.xlabel('Time')
plt.ylabel('Normalized Frequency')
plt.title('Group Delay Estimation')
plt.show()
예제 #36
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2015 jaidev <jaidev@newton>
#
# Distributed under terms of the MIT license.
"""

"""

import numpy as np
import matplotlib.pyplot as plt
from tftb.generators import amgauss, fmlin
from tftb.processing import group_delay

x = amgauss(128, 64.0, 30) * fmlin(128, 0.1, 0.4)[0]
fnorm = np.arange(0.1, 0.38, step=0.04)
gd = group_delay(x, fnorm)
plt.plot(gd, fnorm)
plt.xlim(0, 128)
plt.grid()
plt.title('Group delay estimation of linear chirp')
plt.xlabel('Group delay')
plt.ylabel('Normalized frequency')
plt.show()
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2015 jaidev <jaidev@newton>
#
# Distributed under terms of the MIT license.

"""
Examples from section 3.4.1 of the tutorial.
"""

from tftb.generators import fmlin
from tftb.processing.cohen import Spectrogram
import numpy as np
import matplotlib.pyplot as plt

sig = fmlin(128, 0, 0.3)[0] + fmlin(128, 0.2, 0.5)[0]
window = np.exp(np.log(0.005) * np.linspace(-1, 1, 63) ** 2)
spec = Spectrogram(sig, fwindow=window, n_fbins=128)
spec.run()
spec.plot(show_tf=True, cmap=plt.cm.gray)
예제 #38
0
#
# Copyright © 2015 jaidev <jaidev@newton>
#
# Distributed under terms of the MIT license.

"""
Example from section 1.3.1 of the tutorial.
"""

from tftb.generators import fmlin, sigmerge, noisecg
import matplotlib.pyplot as plt
import numpy as np

# Generate a chirp signal

n_points = 128
fmin, fmax = 0.0, 0.5

signal, _ = fmlin(n_points, fmin, fmax)

# Noisy chirp

noisy_signal = sigmerge(signal, noisecg(128), 0)
plt.plot(np.real(noisy_signal))
plt.xlim(0, 128)
plt.title('Noisy chirp')
plt.ylabel('Real Part')
plt.xlabel('Time')
plt.grid()
plt.show()
예제 #39
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2015 jaidev <jaidev@newton>
#
# Distributed under terms of the MIT license.
"""
Examples from section 4.1.3 of the tutorial.
"""

from tftb.generators import fmlin, amgauss
from tftb.processing.ambiguity import narrow_band
import numpy as np
import matplotlib.pyplot as plt

n_points = 64
sig1 = fmlin(n_points, 0.2, 0.5)[0] * amgauss(n_points)
sig2 = fmlin(n_points, 0.3, 0)[0] * amgauss(n_points)
sig = np.hstack((sig1, sig2))

tfr, x, y = narrow_band(sig)
plt.contour(2 * x, y, np.abs(tfr)**2, 16)
plt.title('Narrow Band ambiguity function')
plt.xlabel('Delay')
plt.ylabel('Doppler')
plt.grid(True)
plt.show()
예제 #40
0
# Distributed under terms of the MIT license.
"""
===============================
Gabor Representation of a Chirp
===============================

Figure 3.11 from the tutorial.
"""

from tftb.generators import fmlin
from tftb.processing.linear import gabor
import matplotlib.pyplot as plt
import numpy as np

N1 = 256
Ng = 33
Q = 1
sig = fmlin(N1)[0]
window = np.exp(np.log(0.005) * np.linspace(-1, 1, Ng)**2)
window = window / np.linalg.norm(window)
tfr, dgr, h = gabor(sig, 16, Q, window)

plt.imshow(np.flipud(tfr)[8:, :],
           aspect='auto',
           extent=[0, 16, 0, 0.5],
           interpolation='none')
plt.xlabel('Time')
plt.ylabel('Normalized frequency')
plt.title('Squared modulus of the Gabor coefficients')
plt.show()
예제 #41
0
    * time center
    * time duration
    * frequency center
    * frequency spreading

Example 2.1 from the tutorial.
"""

from tftb.generators import fmlin, amgauss
from tftb.processing import loctime, locfreq
import numpy as np
import matplotlib.pyplot as plt

# generate signal
signal = fmlin(256)[0] * amgauss(256)
plt.subplot(211), plt.plot(np.real(signal))
plt.xlim(0, 256)
plt.xlabel('Time')
plt.ylabel('Real part')
plt.title('Signal')
plt.grid()
fsig = np.fft.fftshift(np.abs(np.fft.fft(signal))**2)
plt.subplot(212), plt.plot(np.linspace(0, 0.5, 256), fsig)
plt.xlabel('Normalized frequency')
plt.ylabel('Squared modulus')
plt.title('Spectrum')
plt.grid()
plt.subplots_adjust(hspace=0.5)
plt.show()
예제 #42
0
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2015 jaidev <jaidev@newton>
#
# Distributed under terms of the MIT license.

"""
Example showing use of Hough transform on a Wigner-Ville distribution.
"""

import numpy as np
from tftb.generators import noisecg, sigmerge, fmlin
from tftb.processing.cohen import WignerVilleDistribution
from tftb.processing.postprocessing import hough_transform
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

N = 64
sig = sigmerge(fmlin(N, 0, 0.3)[0], noisecg(N), 1)
tfr, _, _ = WignerVilleDistribution(sig).run()

ht, rho, theta = hough_transform(tfr, N, N)
theta, rho = np.meshgrid(theta, rho)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_wireframe(theta, rho, ht)
ax.set_xlabel('Theta')
ax.set_ylabel('Rho')
plt.show()
예제 #43
0
# Distributed under terms of the MIT license.

"""
Example from section 2.7 of the tutorial.
Short time Fourier transform of a multi-component nonstationary signal.
"""

from tftb.generators import fmlin
from tftb.processing.linear import ShortTimeFourierTransform
import matplotlib.pyplot as plt
from scipy.signal import hamming
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable

N = 128
x1, _ = fmlin(N, 0, 0.2)
x2, _ = fmlin(N, 0.3, 0.5)
x = x1 + x2

n_fbins = 128
window = hamming(33)
tfr, _, _ = ShortTimeFourierTransform(x, timestamps=None, n_fbins=n_fbins,
                                      fwindow=window).run()
tfr = tfr[:64, :]
threshold = np.amax(np.abs(tfr)) * 0.05
tfr[np.abs(tfr) <= threshold] = 0.0 + 1j * 0.0
tfr = np.abs(tfr) ** 2
t = np.arange(tfr.shape[1])
f = np.linspace(0, 0.5, tfr.shape[0])

T, F = np.meshgrid(t, f)
예제 #44
0
파일: fmlin.py 프로젝트: dafx/pytftb
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2015 jaidev <jaidev@newton>
#
# Distributed under terms of the MIT license.

"""

"""

from tftb.generators import amgauss, fmlin
import numpy as np
import matplotlib.pyplot as plt

z = amgauss(128, 50.0, 30.0) * fmlin(128, 0.05, 0.3, 50)[0]
plt.plot(np.real(z))
plt.xlim(0, 128)
plt.grid()
plt.title('Linear Frequency Modulation')
plt.show()
======================================================

This example uses Friedman's method to calculate the instantaneous frequency
density of a hybrid signal. The method consists of computing the histograms of
frequency displacements of the spectrogram of the signal.

"""

import numpy as np
import matplotlib.pyplot as plt
from tftb.generators import fmlin, fmsin, fmconst
from tftb.processing.reassigned import pseudo_wigner_ville
from tftb.processing.postprocessing import friedman_density

sig1, if1 = fmsin(60, 0.16, 0.35, 50, 1, 0.35, 1)
sig2, if2 = fmlin(60, 0.3, 0.1)
sig3, if3 = fmconst(60, 0.4)
sig = np.hstack((sig1, np.zeros((8,)), sig2 + sig3))

t = np.arange(1, 128, step=2)
tfr, rtfr, hat = pseudo_wigner_ville(sig, timestamps=t)
tifd = friedman_density(tfr, hat, t)
f = np.linspace(0, 0.5, tifd.shape[0])

plt.contour(t, f, tifd, 4)
plt.grid(True)
plt.title("Friedman's instantaenous frequency density")
plt.xlabel('Time')
plt.ylabel('Frequency')
plt.show()
예제 #46
0
# vim:fenc=utf-8
#
# Copyright © 2015 jaidev <jaidev@newton>
#
# Distributed under terms of the MIT license.
"""
Example in section 2.4 of the tutorial.
"""

import numpy as np
import matplotlib.pyplot as plt
from tftb.generators import amgauss, fmlin
from tftb.processing import loctime, locfreq, inst_freq, group_delay

time_instants = np.arange(2, 256)
sig1 = amgauss(256, 128, 90) * fmlin(256)[0]
tm, T1 = loctime(sig1)
fm, B1 = locfreq(sig1)
ifr1 = inst_freq(sig1, time_instants)[0]
f1 = np.linspace(0, 0.5 - 1.0 / 256, 256)
gd1 = group_delay(sig1, f1)

plt.subplot(211)
plt.plot(time_instants, ifr1, '*', label='inst_freq')
plt.plot(gd1, f1, '-', label='group delay')
plt.xlim(0, 256)
plt.grid(True)
plt.legend()
plt.title("Time-Bandwidth product: {0}".format(T1 * B1))
plt.xlabel('Time')
plt.ylabel('Normalized Frequency')
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2015 jaidev <jaidev@newton>
#
# Distributed under terms of the MIT license.

"""
================================================
Time-frequency Resolution: Long Analysis Window
================================================

This example shows the effect of an analysis window which is long in time on
the time-frequency resolution. Specifically, longer windows have good frequency
resolutions but poor time resolutions.

"""

import numpy as np
from tftb.processing.linear import ShortTimeFourierTransform
from tftb.generators import fmlin, amgauss
import matplotlib.pyplot as plt

x = np.real(amgauss(128) * fmlin(128)[0])
window = np.ones((128,))
stft = ShortTimeFourierTransform(x, n_fbins=128, fwindow=window)
stft.run()
stft.plot(show_tf=True, cmap=plt.cm.gray)
예제 #48
0
from pathlib import Path
from PIL import Image

# Potrebni za del z zvokom
import sounddevice as sd
from scipy.io import wavfile
import time

# ukazi.m:1
# --------------------------------------------------------------------------------------
# Časovno-frekvenčna ločljivost in časovno-frekvenčne porazdelitve
#######################################################################

# ukazi.m:6 -- Note: Preverjeno z Matlab
Fs = 1024
sig = fmlin(1*Fs)[0]    # Ker v pythonu fmlin vrne analitičen signal, ni potrebno napraviti Hilbertove transformacije.

# Narišemo realni del v časovni domeni (signal je kompleksen, a le zaradi umetno zagotovljene analitičnosti.
plt.figure()
plt.plot(np.real(sig), LineWidth=0.4)
plt.xlabel('t')
plt.ylabel('amplituda')

# Analitični signali nimajo simetrije preko Nyquistove frekvence.
plt.figure()
plt.plot(abs(np.fft.fft(sig)), LineWidth=0.4)
plt.xlabel('f')
plt.ylabel('amplituda')

# ukazi.m:16
#######################################################################
예제 #49
0
# Distributed under terms of the MIT license.
"""
==========================================
Wigner-Ville Distribution of a Noisy Chirp
==========================================

Generate a noisy chirp and visualize its Wigner-Ville spectrum.

Figure 1.6 from the tutorial.
"""

from tftb.generators import fmlin, sigmerge, noisecg
from tftb.processing.cohen import WignerVilleDistribution

# Generate a chirp signal

n_points = 128
fmin, fmax = 0.0, 0.5

signal, _ = fmlin(n_points, fmin, fmax)

# Noisy chirp

noisy_signal = sigmerge(signal, noisecg(128), 0)

# Wigner-Ville spectrum of noisy chirp.

wvd = WignerVilleDistribution(noisy_signal)
wvd.run()
wvd.plot(kind='contour')
#
# Copyright © 2015 jaidev <jaidev@newton>
#
# Distributed under terms of the MIT license.

"""
=============================
Biorthonormal Window Function
=============================

"""

from tftb.generators import fmlin
from tftb.processing.linear import gabor
import matplotlib.pyplot as plt
import numpy as np

N1 = 256
Ng = 33
Q = 1
sig = fmlin(N1)[0]
window = np.exp(np.log(0.005) * np.linspace(-1, 1, Ng) ** 2)
window = window / np.linalg.norm(window)
tfr, dgr, h = gabor(sig, 16, Q, window)
plt.plot(h)
plt.ylim(top=0.5)
plt.xlim(right=255)
plt.title('Biorthonormal Window')
plt.grid()
plt.show()
예제 #51
0
 def test_spectrogram_non_negativity(self):
     """Test that the spectrogram is non negative."""
     signal, _ = fmlin(128, 0.1, 0.4)
     window = kaiser(17, 3 * np.pi)
     tfr, _, _ = cohen.Spectrogram(signal, n_fbins=64, fwindow=window).run()
     self.assertTrue(np.all(tfr >= 0))
예제 #52
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2015 jaidev <jaidev@newton>
#
# Distributed under terms of the MIT license.

"""
Wigner Ville distribution of two simultaneous chirps.
"""

from tftb.generators import fmlin, sigmerge
from tftb.processing.cohen import WignerVilleDistribution

N = 64
sig = sigmerge(fmlin(N, 0, 0.4)[0], fmlin(N, 0.3, 0.5)[0], 1)
tfr = WignerVilleDistribution(sig)
tfr.run()
tfr.plot(kind='contour', sqmod=True, show_tf=True)
예제 #53
0
# vim:fenc=utf-8
#
# Copyright © 2015 jaidev <jaidev@newton>
#
# Distributed under terms of the MIT license.
"""
Example from section 2.6 of the tutorial.
Embedding a mono-component nonstationary signal with linear frequency
modulation and Gaussian amplitude modulation into Gaussian colored noise.
"""

from tftb.generators import fmlin, amgauss, noisecg, sigmerge
from numpy import real
import matplotlib.pyplot as plt

fm, _ = fmlin(256)
am = amgauss(256)
signal = fm * am

noise = noisecg(256, .8)
sign = sigmerge(signal, noise, -10)

plt.plot(real(sign))
plt.xlabel('Time')
plt.ylabel('Real part')
plt.title(
    'Gaussian transient signal embedded in -10 dB colored Gaussian noise')
plt.xlim(0, 256)
plt.grid()
plt.show()
#
# Copyright © 2015 jaidev <jaidev@newton>
#
# Distributed under terms of the MIT license.

"""
Example in section 2.2.1 of the tutorial.
"""

from tftb.generators import fmlin, amgauss
from tftb.processing import loctime, locfreq
import numpy as np
import matplotlib.pyplot as plt

# generate signal
signal = fmlin(256)[0] * amgauss(256)
plt.subplot(211), plt.plot(np.real(signal))
plt.xlim(0, 256)
plt.xlabel('Time')
plt.ylabel('Real part')
plt.title('Signal')
plt.grid()
fsig = np.fft.fftshift(np.abs(np.fft.fft(signal)) ** 2)
plt.subplot(212), plt.plot(np.linspace(0, 0.5, 256), fsig)
plt.xlabel('Normalized frequency')
plt.ylabel('Squared modulus')
plt.title('Spectrum')
plt.grid()
plt.subplots_adjust(hspace=0.5)
plt.show()
예제 #55
0
파일: test_cohen.py 프로젝트: dafx/pytftb
 def test_spectrogram_reality(self):
     signal, _ = fmlin(128, 0.1, 0.4)
     window = kaiser(17, 3 * np.pi)
     tfr, _, _ = cohen.spectrogram(signal, n_fbins=64, window=window)
     self.assertTrue(np.all(np.isreal(tfr)))