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