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. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4.  
  5. import sys
  6. from optparse import OptionParser
  7.  
  8. quiet = False
  9.  
  10. def Output (string):
  11. """Output with colors :)"""
  12. if not quiet:
  13. print "\033[32;1m===>\033[0m %s" % string
  14.  
  15. def StartProgram():
  16. """Starting banner"""
  17. if not quiet:
  18. print "\033[31;1m===>\033[0m Discrete Wavelet transform started"
  19.  
  20. def EndProgram():
  21. """End banner"""
  22. if not quiet:
  23. pass
  24.  
  25. def LoadingLibrariesStarted():
  26. """Loading libraries banner"""
  27. if __name__ == "__main__" and not quiet:
  28. print "\033[31;1m===>\033[0m Loading numeric libraries...",
  29. sys.stdout.flush ()
  30.  
  31. def LoadingLibrariesFinished():
  32. """Loading libraries finished banner"""
  33. if __name__ == "__main__" and not quiet:
  34. print "done"
  35.  
  36.  
  37. if __name__ == "__main__":
  38.  
  39. parser = OptionParser (usage = "usage: %prog [options] filename")
  40. parser.add_option("-r", "--rebuild", dest="rebuild",
  41. default=False, action="store_true",
  42. help="Make DWT and then IDWT")
  43. parser.add_option("-q", "--quiet", dest="quiet",
  44. default=False, action="store_true")
  45. parser.add_option("-w", "--write", dest="filewrite", default='rebuilt.raw',
  46. help="Write reconstructed samples to this file")
  47. parser.add_option("-s", "--show", dest="show",
  48. default=True, action="store_true",
  49. help="Show the decomposed waves (this is the default)")
  50. parser.add_option("-d", "--depth", dest="depth",
  51. default=4, help="Set the recursion level of the filter bank (default is 4)")
  52. parser.add_option("-b", "--filterbank", dest="filterbank", default='haar',
  53. help="Set the filterbank to use in the transform. Valid inputs are 'haar', 'daubechies', 'D4', 'strang'")
  54.  
  55.  
  56. (options, args) = parser.parse_args ()
  57.  
  58. try:
  59. filename = args[0]
  60. except:
  61. parser.error ("Please a specify a PCM file to read the samples from")
  62.  
  63. if (not options.show) and (not options.rebuild):
  64. exit
  65.  
  66. quiet = options.quiet
  67.  
  68. LoadingLibrariesStarted()
  69.  
  70. # Importing libraries
  71. try:
  72. from pylab import show, plot, title, xlabel, ylabel, rcParams
  73. except ImportError:
  74. print "Errore nell'importazione della libreria pylab. Installare python-matplotlib"
  75. sys.exit(1)
  76. try:
  77. from numpy import array, sqrt, memmap, roll, inf
  78. from numpy.linalg import norm
  79. except ImportError:
  80. print "Errore nell'importazione delle libreria numpy. Installare python-numpy"
  81. sys.exit(1)
  82. import time
  83. import Filtering
  84.  
  85. params = {
  86. "text.usetex": True,
  87. 'font.family': 'serif',
  88. }
  89.  
  90. rcParams.update(params)
  91.  
  92.  
  93.  
  94. LoadingLibrariesFinished()
  95.  
  96.  
  97. class DWT():
  98.  
  99. def __init__(self, filename, action = 'show', filewrite = 'rebuilt.wav',
  100. filterbank = 'haar', depth = 4):
  101.  
  102. StartProgram ()
  103.  
  104. startingTime = time.time ()
  105. self.depth = depth
  106.  
  107. self.filterBankName = ""
  108.  
  109. # Scelgo la filterbank da utilizzare
  110. if filterbank == 'haar':
  111. filterBank = Filtering.HaarFilterBank
  112. self.filterBankName = "Haar"
  113. elif (filterbank == 'daubechies') or (filterbank.lower() == 'd4'):
  114. filterBank = Filtering.DaubechiesFilterBank
  115. self.filterBankName = "Daubechies D4"
  116. elif filterbank == 'strang':
  117. filterBank = Filtering.StrangFilterBank
  118. self.filterBankName = "Strang"
  119. elif filterbank == 'leo':
  120. # Ci sono ancora dei problemi con questa.
  121. filterBank = Filtering.LeoFilterBank
  122. self.filterBankName = "Leo"
  123. else:
  124. filterBank = Filtering.HaarFilterBank
  125. Output ("FilterBank %s not known. Setting 'haar'" % filterbank)
  126.  
  127. filterBank.SetDepth (int(depth))
  128.  
  129. samples = self.LoadSamples (filename)
  130. wavelets = filterBank.Split (samples)
  131.  
  132. Output ("Decomposed in %f seconds" % (time.time() - startingTime))
  133. Output ("Wavelet size: %d bytes" % (2*wavelets.GetAllSamplesNumber()))
  134.  
  135. # Mostro la decomposizione se l'utente l'ha chiesto
  136. if action == 'show':
  137. self.Show (wavelets)
  138.  
  139.  
  140. if action is 'rebuild':
  141. startingTime = time.time ()
  142. rebuilt = filterBank.Rebuild (wavelets)
  143. Output ("Rebuilt in %f seconds" % (time.time() - startingTime))
  144.  
  145. # Se la differenza in norma è più di 10^-8 possiamo preoccuparci.
  146. a = norm(rebuilt - samples)
  147. if (a > 1E-2):
  148. Output ("Error while reconstructing. Rebuilt samples differs from original ones")
  149. Output ("|rebuilt - samples| = %f" % a)
  150. Output ("|rebuilt - samples|_inf = %f" % norm(rebuilt-samples,inf))
  151. Output ("There is likely an error in the code")
  152.  
  153. elif (a > 1E-6):
  154. Output ("Error while reconstructing. Rebuilt samples differs from original ones")
  155. Output ("This is likely an approximation error (the error is quite small)")
  156. Output ("|rebuilt - samples|_inf = %f" % norm(rebuilt-samples,inf))
  157. else:
  158. Output ("Perfect reconstruction succeeded")
  159. self.WriteSamples(rebuilt, filewrite)
  160.  
  161. EndProgram ()
  162.  
  163.  
  164. def LoadSamples(self, filename):
  165. """
  166. Load the samples from an audio file
  167. """
  168. samples = memmap (filename,
  169. dtype="<h",
  170. mode="r")
  171. Output("Loaded %d samples from %s" % (len(samples), filename))
  172. return samples
  173.  
  174. def WriteSamples(self, samples, filename):
  175. Output("Writing samples to %s" % filename)
  176. data = memmap (filename,
  177. dtype="<h",
  178. mode="w+",
  179. shape = len(samples))
  180. data[:] = samples[:]
  181. data.flush ()
  182.  
  183. def Show(self, wavelets):
  184. """
  185. Shows the result of filtering
  186. """
  187.  
  188. # We set the frequency to have seconds (and not samples)
  189. # in the x-axis of the plot.
  190. frequency = float (44100)
  191.  
  192. # We choose a decreasing scale to sync all the samples
  193. # because they are recursively downsamples by a factor
  194. # of two and we want to plot with the same time-scale.
  195. scale = pow(2, wavelets.GetNumSamples ())
  196.  
  197. singleOffset = 2 * wavelets.GetSamplesMaxValue()
  198. offset = -(self.depth / 2) * singleOffset
  199.  
  200. # We plot only the first 60 seconds of audio, to avoid memory
  201. # being flooded with our data :)
  202. toPlot = int(frequency) * 60
  203.  
  204. # Stampo i low
  205. scale = int(0.5 * scale)
  206. low = wavelets.PopLowSamples()
  207. data = low[:toPlot / scale]
  208.  
  209. axes = array(range(0, len(data) * scale, scale)) / frequency
  210.  
  211. plot(axes, data + offset)
  212.  
  213. offset += singleOffset
  214.  
  215. while (wavelets.GetHighSamplesNumber() > 0):
  216.  
  217. samples = wavelets.PopHighSamples ()
  218.  
  219. data = samples[0:toPlot / scale]
  220. axes = array(range(0, len(data) * scale , scale)) / frequency
  221.  
  222. plot (axes, data + offset)
  223. offset += singleOffset
  224. scale = int(0.5*scale)
  225.  
  226.  
  227. # Set some nice text
  228. title (r"Wavelet decomposition using %s filter bank" % self.filterBankName)
  229. xlabel (r"time (s)")
  230.  
  231. show ()
  232.  
  233.  
  234.  
  235.  
  236. if __name__ == "__main__":
  237.  
  238. # Scegliamo cosa fare, a seconda delle opzioni di cui
  239. # abbiamo fatto il parsing più in alto.
  240. # Partiamo.
  241.  
  242. if options.rebuild:
  243. DWT(filename = filename, action = 'rebuild',
  244. filewrite = options.filewrite, depth = options.depth,
  245. filterbank = options.filterbank)
  246.  
  247. elif options.show:
  248. DWT(filename = filename, action = 'show',
  249. depth = options.depth, filterbank = options.filterbank)
  250.  
  251.  
  252.  
  253.  
  254.