Ora il programma, se avviato in modo interattivo, controlla prima

Leonardo Robol [2010-03-09 09:58]
Ora il programma, se avviato in modo interattivo, controlla prima
le opzioni e poi carica (eventualmente) tutte le librerie necessarie.
Filename
Filtering/Filtering.py
Filtering/dwt
RefinementEquation/Iteration.py
diff --git a/Filtering/Filtering.py b/Filtering/Filtering.py
index bcbf651..652fca8 100644
--- a/Filtering/Filtering.py
+++ b/Filtering/Filtering.py
@@ -234,10 +234,9 @@ StrangFilterBank.SetLength(3)

 def PRCheck(f):

-    a = (f.lowPassFilter * f.lowPassInverseFilter).GetResponse ()
-    b = (f.highPassFilter*f.highPassInverseFilter).GetResponse ()
-    c = (f.highPassFilter*f.lowPassFilter).GetResponse ()
-    return a, b, c
+    a = 0.5 * (f.lowPassFilter * f.lowPassInverseFilter).GetResponse ()
+    b = 0.5 * (f.highPassFilter * f.highPassInverseFilter).GetResponse ()
+    return a + b


 h0 = StrangFilterBank.lowPassFilter
diff --git a/Filtering/dwt b/Filtering/dwt
index 9e269a3..0ae6b82 100755
--- a/Filtering/dwt
+++ b/Filtering/dwt
@@ -3,15 +3,15 @@
 #

 import sys
+from optparse import OptionParser

 def Output (string):
     """Output with colors :)"""
-    print "\033[32;1m===>\033[0m  %s" % string
+    print "\033[32;1m===>\033[0m %s" % string

 def StartProgram():
     """Starting banner"""
-    print "\033[31;1mDWT\033[0m - Discrete Wavelet transform started"
-    print ""
+    print "\033[31;1m===>\033[0m Discrete Wavelet transform started"

 def EndProgram():
     """End banner"""
@@ -20,16 +20,41 @@ def EndProgram():
 def LoadingLibrariesStarted():
     """Loading libraries banner"""
     if __name__ == "__main__":
-        print ""
-        print "\033[31;1mDWT\033[0m - Loading numeric libraries...",
+        print "\033[31;1m===>\033[0m Loading numeric libraries...",
         sys.stdout.flush ()

 def LoadingLibrariesFinished():
     """Loading libraries finished banner"""
     if __name__ == "__main__":
         print "done"
-
-
+
+
+if __name__ == "__main__":
+
+    parser = OptionParser (usage = "usage: %prog [options] filename")
+    parser.add_option("-r", "--rebuild", dest="rebuild",
+                      default=False, action="store_true",
+                      help="Make DWT and then IDWT")
+    parser.add_option("-w", "--write", dest="filewrite", default='rebuilt.wav',
+                      help="Write reconstructed samples to this file")
+    parser.add_option("-s", "--show", dest="show",
+                      default=True, action="store_true",
+                      help="Show the decomposed waves (this is the default)")
+    parser.add_option("-d", "--depth", dest="depth",
+                      default=4, help="Set the recursion level of the filter bank (default is 4)")
+    parser.add_option("-b", "--filterbank", dest="filterbank", default='haar',
+                      help="Set the filterbank to use in the transform. Valid inputs are 'haar', 'daubechies', 'D4', 'strang'")
+
+
+    (options, args) = parser.parse_args ()
+
+    try:
+        filename = args[0]
+    except:
+        parser.error ("Please a specify a PCM file to read the samples from")
+
+    if (not options.show) and (not options.rebuild):
+        exit

 LoadingLibrariesStarted()

@@ -39,11 +64,11 @@ from pylab import show, plot
 from numpy import array, sqrt, memmap, roll
 from numpy.linalg import norm
 import time
+

-from optparse import OptionParser

 LoadingLibrariesFinished()
-
+

 class DWT():

@@ -82,9 +107,11 @@ class DWT():
             rebuilt = filterBank.Rebuild (wavelets)
             Output ("Rebuilt in %f seconds" % (time.time() - startingTime))

-
-            if norm(rebuilt - samples[0:len(rebuilt)]) > 1E-10:
+            # Se la differenza in norma è più di 10^-6 possiamo preoccuparci.
+            a = norm(rebuilt - samples[0:len(rebuilt)])
+            if (a > 1E-6):
                 Output ("Errore while reconstructing. Rebuilt samples differs from original ones")
+                Output ("||rebuilt - samples|| = %f" % a)
             else:
                 Output ("Perfect reconstruction succeeded")
             self.WriteSamples(rebuilt, filewrite)
@@ -96,10 +123,10 @@ class DWT():
         """
         Load the samples from an audio file
         """
-        Output("Loading samples from %s" % filename)
         samples = memmap (filename,
                           dtype="<h",
                           mode="r")
+        Output("Loaded %d samples from %s" % (len(samples), filename))
         return samples

     def WriteSamples(self, samples, filename):
@@ -122,45 +149,34 @@ class DWT():
         # being flooded with our data :)
         toPlot = 1000000
         for samples in wavelets[0:-1]:
-            plot (range(0, toPlot, scale), samples[0:toPlot / scale] + offset)
+
+            data = samples[0:toPlot / scale]
+            axes = range(0, len(data) * scale , scale)
+
+            plot (axes, data + offset)
             offset += singleOffset
             scale = 2*scale
-        plot ( range(0, toPlot, int(0.5 * scale)), wavelets[-1][:2 * toPlot /scale] + offset)
-        show ()
-
-
-if __name__ == "__main__":

-    parser = OptionParser ()
-    parser.add_option("-f", "--file", dest="filename",default=None,
-                      help="Read samples from this .wav file")
-    parser.add_option("-r", "--rebuild", dest="rebuild",
-                      default=False, action="store_true",
-                      help="Make DWT and then IDWT")
-    parser.add_option("-w", "--write", dest="filewrite", default='rebuilt.wav',
-                      help="Write reconstructed samples to this file")
-    parser.add_option("-s", "--show", dest="show",
-                      default=True, action="store_true",
-                      help="Show the decomposed waves (this is the default)")
-    parser.add_option("-d", "--depth", dest="depth",
-                      default=4, help="Set the recursion level of the filter bank (default is 4)")
-    parser.add_option("-b", "--filterbank", dest="filterbank", default='haar',
-                      help="Set the filterbank to use in the transform. Valid inputs are 'haar', 'daubechies', 'D4', 'strang'")
-
+        # Stampo i low
+        scale = int(0.5 * scale)
+        data = wavelets[-1][:toPlot / scale]
+        axes = range(0, len(data) * scale, scale)

-    (options, args) = parser.parse_args ()
-
-    if options.filename is None:
-        parser.error ("Please a specify a PCM .wav file to read the samples from")
+        plot(axes, data + offset)
+        show ()
+
+
+

+if __name__ == "__main__":

     if options.rebuild:
-        DWT(filename = options.filename, action = 'rebuild',
+        DWT(filename = filename, action = 'rebuild',
             filewrite = options.filewrite, depth = options.depth,
             filterbank = options.filterbank)

     elif options.show:
-        DWT(filename = options.filename, action = 'show',
+        DWT(filename = filename, action = 'show',
             depth = options.depth, filterbank = options.filterbank)


diff --git a/RefinementEquation/Iteration.py b/RefinementEquation/Iteration.py
index 66f4fd1..cc1c69d 100755
--- a/RefinementEquation/Iteration.py
+++ b/RefinementEquation/Iteration.py
@@ -7,14 +7,14 @@
 # associata ad un filtro.

 print " => Carico le librerie necessarie...",
-from matplotlib import pyplot as plot
-import numpy as np
+from pylab import *
+import time, numpy
 print "ok"

 # Si comincia ad iterare
-h = np.array([0.125 , 0.25, 0.25, 0.25, 0.125])
+h = numpy.array([0.125 , 0.25, 0.25, 0.25, 0.125])

-t = np.linspace(-10,10,100)
+t = numpy.linspace(-10,10,100)

 def box(x):
     """box function"""
@@ -43,14 +43,16 @@ def phi_func(x):
              break
     return phi[t.tolist().index(item)]

-
+ion ()
 for i in xrange(0,5):
+    plot(t,phi)
+    draw ()

-
-    plot.plot(t,phi)
+    time.sleep (1)
     phi = map(refinement, t)
-
-
-plot.show ()
+
+
+raw_input ()
+

ViewGit