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