annotate trunk/matlab/bmm/carfac/Carfac.py @ 532:9b478420cbe2

Added a calculation (last plot) of the group delay. The previous check in fixed a couple of bugs.
author alan.strelzoff
date Sun, 11 Mar 2012 22:45:36 +0000
parents acd08b2ff774
children
rev   line source
alan@522 1 # Carfac.py - Cochlear filter model based on Dick Lyons work. This material taken from his Hearing book (to be published)
alan@531 2 # Author: Al Strelzoff: strelz@mit.edu
alan@522 3
alan@531 4 # The point of this file is to extract some of the formulas from the book and practice with them so as to better understand the filters.
alan@531 5 # The file has been written and tested for python 2.7
alan@522 6
alan@532 7 from numpy import cos, sin, pi, e, real,imag,arctan2,log10
alan@531 8
alan@531 9
alan@531 10 from pylab import figure, plot,loglog, title, axis, show
alan@522 11
alan@522 12 fs = 22050.0 # sampling rate
alan@522 13
alan@522 14
alan@522 15 # given a frequency f, return the ERB
alan@522 16 def ERB_Hz(f):
alan@522 17 # Ref: Glasberg and Moore: Hearing Research, 47 (1990), 103-138
alan@522 18 return 24.7 * (1.0 + 4.37 * f / 1000.0)
alan@522 19
alan@522 20
alan@522 21 # ERB parameters
alan@522 22 ERB_Q = 1000.0/(24.7*4.37) # 9.2645
alan@522 23 ERB_break_freq = 1000/4.37 # 228.833
alan@522 24
alan@522 25 ERB_per_step = 0.3333
alan@522 26
alan@522 27 # set up channels
alan@522 28
alan@522 29 first_pole_theta = .78 * pi # We start at the top frequency.
alan@522 30 pole_Hz = first_pole_theta * fs / (2.0*pi) # frequency of top pole
alan@522 31 min_pole_Hz = 40.0 # bottom frequency
alan@522 32
alan@522 33 # set up the pole frequencies according to the above parameters
alan@522 34 pole_freqs = [] # empty list of pole frequencies to fill, zeroth will be the top
alan@522 35 while pole_Hz > min_pole_Hz:
alan@522 36 pole_Hz = pole_Hz - ERB_per_step * ERB_Hz(pole_Hz)
alan@522 37 pole_freqs.append(pole_Hz)
alan@522 38
alan@522 39 n_ch = len(pole_freqs) # n_ch is the number of channels or frequency steps
alan@522 40 print('num channels',n_ch)
alan@522 41
alan@522 42 # Now we have n_ch, the number of channels, so can make the array of filters by instantiating the filter class (see below)
alan@522 43
alan@522 44 # before we make the filters, let's plot the position of the frequencies and the values of ERB at each.
alan@522 45
alan@522 46 fscale = []
alan@522 47 erbs = []
alan@522 48
alan@531 49 figure(1)
alan@522 50 for i in range(n_ch):
alan@522 51
alan@522 52 f = pole_freqs[i] # the frequencies from the list
alan@522 53 ERB = ERB_Hz(f) # the ERB value at each frequency
alan@522 54 fscale.append(f)
alan@522 55 erbs.append(ERB)
alan@522 56
alan@522 57 # plot a verticle hash at each frequency:
alan@522 58 u = []
alan@522 59 v = []
alan@522 60 for j in range(5):
alan@522 61 u.append(f)
alan@522 62 v.append(10.0 + float(j))
alan@522 63
alan@522 64 plot(u,v)
alan@522 65
alan@522 66 loglog(fscale,erbs)
alan@522 67
alan@522 68 title('ERB scale')
alan@522 69
alan@522 70
alan@522 71
alan@522 72 # This filter class includes some methods useful only in design. They will not be used in run time implementation.
alan@522 73 # From figure 14.3 in Dick Lyon's book.
alan@531 74 # When translating to C++, this class will become a struct, and all the methods will be moved outside.
alan@522 75
alan@522 76
alan@522 77 #########################################################The Carfac filter class#################################################################################
alan@522 78
alan@522 79 # fixed parameters
alan@522 80 min_zeta = 0.12
alan@522 81
alan@522 82 class carfac():
alan@522 83
alan@522 84
alan@522 85 # instantiate the class (in C++, the constructor)
alan@522 86 def __init__(self,f):
alan@522 87
alan@522 88 self.frequency = f
alan@522 89
alan@522 90 theta = 2.0 * pi * f/fs
alan@522 91 r = 1.0 - sin(theta) * min_zeta
alan@522 92 a = r * cos(theta)
alan@522 93 c = r * sin(theta)
alan@531 94 h = sin(theta)
alan@531 95 g = (1.0 - 2.0 * a + r ** 2)/(1.0 - 2.0 * a + h * c + r ** 2)
alan@531 96
alan@531 97
alan@522 98
alan@531 99 self.gh = g*h # no need to repeat in real time
alan@522 100
alan@522 101 # make all parameters properties of the class
alan@522 102 self.a = a
alan@522 103 self.c = c
alan@522 104 self.r = r
alan@522 105 self.theta = theta
alan@522 106 self.h = h
alan@522 107 self.g = g
alan@522 108
alan@522 109
alan@522 110 # the two storage elements. Referring to diagram 14.3 on p.263, z2 is the upper storage register, z1, the lower
alan@522 111 self.z1 = 0.0
alan@522 112 self.z2 = 0.0
alan@522 113
alan@522 114
alan@522 115 # frequency response of this filter
alan@522 116 self.H = []
alan@522 117
alan@522 118
alan@522 119
alan@522 120 # the total frequency magnitude of this filter including all the filters in front of this one
alan@522 121 self.HT = [] # this list will be filled by multiplying all the H's ahead of it together with its own (H)
alan@522 122
alan@522 123
alan@522 124
alan@522 125 # execute one clock tick. Take in one input and output one result. Execution semantics taken from fig. 14.3
alan@522 126 # This execution model is not tested in this file. Here for reference. See the file Exec.py for testing this execution model. This is the main run time method.
alan@522 127 def input(self,X):
alan@522 128
alan@522 129 # recover the class definitions of these variables. These statements below take up zero time at execution since they are just compiler declarations.
alan@531 130 # computation below is organized as some loads, followed by 3 2x2 multiply accumulates
alan@531 131 # Note: this function is not exercised in this file and is here only for reference
alan@522 132
alan@522 133 a = self.a
alan@522 134 c = self.c
alan@522 135 g = self.g
alan@531 136 gh = self.gh
alan@522 137 z1 = self.z1 # z1 is the lower storage in fig. 14.3
alan@522 138 z2 = self.z2
alan@522 139
alan@522 140 # calculate what the next value of z1 will be, but don't overwrite current value yet.
alan@531 141 next_z1 = (a * z1) + (c * z2) # Note: it is a 2 element multiply accumulate. compute first so as not to have to do twice.
alan@522 142 # the output Y
alan@531 143 Y = g * X + gh * next_z1 # Note: organized as a 2 element multiply accumulate.
alan@522 144
alan@522 145 #stores
alan@531 146 self.z2 = X + (a * z2) - (c * z1) #Note: this is a 2 element multiply accumulate
alan@531 147 self.z1 = next_z1
alan@522 148
alan@522 149 return Y # The output
alan@522 150
alan@522 151 # complex frequency response of this filter at frequency w. That is, what it contributes to the cascade
alan@522 152 # this method is used for test only. It finds the frequency magnitude. Not included in run time filter class.
alan@522 153 def Hw(self,w):
alan@522 154
alan@522 155 a = self.a
alan@522 156 c = self.c
alan@522 157 g = self.g
alan@522 158 h = self.h
alan@522 159 r = self.r
alan@522 160 z = e ** (complex(0,w)) # w is in radians so this is z = exp(jw)
alan@531 161 return g * (1.0 + (h*c*z)/(z**2 - 2.0*a*z + r**2 ))
alan@522 162
alan@522 163
alan@522 164
alan@522 165 ######################################################End of Carfac filter class########################################################################
alan@532 166
alan@532 167
alan@522 168 # instantiate the filters
alan@522 169
alan@522 170 # n_ch is the number of filters as determined above
alan@522 171
alan@522 172 Filters = [] # the list of all filters, the zeroth is the top frequency
alan@522 173 for i in range(n_ch):
alan@522 174 f = pole_freqs[i]
alan@522 175 filter = carfac(f) # note: get the correct parameters for r and h from Dick's matlab script. Load them here from a table.
alan@522 176 Filters.append(filter)
alan@522 177
alan@522 178
alan@522 179
alan@522 180 # sweep parameters
alan@522 181 steps = 1000
alan@522 182
alan@531 183 figure(2)
alan@531 184 title('CarFac individual filter frequency response')
alan@531 185 # note: the scales are linear, not logrithmic as in the book
alan@522 186
alan@522 187
alan@522 188 for i in range(n_ch):
alan@522 189 filter = Filters[i]
alan@522 190 # plotting arrays
alan@522 191 u = []
alan@522 192 v = []
alan@522 193 # calculate the frequency magnitude by stepping the frequency in radians
alan@522 194 for j in range(steps):
alan@522 195
alan@531 196 w = pi * float(j)/steps
alan@522 197 u.append(w)
alan@522 198 mag = filter.Hw(w) # freq mag at freq w
alan@522 199 filter.H.append(mag) # save for later use
alan@522 200 filter.HT.append(mag) # will be total response of cascade to this point after we do the multiplication in a step below
alan@531 201 v.append(abs(mag)) # y plotting axis
alan@522 202
alan@522 203
alan@522 204 plot(u,v)
alan@522 205
alan@522 206
alan@522 207 # calculate the phase response of the same group of filters
alan@522 208 figure(3)
alan@531 209 title('Carfac individual filter Phase lag')
alan@522 210
alan@522 211
alan@522 212 for i in range(n_ch):
alan@522 213 filter = Filters[i]
alan@522 214
alan@522 215 u = []
alan@522 216 v = []
alan@522 217 for j in range(steps):
alan@531 218 x = pi * float(j)/steps
alan@522 219
alan@522 220 u.append(x)
alan@522 221
alan@522 222 mag = filter.H[j]
alan@531 223 phase = arctan2(-imag(mag),-real(mag)) - pi # this formula used to avoid wrap around
alan@522 224
alan@522 225 v.append(phase) # y plotting axis
alan@522 226
alan@522 227 plot(u,v)
alan@531 228 axis([0.0,pi,-3.0,0.05])
alan@522 229
alan@522 230
alan@531 231 # calulate and plot cascaded frequency response
alan@522 232
alan@522 233 figure(4)
alan@531 234 title('CarFac cascaded filter frequency response')
alan@522 235
alan@522 236
alan@522 237 for i in range(n_ch-1):
alan@522 238
alan@522 239 filter = Filters[i]
alan@522 240 next = Filters[i+1]
alan@522 241
alan@522 242
alan@522 243 u = []
alan@522 244 v = []
alan@522 245 for j in range(steps):
alan@531 246 w = pi * float(j)/steps
alan@531 247 u.append(w)
alan@522 248 mag = filter.HT[j] * next.HT[j]
alan@531 249 next.HT[j] = mag
alan@531 250 v.append(abs(mag))
alan@522 251
alan@522 252
alan@522 253 plot(u,v)
alan@522 254
alan@522 255
alan@522 256
alan@522 257 # calculate and plot the phase responses of the cascaded filters
alan@522 258
alan@531 259 figure(5)
alan@531 260 title('Carfac cascaded filter Phase lag')
alan@522 261
alan@522 262 for i in range(n_ch):
alan@531 263
alan@522 264 filter = Filters[i]
alan@522 265
alan@522 266
alan@522 267 u = []
alan@531 268 v = [] # store list of phases
alan@531 269 w = [] # second copy of phases needed for phase unwrapping
alan@522 270 for j in range(steps):
alan@531 271 x = pi * float(j)/steps
alan@522 272
alan@522 273 u.append(x)
alan@522 274 mag = filter.HT[j]
alan@531 275 a = imag(mag)
alan@531 276 b = real(mag)
alan@531 277 phase = arctan2(a,b)
alan@522 278
alan@531 279 v.append(phase)
alan@531 280 w.append(phase)
alan@522 281
alan@531 282 # unwrap the phase
alan@522 283
alan@522 284
alan@531 285 for i in range(1,len(v)):
alan@531 286 diff = v[i]-v[i-1]
alan@531 287 if diff > pi:
alan@531 288 for j in range(i,len(w)):
alan@531 289 w[j] -= 2.0 * pi
alan@531 290 elif diff < -pi:
alan@531 291 for j in range(i,len(w)):
alan@531 292 w[j] += 2.0 * pi
alan@531 293
alan@531 294 else: continue
alan@532 295
alan@532 296 # convert delay to cycles
alan@532 297 for i in range(len(w)):
alan@532 298 w[i] /= 2.0 * pi
alan@532 299
alan@531 300
alan@531 301 plot(u,w)
alan@532 302 axis([0.0,pi,-5.0,0.05])
alan@532 303
alan@532 304 # calculate group delay as cascaded lag/filter center frequency
alan@532 305
alan@532 306 figure(6)
alan@532 307 title('Carfac group delay')
alan@532 308
alan@532 309 for i in range(n_ch):
alan@532 310
alan@532 311 filter = Filters[i]
alan@532 312
alan@532 313
alan@532 314 u = []
alan@532 315 v = [] # store list of phases
alan@532 316 w = [] # second copy of phases needed for phase unwrapping
alan@532 317 for j in range(1,steps):
alan@532 318 x = pi * float(j)/steps
alan@532 319
alan@532 320 u.append(x)
alan@532 321 mag = filter.HT[j]
alan@532 322 a = imag(mag)
alan@532 323 b = real(mag)
alan@532 324 phase = arctan2(a,b)
alan@532 325
alan@532 326 v.append(phase)
alan@532 327 w.append(phase)
alan@532 328
alan@532 329
alan@532 330 for i in range(1,len(v)):
alan@532 331 diff = v[i]-v[i-1]
alan@532 332 if diff > pi:
alan@532 333 for j in range(i,len(w)):
alan@532 334 w[j] -= 2.0 * pi
alan@532 335 elif diff < -pi:
alan@532 336 for j in range(i,len(w)):
alan@532 337 w[j] += 2.0 * pi
alan@532 338
alan@532 339 else: continue
alan@532 340
alan@532 341 # calculate the group delay from: GroupDelay(n)=-[((ph(n+1)-ph(n-1))/(w(n+1)-w(n-1))]/2pi # w in radians
alan@532 342 # or gd[n] = - ((delta ph)/(delta w))/2pi
alan@532 343 # delta ph = w[n+1] - w[n-1]
alan@532 344 # delta w = pi* fs/steps # we divide up the frequency range fs into fractions of pi radians.
alan@532 345 # gd[n] = - steps(w[n+1] - w[n-1])/fs
alan@532 346
alan@532 347 A = -(float(steps))/(2 *fs) # note. could have calculated this once outside the filter loop
alan@532 348
alan@532 349 # gd[n] = A *(w[n+1] - w[n-1])
alan@532 350
alan@532 351 gd = [] # in radians
alan@532 352 gd.append(0.0) # pad to equalize size of u array, end points are then meaningless
alan@532 353 for n in range(1,len(w)-1):
alan@532 354 gd.append(A * (w[n+1] - w[n-1]))
alan@532 355
alan@532 356 gd.append(0.0)
alan@532 357
alan@532 358 plot(u,gd)
alan@532 359 axis([0.1,pi,-0.01,0.05])
alan@532 360
alan@522 361 show()
alan@522 362