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