viewgit/index.php:465 Only variables should be passed by reference [2048]

viewgit/index.php:466 Non-static method GeSHi::get_language_name_from_extension() should not be called statically [2048]

  1. #
  2. # -*- coding: utf-8 -*-
  3. #
  4.  
  5. from numpy import array, zeros, convolve, dot, roll, sqrt, concatenate
  6. from numpy.linalg import norm
  7. from fast_filters import filter_and_downsample, upsample_and_filter
  8.  
  9. class AbstractFilter():
  10.  
  11. def __init__(self):
  12. pass
  13.  
  14. def __call__ (self, samples):
  15. """
  16. Apply the filter to samples. This method has to be
  17. overloaded from the specific filter class
  18. """
  19. pass
  20.  
  21.  
  22. class FIR(AbstractFilter):
  23.  
  24. def __init__(self, coefficients):
  25.  
  26. self.coefficients = array(coefficients)
  27.  
  28. def __call__(self, samples):
  29. """Apply the FIR to samples"""
  30. # Per ora tronchiamo brutalmente la convoluzione, anche se
  31. # questo vuol dire perdere dei samples finali. d'altronde
  32. # sembra essere l'unico modo per prevere i delay.
  33. sz = len(samples)
  34. return convolve (self.coefficients, samples)[0:sz]
  35.  
  36.  
  37. def GetResponse(self):
  38. """
  39. Obtain the vector of coefficients.
  40. """
  41. return self.coefficients
  42.  
  43. def __mul__(self, other):
  44. return FIR(convolve(self.coefficients, other.GetResponse()))
  45.  
  46.  
  47.  
  48. def DownSample(samples):
  49.  
  50. return array(samples[::2])
  51.  
  52. def UpSample(samples):
  53.  
  54. s = zeros(2 * len(samples))
  55. s[::2] = samples
  56. return array(s)
  57.  
  58.  
  59. def PRCheck(f):
  60. """
  61. Return the delay that the filterbank will cause or raise
  62. RuntimeError if PR condition is not satisfied"""
  63. a = 0.5 * (f.lowPassFilter * f.lowPassInverseFilter).GetResponse ()
  64. b = 0.5 * (f.highPassFilter * f.highPassInverseFilter).GetResponse ()
  65. f0 = f.lowPassInverseFilter.GetResponse()
  66. f1 = f.highPassInverseFilter.GetResponse()
  67. f0[1::2] = (-1) * f0[1::2]
  68. f1[1::2] = (-1) * f1[1::2]
  69. c = (f.lowPassFilter * FIR(f0)).GetResponse()
  70. d = (f.highPassFilter * FIR(f1)).GetResponse()
  71.  
  72. # Ora cerco di capire quanto sarà il ritardo.
  73. for i in range(0,len(a+b)):
  74. if (a+b)[i] > 0.5:
  75. break
  76. s = zeros(len(a+b))
  77. s[i] = 1
  78. if (norm(a+b - s) > 1e-15):
  79. raise RuntimeError('PR condition is not satisfied')
  80. if (norm(c+d) > 1e-15):
  81. raise RuntimeError('PR condition on aliasing is not satisfied')
  82. return i
  83.  
  84.  
  85. class WaveletStack():
  86.  
  87. def __init__(self):
  88. """
  89. Creates a new WaveletTransformedSignal to
  90. store the samples from the filterbank
  91. """
  92. self.samples_number = None
  93. self.low_samples = []
  94. self.high_samples = []
  95. self.end = []
  96. self.end_effect = []
  97.  
  98. def PushEndSamples(self, samples):
  99. """Push end samples, i.e. the samples that exceeds the
  100. ideal dimensione pow(2,m) where m is the depth of the
  101. filterbank."""
  102. self.end = samples
  103.  
  104. def PopEndSamples(self):
  105. return self.end
  106.  
  107. def PushEndEffectSamples(self, samples):
  108. """Push some end samples to preserve them to
  109. end effect"""
  110. self.end_effect = samples
  111.  
  112. def PopEndEffectSamples(self):
  113. return self.end_effect
  114.  
  115. def PushHighSamples(self, samples):
  116. """
  117. Add a new High Sample
  118. """
  119. if self.samples_number is None:
  120. self.samples_number = len(samples)
  121. self.high_samples.append(samples)
  122. else:
  123. if len(samples) != (self.samples_number / 2):
  124. raise IndexError("High frequency samples do not have the expected length")
  125. else:
  126. self.high_samples.append (samples)
  127. self.samples_number = len(samples)
  128.  
  129. def PushLowSamples(self, samples):
  130. """
  131. Add the Low samples
  132. """
  133. if self.samples_number != len(samples):
  134. raise IndexError("Low frequency samples do not have the expected length")
  135. else:
  136. self.low_samples.append(samples)
  137.  
  138. def PopLowSamples(self):
  139. """
  140. Get the low frequency samples
  141. """
  142. try:
  143. return self.low_samples.pop()
  144. except:
  145. raise IndexError("No low samples in the WaveletStack")
  146.  
  147. def GetLowSamplesNumber(self):
  148. """Get the length of the lowsample array, i.e. how many low
  149. samples track do we have pushed."""
  150. return len(self.low_samples)
  151.  
  152. def GetHighSamplesNumber(self):
  153. """Get the length of the lowsample array, i.e. how many low
  154. samples track do we have pushed."""
  155. return len(self.high_samples)
  156.  
  157. def GetAllSamplesNumber(self):
  158. return sum(map(len, self.low_samples)) + sum(map(len,self.high_samples)) + len(self.end_effect) + len(self.end)
  159.  
  160. def GetNumSamples(self):
  161. """Get the total number of samples in the WaveletStack."""
  162. return len(self.low_samples) + len(self.high_samples)
  163.  
  164. def GetSamplesMaxValue(self):
  165. """Get the maximum abs value of the lowsample and
  166. high sample array"""
  167. m = [0]
  168. for low in self.low_samples:
  169. m.append (max(abs(low)))
  170. for high in self.high_samples:
  171. m.append(max(abs(high)))
  172. return max(m)
  173.  
  174. def PopHighSamples(self):
  175. """
  176. Get the high frequency samples
  177. """
  178. try:
  179. return self.high_samples.pop ()
  180. except:
  181. raise IndexError("No more high samples in the stack")
  182.  
  183.  
  184. class FilterBank():
  185.  
  186. def __init__(self):
  187. """Create a new empty filter bank"""
  188. self.lowPassFilter = None
  189. self.highPassFilter = None
  190. self.highPassInverseFilter = None
  191. self.lowPassInverseFilter = None
  192.  
  193. self.depth = 1
  194.  
  195. def SetFilterMatrix(self, filter_matrix):
  196. """
  197. Set the filter matrix for the filter bank.
  198. It must have this shape:
  199.  
  200. [ h0 , h1, f0, f1 ]
  201.  
  202. Where h0 is the lowPass coefficients vector,
  203. h1 the high pass one, f0 the inverse low pass
  204. and f1 the inverse high pass.
  205. This method can only use FIR filters, if you are
  206. looking for more freedom use SetLowPassFilter ()
  207. and similar.
  208. """
  209. self.lowPassFilter = FIR (filter_matrix[0])
  210. self.highPassFilter = FIR (filter_matrix[1])
  211. self.lowPassInverseFilter = FIR (filter_matrix[2])
  212. self.highPassInverseFilter = FIR (filter_matrix[3])
  213.  
  214. def _Truncate(self, samples):
  215. """
  216. Returns the samples truncated to make
  217. recursive split possibile
  218. (i.e. len(samples) % 2^depth = 0)
  219. """
  220. toRemove = len(samples) % pow(2,self.depth)
  221. if toRemove is 0:
  222. return samples, []
  223. else:
  224. return samples[:-1 * toRemove], samples[-1 * toRemove:]
  225.  
  226. def SetDepth(self, depth):
  227. """
  228. Set the depth of the filter, i.e. how many recursion
  229. will be done when filtering and downsampling
  230. """
  231. self.depth = depth
  232.  
  233.  
  234. def SetLowPassFilter(self, lowpass):
  235. """
  236. Set the LowPassFilter for the filterbank.
  237. It has to be a callable that transform the
  238. samples. It will usually be a FIR
  239. """
  240. self.lowPassFilter = lowpass
  241.  
  242.  
  243. def SetHighPassFilter(self, highpass):
  244. """
  245. Set the High pass filter. It is usually
  246. a FIR but can be a generic callable that
  247. returns the filtered samples
  248. """
  249. self.highPassFilter = highpass
  250.  
  251. def SetLowPassInverseFilter(self, lowpass):
  252. """
  253. Set the LowPass inverse filter to be used
  254. in reconstruction.
  255. """
  256. self.lowPassInverseFilter = lowpass
  257.  
  258. def SetHighPassInverseFilter(self, highpass):
  259. """
  260. Set the HighPass inverse filter to be used
  261. in signal reconstruction
  262. """
  263. self.highPassInverseFilter = highpass
  264.  
  265. def SetLength(self, length = None):
  266. """
  267. Set the length of the filter, i.e how much
  268. will be the delay when recovering
  269. """
  270. if length is None:
  271. self.length = PRCheck(self)
  272. else:
  273. self.length = length
  274. # print "length set to %d" % self.length
  275.  
  276.  
  277. def EndEffectLength(self):
  278. """Cerchiamo di dare una valutazione di quanto gli effetti
  279. di bordo potrebbero rovinare la traccia per preseravare le
  280. informazioni finali"""
  281. return (-2) * pow(2,self.depth) * len(self.lowPassFilter.GetResponse())
  282.  
  283. def Split(self, samples):
  284. """
  285. Split the samples using the filter provided
  286. by the user. It returns a WaveletStack that
  287. contains the details and the last average.
  288. The original signal can be rebuilt collapsing
  289. all these downsampled signals with the Rebuild
  290. method.
  291. """
  292.  
  293. samplesStack = WaveletStack()
  294. low, end = self._Truncate(samples)
  295. samplesStack.PushEndSamples (end)
  296.  
  297. # Non sono proprio sicuro che questo sia il modo migliore per farlo.
  298. samplesStack.PushEndEffectSamples (low[self.EndEffectLength():])
  299.  
  300. # Do the real filtering and downsampling. Store the downsampled
  301. # details in the array.
  302. for recursion in xrange(0, self.depth):
  303. # samplesStack.PushHighSamples (DownSample (self.highPassFilter (low)))
  304. # low = DownSample (self.lowPassFilter (low))
  305. samplesStack.PushHighSamples (
  306. filter_and_downsample(low, 2, self.highPassFilter.GetResponse()))
  307. low = filter_and_downsample(low, 2, self.lowPassFilter.GetResponse())
  308.  
  309. # In the end append the low downsampled data to the array
  310. samplesStack.PushLowSamples (low)
  311.  
  312. return samplesStack
  313.  
  314. def Rebuild(self, samplesStack):
  315. """
  316. Rebuild an array of samples obtained by the Split()
  317. method.
  318. """
  319.  
  320. low = samplesStack.PopLowSamples ()
  321. end = samplesStack.PopEndSamples ()
  322.  
  323. counter = 0
  324.  
  325. # high = samplesStack.PopHighSamples ()
  326. while(samplesStack.GetHighSamplesNumber() > 0):
  327.  
  328. # Otteniamo l'high samples dallo stack
  329. high = samplesStack.PopHighSamples ()
  330.  
  331. # E li filtriamo insieme ai low samples.
  332. # low = self.lowPassInverseFilter (UpSample (low))
  333. low = upsample_and_filter(low, 2, self.lowPassInverseFilter.GetResponse())
  334.  
  335. # low += self.highPassInverseFilter (UpSample (high))
  336. low += upsample_and_filter(high, 2, self.highPassInverseFilter.GetResponse())
  337.  
  338. # Facciamo shiftare l'array in modo che il delay dei sample
  339. # ricostruiti non disturbi la ricostruzione dei prossimi.
  340. # Sfortunatamente questo ci rovinerà tutta l'ultima parte del
  341. # segnale, ma per ora non vedo una soluzione comoda.
  342. low = roll(low, -1 * self.length)
  343.  
  344. # Riparo gli eventuali end effect
  345. low[self.EndEffectLength():] = samplesStack.PopEndEffectSamples ()
  346.  
  347. # Riattacchiamo la coda
  348. return concatenate ((low, end))
  349.  
  350.  
  351. DaubechiesFilterBank = FilterBank ()
  352. DaubechiesFilterBank.SetFilterMatrix ( [
  353. 0.125 * array([ 1 + sqrt(3), 3 + sqrt(3), 3 - sqrt(3), 1 - sqrt(3)]),
  354. 0.125 * array([ 1 - sqrt(3),-3 + sqrt(3), 3 + sqrt(3),-1 - sqrt(3)]),
  355. 0.25 * array([ 1 - sqrt(3), 3 - sqrt(3), 3 + sqrt(3), 1 + sqrt(3)]),
  356. 0.25 * array([-1 - sqrt(3), 3 + sqrt(3),-3 + sqrt(3), 1 - sqrt(3)])
  357. ])
  358. DaubechiesFilterBank.SetLength (3)
  359.  
  360. HaarFilterBank = FilterBank ()
  361. HaarFilterBank.SetFilterMatrix ( [
  362. [0.5, 0.5],
  363. [0.5 ,-0.5],
  364. [1 , 1 ],
  365. [-1 , 1]
  366. ])
  367. HaarFilterBank.SetLength(1)
  368.  
  369.  
  370. StrangFilterBank = FilterBank ()
  371. StrangFilterBank.SetFilterMatrix ( [
  372. 0.125 * array([-1,2,6,2,-1]),
  373. 0.25 * array([1,-2,1]),
  374. 0.5 * array([1,2,1]),
  375. 0.25 * array([1,2,-6,2,1])
  376. ])
  377. StrangFilterBank.SetLength(3)
  378.  
  379.  
  380.  
  381. h0 = StrangFilterBank.lowPassFilter
  382. h1 = StrangFilterBank.highPassFilter
  383. f0 = StrangFilterBank.lowPassInverseFilter
  384. f1 = StrangFilterBank.highPassInverseFilter
  385.  
  386.  
  387.  
  388.