test_ceps.py 15.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Elie Khoury <Elie.Khoury@idiap.ch>
#
# Copyright (C) 2011-2013 Idiap Research Institute, Martigny, Switzerland

import os, sys
import unittest
import numpy
import array
import math
import time

André Anjos's avatar
André Anjos committed
14
15
from . import Ceps

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#############################################################################
# Tests blitz-based extrapolation implementation with values returned
#############################################################################

########################## Values used for the computation ##################
eps = 1e-3

#############################################################################
numpy.set_printoptions(precision=2, threshold=numpy.nan, linewidth=200)

def _read(filename):
  """Read video.FrameContainer containing preprocessed frames"""

  fileName, fileExtension = os.path.splitext(filename)
  wav_filename = filename
  import scipy.io.wavfile
  rate, data = scipy.io.wavfile.read(str(wav_filename)) # the data is read in its native format
  if data.dtype =='int16':
    data = numpy.cast['float'](data)
  return [rate,data]


def compare(v1, v2, width):
  return abs(v1-v2) <= width

def mel_python(f):
  import math
  return 2595.0*math.log10(1.+f/700.0)

def mel_inv_python(value):
  return 700.0 * (10 ** (value / 2595.0) - 1)

def sig_norm(win_length, frame, flag):
  gain = 0.0
  for i in range(win_length):
    gain = gain + frame[i] * frame[i]

  ENERGY_FLOOR = 1.0
  if gain < ENERGY_FLOOR:
    gain = math.log(ENERGY_FLOOR)
  else:
    gain = math.log(gain)

  if(flag and gain != 0.0):
    for i in range(win_length):
      frame[i] = frame[i] / gain
  return gain

def pre_emphasis(frame, win_length, a):
  if (a < 0.0) or (a >= 1.0):
    print("Error: The emphasis coeff. should be between 0 and 1")
  if (a == 0.0):
    return frame
  else:
    for i in range(win_length - 1, 0, -1):
      frame[i] = frame[i] - a * frame[i - 1]
    frame[0] = (1. - a) * frame[0]
  return frame

def hamming_window(vector, hamming_kernel, win_length):
  for i in range(win_length):
    vector[i] = vector[i] * hamming_kernel[i]
  return vector

def log_filter_bank(x, n_filters, p_index, win_size):
André Anjos's avatar
André Anjos committed
81
82
  from xbob.sp import fft

83
  x1 = numpy.array(x, dtype=numpy.complex128)
André Anjos's avatar
André Anjos committed
84
  complex_ = fft(x1)
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
  for i in range(0, int(win_size / 2) + 1):
    re = complex_[i].real
    im = complex_[i].imag
    x[i] = math.sqrt(re * re + im * im)
  filters = log_triangular_bank(x, n_filters, p_index)
  return filters

def log_triangular_bank(data, n_filters, p_index):
  a = 1.0 / (p_index[1:n_filters+2] - p_index[0:n_filters+1] + 1)
  vec1 =  list(numpy.arange(p_index[i], p_index[i + 1]) for i in range(0, n_filters))
  vec2 =  list(numpy.arange(p_index[i+1], p_index[i + 2] + 1) for i in range(0, n_filters))
  res_ = numpy.array([(numpy.sum(data[vec1[i]]*(1.0 - a [i]* (p_index[i + 1]-(vec1[i])))) +
          numpy.sum(data[vec2[i]] * (1.0 - a[i+1] * ( (vec2[i]) - p_index[i + 1]))))
          for i in range(0, n_filters)])
  FBANK_OUT_FLOOR = 1.0
  filters = numpy.log(numpy.where(res_ < FBANK_OUT_FLOOR, FBANK_OUT_FLOOR, res_))
  return filters

def dct_transform(filters, n_filters, dct_kernel, n_ceps, dct_norm):
  if dct_norm:
    dct_coeff = numpy.sqrt(2.0/(n_filters))
  else :
    dct_coeff = 1.0

  ceps = numpy.zeros(n_ceps + 1)
  vec = numpy.array(range(1, n_filters + 1))
  for i in range(1, n_ceps + 1):
    ceps[i - 1] = numpy.sum(filters[vec - 1] * dct_kernel[i - 1][0:n_filters])
    ceps[i - 1] = ceps[i - 1] * dct_coeff

  return ceps

def cepstral_features_extraction(obj, rate_wavsample, win_length_ms, win_shift_ms, n_filters, n_ceps, dct_norm, f_min, f_max, delta_win,
                               pre_emphasis_coef, mel_scale, with_energy, with_delta, with_delta_delta):
  #########################
  ## Initialisation part ##
  #########################
André Anjos's avatar
André Anjos committed
122
  c = Ceps(rate_wavsample[0], win_length_ms, win_shift_ms, n_filters, n_ceps, f_min, f_max, delta_win, pre_emphasis_coef)
123
124
125
126
127
  c.dct_norm = dct_norm
  c.mel_scale = mel_scale
  c.with_energy = with_energy
  c.with_delta = with_delta
  c.with_delta_delta = with_delta_delta
André Anjos's avatar
André Anjos committed
128
  #ct = TestCeps(c)
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345

  sf = rate_wavsample[0]
  data = rate_wavsample[1]

  win_length = int (sf * win_length_ms / 1000)
  win_shift = int (sf * win_shift_ms / 1000)
  win_size = int (2.0 ** math.ceil(math.log(win_length) / math.log(2)))
  m = int (math.log(win_size) / math.log(2))

  # Hamming initialisation
  cst = 2 * math.pi / (win_length - 1.0)
  hamming_kernel = numpy.zeros(win_length)

  for i in range(win_length):
    hamming_kernel[i] = (0.54 - 0.46 * math.cos(i * cst))

  # Compute cut-off frequencies
  p_index = numpy.array(numpy.zeros(n_filters + 2), dtype=numpy.int16)
  if(mel_scale):
    # Mel scale
    m_max = mel_python(f_max)
    #obj.assertAlmostEqual(ct.herz_to_mel(f_max), m_max, 7, "Error in Mel...")
    m_min = mel_python(f_min)
    #obj.assertAlmostEqual(ct.herz_to_mel(f_min), m_min, 7, "Error in Mel...")

    for i in range(n_filters + 2):
      alpha = ((i) / (n_filters + 1.0))
      f = mel_inv_python(m_min * (1 - alpha) + m_max * alpha)
      #obj.assertAlmostEqual(ct.mel_to_herz(m_min * (1 - alpha) + m_max * alpha), f, 7, "Error in MelInv...")
      factor = f / (sf * 1.0)
      p_index[i] = int (round((win_size) * factor))
  else:
    #linear scale
    for i in range(n_filters + 2):
      alpha = (i) / (n_filters + 1.0)
      f = f_min * (1.0 - alpha) + f_max * alpha
      p_index[i] = int (round((win_size / (sf * 1.0) * f)))

  #Cosine transform initialisation
  dct_kernel = [ [ 0 for i in range(n_filters) ] for j in range(n_ceps) ]

  for i in range(1, n_ceps + 1):
    for j in range(1, n_filters + 1):
      dct_kernel[i - 1][j - 1] = math.cos(math.pi * i * (j - 0.5) / n_filters)

  ######################################
  ### End of the Initialisation part ###
  ######################################

  ######################################
  ###          Core code             ###
  ######################################

  data_size = data.shape[0]
  n_frames = int(1 + (data_size - win_length) / win_shift)

  # create features set
  ceps_sequence = numpy.zeros(n_ceps)
  dim0 = n_ceps
  if(with_energy):
    dim0 += + 1
  dim = dim0
  if(with_delta):
    dim += dim0
    if(with_delta_delta):
      dim += dim0
  else:
    with_delta_delta = False

  params = [ [ 0 for i in range(dim) ] for j in range(n_frames) ]

  # compute cepstral coefficients
  delta = 0
  for i in range(n_frames):
    # create a frame
    frame = numpy.zeros(win_size, dtype=numpy.float64)
    som = 0.0
    vec = numpy.arange(win_length)
    frame[vec] = data[vec + i * win_shift]
    som = numpy.sum(frame)
    som = som / win_size
    frame = frame - som

    if (with_energy):
      energy = sig_norm(win_length, frame, False)
      #e1 = ct.log_energy(frame)
      #obj.assertAlmostEqual(e1, energy, 7, "Error in Energy Computation...")

    f2 = numpy.copy(frame)

    # pre-emphasis filtering
    frame = pre_emphasis(frame, win_length, pre_emphasis_coef)
    #ct.pre_emphasis(f2)
    #for kk in range(len(frame)):
    #  obj.assertAlmostEqual(frame[kk], f2[kk], 7, "Error in Pre-Emphasis Computation...")

    # Hamming windowing
    f2 = numpy.copy(frame)
    frame = hamming_window(frame, hamming_kernel, win_length)
    #ct.hamming_window(f2)
    #for kk in range(len(frame)):
    #  obj.assertAlmostEqual(frame[kk], f2[kk], 7, "Error in Pre-Emphasis Computation...")

    f2=numpy.copy(frame)
    filters = log_filter_bank(frame, n_filters, p_index, win_size)

    #filt2 = ct.log_filter_bank(f2, win_size, n_filters)

    #for kk in range(len(filters)):
    #  obj.assertAlmostEqual(filters[kk], filt2[kk], 7, "Error in log Filtering")

    ceps = dct_transform(filters, n_filters, dct_kernel, n_ceps, dct_norm)
    #ceps2 = ct.apply_dct(n_ceps)


    if(with_energy):
      d1 = n_ceps + 1
      ceps[n_ceps] = energy
        #print(ceps)
    else:
      d1 = n_ceps

    # stock the results in params matrix
    vec=numpy.arange(d1)
    params[i][0:d1]=ceps[vec]

  # compute Delta coefficient
  if(with_delta):
    som = 0.0
    for i in range(1,delta_win+1):
      som = som + i*i
    som = som *2

    for i in range(n_frames):
      for k in range(n_ceps):
        params[i][d1+k] = 0.0
        for l in range(1, delta_win+1):
          if (i+l < n_frames):
            p_ind = i+l
          else:
            p_ind = n_frames - 1
          if (i-l > 0):
            n_ind = i-l
          else:
            n_ind = 0
          params[i][d1+k] = params[i][d1+k] + l * (params[p_ind][k] - params[n_ind][k])
        params[i][d1+k] = params[i][d1+k] / som

  # compute Delta of the Energy
  if(with_delta and with_energy):
    som = 0.0

    vec=numpy.arange(1,delta_win+1)
    som = 2.0* numpy.sum(vec*vec)

    for i in range(n_frames):
      k = n_ceps
      params[i][d1+k] = 0.0
      for l in range(1, delta_win+1):
        if (i+l < n_frames):
          p_ind = i+l
        else:
          p_ind = n_frames - 1
        if (i-l > 0):
          n_ind = i-l
        else:
          n_ind = 0
        params[i][d1+k] = params[i][d1+k] + l* (params[p_ind][k] - params[n_ind][k])
      params[i][d1+k] = params[i][d1+k] / som

  # compute Delta Delta of the coefficients
  if(with_delta_delta):
    som = 0.0
    for i in range(1,delta_win+1):
      som = som + i*i
    som = som *2
    for i in range(n_frames):
      for k in range(n_ceps):
        params[i][2*d1+k] = 0.0
        for l in range(1, delta_win+1):
          if (i+l < n_frames):
            p_ind = i+l
          else:
            p_ind = n_frames - 1
          if (i-l > 0):
            n_ind = i-l
          else:
            n_ind = 0
          params[i][2*d1+k] = params[i][2*d1+k] + l * (params[p_ind][d1+k] - params[n_ind][d1+k])
        params[i][2*d1+k] = params[i][2*d1+k] / som

  # compute Delta Delta of the energy
  if(with_delta_delta and with_energy):
    som = 0.0
    for i in range(1,delta_win+1):
      som = som + i*i
    som = som *2
    for i in range(n_frames):
      k = n_ceps
      params[i][2*d1+k] = 0.0
      for l in range(1, delta_win+1):
        if (i+l < n_frames):
          p_ind = i+l
        else:
          p_ind = n_frames - 1
        if (i-l > 0):
          n_ind = i-l
        else:
          n_ind = 0
        params[i][2*d1+k] = params[i][2*d1+k] + l * (params[p_ind][d1+k] - params[n_ind][d1+k])
      params[i][2*d1+k] = params[i][2*d1+k] / som
  data = numpy.array(params)

  return data

def cepstral_comparison_run(obj, rate_wavsample, win_length_ms, win_shift_ms, n_filters, n_ceps, dct_norm, f_min, f_max, delta_win,
                               pre_emphasis_coef, mel_scale, with_energy, with_delta, with_delta_delta):
André Anjos's avatar
André Anjos committed
346
  c = Ceps(rate_wavsample[0], win_length_ms, win_shift_ms, n_filters, n_ceps, f_min, f_max, delta_win, pre_emphasis_coef, mel_scale, dct_norm)
347
348
349
350
  c.with_energy = with_energy
  c.with_delta = with_delta
  if c.with_delta:
    c.with_delta_delta = with_delta_delta
André Anjos's avatar
André Anjos committed
351
  #ct = TestCeps(c)
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
  A = c(rate_wavsample[1])
  B = cepstral_features_extraction(obj, rate_wavsample, win_length_ms, win_shift_ms, n_filters, n_ceps, dct_norm,
        f_min, f_max, delta_win, pre_emphasis_coef, mel_scale, with_energy, with_delta, with_delta_delta)
  diff=numpy.sum(numpy.sum((A-B)*(A-B)))
  obj.assertAlmostEqual(diff, 0., 7, "Error in Ceps Analysis")

##################### Unit Tests ##################
class CepsTest(unittest.TestCase):
  """Test the Cepstral feature extraction"""

  def test_cepstral(self):
    import pkg_resources
    rate_wavsample = _read(pkg_resources.resource_filename(__name__, os.path.join('data', 'sample.wav')))

    win_length_ms = 20
    win_shift_ms = 10
    n_filters = 24
    n_ceps = 19
    f_min = 0.
    f_max = 4000.
    delta_win = 2
    pre_emphasis_coef = 0.97
    dct_norm = True
    mel_scale = True
    with_energy = True
    with_delta = True
    with_delta_delta = True

    cepstral_comparison_run(self,rate_wavsample, win_length_ms, win_shift_ms, n_filters, n_ceps, dct_norm, f_min, f_max, delta_win,
                               pre_emphasis_coef, mel_scale, with_energy, with_delta, with_delta_delta)

    # Varying win_length_ms
    win_length_ms = 30
    cepstral_comparison_run(self,rate_wavsample, win_length_ms, win_shift_ms, n_filters, n_ceps, dct_norm, f_min, f_max, delta_win,
                               pre_emphasis_coef, mel_scale, with_energy, with_delta, with_delta_delta)
    # Varying win_shift_ms
    win_shift_ms = 15
    cepstral_comparison_run(self,rate_wavsample, win_length_ms, win_shift_ms, n_filters, n_ceps, dct_norm, f_min, f_max, delta_win,
                               pre_emphasis_coef, mel_scale, with_energy, with_delta, with_delta_delta)

    # Varying n_filters
    n_filters = 20
    cepstral_comparison_run(self,rate_wavsample, win_length_ms, win_shift_ms, n_filters, n_ceps, dct_norm, f_min, f_max, delta_win,
                               pre_emphasis_coef, mel_scale, with_energy, with_delta, with_delta_delta)

    # Varying n_ceps
    n_ceps = 12
    cepstral_comparison_run(self,rate_wavsample, win_length_ms, win_shift_ms, n_filters, n_ceps, dct_norm, f_min, f_max, delta_win,
                               pre_emphasis_coef, mel_scale, with_energy, with_delta, with_delta_delta)

    # Varying f_min
    f_min = 300.
    cepstral_comparison_run(self,rate_wavsample, win_length_ms, win_shift_ms, n_filters, n_ceps, dct_norm, f_min, f_max, delta_win,
                               pre_emphasis_coef, mel_scale, with_energy, with_delta, with_delta_delta)

    # Varying f_max
    f_max = 3300.
    cepstral_comparison_run(self,rate_wavsample, win_length_ms, win_shift_ms, n_filters, n_ceps, dct_norm, f_min, f_max, delta_win,
                               pre_emphasis_coef, mel_scale, with_energy, with_delta, with_delta_delta)

    # Varying delta_win
    delta_win = 5
    cepstral_comparison_run(self,rate_wavsample, win_length_ms, win_shift_ms, n_filters, n_ceps, dct_norm, f_min, f_max, delta_win,
                               pre_emphasis_coef, mel_scale, with_energy, with_delta, with_delta_delta)

    # Varying pre_emphasis_coef
    pre_emphasis_coef = 0.7
    cepstral_comparison_run(self,rate_wavsample, win_length_ms, win_shift_ms, n_filters, n_ceps, dct_norm, f_min, f_max, delta_win,
                               pre_emphasis_coef, mel_scale, with_energy, with_delta, with_delta_delta)

    # Varying dct_norm
    dct_norm = False
    cepstral_comparison_run(self,rate_wavsample, win_length_ms, win_shift_ms, n_filters, n_ceps, dct_norm, f_min, f_max, delta_win,
                               pre_emphasis_coef, mel_scale, with_energy, with_delta, with_delta_delta)

    # Varying mel_scale : linear scale
    mel_scale = False
    cepstral_comparison_run(self,rate_wavsample, win_length_ms, win_shift_ms, n_filters, n_ceps, dct_norm, f_min, f_max, delta_win,
                               pre_emphasis_coef, mel_scale, with_energy, with_delta, with_delta_delta)

    # Varying with_energy
    with_energy = False
    cepstral_comparison_run(self,rate_wavsample, win_length_ms, win_shift_ms, n_filters, n_ceps, dct_norm, f_min, f_max, delta_win,
                               pre_emphasis_coef, mel_scale, with_energy, with_delta, with_delta_delta)

    # Varying with_delta
    with_delta = False
    cepstral_comparison_run(self,rate_wavsample, win_length_ms, win_shift_ms, n_filters, n_ceps, dct_norm, f_min, f_max, delta_win,
                               pre_emphasis_coef, mel_scale, with_energy, with_delta, with_delta_delta)

    # Varying with_delta_delta
    with_delta_delta = False
    cepstral_comparison_run(self,rate_wavsample, win_length_ms, win_shift_ms, n_filters, n_ceps, dct_norm, f_min, f_max, delta_win,
                               pre_emphasis_coef, mel_scale, with_energy, with_delta, with_delta_delta)

    # Test comparison operators and copy constructor
André Anjos's avatar
André Anjos committed
448
449
450
    c0 = Ceps(rate_wavsample[0], win_length_ms, win_shift_ms, n_filters, n_ceps, f_min, f_max, delta_win, pre_emphasis_coef, mel_scale, dct_norm)
    c1 = Ceps(c0)
    c2 = Ceps(c1)
451
452
453
454
455
    c2.win_length_ms = 27.
    self.assertTrue( c0 == c1)
    self.assertFalse(c0 != c1)
    self.assertFalse(c0 == c2)
    self.assertTrue( c0 != c2)