Revision: 6044
          http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6044&view=rev
Author:   fer_perez
Date:     2008-08-19 09:35:03 +0000 (Tue, 19 Aug 2008)

Log Message:
-----------
Update examples and skeletons in py4science.

- Fixes after previous feedback so they are all syntactically correct.

- Switch to using nose instead of unittest for an eaiser workflow.

Modified Paths:
--------------
    trunk/py4science/examples/fft_imdenoise.py
    trunk/py4science/examples/qsort.py
    trunk/py4science/examples/skel/fft_imdenoise_skel.py
    trunk/py4science/examples/skel/qsort_skel.py
    trunk/py4science/examples/skel/trapezoid_skel.py
    trunk/py4science/examples/skel/wallis_pi_skel.py
    trunk/py4science/examples/skel/wordfreqs_skel.py
    trunk/py4science/examples/trapezoid.py

Modified: trunk/py4science/examples/fft_imdenoise.py
===================================================================
--- trunk/py4science/examples/fft_imdenoise.py  2008-08-18 21:06:56 UTC (rev 
6043)
+++ trunk/py4science/examples/fft_imdenoise.py  2008-08-19 09:35:03 UTC (rev 
6044)
@@ -20,58 +20,64 @@
     print M.shape, M.dtype
     plt.imshow(M, plt.cm.Blues)
 
-try:
-    # Read in original image, convert to floating point for further
-    # manipulation; imread returns a MxNx4 RGBA image.  Since the
-    # image is grayscale, just extrac the 1st channel
-    im = plt.imread('data/moonlanding.png').astype(float)[:,:,0]
-except:
-    print "Could not open image."
-    sys.exit(-1)
 
-# Compute the 2d FFT of the input image
-F = np.fft.fft2(im)
+if __name__ == '__main__':
 
-# Now, make a copy of the original spectrum and truncate coefficients.
-keep_fraction = 0.1
+    try:
+        # Read in original image, convert to floating point for further
+        # manipulation; imread returns a MxNx4 RGBA image.  Since the image is
+        # grayscale, just extrac the 1st channel
+        im = plt.imread('data/moonlanding.png').astype(float)[:,:,0]
+    except:
+        print "Could not open image."
+        sys.exit(-1)
 
-# Call ff a copy of the original transform.  Numpy arrays have a copy method
-# for this purpose.
-ff = F.copy()
+    # Compute the 2d FFT of the input image
+    F = np.fft.fft2(im)
 
-# Set r and c to be the number of rows and columns of the array.  
-r,c = ff.shape
+    # Now, make a copy of the original spectrum and truncate coefficients.
+    keep_fraction = 0.1
 
-# Set to zero all rows with indices between r*keep_fraction and
-# r*(1-keep_fraction):
-ff[r*keep_fraction:r*(1-keep_fraction)] = 0
+    # Call ff a copy of the original transform.  Numpy arrays have a copy
+    # method for this purpose.
+    ff = F.copy()
 
-# Similarly with the columns:
-ff[:, c*keep_fraction:c*(1-keep_fraction)] = 0
+    # Set r and c to be the number of rows and columns of the array.  
+    r,c = ff.shape
 
-# Reconstruct the denoised image from the filtered spectrum, keep only the real
-# part for display
-im_new = np.fft.ifft2(ff).real
+    # Set to zero all rows with indices between r*keep_fraction and
+    # r*(1-keep_fraction):
+    ff[r*keep_fraction:r*(1-keep_fraction)] = 0
 
-# Show the results
-plt.figure()
+    # Similarly with the columns:
+    ff[:, c*keep_fraction:c*(1-keep_fraction)] = 0
 
-plt.subplot(221)
-plt.title('Original image')
-plt.imshow(im, plt.cm.gray)
+    # Reconstruct the denoised image from the filtered spectrum, keep only the
+    # real part for display
+    im_new = np.fft.ifft2(ff).real
 
-plt.subplot(222)
-plt.title('Fourier transform')
-plot_spectrum(F)
+    # Show the results
+    plt.figure()
 
-plt.subplot(224)
-plt.title('Filtered Spectrum')
-plot_spectrum(ff)
+    plt.subplot(221)
+    plt.title('Original image')
+    plt.imshow(im, plt.cm.gray)
 
-plt.subplot(223)
-plt.title('Reconstructed Image')
-plt.imshow(im_new, plt.cm.gray)
+    plt.subplot(222)
+    plt.title('Fourier transform')
+    plot_spectrum(F)
 
-plt.savefig('fft_imdenoise.png', dpi=150)
-plt.savefig('fft_imdenoise.eps')
-plt.show()
+    plt.subplot(224)
+    plt.title('Filtered Spectrum')
+    plot_spectrum(ff)
+
+    plt.subplot(223)
+    plt.title('Reconstructed Image')
+    plt.imshow(im_new, plt.cm.gray)
+
+    plt.savefig('fft_imdenoise.png', dpi=150)
+    plt.savefig('fft_imdenoise.eps')
+
+    # Adjust the spacing between subplots for readability 
+    plt.subplots_adjust(hspace=0.32)
+    plt.show()

Modified: trunk/py4science/examples/qsort.py
===================================================================
--- trunk/py4science/examples/qsort.py  2008-08-18 21:06:56 UTC (rev 6043)
+++ trunk/py4science/examples/qsort.py  2008-08-19 09:35:03 UTC (rev 6044)
@@ -18,22 +18,28 @@
     
     return qsort(less_than) + [pivot] + qsort(greater_equal)
 
-if __name__ == '__main__':
-    from unittest import main, TestCase
-    import random
 
-    class qsortTestCase(TestCase):
-        def test_sorted(self):
-            seq = range(10)
-            sseq = qsort(seq)
-            self.assertEqual(seq,sseq)
+#-----------------------------------------------------------------------------
+# Tests
+#-----------------------------------------------------------------------------
+import random
 
-        def test_random(self):
-            tseq = range(10)
-            rseq = range(10)
-            random.shuffle(rseq)
-            sseq = qsort(rseq)
-            print tseq
-            print sseq
-            self.assertEqual(tseq,sseq)
-    main()
+import nose, nose.tools as nt
+
+def test_sorted():
+    seq = range(10)
+    sseq = qsort(seq)
+    nt.assert_equal(seq,sseq)
+
+def test_random():
+    tseq = range(10)
+    rseq = range(10)
+    random.shuffle(rseq)
+    sseq = qsort(rseq)
+    nt.assert_equal(tseq,sseq)
+
+# If called from the command line, run all the tests
+if __name__ == '__main__':
+    # This call form is ipython-friendly
+    nose.runmodule(argv=['-s','--with-doctest'],
+                   exit=False)

Modified: trunk/py4science/examples/skel/fft_imdenoise_skel.py
===================================================================
--- trunk/py4science/examples/skel/fft_imdenoise_skel.py        2008-08-18 
21:06:56 UTC (rev 6043)
+++ trunk/py4science/examples/skel/fft_imdenoise_skel.py        2008-08-19 
09:35:03 UTC (rev 6044)
@@ -1,10 +1,11 @@
 #!/usr/bin/env python
 """Image denoising example using 2-dimensional FFT."""
 
-import numpy as N
-import pylab as P
-import scipy as S
+XXX = None # a sentinel for missing pieces
 
+import numpy as np
+from matplotlib import pyplot as plt
+
 def mag_phase(F):
     """Return magnitude and phase components of spectrum F."""
 
@@ -13,7 +14,7 @@
 def plot_spectrum(F, amplify=1000):
     """Normalise, amplify and plot an amplitude spectrum."""
 
-    M = # XXX use mag_phase to get the magnitude...
+    M = XXX # use mag_phase to get the magnitude...
 
     # XXX Now, rescale M by amplify/maximum_of_M.  Numpy arrays can be scaled
     # in-place with ARR *= number.  For the max of an array, look for its max
@@ -25,56 +26,58 @@
 
 
     # Display: this one already works, if you did everything right with M
-    P.imshow(M, P.cm.Blues)
+    plt.imshow(M, plt.cm.Blues)
 
 
-# 'main' script
+if __name__ == '__main__':
 
+    im = XXX # make an image array from the file 'moonlanding.png', using the
+         # pylab imread() function.  You will need to just extract the red
+         # channel from the MxNx4 RGBA matrix to represent the grayscale
+         # intensities
 
-im = # XXX make an image array from the file 'moonlanding.png', using the
-     # pylab imread() function.  You will need to just extract the red
-     # channel from the MxNx4 RGBA matrix to represent the grayscale
-     # intensities
+    F = XXX # Compute the 2d FFT of the input image.  Look for a 2-d FFT in
+            # np.fft.
 
-F = # Compute the 2d FFT of the input image.  Look for a 2-d FFT in N.fft.
+    # Define the fraction of coefficients (in each direction) we keep
+    keep_fraction = 0.1
 
-# Define the fraction of coefficients (in each direction) we keep
-keep_fraction = 0.1
+    # XXX Call ff a copy of the original transform.  Numpy arrays have a copy
+    # method for this purpose.
 
-# XXX Call ff a copy of the original transform.  Numpy arrays have a copy 
method
-# for this purpose.
+    # XXX Set r and c to be the number of rows and columns of the array.  Look
+    # for the shape attribute...
 
-# XXX Set r and c to be the number of rows and columns of the array.  Look for
-# the shape attribute...
+    # Set to zero all rows with indices between r*keep_fraction and
+    # r*(1-keep_fraction):
 
-# Set to zero all rows with indices between r*keep_fraction and
-# r*(1-keep_fraction):
+    # Similarly with the columns:
 
-# Similarly with the columns:
 
+    # Reconstruct the denoised image from the filtered spectrum.  There's an
+    # inverse 2d fft in the dft module as well. Call the result im_new
 
-# Reconstruct the denoised image from the filtered spectrum.  There's an
-# inverse 2d fft in the dft module as well. Call the result im_new
+    # Show the results.
 
-# Show the results.
+    # The code below already works, if you did everything above right.
+    plt.figure()
 
-# The code below already works, if you did everything above right.
-P.figure()
+    plt.subplot(221)
+    plt.title('Original image')
+    plt.imshow(im, plt.cm.gray)
 
-P.subplot(221)
-P.title('Original image')
-P.imshow(im, P.cm.gray)
+    plt.subplot(222)
+    plt.title('Fourier transform')
+    plot_spectrum(F)
 
-P.subplot(222)
-P.title('Fourier transform')
-plot_spectrum(F)
+    plt.subplot(224)
+    plt.title('Filtered Spectrum')
+    plot_spectrum(ff)
 
-P.subplot(224)
-P.title('Filtered Spectrum')
-plot_spectrum(ff)
+    plt.subplot(223)
+    plt.title('Reconstructed Image')
+    plt.imshow(im_new, plt.cm.gray)
 
-P.subplot(223)
-P.title('Reconstructed Image')
-P.imshow(im_new, P.cm.gray)
-
-P.show()
+    # Adjust the spacing between subplots for readability
+    plt.subplots_adjust(hspace=0.32)
+    plt.show()

Modified: trunk/py4science/examples/skel/qsort_skel.py
===================================================================
--- trunk/py4science/examples/skel/qsort_skel.py        2008-08-18 21:06:56 UTC 
(rev 6043)
+++ trunk/py4science/examples/skel/qsort_skel.py        2008-08-19 09:35:03 UTC 
(rev 6044)
@@ -1,24 +1,45 @@
-"""Simple quicksort implementation."""
+"""Simple quicksort implementation.
 
+From http://en.wikipedia.org/wiki/Quicksort:
+
+function quicksort(array)
+     var list less, greater
+     if length(array) ≤ 1  
+         return array  
+     select and remove a pivot value pivot from array
+     for each x in array
+         if x ≤ pivot then append x to less
+         else append x to greater
+     return concatenate(quicksort(less), pivot, quicksort(greater))
+"""
+
 def qsort(lst):
     """Return a sorted copy of the input list."""
 
     raise NotImplementedError
 
-if __name__ == '__main__':
-    from unittest import main, TestCase
-    import random
+#-----------------------------------------------------------------------------
+# Tests
+#-----------------------------------------------------------------------------
+import random
 
-    class qsortTestCase(TestCase):
-        def test_sorted(self):
-            seq = range(10)
-            sseq = qsort(seq)
-            self.assertEqual(seq,sseq)
+import nose.tools as nt
 
-        def test_random(self):
-            tseq = range(10)
-            rseq = range(10)
-            random.shuffle(rseq)
-            sseq = qsort(rseq)
-            self.assertEqual(tseq,sseq)
-    main()
+def test_sorted():
+    seq = range(10)
+    sseq = qsort(seq)
+    nt.assert_equal(seq,sseq)
+
+def test_random():
+    tseq = range(10)
+    rseq = range(10)
+    random.shuffle(rseq)
+    sseq = qsort(rseq)
+    nt.assert_equal(tseq,sseq)
+
+if __name__ == '__main__':
+    # From the command line, run the test suite
+    import nose
+    # This call form is ipython-friendly
+    nose.runmodule(argv=['-s','--with-doctest'],
+                   exit=False)

Modified: trunk/py4science/examples/skel/trapezoid_skel.py
===================================================================
--- trunk/py4science/examples/skel/trapezoid_skel.py    2008-08-18 21:06:56 UTC 
(rev 6043)
+++ trunk/py4science/examples/skel/trapezoid_skel.py    2008-08-19 09:35:03 UTC 
(rev 6044)
@@ -39,29 +39,32 @@
     # x?
     raise NotImplementedError
 
-if __name__ == '__main__':
-    # Simple tests for trapezoid integrator, when this module is called as a
-    # script from the command line.
 
-    import unittest
-    import numpy.testing as ntest
+#-----------------------------------------------------------------------------
+# Tests
+#-----------------------------------------------------------------------------
+import nose, nose.tools as nt
+import numpy.testing as nptest
 
-    def square(x): return x**2
+def square(x): return x**2
 
-    class trapzTestCase(unittest.TestCase):
-        def test_err(self):
-            self.assertRaises(ValueError,trapz,range(2),range(3))
+def test_err():
+    nt.assert_raises(ValueError,trapz,range(2),range(3))
 
-        def test_call(self):
-            x = N.linspace(0,1,100)
-            y = N.array(map(square,x))
-            ntest.assert_almost_equal(trapz(x,y),1./3,4)
+def test_call():
+    x = np.linspace(0,1,100)
+    y = np.array(map(square,x))
+    nptest.assert_almost_equal(trapz(x,y),1./3,4)
 
-    class trapzfTestCase(unittest.TestCase):
-        def test_square(self):
-            ntest.assert_almost_equal(trapzf(square,0,1),1./3,4)
+def test_square():
+    nptest.assert_almost_equal(trapzf(square,0,1),1./3,4)
 
-        def test_square2(self):
-            ntest.assert_almost_equal(trapzf(square,0,3,350),9.0,4)
+def test_square2():
+    nptest.assert_almost_equal(trapzf(square,0,3,350),9.0,4)
 
-    unittest.main()
+
+# If called from the command line, run all the tests
+if __name__ == '__main__':
+    # This call form is ipython-friendly
+    nose.runmodule(argv=['-s','--with-doctest'],
+                   exit=False)

Modified: trunk/py4science/examples/skel/wallis_pi_skel.py
===================================================================
--- trunk/py4science/examples/skel/wallis_pi_skel.py    2008-08-18 21:06:56 UTC 
(rev 6043)
+++ trunk/py4science/examples/skel/wallis_pi_skel.py    2008-08-19 09:35:03 UTC 
(rev 6044)
@@ -8,6 +8,8 @@
 
 from decimal import Decimal
 
+XXX = None # a sentinel for missing pieces
+
 def pi(n):
     """Compute pi using n terms of Wallis' product.
 
@@ -15,7 +17,7 @@
 
     pi(n) = 2 \prod_{i=1}^{n}\frac{4i^2}{4i^2-1}."""
 
-    XXX
+    raise NotImplementedError
     
 # This part only executes when the code is run as a script, not when it is
 # imported as a library

Modified: trunk/py4science/examples/skel/wordfreqs_skel.py
===================================================================
--- trunk/py4science/examples/skel/wordfreqs_skel.py    2008-08-18 21:06:56 UTC 
(rev 6043)
+++ trunk/py4science/examples/skel/wordfreqs_skel.py    2008-08-19 09:35:03 UTC 
(rev 6044)
@@ -1,10 +1,14 @@
 #!/usr/bin/env python
 """Word frequencies - count word frequencies in a string."""
 
+XXX = None # a sentinel for missing pieces
+
 def word_freq(text):
     """Return a dictionary of word frequencies for the given text."""
-    # XXX you need to write this
+    # you need to write this
+    return XXX
 
+
 def print_vk(lst):
     """Print a list of value/key pairs nicely formatted in key/value order."""
 
@@ -17,6 +21,7 @@
     for v,k in lst:
         print fmt % (k,v)
 
+
 def freq_summ(freqs,n=10):
     """Print a simple summary of a word frequencies dictionary.
 
@@ -26,10 +31,10 @@
     Optional inputs:
       - n: the number of items to print"""
 
-    words,counts = # XXX look at the keys and values methods of dicts
+    words,counts =  XXX # look at the keys and values methods of dicts
     # Sort by count
     
-    items = # XXX think of a list, look at zip() and think of sort()
+    items =  XXX # think of a list, look at zip() and think of sort()
 
     print 'Number of words:',len(freqs)
     print
@@ -39,10 +44,12 @@
     print '%d most frequent words:' % n
     print_vk(items[-n:])
 
+
 if __name__ == '__main__':
-    text = # XXX
-    # You need to read the contents of the file HISTORY.gz.  Do NOT unzip it
-    # manually, look at the gzip module from the standard library and  the
-    # read() method of file objects.
+    # You need to read the contents of the file HISTORY.gz and store it in the
+    # variable named 'text'.  Do NOT unzip it manually, look at the gzip module
+    # from the standard library and the read() method of file objects.
+    text =  XXX
+    
     freqs = word_freq(text)
     freq_summ(freqs,20)

Modified: trunk/py4science/examples/trapezoid.py
===================================================================
--- trunk/py4science/examples/trapezoid.py      2008-08-18 21:06:56 UTC (rev 
6043)
+++ trunk/py4science/examples/trapezoid.py      2008-08-19 09:35:03 UTC (rev 
6044)
@@ -1,7 +1,7 @@
 #!/usr/bin/env python
 """Simple trapezoid-rule integrator."""
 
-import numpy as N
+import numpy as np
 
 def trapz(x, y):
     """Simple trapezoid integrator for sequence-based innput.
@@ -40,43 +40,41 @@
       - The value of the trapezoid-rule approximation to the integral."""
 
     # Generate an equally spaced grid to sample the function at
-    x = N.linspace(a,b,npts)
+    x = np.linspace(a,b,npts)
     # For an equispaced grid, the x spacing can just be read off from the first
     # two points and factored out of the summation.
     dx = x[1]-x[0]
     # Sample the input function at all values of x
-    y = N.array(map(f,x))
+    y = np.array(map(f,x))
     # Compute the trapezoid rule sum for the final result
     return 0.5*dx*(y[1:]+y[:-1]).sum()
 
-if __name__ == '__main__':
-    # Simple tests for trapezoid integrator, when this module is called as a
-    # script from the command line.  From ipython, run it via:
-    #
-    # run -e trapezoid
-    #
-    # so that ipython ignores the SystemExit exception automatically raised by
-    # the unittest module at the end.
 
-    import unittest
-    import numpy.testing as ntest
+#-----------------------------------------------------------------------------
+# Tests
+#-----------------------------------------------------------------------------
+import nose, nose.tools as nt
+import numpy.testing as nptest
 
-    def square(x): return x**2
+def square(x): return x**2
 
-    class trapzTestCase(unittest.TestCase):
-        def test_err(self):
-            self.assertRaises(ValueError,trapz,range(2),range(3))
+def test_err():
+    nt.assert_raises(ValueError,trapz,range(2),range(3))
 
-        def test_call(self):
-            x = N.linspace(0,1,100)
-            y = N.array(map(square,x))
-            ntest.assert_almost_equal(trapz(x,y),1./3,4)
+def test_call():
+    x = np.linspace(0,1,100)
+    y = np.array(map(square,x))
+    nptest.assert_almost_equal(trapz(x,y),1./3,4)
 
-    class trapzfTestCase(unittest.TestCase):
-        def test_square(self):
-            ntest.assert_almost_equal(trapzf(square,0,1),1./3,4)
+def test_square():
+    nptest.assert_almost_equal(trapzf(square,0,1),1./3,4)
 
-        def test_square2(self):
-            ntest.assert_almost_equal(trapzf(square,0,3,350),9.0,4)
+def test_square2():
+    nptest.assert_almost_equal(trapzf(square,0,3,350),9.0,4)
 
-    unittest.main()
+
+# If called from the command line, run all the tests
+if __name__ == '__main__':
+    # This call form is ipython-friendly
+    nose.runmodule(argv=['-s','--with-doctest'],
+                   exit=False)


This was sent by the SourceForge.net collaborative development platform, the 
world's largest Open Source development site.

-------------------------------------------------------------------------
This SF.Net email is sponsored by the Moblin Your Move Developer's challenge
Build the coolest Linux based applications with Moblin SDK & win great prizes
Grand prize is a trip for two to an Open Source event anywhere in the world
http://moblin-contest.org/redirect.php?banner_id=100&url=/
_______________________________________________
Matplotlib-checkins mailing list
Matplotlib-checkins@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-checkins

Reply via email to