예제 #1
0
 def test_mfcc_coeffs(self):
     f = filterbank(40, 512)
     c = cvec(512)
     f.set_mel_coeffs_slaney(44100)
     c.norm[:] = np.random.random((int(512 / 2) + 1,)).astype(float_type)
     assert_equal ( f(c) < 1., True )
     assert_equal ( f(c) > 0., True )
예제 #2
0
 def test_vector_created_with_zeroes(self):
     a = cvec(10)
     shape(a.norm)
     shape(a.phas)
     a.norm[0]
     assert_equal(a.norm, 0.)
     assert_equal(a.phas, 0.)
예제 #3
0
 def test_triangle_freqs_zeros(self):
     f = filterbank(9, 1024)
     freq_list = [40, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 15000, 24000]
     freqs = array(freq_list, dtype = float_type)
     f.set_triangle_bands(freqs, 48000)
     _ = f.get_coeffs().T
     assert_equal ( f(cvec(1024)), 0)
예제 #4
0
 def test_assign_cvec_norm_slice(self):
     spec = cvec(1024)
     spec.norm[40:100] = 100
     assert_equal(spec.norm[0:40], 0)
     assert_equal(spec.norm[40:100], 100)
     assert_equal(spec.norm[100:-1], 0)
     assert_equal(spec.phas, 0)
예제 #5
0
파일: test_mfcc.py 프로젝트: aubio/aubio
 def test_set_mel_coeffs_slaney(self):
     buf_size, n_filters, n_coeffs, samplerate = 512, 40, 10, 16000
     m = mfcc(buf_size, n_filters, n_coeffs, samplerate)
     m.set_mel_coeffs_slaney()
     m(cvec(buf_size))
     assert m.get_power() == 1
     assert m.get_scale() == 1
예제 #6
0
파일: test_fft.py 프로젝트: aubio/aubio
 def test_rdo_before_do(self):
     """ check running fft.rdo before fft.do works """
     win_s = 1024
     f = fft(win_s)
     fftgrain = cvec(win_s)
     t = f.rdo( fftgrain )
     assert_equal ( t, 0 )
예제 #7
0
 def test_vector_created_with_zeroes(self):
     a = cvec(10)
     assert_equal(a.norm.shape[0], 10 / 2 + 1)
     assert_equal(a.phas.shape[0], 10 / 2 + 1)
     _ = a.norm[0]
     assert_equal(a.norm, 0.)
     assert_equal(a.phas, 0.)
예제 #8
0
 def test_mkl(self):
     o = specdesc("mkl")
     c = cvec()
     assert_equal( 0., o(c))
     a = arange(c.length, dtype=float_type)
     c.norm = a
     assert_almost_equal( sum(log(1.+ a/1.e-1 ) ) / o(c), 1, decimal=6)
예제 #9
0
 def test_kl(self):
     o = specdesc("kl")
     c = cvec()
     assert_equal(0.0, o(c))
     a = arange(c.length, dtype="float32")
     c.norm = a
     assert_almost_equal(sum(a * log(1.0 + a / 1.0e-1)) / o(c), 1.0, decimal=6)
예제 #10
0
 def test_run_with_params(self, buf_size, n_filters, n_coeffs, samplerate):
     " check mfcc can run with reasonable parameters "
     o = mfcc(buf_size, n_filters, n_coeffs, samplerate)
     spec = cvec(buf_size)
     spec.phas[0] = 0.2
     for _ in range(10):
         o(spec)
예제 #11
0
 def test_vector_assign_element_end(self):
     a = cvec()
     a.norm[-1] = 1
     assert_equal(a.norm[-1], 1)
     assert_equal(a.norm[len(a.norm)-1], 1)
     a.phas[-1] = 1
     assert_equal(a.phas[-1], 1)
     assert_equal(a.phas[len(a.phas)-1], 1)
예제 #12
0
 def test_hfc(self):
     o = specdesc("hfc")
     c = cvec()
     assert_equal( 0., o(c))
     a = arange(c.length, dtype=float_type)
     c.norm = a
     assert_equal (a, c.norm)
     assert_equal ( sum(a*(a+1)), o(c))
예제 #13
0
 def test_pass_to_numpy(self):
     spec = cvec(1024)
     norm = spec.norm
     phas = spec.phas
     del spec
     new_spec = cvec(1024)
     new_spec.norm = norm
     new_spec.phas = phas
     assert_equal(norm, new_spec.norm)
     assert_equal(phas, new_spec.phas)
     assert_equal(id(norm), id(new_spec.norm))
     assert_equal(id(phas), id(new_spec.phas))
     del norm
     del phas
     assert_equal(new_spec.norm, 0.)
     assert_equal(new_spec.phas, 0.)
     del new_spec
예제 #14
0
 def test_phase(self):
     o = specdesc("phase", buf_size)
     spec = cvec(buf_size)
     # phase of zeros is zero
     assert_equal(o(spec), 0.0)
     spec.phas = random.random_sample((len(spec.phas),)).astype("float32")
     # phase of random is not zero
     spec.norm[:] = 1
     assert o(spec) != 0.0
예제 #15
0
 def test_specdiff(self):
     o = specdesc("phase", buf_size)
     spec = cvec(buf_size)
     # specdiff of zeros is zero
     assert_equal (o(spec), 0.)
     spec.phas = random.random_sample((len(spec.phas),)).astype(float_type)
     # phase of random is not zero
     spec.norm[:] = 1
     assert (o(spec) != 0.)
예제 #16
0
 def test_triangle_freqs_zeros(self):
     f = filterbank(9, 1024)
     freq_list = [
         40, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 15000, 24000
     ]
     freqs = np.array(freq_list, dtype=float_type)
     f.set_triangle_bands(freqs, 48000)
     assert_equal(f(cvec(1024)), 0)
     self.assertIsInstance(f.get_coeffs(), np.ndarray)
예제 #17
0
 def test_specdiff(self):
     o = specdesc("phase", buf_size)
     spec = cvec(buf_size)
     # specdiff of zeros is zero
     assert_equal (o(spec), 0.)
     spec.phas = random.random_sample((len(spec.phas),)).astype(float_type)
     # phase of random is not zero
     spec.norm[:] = 1
     assert (o(spec) != 0.)
 def test_random_coeffs(self):
   f = filterbank(40, 512)
   c = cvec(512)
   r = random.random([40, 512 / 2 + 1]).astype('float32')
   r /= r.sum()
   f.set_coeffs(r)
   c.norm[:] = random.random((512 / 2 + 1,)).astype('float32')
   assert_equal ( f(c) < 1., True )
   assert_equal ( f(c) > 0., True )
예제 #19
0
    def activate(self):

        if self._audio is None:
            self._audio = pyaudio.PyAudio()

        # Setup a pre-emphasis filter to help balance the highs
        self.pre_emphasis = None
        if self._config['pre_emphasis']:
            self.pre_emphasis = aubio.digital_filter(3)
            # old, do not use
            #self.pre_emphasis.set_biquad(1., -self._config['pre_emphasis'], 0, 0, 0)

            # USE THESE FOR SCOTT_MEL OR OTHERS
            #self.pre_emphasis.set_biquad(1.3662, -1.9256, 0.5621, -1.9256, 0.9283)

            # USE THESE FOR MATT_MEl
            # weaker bass, good for vocals, highs
            #self.pre_emphasis.set_biquad(0.87492, -1.74984, 0.87492, -1.74799, 0.75169)
            # bass heavier overall more balanced
            self.pre_emphasis.set_biquad(0.85870, -1.71740, 0.85870, -1.71605,
                                         0.71874)

        # Setup the phase vocoder to perform a windowed FFT
        self._phase_vocoder = aubio.pvoc(
            self._config['fft_size'],
            self._config['mic_rate'] // self._config['sample_rate'])
        self._frequency_domain_null = aubio.cvec(self._config['fft_size'])
        self._frequency_domain = self._frequency_domain_null
        self._frequency_domain_x = np.linspace(
            0, self._config['mic_rate'], (self._config["fft_size"] // 2) + 1)

        # Enumerate all of the input devices and find the one matching the
        # configured device index
        _LOGGER.info("Audio Input Devices:")
        info = self._audio.get_host_api_info_by_index(0)
        for i in range(0, info.get('deviceCount')):
            if (self._audio.get_device_info_by_host_api_device_index(
                    0, i).get('maxInputChannels')) > 0:
                _LOGGER.info("  [{}] {}".format(
                    i,
                    self._audio.get_device_info_by_host_api_device_index(
                        0, i).get('name')))

        # Open the audio stream and start processing the input
        self._stream = self._audio.open(
            input_device_index=self._config['device_index'],
            format=pyaudio.paFloat32,
            channels=1,
            rate=self._config['mic_rate'],
            input=True,
            frames_per_buffer=self._config['mic_rate'] //
            self._config['sample_rate'],
            stream_callback=self._audio_sample_callback)
        self._stream.start_stream()

        _LOGGER.info("Audio source opened.")
예제 #20
0
 def test_kurtosis(self):
     o = specdesc("kurtosis")
     c = cvec()
     assert_equal( 0., o(c))
     a = arange(c.length, dtype=float_type)
     c.norm = a
     centroid = sum(a*a) / sum(a)
     spread = sum( (a - centroid)**2 *a) / sum(a)
     kurtosis = sum( (a - centroid)**4 *a) / sum(a) / spread **2
     assert_almost_equal (kurtosis, o(c), decimal = 2)
예제 #21
0
 def test_random_coeffs(self):
     win_s = 128
     f = filterbank(40, win_s)
     c = cvec(win_s)
     r = np.random.random([40, int(win_s / 2) + 1]).astype(float_type)
     r /= r.sum()
     f.set_coeffs(r)
     c.norm[:] = np.random.random((int(win_s / 2) + 1,)).astype(float_type)
     assert_equal ( f(c) < 1., True )
     assert_equal ( f(c) > 0., True )
예제 #22
0
 def test_kurtosis(self):
     o = specdesc("kurtosis")
     c = cvec()
     assert_equal( 0., o(c))
     a = arange(c.length, dtype='float32')
     c.norm = a
     centroid = sum(a*a) / sum(a)
     spread = sum( (a - centroid)**2 *a) / sum(a)
     kurtosis = sum( (a - centroid)**4 *a) / sum(a) / spread **2
     assert_almost_equal (kurtosis, o(c), decimal = 2)
예제 #23
0
 def test_specflux(self):
     o = specdesc("specflux")
     c = cvec()
     assert_equal( 0., o(c))
     a = arange(c.length, dtype=float_type)
     c.norm = a
     assert_equal( sum(a), o(c))
     assert_equal( 0, o(c))
     c.norm = zeros(c.length, dtype=float_type)
     assert_equal( 0, o(c))
예제 #24
0
 def test_specflux(self):
     o = specdesc("specflux")
     c = cvec()
     assert_equal( 0., o(c))
     a = arange(c.length, dtype='float32')
     c.norm = a
     assert_equal( sum(a), o(c))
     assert_equal( 0, o(c))
     c.norm = zeros(c.length, dtype='float32')
     assert_equal( 0, o(c))
예제 #25
0
    def activate(self):

        if self._audio is None:
            self._audio = pyaudio.PyAudio()

        # Setup a pre-emphasis filter to help balance the highs
        self.pre_emphasis = None
        if self._config['pre_emphasis']:
            self.pre_emphasis = aubio.digital_filter(3)
            self.pre_emphasis.set_biquad(1., -self._config['pre_emphasis'], 0,
                                         0, 0)

        # Setup the phase vocoder to perform a windowed FFT
        self._phase_vocoder = aubio.pvoc(
            self._config['fft_size'],
            self._config['mic_rate'] // self._config['sample_rate'])
        self._frequency_domain_null = aubio.cvec(self._config['fft_size'])
        self._frequency_domain = self._frequency_domain_null
        self._frequency_domain_x = np.linspace(
            0, self._config['mic_rate'], (self._config["fft_size"] // 2) + 1)

        # Enumerate all of the input devices and find the one matching the
        # configured device index
        _LOGGER.info("Audio Input Devices:")
        info = self._audio.get_host_api_info_by_index(0)
        for i in range(0, info.get('deviceCount')):
            if (self._audio.get_device_info_by_host_api_device_index(
                    0, i).get('maxInputChannels')) > 0:
                _LOGGER.info("  [{}] {}".format(
                    i,
                    self._audio.get_device_info_by_host_api_device_index(
                        0, i).get('name')))

        # PyAudio may segfault, reset device index if it seems implausible
        if self._config['device_index'] >= info.get(
                'deviceCount'
        ) or self._audio.get_device_info_by_host_api_device_index(
                0, self._config['device_index']).get('maxInputChannels') <= 0:
            _LOGGER.warn("Invalid device_index setting, resetting it to 0")
            self._config['device_index'] = 0

        # Open the audio stream and start processing the input
        self._stream = self._audio.open(
            input_device_index=self._config['device_index'],
            format=pyaudio.paFloat32,
            channels=1,
            rate=self._config['mic_rate'],
            input=True,
            frames_per_buffer=self._config['mic_rate'] //
            self._config['sample_rate'],
            stream_callback=self._audio_sample_callback)
        self._stream.start_stream()

        _LOGGER.info("Audio source opened.")
예제 #26
0
 def test_triangle_freqs_ones(self):
     f = filterbank(9, 1024)
     freq_list = [40, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 15000, 24000]
     freqs = array(freq_list, dtype = float_type)
     f.set_triangle_bands(freqs, 48000)
     _ = f.get_coeffs().T
     spec = cvec(1024)
     spec.norm[:] = 1
     assert_almost_equal ( f(spec),
             [ 0.02070313, 0.02138672, 0.02127604, 0.02135417,
                 0.02133301, 0.02133301, 0.02133311, 0.02133334, 0.02133345])
예제 #27
0
 def test_triangle_freqs_ones(self):
     f = filterbank(9, 1024)
     freq_list = [40, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 15000, 24000]
     freqs = np.array(freq_list, dtype = float_type)
     f.set_triangle_bands(freqs, 48000)
     self.assertIsInstance(f.get_coeffs(), np.ndarray)
     spec = cvec(1024)
     spec.norm[:] = 1
     assert_almost_equal ( f(spec),
             [ 0.02070313, 0.02138672, 0.02127604, 0.02135417,
                 0.02133301, 0.02133301, 0.02133311, 0.02133334, 0.02133345])
예제 #28
0
    def test_spread(self):
        o = specdesc("spread")
        c = cvec(2048)
        ramp = arange(c.length, dtype=float_type)
        assert_equal( 0., o(c))

        a = ramp
        c.norm = a
        centroid = sum(a*a) / sum(a)
        spread = sum( a * pow(ramp - centroid, 2.) ) / sum(a)
        assert_almost_equal (o(c), spread, decimal = 1)
예제 #29
0
    def test_spread(self):
        o = specdesc("spread")
        c = cvec(2048)
        ramp = arange(c.length, dtype='float32')
        assert_equal( 0., o(c))

        a = ramp
        c.norm = a
        centroid = sum(a*a) / sum(a)
        spread = sum( a * pow(ramp - centroid, 2.) ) / sum(a)
        assert_almost_equal (o(c), spread, decimal = 1)
예제 #30
0
 def test_triangle_freqs_with_power(self):
     f = filterbank(9, 1024)
     freqs = fvec([40, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 15000,
         24000])
     f.set_power(2)
     f.set_triangle_bands(freqs, 48000)
     spec = cvec(1024)
     spec.norm[:] = .1
     expected = fvec([0.02070313, 0.02138672, 0.02127604, 0.02135417,
         0.02133301, 0.02133301, 0.02133311, 0.02133334, 0.02133345])
     expected /= 100.
     assert_almost_equal(f(spec), expected)
예제 #31
0
    def test_spread(self):
        o = specdesc("spread")
        c = cvec()
        assert_equal( 0., o(c))
        a = arange(c.length, dtype='float32')
        c.norm = a
        centroid = sum(a*a) / sum(a)
        spread = sum( (a - centroid)**2 *a) / sum(a)
        assert_almost_equal (spread, o(c), decimal = 2)

        c.norm = a * 3
        assert_almost_equal (spread, o(c), decimal = 2)
예제 #32
0
 def test_hfc(self):
     o = specdesc("hfc", buf_size)
     spec = cvec(buf_size)
     # hfc of zeros is zero
     assert_equal(o(spec), 0.0)
     # hfc of ones is sum of all bin numbers
     spec.norm[:] = 1
     expected = sum(range(buf_size / 2 + 2))
     assert_equal(o(spec), expected)
     # changing phase doesn't change anything
     spec.phas[:] = 1
     assert_equal(o(spec), sum(range(buf_size / 2 + 2)))
예제 #33
0
    def test_centroid(self):
        o = specdesc("centroid")
        c = cvec()
        # make sure centroid of zeros is zero
        assert_equal( 0., o(c))
        a = arange(c.length, dtype=float_type)
        c.norm = a
        centroid = sum(a*a) / sum(a)
        assert_almost_equal (centroid, o(c), decimal = 2)

        c.norm = a * .5 
        assert_almost_equal (centroid, o(c), decimal = 2)
예제 #34
0
 def test_complex(self):
     o = specdesc("complex")
     c = cvec()
     assert_equal( 0., o(c))
     a = arange(c.length, dtype=float_type)
     c.norm = a
     assert_equal (a, c.norm)
     # the previous run was on zeros, so previous frames are still 0
     # so we have sqrt ( abs ( r2 ^ 2) ) == r2
     assert_equal ( sum(a), o(c))
     # second time. c.norm = a, so, r1 = r2, and the euclidian distance is 0
     assert_equal ( 0, o(c))
예제 #35
0
    def test_centroid(self):
        o = specdesc("centroid")
        c = cvec()
        # make sure centroid of zeros is zero
        assert_equal( 0., o(c))
        a = arange(c.length, dtype='float32')
        c.norm = a
        centroid = sum(a*a) / sum(a)
        assert_almost_equal (centroid, o(c), decimal = 2)

        c.norm = a * .5 
        assert_almost_equal (centroid, o(c), decimal = 2)
예제 #36
0
 def test_hfc(self):
     o = specdesc("hfc", buf_size)
     spec = cvec(buf_size)
     # hfc of zeros is zero
     assert_equal (o(spec), 0.)
     # hfc of ones is sum of all bin numbers
     spec.norm[:] = 1
     expected = sum(range(buf_size/2 + 2))
     assert_equal (o(spec), expected)
     # changing phase doesn't change anything
     spec.phas[:] = 1
     assert_equal (o(spec), sum(range(buf_size/2 + 2)))
예제 #37
0
 def test_complex(self):
     o = specdesc("complex")
     c = cvec()
     assert_equal( 0., o(c))
     a = arange(c.length, dtype='float32')
     c.norm = a
     assert_equal (a, c.norm)
     # the previous run was on zeros, so previous frames are still 0
     # so we have sqrt ( abs ( r2 ^ 2) ) == r2
     assert_equal ( sum(a), o(c))
     # second time. c.norm = a, so, r1 = r2, and the euclidian distance is 0
     assert_equal ( 0, o(c))
예제 #38
0
    def test_skewness(self):
        o = specdesc("skewness")
        c = cvec()
        assert_equal( 0., o(c))
        a = arange(c.length, dtype=float_type)
        c.norm = a
        centroid = sum(a*a) / sum(a)
        spread = sum( (a - centroid)**2 *a) / sum(a)
        skewness = sum( (a - centroid)**3 *a) / sum(a) / spread **1.5
        assert_almost_equal (skewness, o(c), decimal = 2)

        c.norm = a * 3
        assert_almost_equal (skewness, o(c), decimal = 2)
예제 #39
0
 def test_rolloff(self):
     o = specdesc("rolloff")
     c = cvec()
     assert_equal( 0., o(c))
     a = arange(c.length * 2, 0, -2, dtype=float_type)
     c.norm = a
     cumsum = .95*sum(a*a)
     i = 0; rollsum = 0
     while rollsum < cumsum:
         rollsum += a[i]*a[i]
         i+=1
     rolloff = i 
     assert_equal (rolloff, o(c))
예제 #40
0
    def test_skewness(self):
        o = specdesc("skewness")
        c = cvec()
        assert_equal( 0., o(c))
        a = arange(c.length, dtype='float32')
        c.norm = a
        centroid = sum(a*a) / sum(a)
        spread = sum( (a - centroid)**2 *a) / sum(a)
        skewness = sum( (a - centroid)**3 *a) / sum(a) / spread **1.5
        assert_almost_equal (skewness, o(c), decimal = 2)

        c.norm = a * 3
        assert_almost_equal (skewness, o(c), decimal = 2)
예제 #41
0
 def test_assign_cvec_with_other_cvec(self):
     """ check dest cvec is still reachable after source was deleted """
     spec = cvec(1024)
     a = np.random.rand(1024 // 2 + 1).astype(float_type)
     b = np.random.rand(1024 // 2 + 1).astype(float_type)
     spec.norm = a
     spec.phas = b
     new_spec = spec
     del spec
     assert_equal(a, new_spec.norm)
     assert_equal(b, new_spec.phas)
     assert_equal(id(a), id(new_spec.norm))
     assert_equal(id(b), id(new_spec.phas))
예제 #42
0
 def test_assign_cvec_with_other_cvec(self):
     """ check dest cvec is still reachable after source was deleted """
     spec = cvec(1024)
     a = np.random.rand(1024//2+1).astype(float_type)
     b = np.random.rand(1024//2+1).astype(float_type)
     spec.norm = a
     spec.phas = b
     new_spec = spec
     del spec
     assert_equal(a, new_spec.norm)
     assert_equal(b, new_spec.phas)
     assert_equal(id(a), id(new_spec.norm))
     assert_equal(id(b), id(new_spec.phas))
예제 #43
0
    def test_members(self):
        o = specdesc()

        for method in methods:
            o = specdesc(method, buf_size)
            assert_equal ([o.buf_size, o.method], [buf_size, method])

            spec = cvec(buf_size)
            spec.norm[0] = 1
            spec.norm[1] = 1./2.
            #print "%20s" % method, str(o(spec))
            o(spec)
            spec.norm = random.random_sample((len(spec.norm),)).astype(float_type)
            spec.phas = random.random_sample((len(spec.phas),)).astype(float_type)
            #print "%20s" % method, str(o(spec))
            assert (o(spec) != 0.)
예제 #44
0
    def test_members(self):

        o = mfcc(buf_size, n_filters, n_coeffs, samplerate)
        #assert_equal ([o.buf_size, o.method], [buf_size, method])

        spec = cvec(buf_size)
        #spec.norm[0] = 1
        #spec.norm[1] = 1./2.
        #print "%20s" % method, str(o(spec))
        coeffs = o(spec)
        self.assertEqual(coeffs.size, n_coeffs)
        #print coeffs
        spec.norm = random.random_sample((len(spec.norm), )).astype(float_type)
        spec.phas = random.random_sample((len(spec.phas), )).astype(float_type)
        #print "%20s" % method, str(o(spec))
        self.assertEqual(count_nonzero(o(spec) != 0.), n_coeffs)
예제 #45
0
    def test_members(self):

        o = mfcc(buf_size, n_filters, n_coeffs, samplerate)
        #assert_equal ([o.buf_size, o.method], [buf_size, method])

        spec = cvec(buf_size)
        #spec.norm[0] = 1
        #spec.norm[1] = 1./2.
        #print "%20s" % method, str(o(spec))
        coeffs = o(spec)
        self.assertEqual(coeffs.size, n_coeffs)
        #print coeffs
        spec.norm = random.random_sample((len(spec.norm),)).astype(float_type)
        spec.phas = random.random_sample((len(spec.phas),)).astype(float_type)
        #print "%20s" % method, str(o(spec))
        self.assertEqual(count_nonzero(o(spec) != 0.), n_coeffs)
예제 #46
0
    def test_members(self):
        o = specdesc()

        for method in methods:
          o = specdesc(method, buf_size)
          assert_equal ([o.buf_size, o.method], [buf_size, method])

          spec = cvec(buf_size)
          spec.norm[0] = 1
          spec.norm[1] = 1./2.
          #print "%20s" % method, str(o(spec))
          o(spec)
          spec.norm = random.random_sample((len(spec.norm),)).astype('float32')
          spec.phas = random.random_sample((len(spec.phas),)).astype('float32')
          #print "%20s" % method, str(o(spec))
          assert (o(spec) != 0.)
예제 #47
0
    def test_decrease(self):
        o = specdesc("decrease")
        c = cvec()
        assert_equal( 0., o(c))
        a = arange(c.length * 2, 0, -2, dtype='float32')
        k = arange(c.length, dtype='float32')
        c.norm = a
        decrease = sum((a[1:] - a [0]) / k[1:]) / sum(a[1:]) 
        assert_almost_equal (decrease, o(c), decimal = 5)

        a = arange(0, c.length * 2, +2, dtype='float32')
        c.norm = a
        decrease = sum((a[1:] - a [0]) / k[1:]) / sum(a[1:]) 
        assert_almost_equal (decrease, o(c), decimal = 5)

        a = arange(0, c.length * 2, +2, dtype='float32')
        c.norm = a * 2
        decrease = sum((a[1:] - a [0]) / k[1:]) / sum(a[1:]) 
        assert_almost_equal (decrease, o(c), decimal = 5)
예제 #48
0
    def test_slope(self):
        o = specdesc("slope")
        c = cvec()
        assert_equal( 0., o(c))
        a = arange(c.length * 2, 0, -2, dtype='float32')
        k = arange(c.length, dtype='float32')
        c.norm = a
        num = len(a) * sum(k*a) - sum(k)*sum(a)
        den = (len(a) * sum(k**2) - sum(k)**2)
        slope = num/den/sum(a)
        assert_almost_equal (slope, o(c), decimal = 5)

        a = arange(0, c.length * 2, +2, dtype='float32')
        c.norm = a
        num = len(a) * sum(k*a) - sum(k)*sum(a)
        den = (len(a) * sum(k**2) - sum(k)**2)
        slope = num/den/sum(a)
        assert_almost_equal (slope, o(c), decimal = 5)

        a = arange(0, c.length * 2, +2, dtype='float32')
        c.norm = a * 2
        assert_almost_equal (slope, o(c), decimal = 5)
예제 #49
0
def Stretch(inputfilename, outputfilename, stretchfactor, sample_rate=0):

    win_s = 1024
    hop_s = win_s // 8  # 87.5 % overlap

    warmup = win_s // hop_s - 1

    source_filename = inputfilename
    output_filename = outputfilename
    rate = float(stretchfactor)

    samplerate = sample_rate
    source_in = source(source_filename, samplerate, hop_s)
    samplerate = source_in.samplerate
    p = pvoc(win_s, hop_s)

    # allocate memory to store norms and phases
    n_blocks = source_in.duration // hop_s + 1
    # adding an empty frame at end of spectrogram
    norms = np.zeros((n_blocks + 1, win_s // 2 + 1), dtype=float_type)
    phases = np.zeros((n_blocks + 1, win_s // 2 + 1), dtype=float_type)

    block_read = 0
    while True:
        # read from source
        samples, read = source_in()
        # compute fftgrain
        spec = p(samples)
        # store current grain
        norms[block_read] = spec.norm
        phases[block_read] = spec.phas
        # until end of file
        if read < hop_s: break
        # increment block counter
        block_read += 1

        # just to make sure
        #source_in.close()

    sink_out = sink(output_filename, samplerate)

    # interpolated time steps (j = alpha * i)
    steps = np.arange(0, n_blocks, rate, dtype=float_type)
    # initial phase
    phas_acc = phases[0]
    # excepted phase advance in each bin
    phi_advance = np.linspace(0, np.pi * hop_s,
                              win_s / 2 + 1).astype(float_type)

    new_grain = cvec(win_s)

    for (t, step) in enumerate(steps):

        frac = 1. - np.mod(step, 1.0)
        # get pair of frames
        t_norms = norms[int(step):int(step + 2)]
        t_phases = phases[int(step):int(step + 2)]

        # compute interpolated frame
        new_grain.norm = frac * t_norms[0] + (1. - frac) * t_norms[1]
        new_grain.phas = phas_acc
        #print t, step, new_grain.norm
        #print t, step, phas_acc

        # psola
        samples = p.rdo(new_grain)
        if t > warmup:  # skip the first few frames to warm up phase vocoder
            # write to sink
            sink_out(samples, hop_s)

        # calculate phase advance
        dphas = t_phases[1] - t_phases[0] - phi_advance
        # unwrap angle to [-pi; pi]
        dphas = unwrap2pi(dphas)
        # cumulate phase, to be used for next frame
        phas_acc += phi_advance + dphas

    for t in range(warmup + 1):  # purge the last frames from the phase vocoder
        new_grain.norm[:] = 0
        new_grain.phas[:] = 0
        samples = p.rdo(new_grain)
        sink_out(samples, read if t == warmup else hop_s)

    # just to make sure
    #sink_out.close()

    format_out = "read {:d} blocks from {:s} at {:d}Hz and rate {:f}, wrote {:d} blocks to {:s}"
    print(
        format_out.format(block_read, source_filename, samplerate, rate,
                          len(steps), output_filename))
예제 #50
0
 def test_assign_cvec_phas_slice(self):
     spec = cvec(1024)
     spec.phas[39:-1] = -pi
     assert_equal(spec.phas[0:39], 0)
     assert_equal(spec.phas[39:-1], -pi)
     assert_equal(spec.norm, 0)
예제 #51
0
 def test_vector_assign_element(self):
     a = cvec()
     a.norm[0] = 1
     assert_equal(a.norm[0], 1)
     a.phas[0] = 1
     assert_equal(a.phas[0], 1)
예제 #52
0
 def test_assign_phas_too_small(self):
     a = cvec(512)
     b = fvec(512 // 2 + 1 - 4)
     with self.assertRaises(ValueError):
         a.phas = b
예제 #53
0
 def test_assign_norm_too_large(self):
     a = cvec(512)
     b = fvec(512 // 2 + 1 + 4)
     with self.assertRaises(ValueError):
         a.norm = b
예제 #54
0
 def test_set_norm_with_wrong_2d_array(self):
     a = cvec(512)
     with self.assertRaises(ValueError):
         a.norm = np.zeros((512 // 2 + 1, 2), dtype=float_type)
예제 #55
0
 def test_set_norm_with_int_array(self):
     a = cvec(512)
     with self.assertRaises(ValueError):
         a.norm = np.zeros(512 // 2 + 1, dtype='int')
예제 #56
0
 def test_set_norm_with_scalar_array(self):
     a = cvec(512)
     with self.assertRaises(ValueError):
         a.norm = np.ndarray(1, dtype='int')
예제 #57
0
 def test_set_norm_with_scalar(self):
     a = cvec(512)
     with self.assertRaises(ValueError):
         a.norm = 1
예제 #58
0
 def test_wrong_length(self):
     with self.assertRaises(ValueError):
         cvec(-1)