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 numpy import array, sqrt, memmap, roll, inf
  73. from numpy.linalg import norm
  74. except ImportError:
  75. print "Errore nell'importazione delle libreria numpy. Installare python-numpy"
  76. sys.exit(1)
  77. import time
  78. import Filtering
  79.  
  80.  
  81.  
  82. LoadingLibrariesFinished()
  83.  
  84.  
  85. class DWT():
  86.  
  87. def __init__(self, filename, action = 'show', filewrite = 'rebuilt.wav',
  88. filterbank = 'haar', depth = 4):
  89.  
  90. StartProgram ()
  91.  
  92. startingTime = time.time ()
  93. self.depth = depth
  94.  
  95. self.filterBankName = ""
  96.  
  97. # Scelgo la filterbank da utilizzare
  98. if filterbank == 'haar':
  99. filterBank = Filtering.HaarFilterBank
  100. self.filterBankName = "Haar"
  101. elif (filterbank == 'daubechies') or (filterbank.lower() == 'd4'):
  102. filterBank = Filtering.DaubechiesFilterBank
  103. self.filterBankName = "Daubechies D4"
  104. elif filterbank == 'strang':
  105. filterBank = Filtering.StrangFilterBank
  106. self.filterBankName = "Strang"
  107. elif filterbank == 'leo':
  108. # Ci sono ancora dei problemi con questa.
  109. filterBank = Filtering.LeoFilterBank
  110. self.filterBankName = "Leo"
  111. else:
  112. filterBank = Filtering.HaarFilterBank
  113. Output ("FilterBank %s not known. Setting 'haar'" % filterbank)
  114.  
  115. filterBank.SetDepth (int(depth))
  116.  
  117. samples = self.LoadSamples (filename)
  118. wavelets = filterBank.Split (samples)
  119.  
  120. Output ("Decomposed in %f seconds" % (time.time() - startingTime))
  121. Output ("Wavelet size: %d bytes" % (2*wavelets.GetAllSamplesNumber()))
  122.  
  123. # Mostro la decomposizione se l'utente l'ha chiesto
  124. if action == 'show':
  125. self.Show (wavelets)
  126.  
  127.  
  128. if action is 'rebuild':
  129. startingTime = time.time ()
  130. rebuilt = filterBank.Rebuild (wavelets)
  131. Output ("Rebuilt in %f seconds" % (time.time() - startingTime))
  132.  
  133. # Se la differenza in norma è più di 10^-8 possiamo preoccuparci.
  134. a = norm(rebuilt - samples)
  135. if (a > 1E-2):
  136. Output ("Error while reconstructing. Rebuilt samples differs from original ones")
  137. Output ("|rebuilt - samples| = %f" % a)
  138. Output ("|rebuilt - samples|_inf = %f" % norm(rebuilt-samples,inf))
  139. Output ("There is likely an error in the code")
  140.  
  141. elif (a > 1E-6):
  142. Output ("Error while reconstructing. Rebuilt samples differs from original ones")
  143. Output ("This is likely an approximation error (the error is quite small)")
  144. Output ("|rebuilt - samples|_inf = %f" % norm(rebuilt-samples,inf))
  145. else:
  146. Output ("Perfect reconstruction succeeded")
  147. self.WriteSamples(rebuilt, filewrite)
  148.  
  149. EndProgram ()
  150.  
  151.  
  152. def LoadSamples(self, filename):
  153. """
  154. Load the samples from an audio file
  155. """
  156. samples = memmap (filename,
  157. dtype="<h",
  158. mode="r")
  159. Output("Loaded %d samples from %s" % (len(samples), filename))
  160. return samples
  161.  
  162. def WriteSamples(self, samples, filename):
  163. Output("Writing samples to %s" % filename)
  164. data = memmap (filename,
  165. dtype="<h",
  166. mode="w+",
  167. shape = len(samples))
  168. data[:] = samples[:]
  169. data.flush ()
  170.  
  171. def Show(self, wavelets):
  172. """
  173. Shows the result of filtering
  174. """
  175.  
  176. # Carichiamo la libreria pylab che non abbiamo caricato prima
  177. # perché ci mette un sacco di tempo e non ci server nel caso
  178. # della ricostruzione.
  179. try:
  180. from pylab import show, plot, title, xlabel, ylabel, rcParams
  181.  
  182. params = {
  183. "text.usetex": True,
  184. 'font.family': 'serif',
  185. }
  186.  
  187. rcParams.update(params)
  188.  
  189. except ImportError:
  190. print "Errore nell'importazione della libreria pylab. Installare python-matplotlib"
  191. sys.exit(1)
  192.  
  193.  
  194. # We set the frequency to have seconds (and not samples)
  195. # in the x-axis of the plot.
  196. frequency = float (44100)
  197.  
  198. # We choose a decreasing scale to sync all the samples
  199. # because they are recursively downsamples by a factor
  200. # of two and we want to plot with the same time-scale.
  201. scale = pow(2, wavelets.GetNumSamples ())
  202.  
  203. singleOffset = 2 * wavelets.GetSamplesMaxValue()
  204. offset = -(self.depth / 2) * singleOffset
  205.  
  206. # We plot only the first 60 seconds of audio, to avoid memory
  207. # being flooded with our data :)
  208. toPlot = int(frequency) * 60
  209.  
  210. # Stampo i low
  211. scale = int(0.5 * scale)
  212. low = wavelets.PopLowSamples()
  213. data = low[:toPlot / scale]
  214.  
  215. axes = array(range(0, len(data) * scale, scale)) / frequency
  216.  
  217. plot(axes, data + offset)
  218.  
  219. offset += singleOffset
  220.  
  221. while (wavelets.GetHighSamplesNumber() > 0):
  222.  
  223. samples = wavelets.PopHighSamples ()
  224.  
  225. data = samples[0:toPlot / scale]
  226. axes = array(range(0, len(data) * scale , scale)) / frequency
  227.  
  228. plot (axes, data + offset)
  229. offset += singleOffset
  230. scale = int(0.5*scale)
  231.  
  232.  
  233. # Set some nice text
  234. title (r"Wavelet decomposition using %s filter bank" % self.filterBankName)
  235. xlabel (r"time (s)")
  236.  
  237. show ()
  238.  
  239.  
  240.  
  241.  
  242. if __name__ == "__main__":
  243.  
  244. # Scegliamo cosa fare, a seconda delle opzioni di cui
  245. # abbiamo fatto il parsing più in alto.
  246. # Partiamo.
  247.  
  248. if options.rebuild:
  249. DWT(filename = filename, action = 'rebuild',
  250. filewrite = options.filewrite, depth = options.depth,
  251. filterbank = options.filterbank)
  252.  
  253. elif options.show:
  254. DWT(filename = filename, action = 'show',
  255. depth = options.depth, filterbank = options.filterbank)
  256.  
  257.  
  258.  
  259.  
  260.