|
From: <fer...@us...> - 2008-08-19 09:35:08
|
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.
|
|
From: <fer...@us...> - 2008-10-08 04:07:40
|
Revision: 6167
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6167&view=rev
Author: fer_perez
Date: 2008-10-08 04:07:21 +0000 (Wed, 08 Oct 2008)
Log Message:
-----------
Major rework of the sphinx template.
I'm committing this as a separate directory because I changed way too
much of the original code and I want to make sure others can have a
look before removing the old code.
Added Paths:
-----------
trunk/py4science/examples/sphinx_template2/
trunk/py4science/examples/sphinx_template2/Makefile
trunk/py4science/examples/sphinx_template2/README.txt
trunk/py4science/examples/sphinx_template2/conf.py
trunk/py4science/examples/sphinx_template2/index.rst
trunk/py4science/examples/sphinx_template2/model/
trunk/py4science/examples/sphinx_template2/model/api_docs.rst
trunk/py4science/examples/sphinx_template2/model/index.rst
trunk/py4science/examples/sphinx_template2/model/introduction.rst
trunk/py4science/examples/sphinx_template2/model/next_steps.rst
trunk/py4science/examples/sphinx_template2/model/sphinx_helpers.rst
trunk/py4science/examples/sphinx_template2/pyplots/
trunk/py4science/examples/sphinx_template2/pyplots/elegant.py
trunk/py4science/examples/sphinx_template2/pyplots/hairy.py
trunk/py4science/examples/sphinx_template2/simulations/
trunk/py4science/examples/sphinx_template2/simulations/finale.rst
trunk/py4science/examples/sphinx_template2/simulations/index.rst
trunk/py4science/examples/sphinx_template2/simulations/introduction.rst
trunk/py4science/examples/sphinx_template2/simulations/preliminary.rst
trunk/py4science/examples/sphinx_template2/tools/
trunk/py4science/examples/sphinx_template2/tools/sphinxext/
trunk/py4science/examples/sphinx_template2/tools/sphinxext/inheritance_diagram.py
trunk/py4science/examples/sphinx_template2/tools/sphinxext/ipython_console_highlighting.py
trunk/py4science/examples/sphinx_template2/tools/sphinxext/mathmpl.py
trunk/py4science/examples/sphinx_template2/tools/sphinxext/only_directives.py
trunk/py4science/examples/sphinx_template2/tools/sphinxext/plot_directive.py
trunk/py4science/examples/sphinx_template2/tools/static/
trunk/py4science/examples/sphinx_template2/tools/templates/
Added: trunk/py4science/examples/sphinx_template2/Makefile
===================================================================
--- trunk/py4science/examples/sphinx_template2/Makefile (rev 0)
+++ trunk/py4science/examples/sphinx_template2/Makefile 2008-10-08 04:07:21 UTC (rev 6167)
@@ -0,0 +1,89 @@
+# Makefile for Sphinx documentation
+#
+
+PDFNAME=sampledoc
+SRCDIR=.
+
+# You can set these variables from the command line.
+SPHINXOPTS =
+SPHINXBUILD = sphinx-build
+PAPER = letter
+
+# Internal variables.
+PAPEROPT_a4 = -D latex_paper_size=a4
+PAPEROPT_letter = -D latex_paper_size=letter
+ALLSPHINXOPTS = -d build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) $(SRCDIR)
+
+.PHONY: help clean html web pickle htmlhelp latex changes linkcheck pdf all dist
+
+help:
+ @echo "Please use \`make <target>' where <target> is one of"
+ @echo " html to make standalone HTML files"
+ @echo " pickle to make pickle files (usable by e.g. sphinx-web)"
+ @echo " htmlhelp to make HTML files and a HTML help project"
+ @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
+ @echo " changes to make an overview over all changed/added/deprecated items"
+ @echo " linkcheck to check all external links for integrity"
+ @echo
+ @echo "Compound utility targets:"
+ @echo " pdf latex and then runs the PDF generation"
+ @echo " all html and pdf"
+ @echo " dist all, and then puts the results in dist/"
+
+clean:
+ -rm -rf build/ dist/ _static/ pyplots/*png pyplots/*pdf
+
+pdf: latex
+ cd build/latex && make all-pdf
+
+all: html pdf
+
+dist: clean all
+ mkdir -p dist
+ ln build/latex/$(PDFNAME).pdf dist/
+ cp -al build/html dist/
+ @echo "Build finished. Final docs are in dist/"
+
+html:
+ mkdir -p build/html build/doctrees
+ $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html
+ @echo
+ @echo "Build finished. The HTML pages are in build/html."
+
+pickle:
+ mkdir -p build/pickle build/doctrees
+ $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) build/pickle
+ @echo
+ @echo "Build finished; now you can process the pickle files or run"
+ @echo " sphinx-web build/pickle"
+ @echo "to start the sphinx-web server."
+
+web: pickle
+
+htmlhelp:
+ mkdir -p build/htmlhelp build/doctrees
+ $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) build/htmlhelp
+ @echo
+ @echo "Build finished; now you can run HTML Help Workshop with the" \
+ ".hhp project file in build/htmlhelp."
+
+latex:
+ mkdir -p build/latex build/doctrees
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) build/latex
+ @echo
+ @echo "Build finished; the LaTeX files are in build/latex."
+ @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
+ "run these through (pdf)latex."
+
+changes:
+ mkdir -p build/changes build/doctrees
+ $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) build/changes
+ @echo
+ @echo "The overview file is in build/changes."
+
+linkcheck:
+ mkdir -p build/linkcheck build/doctrees
+ $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) build/linkcheck
+ @echo
+ @echo "Link check complete; look for any errors in the above output " \
+ "or in build/linkcheck/output.txt."
Added: trunk/py4science/examples/sphinx_template2/README.txt
===================================================================
--- trunk/py4science/examples/sphinx_template2/README.txt (rev 0)
+++ trunk/py4science/examples/sphinx_template2/README.txt 2008-10-08 04:07:21 UTC (rev 6167)
@@ -0,0 +1,54 @@
+===========================
+ sphinx template sampledoc
+===========================
+
+This is the top level build directory for the sphinx "sampledoc" documentation.
+You can use this as a starter template for your own projects. The name
+"sampledoc" is the mock name for the project, you'll need to configure this for
+your needs by editing the conf.py and index.rst files.
+
+All of the documentation is written using reStructuredText and is meant to be
+built Sphinx, a python documentation system built on top of ReST. As of Python
+2.6, Sphinx is the default docuentation system for Python itself, and it is
+becoming rapidly adopted by multiple projects.
+
+This directory contains:
+
+* index.rst - the top level include document for your project.
+
+* conf.py - the sphinx configuration file. You need to edit this file to set
+ your project name, authors, etc.
+
+* Makefile - just type 'make' to see a list of available targets.
+
+* model - A directory for a mock document describing a model. Be sure to see
+ the cheat sheet file "model/sphinx_helpers.rst".
+
+* simulations - A directory for another mock part of your project.
+
+* pyplots - a directory with matplotlib scripts to generate figures that can be
+ included in your document with the 'plot' directive. See the
+ sphinx_helpers.rst file for details.
+
+* tools - a directory that contains:
+
+ * sphinxext - some extensions to sphinx to handle math, ipython syntax
+ highlighting, autodocs.
+
+ * static - directory where you can put your static content, meant to be
+ copied on output by Sphinx into the top-level _static directory. This is
+ never overwritten, so you can keep static CSS files, etc here, that can
+ then override the Sphinx ones.
+
+ * templates - directory for your own templates, also used by sphinx.
+
+
+Note: The makefile and sphinx build system create three directories when
+bulding the output, named ``build``, ``dist`` and ``_static``. Do *not* make
+directories with these names as part of your project, to avoid possible
+conflicts.
+
+
+You can get the latest svn of this document with::
+
+ svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/py4science/examples/sphinx_template2
Added: trunk/py4science/examples/sphinx_template2/conf.py
===================================================================
--- trunk/py4science/examples/sphinx_template2/conf.py (rev 0)
+++ trunk/py4science/examples/sphinx_template2/conf.py 2008-10-08 04:07:21 UTC (rev 6167)
@@ -0,0 +1,177 @@
+# -*- coding: utf-8 -*-
+#
+# sampledoc documentation build configuration file, created by
+# sphinx-quickstart on Tue Jun 3 12:40:24 2008.
+#
+# This file is execfile()d with the current directory set to its containing dir.
+#
+# The contents of this file are pickled, so don't put values in the namespace
+# that aren't pickleable (module imports are okay, they're removed automatically).
+#
+# All configuration values have a default value; values that are commented out
+# serve to show the default value.
+
+import sys, os
+
+# If your extensions are in another directory, add it here. If the directory
+# is relative to the documentation root, use os.path.abspath to make it
+# absolute, like shown here.
+sys.path.append(os.path.abspath('tools/sphinxext'))
+
+
+# Import support for ipython console session syntax highlighting (lives
+# in the sphinxext directory defined above)
+import ipython_console_highlighting
+
+# General configuration
+# ---------------------
+
+# Add any Sphinx extension module names here, as strings. They can be extensions
+# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+extensions = [#'mathmpl',
+ 'ipython_console_highlighting', 'sphinx.ext.autodoc',
+ 'inheritance_diagram', 'only_directives', 'plot_directive',
+ 'sphinx.ext.pngmath',
+ ]
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['tools/templates']
+
+# The suffix of source filenames.
+source_suffix = '.rst'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General substitutions.
+project = 'sampledoc'
+copyright = '2008, John D. Hunter, Cast of Thousands'
+
+# The default replacements for |version| and |release|, also used in various
+# other places throughout the built documents.
+#
+# The short X.Y version.
+version = '0.2'
+# The full version, including alpha/beta/rc tags.
+release = '0.2'
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+today_fmt = '%B %d, %Y'
+
+# List of documents that shouldn't be included in the build.
+#unused_docs = []
+
+# List of directories, relative to source directories, that shouldn't be
+# searched for source files.
+#exclude_dirs = []
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+#add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+#show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'sphinx'
+
+
+# Options for HTML output
+# -----------------------
+
+# The style sheet to use for HTML and HTML Help pages. A file of that name
+# must exist either in Sphinx' static/ path, or in one of the custom paths
+# given in html_static_path.
+html_style = 'default.css'
+
+# The name for this set of Sphinx documents. If None, it defaults to
+# "<project> v<release> documentation".
+#html_title = None
+
+# The name of an image file (within the static path) to place at the top of
+# the sidebar.
+#html_logo = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['tools/static','_static']
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+#html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+#html_use_modindex = True
+
+# If true, the reST sources are included in the HTML build as _sources/<name>.
+#html_copy_source = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a <link> tag referring to it. The value of this option must be the
+# base URL from which the finished HTML is served.
+#html_use_opensearch = ''
+
+# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
+#html_file_suffix = ''
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = project
+
+
+# Options for LaTeX output
+# ------------------------
+
+# The paper size ('letter' or 'a4').
+#latex_paper_size = 'letter'
+
+# The font size ('10pt', '11pt' or '12pt').
+#latex_font_size = '10pt'
+
+# Grouping the document tree into LaTeX files. List of tuples (source start
+# file, target name, title, author, document class [howto/manual]).
+
+main_manual_tex = project + '.tex'
+
+latex_documents = [
+ (master_doc,
+ main_manual_tex,
+ 'sampledoc Documentation',
+ 'John D. Hunter, Cast of Thousands',
+ 'manual'),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+#latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+#latex_use_parts = False
+
+# Additional stuff for the LaTeX preamble.
+#latex_preamble = ''
+
+# Documents to append as an appendix to all manuals.
+#latex_appendices = []
+
+# If false, no module index is generated.
+#latex_use_modindex = True
Added: trunk/py4science/examples/sphinx_template2/index.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/index.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template2/index.rst 2008-10-08 04:07:21 UTC (rev 6167)
@@ -0,0 +1,25 @@
+.. sampledoc documentation master file
+ You can adapt this file completely to your liking, but it should at least
+ contain the root `toctree` directive.
+
+Welcome to sampledoc's documentation!
+=====================================
+
+.. htmlonly::
+
+ :Release: |version|
+ :Date: |today|
+
+.. toctree::
+ :maxdepth: 2
+
+ model/index.rst
+ simulations/index.rst
+
+
+.. htmlonly::
+
+ * :ref:`genindex`
+ * :ref:`modindex`
+ * :ref:`search`
+
Added: trunk/py4science/examples/sphinx_template2/model/api_docs.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/model/api_docs.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template2/model/api_docs.rst 2008-10-08 04:07:21 UTC (rev 6167)
@@ -0,0 +1,16 @@
+.. _samplecode-api:
+
+**************
+Samplecode API
+**************
+
+It is easy to autodocument API code if the code has REST docstrings
+using the sphinx `autodoc <http://sphinx.pocoo.org/ext/autodoc.html>`_
+facilities.
+
+:mod:`matplotlib.backend_bases`
+================================
+
+.. automodule:: matplotlib.backend_bases
+ :members:
+ :undoc-members:
Added: trunk/py4science/examples/sphinx_template2/model/index.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/model/index.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template2/model/index.rst 2008-10-08 04:07:21 UTC (rev 6167)
@@ -0,0 +1,13 @@
+.. _model-index:
+
+================
+ My Fancy Model
+================
+
+.. toctree::
+
+ introduction.rst
+ next_steps.rst
+ sphinx_helpers.rst
+ api_docs.rst
+
\ No newline at end of file
Added: trunk/py4science/examples/sphinx_template2/model/introduction.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/model/introduction.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template2/model/introduction.rst 2008-10-08 04:07:21 UTC (rev 6167)
@@ -0,0 +1,30 @@
+.. _model-introduction:
+
+******************
+Model Introduction
+******************
+
+Wherein I describe my fancy model :math:`E=MC^2`
+and also
+
+.. math::
+
+ \frac{5 - \frac{1}{x}}{4}
+
+For more details, see :ref:`using-math`.
+
+.. _other-models:
+
+Other Models
+============
+
+Where in I describe
+
+* model A
+
+* model B
+
+* model C
+
+and why they all suck
+
Added: trunk/py4science/examples/sphinx_template2/model/next_steps.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/model/next_steps.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template2/model/next_steps.rst 2008-10-08 04:07:21 UTC (rev 6167)
@@ -0,0 +1,8 @@
+.. _next-steps:
+
+**********
+Next steps
+**********
+
+Wherein I describe my next steps
+
Added: trunk/py4science/examples/sphinx_template2/model/sphinx_helpers.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/model/sphinx_helpers.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template2/model/sphinx_helpers.rst 2008-10-08 04:07:21 UTC (rev 6167)
@@ -0,0 +1,220 @@
+.. _sphinx_helpers:
+
+******************
+Sphinx Cheat Sheet
+******************
+
+Wherein I show by example how to do some things in Sphinx (you can see
+a literal version of this file below in :ref:`sphinx-literal`)
+
+
+.. _making-a-list:
+
+Making a list
+=============
+
+It is easy to make lists in rest
+
+Bullet points
+-------------
+
+This is a subsection making bullet points
+
+* point A
+
+* point B
+
+* point C
+
+
+Enumerated points
+------------------
+
+This is a subsection making numbered points
+
+#. point A
+
+#. point B
+
+#. point C
+
+
+.. _making-a-table:
+
+Making a table
+==============
+
+This shows you how to make a table -- if you only want to make a list see :ref:`making-a-list`.
+
+================== ============
+Name Age
+================== ============
+John D Hunter 40
+Cast of Thousands 41
+And Still More 42
+================== ============
+
+.. _making-links:
+
+Making links
+============
+
+It is easy to make a link to `yahoo <http://yahoo.com>`_ or to some
+section inside this document (see :ref:`making-a-table`) or another
+document (see :ref:`final-results`).
+
+You can also reference classes, modules, functions, etc that are
+documented using the sphinx `autodoc
+<http://sphinx.pocoo.org/ext/autodoc.html>`_ facilites. For example,
+see the module :mod:`matplotlib.backend_bases` documentation, or the
+class :class:`~matplotlib.backend_bases.LocationEvent`, or the method
+:meth:`~matplotlib.backend_bases.FigureCanvasBase.mpl_connect`.
+
+.. _ipython-highlighting:
+
+ipython sessions
+================
+
+Michael Droettboom contributed a sphinx extension which does pygments
+syntax highlighting on ipython sessions
+
+.. sourcecode:: ipython
+
+ In [69]: lines = plot([1,2,3])
+
+ In [70]: setp(lines)
+ alpha: float
+ animated: [True | False]
+ antialiased or aa: [True | False]
+ ...snip
+
+This support is included in this template, but will also be included
+in a future version of Pygments by default.
+
+.. _formatting-text:
+
+Formatting text
+===============
+
+You use inline markup to make text *italics*, **bold**, or ``monotype``.
+
+You can represent code blocks fairly easily::
+
+ import numpy as np
+ x = np.random.rand(12)
+
+Or literally include code:
+
+.. literalinclude:: ../pyplots/elegant.py
+
+
+.. _using-math:
+
+Using math
+==========
+
+In sphinx you can include inline math :math:`x\leftarrow y\ x\forall
+y\ x-y` or display math
+
+.. math::
+
+ W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]
+
+This documentation framework includes a Sphinx extension,
+:file:`sphinxext/mathmpl.py`, that uses matplotlib to render math
+equations when generating HTML, and LaTeX itself when generating a
+PDF. This can be useful on systems that have matplotlib, but not
+LaTeX, installed. To use it, add ``mathmpl`` to the list of
+extensions in :file:`conf.py`.
+
+Current SVN versions of Sphinx now include built-in support for math.
+There are two flavors:
+
+ - pngmath: uses dvipng to render the equation
+
+ - jsmath: renders the math in the browser using Javascript
+
+To use these extensions instead, add ``sphinx.ext.pngmath`` or
+``sphinx.ext.jsmath`` to the list of extensions in :file:`conf.py`.
+
+All three of these options for math are designed to behave in the same
+way.
+
+.. _emacs-helpers:
+
+Inserting matplotlib plots
+==========================
+
+Inserting automatically-generated plots is easy. Simply put the
+script to generate the plot in the :file:`pyplots` directory, and
+refer to it using the ``plot`` directive. To include the source code
+for the plot in the document, pass the ``include-source`` parameter::
+
+ .. plot:: ../pyplots/elegant.py
+ :include-source:
+
+In the HTML version of the document, the plot includes links to the
+original source code, a high-resolution PNG and a PDF. In the PDF
+version of the document, the plot is included as a scalable PDF.
+
+.. plot:: ../pyplots/elegant.py
+ :include-source:
+
+Inheritance diagrams
+====================
+
+Inheritance diagrams can be inserted directly into the document by
+providing a list of class or module names to the
+``inheritance-diagram`` directive.
+
+For example::
+
+ .. inheritance-diagram:: codecs
+
+produces:
+
+.. inheritance-diagram:: codecs
+
+Emacs helpers
+=============
+
+There is an emacs mode `rst.el
+<http://docutils.sourceforge.net/tools/editors/emacs/rst.el>`_ which
+automates many important ReST tasks like building and updateing
+table-of-contents, and promoting or demoting section headings. Here
+is the basic ``.emacs`` configuration::
+
+ (require 'rst)
+ (setq auto-mode-alist
+ (append '(("\\.txt$" . rst-mode)
+ ("\\.rst$" . rst-mode)
+ ("\\.rest$" . rst-mode)) auto-mode-alist))
+
+
+Some helpful functions::
+
+ C-c TAB - rst-toc-insert
+
+ Insert table of contents at point
+
+ C-c C-u - rst-toc-update
+
+ Update the table of contents at point
+
+ C-c C-l rst-shift-region-left
+
+ Shift region to the left
+
+ C-c C-r rst-shift-region-right
+
+ Shift region to the right
+
+
+.. _sphinx-literal:
+
+This file
+=========
+
+.. literalinclude:: sphinx_helpers.rst
+
+
Added: trunk/py4science/examples/sphinx_template2/pyplots/elegant.py
===================================================================
--- trunk/py4science/examples/sphinx_template2/pyplots/elegant.py (rev 0)
+++ trunk/py4science/examples/sphinx_template2/pyplots/elegant.py 2008-10-08 04:07:21 UTC (rev 6167)
@@ -0,0 +1,4 @@
+import matplotlib.pyplot as plt
+plt.plot([1,2,3], [4,5,6])
+plt.ylabel('some more numbers')
+
Added: trunk/py4science/examples/sphinx_template2/pyplots/hairy.py
===================================================================
--- trunk/py4science/examples/sphinx_template2/pyplots/hairy.py (rev 0)
+++ trunk/py4science/examples/sphinx_template2/pyplots/hairy.py 2008-10-08 04:07:21 UTC (rev 6167)
@@ -0,0 +1,4 @@
+import matplotlib.pyplot as plt
+plt.plot([1,2,3])
+plt.ylabel('some numbers')
+
Added: trunk/py4science/examples/sphinx_template2/simulations/finale.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/simulations/finale.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template2/simulations/finale.rst 2008-10-08 04:07:21 UTC (rev 6167)
@@ -0,0 +1,12 @@
+.. _final-results:
+
+*************
+Final Results
+*************
+
+
+After much head scratching, I wrote this big elegant piece of code, to
+produce this much more elegant figure:
+
+.. plot:: ../pyplots/elegant.py
+ :include-source:
Added: trunk/py4science/examples/sphinx_template2/simulations/index.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/simulations/index.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template2/simulations/index.rst 2008-10-08 04:07:21 UTC (rev 6167)
@@ -0,0 +1,11 @@
+.. _simulations-index:
+
+===========================
+ My Stupendous Simulations
+===========================
+
+.. toctree::
+
+ introduction.rst
+ preliminary.rst
+ finale.rst
Added: trunk/py4science/examples/sphinx_template2/simulations/introduction.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/simulations/introduction.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template2/simulations/introduction.rst 2008-10-08 04:07:21 UTC (rev 6167)
@@ -0,0 +1,24 @@
+.. _simulations-introduction:
+
+********************
+Simulations overview
+********************
+
+Wherein I describe my fancy code and libraries to implement my fancy model (:ref:`model-introduction`)
+
+.. _python-libraries:
+
+The python libraries
+====================
+
+Why `matplotlib <http://matplotlib.sf.net>`_ rules
+
+.. _data-sources:
+
+The data sources
+====================
+
+Now how much would you pay?
+
+
+
Added: trunk/py4science/examples/sphinx_template2/simulations/preliminary.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/simulations/preliminary.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template2/simulations/preliminary.rst 2008-10-08 04:07:21 UTC (rev 6167)
@@ -0,0 +1,11 @@
+.. _preliminary-tests:
+
+*****************
+Preliminary tests
+*****************
+
+I wrote this big hairy piece of code to make the following plot:
+
+.. plot:: ../pyplots/hairy.py
+ :include-source:
+
Added: trunk/py4science/examples/sphinx_template2/tools/sphinxext/inheritance_diagram.py
===================================================================
--- trunk/py4science/examples/sphinx_template2/tools/sphinxext/inheritance_diagram.py (rev 0)
+++ trunk/py4science/examples/sphinx_template2/tools/sphinxext/inheritance_diagram.py 2008-10-08 04:07:21 UTC (rev 6167)
@@ -0,0 +1,458 @@
+"""
+Defines a docutils directive for inserting inheritance diagrams.
+
+Provide the directive with one or more classes or modules (separated
+by whitespace). For modules, all of the classes in that module will
+be used.
+
+Example::
+
+ Given the following classes:
+
+ class A: pass
+ class B(A): pass
+ class C(A): pass
+ class D(B, C): pass
+ class E(B): pass
+
+ .. inheritance-diagram: D E
+
+ Produces a graph like the following:
+
+ A
+ / \
+ B C
+ / \ /
+ E D
+
+The graph is inserted as a PNG+image map into HTML and a PDF in
+LaTeX.
+"""
+
+#-----------------------------------------------------------------------------
+# Module and package imports
+
+# From the standard library
+
+import inspect
+import os
+import re
+import subprocess
+
+try:
+ from hashlib import md5
+except ImportError:
+ from md5 import md5
+
+# Third party
+from docutils.nodes import Body, Element
+from docutils.writers.html4css1 import HTMLTranslator
+from docutils.parsers.rst import directives
+
+from sphinx.latexwriter import LaTeXTranslator
+from sphinx.roles import xfileref_role
+
+#-----------------------------------------------------------------------------
+# Global Constants
+# Sphinx automatically copies out the contents of this directory to the html
+# output, so by putting things in here they get correctly picked up in the end
+STATIC_DIR='_static'
+
+options_spec = {
+ 'parts': directives.nonnegative_int
+ }
+
+#-----------------------------------------------------------------------------
+# Main code begins, classes and functions
+
+class DotException(Exception):
+ pass
+
+class InheritanceGraph(object):
+ """
+ Given a list of classes, determines the set of classes that
+ they inherit from all the way to the root "object", and then
+ is able to generate a graphviz dot graph from them.
+ """
+ def __init__(self, class_names, show_builtins=False):
+ """
+ *class_names* is a list of child classes to show bases from.
+
+ If *show_builtins* is True, then Python builtins will be shown
+ in the graph.
+ """
+ self.class_names = class_names
+ self.classes = self._import_classes(class_names)
+ self.all_classes = self._all_classes(self.classes)
+ if len(self.all_classes) == 0:
+ raise ValueError("No classes found for inheritance diagram")
+ self.show_builtins = show_builtins
+
+ py_sig_re = re.compile(r'''^([\w.]*\.)? # class names
+ (\w+) \s* $ # optionally arguments
+ ''', re.VERBOSE)
+
+ def _import_class_or_module(self, name):
+ """
+ Import a class using its fully-qualified *name*.
+ """
+ try:
+ path, base = self.py_sig_re.match(name).groups()
+ except:
+ raise ValueError(
+ "Invalid class or module '%s' specified for inheritance diagram" % name)
+ fullname = (path or '') + base
+ path = (path and path.rstrip('.'))
+ if not path:
+ path = base
+ if not path:
+ raise ValueError(
+ "Invalid class or module '%s' specified for inheritance diagram" % ...
[truncated message content] |
|
From: <jd...@us...> - 2008-10-16 11:43:39
|
Revision: 6218
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6218&view=rev
Author: jdh2358
Date: 2008-10-16 11:43:33 +0000 (Thu, 16 Oct 2008)
Log Message:
-----------
added load and csv2rec followups to recarray demo
Added Paths:
-----------
trunk/py4science/examples/recarray_demo2.py
trunk/py4science/examples/recarray_demo3.py
Added: trunk/py4science/examples/recarray_demo2.py
===================================================================
--- trunk/py4science/examples/recarray_demo2.py (rev 0)
+++ trunk/py4science/examples/recarray_demo2.py 2008-10-16 11:43:33 UTC (rev 6218)
@@ -0,0 +1,51 @@
+"""
+parse and load ge.csv into a record array
+"""
+import time, datetime, csv
+import dateutil.parser
+import matplotlib.mlab as mlab
+import matplotlib.dates as mdates
+import matplotlib.cbook as cbook
+import numpy as np
+
+# this is how you can use the function np.loadtxt to do the same
+# JDH TODO: this isn't working in mlab.load or np.loadtxt. Fix
+#rows = np.loadtxt('data/ge.csv', skiprows=1, converters={0:mdates.date2num}, delimiter=',')
+rows = mlab.load('data/ge.csv', skiprows=1, converters={0:mdates.date2num}, delimiter=',')
+r = np.rec.fromrecords(rows, names='date,open,high,low,close,volume,adjclose')
+
+# compute the average approximate dollars traded over the last 10 days
+# hint: closing price * volume trades approx equals dollars trades
+recent = r[-10:]
+dollars = (recent.close * recent.volume).mean()
+print '$%1.2fM'%(dollars/1e6)
+
+# plot the adjusted closing price vs time since 2003 - hint, you must
+# use date2num to convert the date to a float for mpl. Make two axes,
+# one for price and one for volume. Use a bar chart for volume
+
+import matplotlib.pyplot as plt
+dates = mdates.num2date(r.date) # convert these to native datetime.date objects
+mask = dates > datetime.date(2003,1,1)
+price = r.adjclose[mask]
+volume = r.volume[mask]
+
+fig = plt.figure()
+fig.subplots_adjust(hspace=0)
+ax1 = fig.add_subplot(211)
+ax1.plot(dates, price, '-');
+
+ax1.grid()
+for label in ax1.get_xticklabels():
+ label.set_visible(False)
+
+ax2 = fig.add_subplot(212, sharex=ax1)
+ax2.bar(dates, volume);
+
+ax2.grid()
+for label in ax2.get_xticklabels():
+ label.set_rotation(30)
+ label.set_horizontalalignment('right')
+
+fig.autofmt_xdate()
+plt.show()
Added: trunk/py4science/examples/recarray_demo3.py
===================================================================
--- trunk/py4science/examples/recarray_demo3.py (rev 0)
+++ trunk/py4science/examples/recarray_demo3.py 2008-10-16 11:43:33 UTC (rev 6218)
@@ -0,0 +1,47 @@
+"""
+parse and load ge.csv into a record array
+"""
+import time, datetime, csv
+import dateutil.parser
+import matplotlib.mlab as mlab
+import matplotlib.dates as mdates
+import matplotlib.cbook as cbook
+import numpy as np
+
+# this is how you can use the function mlab.csv2rec to do the same
+r = mlab.csv2rec('data/ge.csv')
+r.sort() #sort by date, the first column
+
+# compute the average approximate dollars traded over the last 10 days
+# hint: closing price * volume trades approx equals dollars trades
+recent = r[-10:]
+dollars = (recent.close * recent.volume).mean()
+print '$%1.2fM'%(dollars/1e6)
+
+# plot the adjusted closing price vs time since 2003 - hint, you must
+# use date2num to convert the date to a float for mpl. Make two axes,
+# one for price and one for volume. Use a bar chart for volume
+
+import matplotlib.pyplot as plt
+# filter to get dates since 2003
+r = r[r.date > datetime.date(2003,1,1)]
+
+fig = plt.figure()
+fig.subplots_adjust(hspace=0)
+ax1 = fig.add_subplot(211)
+ax1.plot(r.date, r.adj_close, '-');
+
+ax1.grid()
+for label in ax1.get_xticklabels():
+ label.set_visible(False)
+
+ax2 = fig.add_subplot(212, sharex=ax1)
+ax2.bar(r.date, r.volume);
+
+ax2.grid()
+for label in ax2.get_xticklabels():
+ label.set_rotation(30)
+ label.set_horizontalalignment('right')
+
+fig.autofmt_xdate()
+plt.show()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <fer...@us...> - 2008-10-19 07:53:56
|
Revision: 6270
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6270&view=rev
Author: fer_perez
Date: 2008-10-19 07:53:47 +0000 (Sun, 19 Oct 2008)
Log Message:
-----------
Cleanup and updates to many examples.
Added new tool to create skeletons and solutions from a single source
script.
Modified Paths:
--------------
trunk/py4science/examples/bessel.py
trunk/py4science/examples/butter_filter.py
trunk/py4science/examples/fft_imdenoise.py
trunk/py4science/examples/filtilt_demo.py
trunk/py4science/examples/fitting.py
trunk/py4science/examples/montecarlo_pi.py
trunk/py4science/examples/qsort.py
trunk/py4science/examples/quad_newton.py
trunk/py4science/examples/recarray_demo.py
trunk/py4science/examples/trapezoid.py
Added Paths:
-----------
trunk/py4science/examples/mkskel.py
trunk/py4science/examples/skel/fortran_wrap/test_example.py
trunk/py4science/examples/skel/fortran_wrap/test_fib.py
Modified: trunk/py4science/examples/bessel.py
===================================================================
--- trunk/py4science/examples/bessel.py 2008-10-19 07:48:51 UTC (rev 6269)
+++ trunk/py4science/examples/bessel.py 2008-10-19 07:53:47 UTC (rev 6270)
@@ -1,45 +1,46 @@
#!/usr/bin/env python
"""Plot some Bessel functions of integer order, using Scipy and pylab"""
-import scipy.special
+from scipy import special
-import numpy as N
-import scipy as S
-import pylab as P
+import numpy as np
+import matplotlib.pyplot as plt
-# shorthand
-special = S.special
-
def jn_asym(n,x):
"""Asymptotic form of jn(x) for x>>n"""
+
+ #@ The asymptotic formula is:
+ #@ j_n(x) ~ sqrt(2.0/pi/x)*cos(x-(n*pi/2.0+pi/4.0))
- return S.sqrt(2.0/S.pi/x)*S.cos(x-(n*S.pi/2.0+S.pi/4.0))
+ return np.sqrt(2.0/np.pi/x)*np.cos(x-(n*np.pi/2.0+np.pi/4.0)) #@
# build a range of values to plot in
-x = N.linspace(0,30,400)
+x = np.linspace(0,30,400)
# Start by plotting the well-known j0 and j1
-P.figure()
-P.plot(x,special.j0(x),label='$J_0$')
-P.plot(x,special.j1(x),label='$J_1$')
+plt.figure()
+plt.plot(x,special.j0(x),label='$J_0$') #@
+plt.plot(x,special.j1(x),label='$J_1$') #@
# Show a higher-order Bessel function
n = 5
-P.plot(x,special.jn(n,x),label='$J_%s$' % n)
+plt.plot(x,special.jn(n,x),label='$J_%s$' % n)
# and compute its asymptotic form (valid for x>>n, where n is the order). We
-# must first find the valid range of x where at least x>n:
-x_asym = S.compress(x>n,x)
-P.plot(x_asym,jn_asym(n,x_asym),label='$J_%s$ (asymptotic)' % n)
+# must first find the valid range of x where at least x>n.
+#@ Find where x>n and evaluate the asymptotic relation only there
+x_asym = x[x>n] #@
+plt.plot(x_asym,jn_asym(n,x_asym),label='$J_%s$ (asymptotic)' % n) #@
# Finish off the plot
-P.legend()
-P.title('Bessel Functions')
+plt.legend()
+plt.title('Bessel Functions')
# horizontal line at 0 to show x-axis, but after the legend
-P.axhline(0)
+plt.axhline(0)
-# EXERCISE: redo the above, for the asymptotic range 0<x<<n. The asymptotic
-# form in this regime is
+# Extra credit: redo the above, for the asymptotic range 0<x<<n. The
+# asymptotic form in this regime is:
+#
# J(n,x) = (1/gamma(n+1))(x/2)^n
# Now, let's verify numerically the recursion relation
@@ -47,17 +48,25 @@
jn = special.jn # just a shorthand
# Be careful to check only for x!=0, to avoid divisions by zero
-xp = S.compress(x>0.0,x) # positive x
+#@ xp contains the positive values of x
+xp = x[x>0.0] #@
# construct both sides of the recursion relation, these should be equal
+#@ Define j_np1 to hold j_(n+1) evaluated at the points xp
j_np1 = jn(n+1,xp)
+#@ Define j_np1_rec to express j_(n+1) via a recursion relation, at points xp
j_np1_rec = (2.0*n/xp)*jn(n,xp)-jn(n-1,xp)
# Now make a nice error plot of the difference, in a new figure
-P.figure()
-P.semilogy(xp,abs(j_np1-j_np1_rec),'r+-')
-P.title('Error in recursion for $J_%s$' % n)
-P.grid()
+plt.figure()
+#@ We now plot the difference between the two formulas above. Note that to
+#@ properly display the errors, we want to use a logarithmic y scale. Search
+#@ the matplotlib docs for the proper calls.
+plt.semilogy(xp,abs(j_np1-j_np1_rec),'r+-') #@
+
+plt.title('Error in recursion for $J_%s$' % n)
+plt.grid()
+
# Don't forget a show() call at the end of the script
-P.show()
+plt.show()
Modified: trunk/py4science/examples/butter_filter.py
===================================================================
--- trunk/py4science/examples/butter_filter.py 2008-10-19 07:48:51 UTC (rev 6269)
+++ trunk/py4science/examples/butter_filter.py 2008-10-19 07:53:47 UTC (rev 6270)
@@ -1,13 +1,13 @@
-import numpy as n
+import numpy as np
import scipy.signal as signal
-from pylab import figure, show
+from matplotlib.pyplot import figure, show
dt = 0.01
-t = n.arange(0, 2, dt)
-s = n.sin(2*n.pi*t)
+t = np.arange(0, 2, dt)
+s = np.sin(2*np.pi*t)
# sine corrupted wih gaussian white noise
-sn = s + 0.1*n.random.randn(len(s)) # noisy sine
+sn = s + 0.1*np.random.randn(len(s)) # noisy sine
# the nyquist frequency 1/(2dt) is the maximum frequency in a sampled
# signal
Modified: trunk/py4science/examples/fft_imdenoise.py
===================================================================
--- trunk/py4science/examples/fft_imdenoise.py 2008-10-19 07:48:51 UTC (rev 6269)
+++ trunk/py4science/examples/fft_imdenoise.py 2008-10-19 07:53:47 UTC (rev 6270)
@@ -1,62 +1,86 @@
#!/usr/bin/env python
-"""Image denoising example using 2-dimensional FFT."""
+"""Simple image denoising example using 2-dimensional FFT."""
import sys
import numpy as np
from matplotlib import pyplot as plt
-def mag_phase(F):
- """Return magnitude and phase components of spectrum F."""
-
- return (np.absolute(F), np.angle(F))
-
def plot_spectrum(F, amplify=1000):
"""Normalise, amplify and plot an amplitude spectrum."""
- M, Phase = mag_phase(F)
- M *= amplify/M.max()
- M[M > 1] = 1
- print M.shape, M.dtype
- plt.imshow(M, plt.cm.Blues)
+ # Note: the problem here is that we have a spectrum whose histogram is
+ # *very* sharply peaked at small values. To get a meaningful display, a
+ # simple strategy to improve the display quality consists of simply
+ # amplifying the values in the array and then clipping.
+ # Compute the magnitude of the input F (call it mag). Then, rescale mag by
+ # amplify/maximum_of_mag. Numpy arrays can be scaled in-place with ARR *=
+ # number. For the max of an array, look for its max method.
+ mag = abs(F) #@
+ mag *= amplify/mag.max() #@
+
+ # Next, clip all values larger than one to one. You can set all elements
+ # of an array which satisfy a given condition with array indexing syntax:
+ # ARR[ARR<VALUE] = NEWVALUE, for example.
+ mag[mag > 1] = 1 #@
+ # Display: this one already works, if you did everything right with mag
+ plt.imshow(mag, plt.cm.Blues)
+
if __name__ == '__main__':
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]
+ # grayscale, just extract the 1st channel
+ #@ Hints:
+ #@ - use plt.imread() to load the file
+ #@ - convert to a float array with the .astype() method
+ #@ - extract all rows, all columns, 0-th plane to get the first
+ #@ channel
+ #@ - the resulting array should have 2 dimensions only
+ im = plt.imread('data/moonlanding.png').astype(float)[:,:,0] #@
+ print "Image shape:",im.shape
except:
print "Could not open image."
sys.exit(-1)
# Compute the 2d FFT of the input image
- F = np.fft.fft2(im)
+ #@ Hint: Look for a 2-d FFT in np.fft.
+ #@ Note: call this variable 'F', which is the name we'll be using below.
+ F = np.fft.fft2(im) #@
- # Now, make a copy of the original spectrum and truncate coefficients.
+ # In the lines following, we'll make a copy of the original spectrum and
+ # truncate coefficients. NO immediate code is to be written right here.
+
+ # Define the fraction of coefficients (in each direction) we keep
keep_fraction = 0.1
# Call ff a copy of the original transform. Numpy arrays have a copy
# method for this purpose.
- ff = F.copy()
+ ff = F.copy() #@
- # Set r and c to be the number of rows and columns of the array.
- r,c = ff.shape
+ # Set r and c to be the number of rows and columns of the array.
+ #@ Hint: use the array's shape attribute.
+ r,c = ff.shape #@
# 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
+ ff[r*keep_fraction:r*(1-keep_fraction)] = 0 #@
# Similarly with the columns:
- ff[:, c*keep_fraction:c*(1-keep_fraction)] = 0
+ ff[:, c*keep_fraction:c*(1-keep_fraction)] = 0 #@
# Reconstruct the denoised image from the filtered spectrum, keep only the
- # real part for display
- im_new = np.fft.ifft2(ff).real
-
+ # real part for display.
+ #@ Hint: There's an inverse 2d fft in the np.fft module as well (don't
+ #@ forget that you only want the real part).
+ #@ Call the result im_new,
+ im_new = np.fft.ifft2(ff).real #@
+
# Show the results
+ #@ The code below already works, if you did everything above right.
plt.figure()
plt.subplot(221)
@@ -75,9 +99,6 @@
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/filtilt_demo.py
===================================================================
--- trunk/py4science/examples/filtilt_demo.py 2008-10-19 07:48:51 UTC (rev 6269)
+++ trunk/py4science/examples/filtilt_demo.py 2008-10-19 07:53:47 UTC (rev 6270)
@@ -7,10 +7,11 @@
order. The function also computes the initial filter parameters in
order to provide a more stable response (via lfilter_zi). The
following code has been tested with Python 2.4.4 and Scipy 0.5.1.
+"""
-"""
-from numpy import vstack, hstack, eye, ones, zeros, linalg, \
-newaxis, r_, flipud, convolve, matrix, array
+from numpy import (vstack, hstack, eye, ones, zeros, linalg,
+ newaxis, r_, flipud, convolve, matrix, array)
+
from scipy.signal import lfilter
def lfilter_zi(b,a):
@@ -38,19 +39,18 @@
return array(zi_return)
-
-
def filtfilt(b,a,x):
#For now only accepting 1d arrays
ntaps=max(len(a),len(b))
edge=ntaps*3
if x.ndim != 1:
- raise ValueError, "Filiflit is only accepting 1 dimension arrays."
+ raise ValueError("Filiflit is only accepting 1 dimension arrays.")
- #x must be bigger than edge
+ # x must be bigger than edge
if x.size < edge:
- raise ValueError, "Input vector needs to be bigger than 3 * max(len(a),len(b)."
+ e="Input vector needs to be bigger than 3 * max(len(a),len(b)."
+ raise ValueError(e)
if len(a) < ntaps:
a=r_[a,zeros(len(b)-len(a))]
Modified: trunk/py4science/examples/fitting.py
===================================================================
--- trunk/py4science/examples/fitting.py 2008-10-19 07:48:51 UTC (rev 6269)
+++ trunk/py4science/examples/fitting.py 2008-10-19 07:53:47 UTC (rev 6270)
@@ -7,10 +7,11 @@
from scipy.optimize import leastsq
from scipy.interpolate import splrep,splev
-import numpy as N
-import scipy as S
-import pylab as P
+import numpy as np
+import matplotlib as mpl
+import matplotlib.pyplot as plt
+
def func(pars):
a, alpha, k = pars
return a*exp(alpha*x_vals) + k
@@ -35,7 +36,7 @@
print 'Least-squares fit to the data'
print 'true', pars_true
print 'best', best
-print '|err|_l2 =',P.l2norm(pars_true-best)
+print '|err|_l2 =',np.linalg.norm(pars_true-best)
# scipy's splrep uses FITPACK's curfit (B-spline interpolation)
print
@@ -48,27 +49,27 @@
def plot_polyfit(x,y,n,fignum=None):
""" """
if fignum is None:
- fignum = P.figure().number
- P.plot(x,y,label='Data')
+ fignum = plt.figure().number
+ plt.plot(x,y,label='Data')
- fit_coefs = N.polyfit(x,y,n)
- fit_val = N.polyval(fit_coefs,x)
- P.plot(x,fit_val,label='Polynomial fit, $n=%d$' % n)
- P.legend()
+ fit_coefs = np.polyfit(x,y,n)
+ fit_val = np.polyval(fit_coefs,x)
+ plt.plot(x,fit_val,label='Polynomial fit, $n=%d$' % n)
+ plt.legend()
return fignum
# Now use pylab to plot
-P.figure()
-P.plot(x_vals,y_noisy,label='Noisy data')
-P.plot(x_vals,func(best),lw=2,label='Least-squares fit')
-P.legend()
-P.figure()
-P.plot(x_vals,y_noisy,label='Noisy data')
-P.plot(x_vals,smooth,lw=2,label='Spline-smoothing')
-P.legend()
+plt.figure()
+plt.plot(x_vals,y_noisy,label='Noisy data')
+plt.plot(x_vals,func(best),lw=2,label='Least-squares fit')
+plt.legend()
+plt.figure()
+plt.plot(x_vals,y_noisy,label='Noisy data')
+plt.plot(x_vals,smooth,lw=2,label='Spline-smoothing')
+plt.legend()
fignum = plot_polyfit(x_vals,y_noisy,1)
plot_polyfit(x_vals,y_noisy,2,fignum)
plot_polyfit(x_vals,y_noisy,3,fignum)
-P.show()
+plt.show()
Added: trunk/py4science/examples/mkskel.py
===================================================================
--- trunk/py4science/examples/mkskel.py (rev 0)
+++ trunk/py4science/examples/mkskel.py 2008-10-19 07:53:47 UTC (rev 6270)
@@ -0,0 +1,325 @@
+#!/usr/bin/env python
+"""Make skeletons out of Python scripts.
+
+Usage:
+
+ mkskel [--test] file1.py file2.py ....
+
+If --test is given, the test suite is run instead.
+
+For each input filename f.py, a pair of output files is generated, f_soln.py
+and f_skel.py.
+
+Source markup is very simple. The tests in the file show precisely how it
+works, but in summary:
+
+- Pure comment lines with the special marker (#@) are left in the skeleton
+ (only the marker is stripped, but they remain as valid comments). These are
+ typically used for hints.
+
+- Code lines terminated with the marker are:
+
+ - In the skeleton, replaced by a NotImplementedError call. Consecutive lines
+ are replaced by a single call.
+
+ - In the solution, kept as is but the marker is removed.
+"""
+
+from __future__ import with_statement
+
+#-----------------------------------------------------------------------------
+# Stdlib imports
+import os
+import re
+import shutil
+import sys
+
+# Third-party imports
+import nose
+
+# Constants
+MARKER = '#@'
+DEL_RE = re.compile(r'''^((\s*)(.*?))\s*%s\s*$''' % MARKER)
+HINT_RE = re.compile(r'''^(?P<space>\s*)%s\s+(?P<hint>.*)$''' % MARKER)
+
+
+#-----------------------------------------------------------------------------
+# Main code begins
+
+def src2soln(src):
+ """Remove markers from input source, leaving all else intact.
+
+ Inputs:
+ src : sequence of lines (file-like objects work out of the box)
+ """
+
+ out = []
+ addline = out.append
+ for line in src:
+ # Check for lines to delete and with hints
+ mdel = DEL_RE.match(line)
+ mhint = HINT_RE.match(line)
+
+ # All hints are unconditionally removed
+ if mhint is None:
+ if mdel:
+ # if marker is matched in code, strip it and leave the code
+ line = mdel.group(1)+'\n'
+ addline(line)
+
+ return ''.join(out)
+
+
+def src2skel(src):
+ """Remove markers from input source, replacing marked lines.
+
+ Marked lines are replaced with "raise NotImplementedError" calls that
+ summarize the total number of deleted lines.
+
+ Inputs:
+ src : sequence of lines (file-like objects work out of the box)
+ """
+
+ def flush_buffers(normal_lines,del_lines=0):
+ """Local function to reuse some common code"""
+
+ if state_cur == normal:
+ # add the normal lines
+ out.extend(normal_lines)
+ normal_lines[:] = []
+ else:
+ # Add the summary of 'raise' lines
+
+ # flush counter of code (disabled, we report static summary)
+ #msg = '1 line' if del_lines==1 else ('%s lines' % del_lines)
+ #exc = exc_tpl % msg
+ exc = exc_tpl
+
+ # Use the last value of 'space'
+ line = '%s%s' % (spaces[0],exc)
+ out.append(line)
+ del_lines = 0
+ spaces[:] = []
+
+ return del_lines
+
+ # used to report actual # of lines removed - disabled
+ #exc_tpl = "raise NotImplementedError('%s missing')\n"
+ exc_tpl = "raise NotImplementedError('insert missing code here')\n"
+
+ # states for state machine and other initialization
+ normal,delete = 0,1
+ state_cur = normal
+ del_lines = 0 # counter, in case we want to report # of deletions
+ spaces = []
+ normal_lines = []
+ out = []
+
+ # To remove multiple consecutive lines of input marked for deletion, we
+ # need a small state machine.
+ for line in src:
+ # Check for lines to delete and with hints
+ mdel = DEL_RE.match(line)
+ mhint = HINT_RE.match(line)
+
+ if mhint:
+ state_new = normal
+ hint = mhint.group('space')+'# ' + mhint.group('hint') +'\n'
+ normal_lines.append(hint)
+ else:
+ if mdel is None:
+ state_new = normal
+ normal_lines.append(line)
+ else:
+ state_new = delete
+ del_lines += 1
+ spaces.append(mdel.group(2))
+
+ # Flush output only when there's a change of state
+ if state_new != state_cur:
+ del_lines = flush_buffers(normal_lines,del_lines)
+
+ # Update state machine
+ state_cur = state_new
+
+ # Final buffer flush is unconditional
+ flush_buffers(normal_lines)
+
+ return ''.join(out)
+
+
+def transform_file(fpath,fname_skel,fname_soln):
+ """Run the cleanup routines for a given input, creating skel and soln.
+ """
+
+ # get the mode of the input so that we can create the output files with the
+ # same mode
+ fmode = os.stat(fpath).st_mode
+
+ with open(fpath) as infile:
+ # Generate the skeleton
+ skel = src2skel(infile)
+ with open(fname_skel,'w') as fskel:
+ fskel.write(skel)
+ os.chmod(fname_skel,fmode)
+
+ # Reset the input file pointer and generate the solution
+ infile.seek(0)
+ soln = src2soln(infile)
+ with open(fname_soln,'w') as fsoln:
+ fsoln.write(soln)
+ os.chmod(fname_soln,fmode)
+
+#-----------------------------------------------------------------------------
+# Main execution routines
+
+def copyforce(src,dest):
+ """Forceful file link/copy that overwrites destination files."""
+ try:
+ copy = os.link
+ except AttributeError:
+ copy = shutil.copy
+ if os.path.isfile(dest):
+ os.remove(dest)
+ copy(src,dest)
+
+
+def mvforce(src,dest):
+ """Forceful file copy that overwrites destination files."""
+ if os.path.isfile(dest):
+ os.remove(dest)
+ shutil.move(src,dest)
+
+
+def main(argv=None):
+ """Main entry point as a command line script for normal execution"""
+
+ if argv is None:
+ argv = sys.argv
+
+ # If there are subdirs called skel and soln, we populate them by moving the
+ # generated files there, otherwise they're left in the current dir.
+ skel_dir = 'skel'
+ soln_dir = 'soln'
+ has_skel_dir = os.path.isdir(skel_dir)
+ has_soln_dir = os.path.isdir(soln_dir)
+
+ # First, check that all files are present and abort immediately if any of
+ # them isn't there.
+ for fpath in argv[1:]:
+ if not os.path.isfile(fpath):
+ raise OSError("file %r not found" % fpath)
+
+ # If all files are there, then go ahead and process them unconditionally
+ for fpath in argv[1:]:
+ basename, ext = os.path.splitext(fpath)
+ fname_skel = basename + '_skel' + ext
+ fname_soln = basename + '_soln' + ext
+ transform_file(fpath,fname_skel,fname_soln)
+ # Move files over to final dirs if present
+ if has_skel_dir:
+ mvforce(fname_skel,os.path.join(skel_dir,fname_skel))
+ if has_soln_dir:
+ mvforce(fname_soln,os.path.join(soln_dir,fname_soln))
+
+#-----------------------------------------------------------------------------
+# Tests
+
+def str_match(s1,s2):
+ """Check that two strings are equal ignoring trailing whitespace."""
+ #print '***S1\n',s1,'\n***S2\n',s2 # dbg
+ nose.tools.assert_equal(s1.rstrip(),s2.rstrip())
+
+
+def test_simple():
+ src = """
+ first line
+ del line #@
+ second line
+ """
+ srclines = src.splitlines(True)
+
+ clean = """
+ first line
+ raise NotImplementedError('insert missing code here')
+ second line
+ """
+
+ cleaned = src2skel(srclines)
+ yield str_match,cleaned,clean
+
+ clean = """
+ first line
+ del line
+ second line
+ """
+ cleaned = src2soln(src.splitlines(True))
+ yield str_match,cleaned,clean
+
+
+def test_multi():
+ src = """
+ first line
+ #@ Hint: remember that
+ #@ idea we discussed before...
+ del line #@
+ del line2 #@
+ del line3 #@
+ second line:
+ del line4 #@
+ del line5 #@
+ third line
+
+ some indented code: #@
+ with more... #@
+ """
+ srclines = src.splitlines(True)
+
+ clean = """
+ first line
+ # Hint: remember that
+ # idea we discussed before...
+ raise NotImplementedError('insert missing code here')
+ second line:
+ raise NotImplementedError('insert missing code here')
+ third line
+
+ raise NotImplementedError('insert missing code here')
+ """
+ cleaned = src2skel(srclines)
+ yield str_match,cleaned,clean
+
+ clean = """
+ first line
+ del line
+ del line2
+ del line3
+ second line:
+ del line4
+ del line5
+ third line
+
+ some indented code:
+ with more...
+ """
+ cleaned = src2soln(srclines)
+ yield str_match,cleaned,clean
+
+
+@nose.tools.nottest
+def test():
+ """Simple self-contained test runner."""
+ nose.runmodule(__name__,exit=False,
+ argv=['--doctests',
+ #'-s',
+ #'--pdb-failures',
+ ])
+
+#-----------------------------------------------------------------------------
+# Execution from the command line.
+
+if __name__ == "__main__":
+ if '--test' in sys.argv:
+ test()
+ else:
+ main(sys.argv)
Property changes on: trunk/py4science/examples/mkskel.py
___________________________________________________________________
Added: svn:executable
+ *
Modified: trunk/py4science/examples/montecarlo_pi.py
===================================================================
--- trunk/py4science/examples/montecarlo_pi.py 2008-10-19 07:48:51 UTC (rev 6269)
+++ trunk/py4science/examples/montecarlo_pi.py 2008-10-19 07:53:47 UTC (rev 6270)
@@ -15,7 +15,7 @@
import math
import random
-import numpy as N
+import numpy as np
from scipy import weave
from scipy.weave import inline,converters
@@ -110,7 +110,7 @@
print 'pi - weave :',v2()
# make a simple 10x10 array
- a = N.arange(100)
+ a = np.arange(100)
a.shape = 10,10
# Print it using our printer
Modified: trunk/py4science/examples/qsort.py
===================================================================
--- trunk/py4science/examples/qsort.py 2008-10-19 07:48:51 UTC (rev 6269)
+++ trunk/py4science/examples/qsort.py 2008-10-19 07:53:47 UTC (rev 6270)
@@ -1,29 +1,60 @@
-"""
-Simple quicksort implementation.
+"""Simple quicksort implementation.
-See http://en.wikipedia.org/wiki/Quicksort for algorithm, pseudocode
-and C implementation for comparison
+From http://en.wikipedia.org/wiki/Quicksort we have this pseudocode (see also
+the C implementation for comparison).
+
+Note: what follows is NOT python code, it's meant to only illustrate the
+algorithm for you. Below you'll need to actually implement it in real Python.
+You may be surprised at how close a working Python implementation can be to
+this pseudocode.
+
+
+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."""
+ """Return a sorted copy of the input list.
- if len(lst) <= 1:
- return lst
+ Input:
- # Select pivot and apply recursively
- pivot, rest = lst[0],lst[1:]
- less_than = [ lt for lt in rest if lt < pivot ]
- greater_equal = [ ge for ge in rest if ge >= pivot ]
-
- return qsort(less_than) + [pivot] + qsort(greater_equal)
+ lst : a list of elements which can be compared.
+ Examples:
+ >>> qsort([])
+ []
+
+ >>> qsort([3,2,5])
+ [2, 3, 5]
+ """
+
+ #@ Hint: remember that all recursive functions need an exit condition
+ if len(lst) <= 1: #@
+ return lst #@
+
+ #@ Select pivot and apply recursively
+ pivot, rest = lst[0],lst[1:] #@
+ less_than = [ lt for lt in rest if lt < pivot ] #@
+ greater_equal = [ ge for ge in rest if ge >= pivot ] #@
+
+ #@ Upon return, make sure to properly concatenate the output lists
+ return qsort(less_than) + [pivot] + qsort(greater_equal) #@
+
+
#-----------------------------------------------------------------------------
# Tests
#-----------------------------------------------------------------------------
import random
+import nose
import nose, nose.tools as nt
def test_sorted():
Modified: trunk/py4science/examples/quad_newton.py
===================================================================
--- trunk/py4science/examples/quad_newton.py 2008-10-19 07:48:51 UTC (rev 6269)
+++ trunk/py4science/examples/quad_newton.py 2008-10-19 07:53:47 UTC (rev 6270)
@@ -4,35 +4,35 @@
from math import sin
-import scipy, scipy.integrate, scipy.optimize
+from scipy.integrate import quad
+from scipy.optimize import newton
-quad = scipy.integrate.quad
-newton = scipy.optimize.newton
-
# test input function
def f(t):
- return t*(sin(t))**2
+ #@ f(t): t * sin^2(t)
+ return t*(sin(t))**2 #@
-# exact \int_0^t f(s) ds - u
def g(t):
+ "Exact form for g by integrating f(t)"
u = 0.25
return .25*(t**2-t*sin(2*t)+(sin(t))**2)-u
-# now let's construct g(t) via numerical integration
def gn(t):
+ "g(t) obtained by numerical integration"
u = 0.25
- return quad(f,0.0,t)[0] - u
+ #@ Hint: use quad, see its return value carefully.
+ return quad(f,0.0,t)[0] - u #@
# main
tguess = 10.0
print '"Exact" solution (knowing the analytical form of the integral)'
-t0 = newton(g,tguess,f)
+t0 = newton(g,tguess,f) #@
print "t0, g(t0) =",t0,g(t0)
print
print "Solution using the numerical integration technique"
-t1 = newton(gn,tguess,f)
+t1 = newton(gn,tguess,f) #@
print "t1, g(t1) =",t1,g(t1)
print
Modified: trunk/py4science/examples/recarray_demo.py
===================================================================
--- trunk/py4science/examples/recarray_demo.py 2008-10-19 07:48:51 UTC (rev 6269)
+++ trunk/py4science/examples/recarray_demo.py 2008-10-19 07:53:47 UTC (rev 6270)
@@ -1,67 +1,53 @@
"""
parse and load ge.csv into a record array
"""
-import time, datetime, csv
-import dateutil.parser
-import numpy
-if 0:
- # create a csv reader to parse the file
- fh = file('data/ge.csv')
- reader = csv.reader(fh)
- header = reader.next()
+import datetime
- # iterate over the remaining rows and convert the data to date
- # objects, ints, or floats as approriate
- rows = []
- for date, open, high, low, close, volume, adjclose in reader:
- date = dateutil.parser.parse(date).date()
- volume = int(volume)
- open, high, low, close, adjclose = map(float, (
- open, high, low, close, adjclose))
- rows.append((date, open, high, low, close, volume, adjclose))
+import numpy as np
- fh.close()
+import matplotlib
+from matplotlib import pyplot as plt
- # this is how you can use the function matplotlib.mlab.load to do the same
- #rows = load('data/ge.csv', skiprows=1, converters={0:datestr2num}, delimiter=',')
+# Disable latex support just in case, so we can rotate text
+matplotlib.rcParams['text.usetex'] = False
- r = numpy.rec.fromrecords(rows, names='date,open,high,low,close,volume,adjclose')
+# Load a data file into a record array using the matplotlib csv2rec utility
+r = matplotlib.mlab.csv2rec('data/ge.csv')
+r.sort() #sort by date, the first column
# compute the average approximate dollars traded over the last 10 days
# hint: closing price * volume trades approx equals dollars trades
recent = r[-10:]
-dollars = numpy.mean(recent.close * recent.volume)
-print '$%1.2fM'%(dollars/1e6)
+dollars = np.mean(recent.close * recent.volume)
+print 'Total traded over last 10 days: $%1.2fM'%(dollars/1e6)
-# plot the adjusted closing price vs time since 2003 - hint, you must
-# use date2num to convert the date to a float for mpl. Make two axes,
-# one for price and one for volume. Use a bar chart for volume
-import matplotlib
-matplotlib.rcParams['usetex'] = False
-from matplotlib.dates import date2num
-import pylab
-mask = r.date>datetime.date(2003,1,1)
-date = date2num(r.date[mask])
-price = r.adjclose[mask]
+# plot the adjusted closing price vs time since 2003. Make two axes, one for
+# price and one for volume. Use a bar chart for volume
+
+# Record arr...
[truncated message content] |
|
From: <fer...@us...> - 2008-10-19 08:35:19
|
Revision: 6271
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6271&view=rev
Author: fer_perez
Date: 2008-10-19 08:30:58 +0000 (Sun, 19 Oct 2008)
Log Message:
-----------
Update more examples. Also removed some figures that can be
auto-generated and don't need to clutter the repo.
Added Paths:
-----------
trunk/py4science/examples/iterators.py
trunk/py4science/examples/iterators_example.py
trunk/py4science/examples/numpy_wrap/f2py/example3/test_example.py
trunk/py4science/examples/numpy_wrap/f2py/example3/test_fib.py
trunk/py4science/examples/numpytemps.py
trunk/py4science/examples/recarray/
trunk/py4science/examples/recarray/recarr_simple.py
trunk/py4science/examples/recarray/recarr_simple_data.txt
trunk/py4science/examples/soln/
trunk/py4science/examples/txt_data_load.py
trunk/py4science/examples/txt_data_sample.txt
Removed Paths:
-------------
trunk/py4science/examples/numpy-blitz_1000.png
trunk/py4science/examples/numpy-blitz_300.png
trunk/py4science/examples/numpy-blitz_500.png
trunk/py4science/examples/weave_blitz_comp.png
Added: trunk/py4science/examples/iterators.py
===================================================================
--- trunk/py4science/examples/iterators.py (rev 0)
+++ trunk/py4science/examples/iterators.py 2008-10-19 08:30:58 UTC (rev 6271)
@@ -0,0 +1,82 @@
+import numpy as np
+from scipy.weave import inline
+from numpy.testing import assert_array_almost_equal, assert_almost_equal
+
+def prodsum(a, b, axis=None):
+ assert a.shape == b.shape, "cannot take prodsum of different size arrays"
+ nd = len(a.shape)
+ if axis is not None:
+ caxis = axis if axis >=0 else nd + axis
+ assert caxis < nd, "cannot perform operation in this axis: %d"%axis
+ dims = list(a.shape)
+ dims.pop(axis)
+ c = np.zeros(tuple(dims), np.float64)
+ else:
+ caxis = -1
+ c = np.array([0.0])
+
+ xtra = \
+"""
+double prodsum(double *d1, double *d2, int stride, int size)
+{
+ double sum = 0.0;
+
+ while(size--) {
+ sum += (*d1) * (*d2);
+ d1 += stride;
+ d2 += stride;
+ }
+ return sum;
+}
+"""
+
+ code = \
+"""
+double *d1, *d2, *d3;
+int sumall = caxis < 0 ? 1 : 0;
+PyArrayIterObject *itr1, *itr2, *itr3;
+
+itr1 = (PyArrayIterObject *) PyArray_IterAllButAxis(py_a, &caxis);
+itr2 = (PyArrayIterObject *) PyArray_IterAllButAxis(py_b, &caxis);
+if (!sumall) itr3 = (PyArrayIterObject *) PyArray_IterNew(py_c);
+
+//...... more definitions here
+
+// make use of auto defined arrays, be careful to use "axis" AFTER
+// creating iterators, in case it gets chosen for you
+int stride = Sa[caxis]/sizeof(double);
+int size = Na[caxis];
+while( PyArray_ITER_NOTDONE(itr1) ) {
+
+ //...... iter loop here
+ d1 = (double *) itr1->dataptr;
+ d2 = (double *) itr2->dataptr;
+ if(sumall) {
+ d3 = c;
+ } else {
+ d3 = (double *) itr3->dataptr;
+ PyArray_ITER_NEXT(itr3);
+ }
+ *d3 += prodsum(d1, d2, stride, size);
+ PyArray_ITER_NEXT(itr1);
+ PyArray_ITER_NEXT(itr2);
+}
+"""
+ inline(code, ['a', 'b', 'c', 'caxis'], compiler='gcc',
+ support_code=xtra)
+ return c[0] if axis is None else c
+
+
+def tests():
+ a = np.random.rand(4,2,9)
+ b = np.ones_like(a)
+
+ assert_almost_equal(prodsum(a,b), a.sum())
+ assert_array_almost_equal(prodsum(a,b,axis=-1), a.sum(axis=-1))
+ assert_array_almost_equal(prodsum(a[:2,:,1::2], b[:2,:,1::2], axis=0),
+ a[:2,:,1::2].sum(axis=0))
+ assert_array_almost_equal(prodsum(a[:,:,::-1], b[:,:,::-1], axis=-1),
+ a[:,:,::-1].sum(axis=-1))
+
+if __name__ == '__main__':
+ tests()
Added: trunk/py4science/examples/iterators_example.py
===================================================================
--- trunk/py4science/examples/iterators_example.py (rev 0)
+++ trunk/py4science/examples/iterators_example.py 2008-10-19 08:30:58 UTC (rev 6271)
@@ -0,0 +1,229 @@
+#!/usr/bin/env python
+"""Blitz conversion is terrific, but sometimes you don't have fixed array sizes
+in your problem. Fortunately numpy iterators still make writing inline weave
+code very, very simple."""
+
+import sys
+
+import numpy as np
+from numpy.testing.utils import jiffies
+
+from matplotlib import pyplot as plt
+
+from scipy.weave import inline, converters, blitz
+
+# A little timing utility taken from the old scipy.testing
+def measure(code_str,times=1):
+ """ Return elapsed time for executing code_str in the
+ namespace of the caller for given times.
+ """
+ frame = sys._getframe(1)
+ locs,globs = frame.f_locals,frame.f_globals
+ code = compile(code_str,'<Timing code>','exec')
+ i = 0
+ elapsed = jiffies()
+ while i<times:
+ i += 1
+ exec code in globs,locs
+ elapsed = jiffies() - elapsed
+ return 0.01*elapsed
+
+
+def multi_iter_example():
+ # This is a very simple example of multi dimensional iterators, and
+ # their power to "broadcast" arrays of compatible shapes. It shows that
+ # the very same code that is entirely ignorant of dimensionality can
+ # achieve completely different computations based on the rules of
+ # broadcasting.
+
+ # it is important to know that the weave array conversion of "a"
+ # gives you access in C++ to:
+ # py_a -- PyObject *
+ # a_array -- PyArrayObject *
+ # a -- py_array->data cast to the proper data type
+
+ a = np.ones((4,4), np.float64)
+ # for the sake of driving home the "dynamic code" approach...
+ dtype2ctype = {
+ np.dtype(np.float64): 'double',
+ np.dtype(np.float32): 'float',
+ np.dtype(np.int32): 'int',
+ np.dtype(np.int16): 'short',
+ }
+ dt = dtype2ctype.get(a.dtype)
+
+ # this code does a = a*b inplace, broadcasting b to fit the shape of a
+ code = \
+"""
+%s *p1, *p2;
+PyObject *itr;
+itr = PyArray_MultiIterNew(2, a_array, b_array);
+while(PyArray_MultiIter_NOTDONE(itr)) {
+ p1 = (%s *) PyArray_MultiIter_DATA(itr, 0);
+ p2 = (%s *) PyArray_MultiIter_DATA(itr, 1);
+ *p1 = (*p1) * (*p2);
+ PyArray_MultiIter_NEXT(itr);
+}
+""" % (dt, dt, dt)
+
+ b = np.arange(4, dtype=a.dtype)
+ print '\n A B '
+ print a, b
+ # this reshaping is redundant, it would be the default broadcast
+ b.shape = (1,4)
+ inline(code, ['a', 'b'])
+ print "\ninline version of a*b,"
+ print a
+ a = np.ones((4,4), np.float64)
+ b.shape = (4,1)
+ inline(code, ['a', 'b'])
+ print "\ninline version of a*b[:,None],"
+ print a
+
+def data_casting_test():
+ # In my MR application, raw data is stored as a file with one or more
+ # (block-hdr, block-data) pairs. Block data is one or more
+ # rows of Npt complex samples in big-endian integer pairs (real, imag).
+ #
+ # At the block level, I encounter three different raw data layouts--
+ # 1) one plane, or slice: Y rows by 2*Npt samples
+ # 2) one volume: Z slices * Y rows by 2*Npt samples
+ # 3) one row sliced across the z-axis: Z slices by 2*Npt samples
+ #
+ # The task is to tease out one volume at a time from any given layout,
+ # and cast the integer precision data into a complex64 array.
+ # Given that contiguity is not guaranteed, and the number of dimensions
+ # can vary, Numpy iterators are useful to provide a single code that can
+ # carry out the conversion.
+ #
+ # Other solutions include:
+ # 1) working entirely with the string data from file.read() with string
+ # manipulations (simulated below).
+ # 2) letting numpy handle automatic byteorder/dtype conversion
+
+ nsl, nline, npt = (20,64,64)
+ hdr_dt = np.dtype('>V28')
+ # example 1: a block is one slice of complex samples in short integer pairs
+ blk_dt1 = np.dtype(('>i2', nline*npt*2))
+ dat_dt = np.dtype({'names': ['hdr', 'data'], 'formats': [hdr_dt, blk_dt1]})
+ # create an empty volume-- nsl contiguous blocks
+ vol = np.empty((nsl,), dat_dt)
+ t = time_casting(vol[:]['data'])
+ plt.plot(100*t/t.max(), 'b--', label='vol=20 contiguous blocks')
+ plt.plot(100*t/t.max(), 'bo')
+ # example 2: a block is one entire volume
+ blk_dt2 = np.dtype(('>i2', nsl*nline*npt*2))
+ dat_dt = np.dtype({'names': ['hdr', 'data'], 'formats': [hdr_dt, blk_dt2]})
+ # create an empty volume-- 1 block
+ vol = np.empty((1,), dat_dt)
+ t = time_casting(vol[0]['data'])
+ plt.plot(100*t/t.max(), 'g--', label='vol=1 contiguous block')
+ plt.plot(100*t/t.max(), 'go')
+ # example 3: a block slices across the z dimension, long integer precision
+ # ALSO--a given volume is sliced discontiguously
+ blk_dt3 = np.dtype(('>i4', nsl*npt*2))
+ dat_dt = np.dtype({'names': ['hdr', 'data'], 'formats': [hdr_dt, blk_dt3]})
+ # a real data set has volumes interleaved, so create two volumes here
+ vols = np.empty((2*nline,), dat_dt)
+ # and work on casting the first volume
+ t = time_casting(vols[0::2]['data'])
+ plt.plot(100*t/t.max(), 'r--', label='vol=64 discontiguous blocks')
+ plt.plot(100*t/t.max(), 'ro')
+ plt.xticks([0,1,2], ('strings', 'numpy auto', 'inline'))
+ plt.gca().set_xlim((-0.25, 2.25))
+ plt.gca().set_ylim((0, 110))
+ plt.gca().set_ylabel(r"% of slowest time")
+ plt.legend(loc=8)
+ plt.title('Casting raw file data to an MR volume')
+ plt.show()
+
+
+def time_casting(int_data):
+ nblk = 1 if len(int_data.shape) < 2 else int_data.shape[0]
+ bias = (np.random.rand(nblk) + \
+ 1j*np.random.rand(nblk)).astype(np.complex64)
+ dstr = int_data.tostring()
+ dt = np.int16 if int_data.dtype.itemsize == 2 else np.int32
+ fshape = list(int_data.shape)
+ fshape[-1] = fshape[-1]/2
+ float_data = np.empty(fshape, np.complex64)
+ # method 1: string conversion
+ float_data.shape = (np.product(fshape),)
+ tstr = measure("float_data[:] = complex_fromstring(dstr, dt)", times=25)
+ float_data.shape = fshape
+ print "to-/from- string: ", tstr, "shape=",float_data.shape
+
+ # method 2: numpy dtype magic
+ sl = [None, slice(None)] if len(fshape)<2 else [slice(None)]*len(fshape)
+ # need to loop since int_data need not be contiguous
+ tnpy = measure("""
+for fline, iline, b in zip(float_data[sl], int_data[sl], bias):
+ cast_to_complex_npy(fline, iline, bias=b)""", times=25)
+ print"numpy automagic: ", tnpy
+
+ # method 3: plain inline brute force!
+ twv = measure("cast_to_complex(float_data, int_data, bias=bias)",
+ times=25)
+ print"inline casting: ", twv
+ return np.array([tstr, tnpy, twv], np.float64)
+
+def complex_fromstring(data, numtype):
+ if sys.byteorder == "little":
+ return np.fromstring(
+ np.fromstring(data,numtype).byteswap().astype(np.float32).tostring(),
+ np.complex64)
+ else:
+ return np.fromstring(
+ np.fromstring(data,numtype).astype(np.float32).tostring(),
+ np.complex64)
+
+def cast_to_complex(cplx_float, cplx_integer, bias=None):
+ if cplx_integer.dtype.itemsize == 4:
+ replacements = tuple(["l", "long", "SWAPLONG", "l"]*2)
+ else:
+ replacements = tuple(["s", "short", "SWAPSHORT", "s"]*2)
+ if sys.byteorder == "big":
+ replacements[-2] = replacements[-6] = "NOP"
+
+ cast_code = """
+ #define SWAPSHORT(x) ((short) ((x >> 8) | (x << 8)) )
+ #define SWAPLONG(x) ((long) ((x >> 24) | (x << 24) | ((x & 0x00ff0000) >> 8) | ((x & 0x0000ff00) << 8)) )
+ #define NOP(x) x
+
+ unsigned short *s;
+ unsigned long *l;
+ float repart, impart;
+ PyObject *itr;
+ itr = PyArray_IterNew(py_cplx_integer);
+ while(PyArray_ITER_NOTDONE(itr)) {
+
+ // get real part
+ %s = (unsigned %s *) PyArray_ITER_DATA(itr);
+ repart = %s(*%s);
+ PyArray_ITER_NEXT(itr);
+ // get imag part
+ %s = (unsigned %s *) PyArray_ITER_DATA(itr);
+ impart = %s(*%s);
+ PyArray_ITER_NEXT(itr);
+ *(cplx_float++) = std::complex<float>(repart, impart);
+
+ }
+ """ % replacements
+
+ inline(cast_code, ['cplx_float', 'cplx_integer'])
+ if bias is not None:
+ if len(cplx_float.shape) > 1:
+ bsl = [slice(None)]*(len(cplx_float.shape)-1) + [None]
+ else:
+ bsl = slice(None)
+ np.subtract(cplx_float, bias[bsl], cplx_float)
+
+def cast_to_complex_npy(cplx_float, cplx_integer, bias=None):
+ cplx_float.real[:] = cplx_integer[0::2]
+ cplx_float.imag[:] = cplx_integer[1::2]
+ if bias is not None:
+ np.subtract(cplx_float, bias, cplx_float)
+
+if __name__=="__main__":
+ data_casting_test()
+ multi_iter_example()
Property changes on: trunk/py4science/examples/iterators_example.py
___________________________________________________________________
Added: svn:executable
+ *
Deleted: trunk/py4science/examples/numpy-blitz_1000.png
===================================================================
(Binary files differ)
Deleted: trunk/py4science/examples/numpy-blitz_300.png
===================================================================
(Binary files differ)
Deleted: trunk/py4science/examples/numpy-blitz_500.png
===================================================================
(Binary files differ)
Added: trunk/py4science/examples/numpy_wrap/f2py/example3/test_example.py
===================================================================
--- trunk/py4science/examples/numpy_wrap/f2py/example3/test_example.py (rev 0)
+++ trunk/py4science/examples/numpy_wrap/f2py/example3/test_example.py 2008-10-19 08:30:58 UTC (rev 6271)
@@ -0,0 +1,9 @@
+import example
+import numpy
+
+x = numpy.arange(10.)
+
+yf = example.cumsum(x)
+yn = numpy.cumsum(x)
+
+numpy.testing.assert_array_almost_equal(yf, yn)
Added: trunk/py4science/examples/numpy_wrap/f2py/example3/test_fib.py
===================================================================
--- trunk/py4science/examples/numpy_wrap/f2py/example3/test_fib.py (rev 0)
+++ trunk/py4science/examples/numpy_wrap/f2py/example3/test_fib.py 2008-10-19 08:30:58 UTC (rev 6271)
@@ -0,0 +1,13 @@
+import numpy as N
+
+import example
+
+n = 10
+fn = example.fib(n)
+
+print 'Fibonacci numbers:'
+print fn
+
+# Check validity
+assert N.alltrue(fn[2:]== fn[1:-1]+fn[:-2]), "Fibonacci mismatch"
+
Added: trunk/py4science/examples/numpytemps.py
===================================================================
--- trunk/py4science/examples/numpytemps.py (rev 0)
+++ trunk/py4science/examples/numpytemps.py 2008-10-19 08:30:58 UTC (rev 6271)
@@ -0,0 +1,85 @@
+#!/usr/bin/env python
+"""Demonstration of temporaries in Numpy.
+"""
+
+import numpy as np
+import numpy.testing as nptest
+
+import nose
+
+# convenience global names
+from numpy import (pi, sin, cos, add, subtract, multiply, power)
+
+def test1():
+ """Verify an expression using temporaries.
+ """
+ x = np.linspace(0,2*pi,100)
+
+ # We compute a simple mathematical expression using algebra and functions
+ # of x. This uses a lot of temporaries that are implicitly created. In
+ # total, the variable count is:
+ # sin(x): 1
+ # sin(2*x): 2
+ # 4.5*cos(3*x**2): 4
+ # The final temporaries for each term are added and the result stored as y,
+ # which is also created. So we have 1 array for the result and 7 temps.
+ y = sin(x) + sin(2*x) - 4.5*cos(3*x**2)
+
+ # Now we do it again, but here, we control the temporary creation
+ # ourselves. We use the output argument of all numpy functional forms of
+ # the operators.
+
+ # Initialize the array that will hold the output, empty
+ z = np.empty_like(x)
+ # This version in total uses 1 array for the result and one temporary.
+ tmp = np.empty_like(x)
+
+ # Now, we compute each term of the expression above. Each time, we either
+ # store the output back into the temporary or we accumulate it in z.
+
+ # sin(x)
+ sin(x,z)
+
+ # + sin(2*x)
+ add(z,sin(multiply(2,x,tmp),tmp),z)
+
+ # - 4.5*cos(3*x**2)
+ power(x,2,tmp)
+ multiply(3,tmp,tmp)
+ cos(tmp,tmp)
+ multiply(4.5,tmp,tmp)
+ subtract(z,tmp,z)
+
+ # Verify that the two forms match to 13 digits
+ nptest.assert_almost_equal(y,z,13)
+
+
+def test2():
+ """Compute the same expression, using in-place operations
+ """
+ x = np.linspace(0,2*pi,100)
+
+ y = sin(x) + sin(2*x) - 4.5*cos(3*x**2)
+
+ # This version of the code uses more in-place operators, which make it a
+ # bit more readable and still avoid temporaries
+ tmp = np.empty_like(x)
+
+ # sin(x)
+ z = sin(x)
+
+ # + sin(2*x)
+ z += sin(multiply(2,x,tmp),tmp)
+
+ # - 4.5*cos(3*x**2)
+ power(x,2,tmp)
+ tmp *= 3
+ cos(tmp,tmp)
+ tmp *= 4.5
+ z -= tmp
+
+ # Verify that the two forms match to 13 digits
+ nptest.assert_almost_equal(y,z,13)
+
+if __name__ == '__main__':
+ nose.runmodule(exit=False)
Property changes on: trunk/py4science/examples/numpytemps.py
___________________________________________________________________
Added: svn:executable
+ *
Added: trunk/py4science/examples/recarray/recarr_simple.py
===================================================================
--- trunk/py4science/examples/recarray/recarr_simple.py (rev 0)
+++ trunk/py4science/examples/recarray/recarr_simple.py 2008-10-19 08:30:58 UTC (rev 6271)
@@ -0,0 +1,43 @@
+"""Utility module to load measurements into Numpy record arrays.
+
+Loading measurement files with the format:
+
+#Station Lat Long Elev
+BIRA 26.4840 87.2670 0.0120
+BUNG 27.8771 85.8909 1.1910
+etc...
+"""
+
+import numpy as np
+import pylab as plt
+
+# Simple example of usage
+
+# Data descriptor to make a proper array.
+dt = [('station','S4'),('lat',np.float32),('lon',np.float32),
+ ('elev',np.float32)]
+# This is an alternate and fully equivalent form:
+dt = dict(names = ('station','lat','lon','elev'),
+ formats = ('S4',np.float32,np.float32,np.float32) )
+
+# For more on dtypes, see:
+# http://mentat.za.net/numpy/refguide/arrays.recarray.xhtml
+import math
+
+def tlog(s):
+ return np.float32(math.log(float(s)))
+
+tab = np.loadtxt('HIMNTstations2.txt',dt,
+ converters={1:tlog})
+
+print 'Stations:',tab['station']
+print 'Elevations:',tab['elev']
+print 'First station:',tab[0]
+print 'Mean latitude:',tab['lat'].mean()
+
+plt.figure()
+plt.scatter(tab['lat'],tab['lon'],30*tab['elev'],
+ c=tab['elev'],
+ cmap=plt.cm.bone,
+ )
+plt.show()
Added: trunk/py4science/examples/recarray/recarr_simple_data.txt
===================================================================
--- trunk/py4science/examples/recarray/recarr_simple_data.txt (rev 0)
+++ trunk/py4science/examples/recarray/recarr_simple_data.txt 2008-10-19 08:30:58 UTC (rev 6271)
@@ -0,0 +1,29 @@
+BIRA 26.4840 87.2670 0.0120
+BUNG 27.8771 85.8909 1.1910
+GAIG 26.8380 86.6318 0.1660
+HILE 27.0482 87.3242 2.0880
+ILAM 26.9102 87.9227 1.1810
+JIRI 27.6342 86.2303 1.8660
+NAMC 27.8027 86.7146 3.5230
+PHAP 27.5150 86.5842 2.4880
+PHID 27.1501 87.7645 1.1760
+RUMJ 27.3038 86.5482 1.3190
+SIND 27.2107 85.9088 0.4650
+THAK 27.5996 85.5566 1.5510
+TUML 27.3208 87.1950 0.3600
+LAZE 29.1403 87.5922 4.0110
+SAJA 28.9093 88.0209 4.3510
+ONRN 29.3020 87.2440 4.3500
+SSAN 29.4238 86.7290 4.5850
+SAGA 29.3292 85.2321 4.5240
+DINX 28.6646 87.1157 4.3740
+RBSH 28.1955 86.8280 5.1000
+NAIL 28.6597 86.4126 4.3780
+MNBU 28.7558 86.1610 4.5000
+NLMU 28.1548 85.9777 3.8890
+YALA 28.4043 86.1133 4.4340
+XIXI 28.7409 85.6904 4.6600
+RC14 29.4972 86.4373 4.7560
+MAZA 28.6713 87.8553 4.3670
+JANA 26.7106 85.9242 0.0770
+SUKT 27.7057 85.7611 0.7450
Added: trunk/py4science/examples/txt_data_load.py
===================================================================
--- trunk/py4science/examples/txt_data_load.py (rev 0)
+++ trunk/py4science/examples/txt_data_load.py 2008-10-19 08:30:58 UTC (rev 6271)
@@ -0,0 +1,98 @@
+#!/usr/bin/env python
+"""Read files from Maribeth's format into arrays."""
+
+# Needed modules from the standard library
+import re
+import sys
+
+# Third party modules
+import numpy as N
+
+# Code begins
+def mwread(fname):
+ """Read mw file and return dict with arrays.
+
+ The input data is assumed to be in a file whose format is:
+
+ r:
+ 0.250029, 0.249549, 0.25019, 0.250232
+
+ A:
+ 0.399973, 0.199979, 0.200005, 0.200014
+ 0.199992, 0.400235, 0.200033, 0.200102
+
+ B:
+ 0.428502, 0.142868, 0.142897, 0.142838
+ 0.142884, 0.57165, 0.143053, 0.285911
+
+ The output is a dict whose keys are the letter labels ('r','A','B', etc)
+ and whose values are one-dimensional NumPy arrays with the numbers, in
+ double precision.
+
+ :Parameters:
+ fname : string
+ Name of the input file."""
+
+ fobj = open(fname)
+
+ # Regular expression to match array labels
+ label_re = re.compile('^([a-zA-Z])+:')
+
+ # Initialize output dict
+ dct = {}
+ # Start the state machine in 'scan' mode and switch to data reading mode
+ # ('read') whenever we find what looks like a label.
+ mode = 'scan'
+ for line in fobj:
+ if mode == 'scan':
+ match = label_re.match(line)
+ if match:
+ # Switch modes
+ mode = 'read'
+ # Prepare state for read mode
+ name = match.group(1)
+ data = []
+ elif mode == 'read':
+ if line.isspace():
+ # Pure whitespace lines force a mode switch back to
+ # scanning for variables
+ mode = 'scan'
+ # Store the data that we'd been accumulating for the
+ # current array
+ dct[name] = N.array(data,float)
+ else:
+ # Read data, assume line contains comma-separated strings
+ # of numbers
+ data.extend([float(n) for n in line.split(',')])
+
+ # Cleanup before exiting
+ fobj.close()
+
+ return dct
+
+
+# If run as a script
+if __name__ == '__main__':
+ # This allows calling it from the command line with the name of the file to
+ # read as an argument
+ try:
+ fname = sys.argv[1]
+ except IndexError:
+ print 'First argument must be filename to read'
+ sys.exit(1)
+
+ data = mwread(fname)
+ print 'Data dict:'
+ for k,val in data.iteritems():
+ print '%s:' % k
+ print val
+ print
+
+ # Now, load the names from the data dict as top-level variables (use
+ # specially named counters just in case the file declares something common
+ # like 'k'):
+ for _k,_val in data.iteritems():
+ exec '%s = _val' % _k
+
+ print "Now, you can use either the top-level dict 'data', or the variables:"
+ print data.keys()
Property changes on: trunk/py4science/examples/txt_data_load.py
___________________________________________________________________
Added: svn:executable
+ *
Added: trunk/py4science/examples/txt_data_sample.txt
===================================================================
--- trunk/py4science/examples/txt_data_sample.txt (rev 0)
+++ trunk/py4science/examples/txt_data_sample.txt 2008-10-19 08:30:58 UTC (rev 6271)
@@ -0,0 +1,21 @@
+r:
+ 0.250029, 0.249549, 0.25019, 0.250232
+
+A:
+ 0.399973, 0.199979, 0.200005, 0.200014
+ 0.199992, 0.400235, 0.200033, 0.200102
+ 0.2, 0.199919, 0.399979, 0.199954
+ 0.200035, 0.199867, 0.199984, 0.39993
+
+B:
+ 0.428502, 0.142868, 0.142897, 0.142838
+ 0.142884, 0.57165, 0.143053, 0.285911
+ 0.285747, 0.142757, 0.71391, 0.142854
+ 0.142867, 0.142725, 0.000140224, 0.428397
+
+C:
+ 0.666707, 0.166664, 0.166626, 0.16662
+ 0.166638, 0.500328, 0.166752, 0.166883
+ 0.166654, 0.166609, 0.333309, 0.166638
+1.49295e-07, 0.166399, 0.333314, 0.499859
+
Deleted: trunk/py4science/examples/weave_blitz_comp.png
===================================================================
(Binary files differ)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-10-24 15:54:02
|
Revision: 6321
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6321&view=rev
Author: jdh2358
Date: 2008-10-24 15:53:59 +0000 (Fri, 24 Oct 2008)
Log Message:
-----------
added action potential example
Added Paths:
-----------
trunk/py4science/examples/data/membrane.dat
trunk/py4science/examples/detect_action_potentials.py
Added: trunk/py4science/examples/data/membrane.dat
===================================================================
--- trunk/py4science/examples/data/membrane.dat (rev 0)
+++ trunk/py4science/examples/data/membrane.dat 2008-10-24 15:53:59 UTC (rev 6321)
@@ -0,0 +1,64 @@
+\xB0\xFA*\xBF\xB0\xFA*\xBF\xBA\x9A+\xBF\xB0\xFA*\xBF\xB0\xFA*\xBF\xC4:,\xBF\xC4:,\xBF\xC4:,\xBF\xB0\xFA*\xBF\xBA\x9A+\xBF\xBA\x9A+\xBF\xB0\xFA*\xBF\xBA\x9A+\xBF\xB0\xFA*\xBF\xA6Z*\xBF\xB0\xFA*\xBF\xB0\xFA*\xBF\xA6Z*\xBF\xA6Z*\xBF\xB0\xFA*\xBF\xC4:,\xBF\xC4:,\xBF\x9C\xBA)\xBF\xA6Z*\xBF\xA6Z*\xBF\xB0\xFA*\xBF\xB0\xFA*\xBF\xB0\xFA*\xBF\xBA\x9A+\xBF\xC4:,\xBF\xC4:,\xBF\xB0\xFA*\xBF\xBA\x9A+\xBF\xB0\xFA*\xBF\xBA\x9A+\xBF\xBA\x9A+\xBF\xBA\x9A+\xBF\xBA\x9A+\xBF\xBA\x9A+\xBF\xBA\x9A+\xBF\xB0\xFA*\xBF\xB0\xFA*\xBF\xBA\x9A+\xBF\xBA\x9A+\xBF\xBA\x9A+\xBF\xB0\xFA*\xBF\xB0\xFA*\xBF\xBA\x9A+\xBF\xA6Z*\xBF\xB0\xFA*\xBF\xB0\xFA*\xBF\xBA\x9A+\xBF\xBA\x9A+\xBF\xB0\xFA*\xBF\xBA\x9A+\xBF\xBA\x9A+\xBF\xBA\x9A+\xBF\xB0\xFA*\xBF\xB0\xFA*\xBF\xB0\xFA*\xBF\xA6Z*\xBF\xA6Z*\xBF\xB0\xFA*\xBF\xBA\x9A+\xBF\xA6Z*\xBF\xBA\x9A+\xBF\xBA\x9A+\xBF\xA6Z*\xBF\x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F\xA8x
+\xBF\x8A\x98\xBF\xA8x
+\xBF\x9E\xD8 \xBF\x948 \xBF\x8A\x98\xBF\xA8x
+\xBF\xA8x
+\xBF\x80\xF8\xBF\x8A\x98\xBF\x8A\x98\xBF\x80\xF8\xBFl\xB8\xBFl\xB8\xBFvX\xBFl\xB8\xBFl\xB8\xBFN\xD8\xBFb\xBFb\xBFXx\xBFXx\xBFN\xD8\xBF:\x98\xBF:\x98\xBF:\x98\xBF&X\xBF&X\xBF\xB8\xBF&X\xBF&X\xBF\xFB\xAF\xFF\xBEx |
|
From: <fer...@us...> - 2008-10-25 03:44:47
|
Revision: 6331
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6331&view=rev
Author: fer_perez
Date: 2008-10-25 03:44:44 +0000 (Sat, 25 Oct 2008)
Log Message:
-----------
Updated skeletons and mkprob to report number of lines missing.
Modified Paths:
--------------
trunk/py4science/examples/mkprob.py
trunk/py4science/examples/skel/fft_imdenoise_skel.py
trunk/py4science/examples/skel/qsort_skel.py
trunk/py4science/examples/skel/quad_newton_skel.py
trunk/py4science/examples/skel/trapezoid_skel.py
Modified: trunk/py4science/examples/mkprob.py
===================================================================
--- trunk/py4science/examples/mkprob.py 2008-10-25 03:37:12 UTC (rev 6330)
+++ trunk/py4science/examples/mkprob.py 2008-10-25 03:44:44 UTC (rev 6331)
@@ -91,9 +91,9 @@
# Add the summary of 'raise' lines
# flush counter of code (disabled, we report static summary)
- #msg = '1 line' if del_lines==1 else ('%s lines' % del_lines)
- #exc = exc_tpl % msg
- exc = exc_tpl
+ msg = '1 line' if del_lines==1 else ('%s lines' % del_lines)
+ exc = exc_tpl % msg
+ #exc = exc_tpl
# Use the last value of 'space'
line = '%s%s' % (spaces[0],exc)
@@ -104,8 +104,8 @@
return del_lines
# used to report actual # of lines removed - disabled
- #exc_tpl = "raise NotImplementedError('%s missing')\n"
- exc_tpl = "raise NotImplementedError('insert missing code here')\n"
+ exc_tpl = "raise NotImplementedError('Original solution has %s')\n"
+ #exc_tpl = "raise NotImplementedError('insert missing code here')\n"
# states for state machine and other initialization
normal,delete = 0,1
@@ -241,7 +241,7 @@
clean = """
first line
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 1 line')
second line
"""
@@ -279,12 +279,12 @@
first line
# Hint: remember that
# idea we discussed before...
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 3 lines')
second line:
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 2 lines')
third line
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 2 lines')
"""
cleaned = src2skel(srclines)
yield str_match,cleaned,clean
Modified: trunk/py4science/examples/skel/fft_imdenoise_skel.py
===================================================================
--- trunk/py4science/examples/skel/fft_imdenoise_skel.py 2008-10-25 03:37:12 UTC (rev 6330)
+++ trunk/py4science/examples/skel/fft_imdenoise_skel.py 2008-10-25 03:44:44 UTC (rev 6331)
@@ -17,12 +17,12 @@
# Compute the magnitude of the input F (call it mag). Then, rescale mag by
# amplify/maximum_of_mag. Numpy arrays can be scaled in-place with ARR *=
# number. For the max of an array, look for its max method.
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 2 lines')
# Next, clip all values larger than one to one. You can set all elements
# of an array which satisfy a given condition with array indexing syntax:
# ARR[ARR<VALUE] = NEWVALUE, for example.
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 1 line')
# Display: this one already works, if you did everything right with mag
plt.imshow(mag, plt.cm.Blues)
@@ -39,7 +39,7 @@
# - extract all rows, all columns, 0-th plane to get the first
# channel
# - the resulting array should have 2 dimensions only
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 1 line')
print "Image shape:",im.shape
except:
print "Could not open image."
@@ -48,7 +48,7 @@
# Compute the 2d FFT of the input image
# Hint: Look for a 2-d FFT in np.fft.
# Note: call this variable 'F', which is the name we'll be using below.
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 1 line')
# In the lines following, we'll make a copy of the original spectrum and
# truncate coefficients. NO immediate code is to be written right here.
@@ -58,25 +58,25 @@
# Call ff a copy of the original transform. Numpy arrays have a copy
# method for this purpose.
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 1 line')
# Set r and c to be the number of rows and columns of the array.
# Hint: use the array's shape attribute.
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 1 line')
# Set to zero all rows with indices between r*keep_fraction and
# r*(1-keep_fraction):
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 1 line')
# Similarly with the columns:
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 1 line')
# Reconstruct the denoised image from the filtered spectrum, keep only the
# real part for display.
# Hint: There's an inverse 2d fft in the np.fft module as well (don't
# forget that you only want the real part).
# Call the result im_new,
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 1 line')
# Show the results
# The code below already works, if you did everything above right.
Modified: trunk/py4science/examples/skel/qsort_skel.py
===================================================================
--- trunk/py4science/examples/skel/qsort_skel.py 2008-10-25 03:37:12 UTC (rev 6330)
+++ trunk/py4science/examples/skel/qsort_skel.py 2008-10-25 03:44:44 UTC (rev 6331)
@@ -37,13 +37,13 @@
"""
# Hint: remember that all recursive functions need an exit condition
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 2 lines')
# Select pivot and apply recursively
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 3 lines')
# Upon return, make sure to properly concatenate the output lists
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 1 line')
#-----------------------------------------------------------------------------
Modified: trunk/py4science/examples/skel/quad_newton_skel.py
===================================================================
--- trunk/py4science/examples/skel/quad_newton_skel.py 2008-10-25 03:37:12 UTC (rev 6330)
+++ trunk/py4science/examples/skel/quad_newton_skel.py 2008-10-25 03:44:44 UTC (rev 6331)
@@ -10,7 +10,7 @@
# test input function
def f(t):
# f(t): t * sin^2(t)
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 1 line')
def g(t):
"Exact form for g by integrating f(t)"
@@ -21,18 +21,18 @@
"g(t) obtained by numerical integration"
u = 0.25
# Hint: use quad, see its return value carefully.
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 1 line')
# main
tguess = 10.0
print '"Exact" solution (knowing the analytical form of the integral)'
-raise NotImplementedError('insert missing code here')
+raise NotImplementedError('Original solution has 1 line')
print "t0, g(t0) =",t0,g(t0)
print
print "Solution using the numerical integration technique"
-raise NotImplementedError('insert missing code here')
+raise NotImplementedError('Original solution has 1 line')
print "t1, g(t1) =",t1,g(t1)
print
Modified: trunk/py4science/examples/skel/trapezoid_skel.py
===================================================================
--- trunk/py4science/examples/skel/trapezoid_skel.py 2008-10-25 03:37:12 UTC (rev 6330)
+++ trunk/py4science/examples/skel/trapezoid_skel.py 2008-10-25 03:44:44 UTC (rev 6331)
@@ -20,13 +20,13 @@
#
# Hint: if the two inputs have mismatched lengths or less than 2
# elements, we raise ValueError with an explanatory message.
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 4 lines')
# Efficient application of trapezoid rule via numpy
#
# Hint: think of using numpy slicing to compute the moving difference in
# the basic trapezoid formula.
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 1 line')
def trapzf(f,a,b,npts=100):
"""Simple trapezoid-based integrator.
@@ -48,20 +48,20 @@
# what differences in timings result for long vectors x?
# Generate an equally spaced grid to sample the function.
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 1 line')
# For an equispaced grid, the x spacing can just be read off from the first
# two points and factored out of the summation.
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 1 line')
# Sample the input function at all values of x
#
# Hint: you need to make an array out of the evaluations, and the python
# builtin 'map' function can come in handy.
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 1 line')
# Compute the trapezoid rule sum for the final result
- raise NotImplementedError('insert missing code here')
+ raise NotImplementedError('Original solution has 1 line')
#-----------------------------------------------------------------------------
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-10-26 14:33:46
|
Revision: 6336
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6336&view=rev
Author: jdh2358
Date: 2008-10-26 14:33:36 +0000 (Sun, 26 Oct 2008)
Log Message:
-----------
added glass dots skel
Modified Paths:
--------------
trunk/py4science/examples/glass_dots1.py
trunk/py4science/examples/glass_dots2.py
Added Paths:
-----------
trunk/py4science/examples/glass_dots1_skel.py
Modified: trunk/py4science/examples/glass_dots1.py
===================================================================
--- trunk/py4science/examples/glass_dots1.py 2008-10-25 07:06:53 UTC (rev 6335)
+++ trunk/py4science/examples/glass_dots1.py 2008-10-26 14:33:36 UTC (rev 6336)
@@ -6,10 +6,9 @@
See L. Glass. 'Moire effect from random dots' Nature 223, 578580 (1969).
"""
import cmath
-from numpy import cos, sin, pi, matrix
-import numpy as npy
+import numpy as np
import numpy.linalg as linalg
-from pylab import figure, show
+import matplotlib.pyplot as plt
def myeig(M):
@@ -18,10 +17,16 @@
Solve quadratic:
- lamba^2 - tau*lambda + Delta = 0
+ lamba^2 - tau*lambda +/- Delta = 0
where tau = trace(M) and Delta = Determinant(M)
-
+
+ if M = | a b |
+ | c d |
+
+ the trace is a+d and the determinant is a*d-b*c
+
+ Return value is lambda1, lambda2
"""
a,b = M[0,0], M[0,1]
@@ -32,31 +37,29 @@
lambda1 = (tau + cmath.sqrt(tau**2 - 4*delta))/2.
lambda2 = (tau - cmath.sqrt(tau**2 - 4*delta))/2.
return lambda1, lambda2
-
+
# 2000 random x,y points in the interval[-0.5 ... 0.5]
-X1 = matrix(npy.random.rand(2,2000)
- )-0.5
+X1 = np.random.rand(2,2000)-0.5
-name = 'saddle'
-sx, sy, angle = 1.05, 0.95, 0.
+#name = 'saddle'
+#sx, sy, angle = 1.05, 0.95, 0.
-#name = 'center'
-#sx, sy, angle = 1., 1., 2.5
+name = 'center'
+sx, sy, angle = 1., 1., 2.5
#name= 'stable focus' # spiral
#sx, sy, angle = 0.95, 0.95, 2.5
-theta = angle * pi/180.
+theta = angle * cmath.pi/180.
+S = np.array([[sx, 0],
+ [0, sy]])
-S = matrix([[sx, 0],
- [0, sy]])
+R = np.array([[np.cos(theta), -np.sin(theta)],
+ [np.sin(theta), np.cos(theta)],])
-R = matrix([[cos(theta), -sin(theta)],
- [sin(theta), cos(theta)],])
+M = np.dot(S, R) # rotate then stretch
-M = S*R # rotate then stretch
-
# compute the eigenvalues using numpy linear algebra
vals, vecs = linalg.eig(M)
print 'numpy eigenvalues', vals
@@ -66,17 +69,17 @@
print 'analytic eigenvalues', avals
# transform X1 by the matrix
-X2 = M*X1
+X2 = np.dot(M, X1)
# plot the original x,y as green dots and the transformed x, y as red
# dots
-fig = figure()
+fig = plt.figure()
ax = fig.add_subplot(111)
-x1 = X1[0].flat
-y1 = X1[1].flat
-x2 = X2[0].flat
-y2 = X2[1].flat
+x1 = X1[0]
+y1 = X1[1]
+x2 = X2[0]
+y2 = X2[1]
ax = fig.add_subplot(111)
line1, line2 = ax.plot(x1, y1, 'go', x2, y2, 'ro', markersize=2)
@@ -85,4 +88,4 @@
fig.savefig('glass_dots1.png', dpi=100)
fig.savefig('glass_dots1.eps', dpi=100)
-show()
+plt.show()
Added: trunk/py4science/examples/glass_dots1_skel.py
===================================================================
--- trunk/py4science/examples/glass_dots1_skel.py (rev 0)
+++ trunk/py4science/examples/glass_dots1_skel.py 2008-10-26 14:33:36 UTC (rev 6336)
@@ -0,0 +1,80 @@
+"""
+Moire patterns from random dot fields
+
+http://en.wikipedia.org/wiki/Moir%C3%A9_pattern
+
+See L. Glass. 'Moire effect from random dots' Nature 223, 578580 (1969).
+"""
+import cmath
+import numpy as np
+import numpy.linalg as linalg
+import matplotlib.pyplot as plt
+
+# search for TODO to find the places you need to fix
+TODO = None
+
+def myeig(M):
+ """
+ compute eigen values and eigenvectors analytically
+
+ Solve quadratic:
+
+ lamba^2 - tau*lambda +/- Delta = 0
+
+ where tau = trace(M) and Delta = Determinant(M)
+
+ if M = | a b |
+ | c d |
+
+ the trace is a+d and the determinant is a*d-b*c
+
+ Return value is lambda1, lambda2
+
+ Return value is lambda1, lambda2
+ """
+ # TODO : compute the real values here. 0, 1 is just a place holder
+ return 0, 1
+
+# Generate and shape (2000,2) random x,y points in the
+# interval [-0.5 ... 0.5]
+X1 = TODO
+
+# these are the scaling factor sx, the scaling factor sy, and the
+# rotation angle 0
+name = 'saddle'
+sx, sy, angle = 1.05, 0.95, 0.
+
+# OPTIONAL: try and find other sx, sy, theta for other kinds of nodes:
+# stable node, unstable node, center, spiral, saddle
+
+# convert theta to radians: theta = angle * pi/180
+theta = TODO
+
+# Create a 2D scaling array
+# S = | sx 0 |
+# | 0 sy |
+S = TODO
+
+# create a 2D rotation array
+# R = | cos(theta) -sin(theta) |
+# | sin(theta) cos(theta) |
+R = TODO
+
+# do a matrix multiply M = S x R where x is *matrix* multiplication
+M = TODO
+
+# compute the eigenvalues using numpy linear algebra
+vals, vecs = linalg.eig(M)
+print 'numpy eigenvalues', vals
+
+# compare with the analytic values from myeig
+avals = myeig(M)
+print 'analytic eigenvalues', avals
+
+# transform X1 by the matrix
+# X2 = M x X1 where x is *matrix* multiplication
+X2 = np.dot(M, X1)
+
+# plot the original x,y as green dots and the transformed x, y as red
+# dots
+TODO
Modified: trunk/py4science/examples/glass_dots2.py
===================================================================
--- trunk/py4science/examples/glass_dots2.py 2008-10-25 07:06:53 UTC (rev 6335)
+++ trunk/py4science/examples/glass_dots2.py 2008-10-26 14:33:36 UTC (rev 6336)
@@ -1,4 +1,4 @@
-import numpy as npy
+import numpy as np
import numpy.linalg as linalg
from pylab import figure, show
@@ -12,15 +12,15 @@
self.axes = axes
self.canvas = axes.figure.canvas
self.canvas.mpl_connect('button_press_event', self.press)
- self.canvas.mpl_connect('button_release_event', self.release)
- self.canvas.mpl_connect('motion_notify_event', self.move)
+ self.canvas.mpl_connect('button_release_event', self.release)
+ self.canvas.mpl_connect('motion_notify_event', self.move)
- X1 = self.X1 = npy.matrix(npy.random.rand(2,2000))-0.5
+ X1 = self.X1 = np.random.rand(2,2000)-0.5
- x1 = X1[0].flat
- y1 = X1[1].flat
- x2 = X1[0].flat # no transformation yet
- y2 = X1[1].flat
+ x1 = X1[0]
+ y1 = X1[1]
+ x2 = X1[0] # no transformation yet
+ y2 = X1[1]
self.line1, self.line2 = ax.plot(x1, y1,'go', x2, y2, 'ro', markersize=2)
self.xlast = None
self.ylast = None
@@ -37,37 +37,37 @@
self.xlast = None
self.ylast = None
self.draw()
-
+
def draw(self):
sx, sy, theta = self.sx, self.sy, self.theta
- a = sx*npy.cos(theta)
- b = -sx*npy.sin(theta)
- c = sy*npy.sin(theta)
- d = sy*npy.cos(theta)
- M = npy.matrix([[a,b],[c,d]])
+ a = sx*np.cos(theta)
+ b = -sx*np.sin(theta)
+ c = sy*np.sin(theta)
+ d = sy*np.cos(theta)
+ M = np.array([[a,b],[c,d]])
- X2 = M*self.X1
- x2 = X2[0].flat
- y2 = X2[1].flat
+ X2 = np.dot(M, self.X1)
+ x2 = X2[0]
+ y2 = X2[1]
self.line2.set_data(x2,y2)
self.canvas.draw()
-
+
def move(self, event):
if not event.inaxes: return # not over axes
if self.xlast is None: return # no initial data
if not event.button: return # no button press
-
+
dx = event.xdata - self.xlast
- dy = event.ydata - self.ylast
+ dy = event.ydata - self.ylast
if event.button==1:
self.theta += dx
elif event.button==3:
self.sx += dx
self.sy += dy
-
+
self.title.set_text('sx=%1.2f, sy=%1.2f, theta=%1.2f'%(self.sx, self.sy, self.theta))
self.draw()
self.xlast = event.xdata
@@ -75,9 +75,9 @@
-
-from pylab import subplot, show
-fig = figure()
+
+import matplotlib.pyplot as plt
+fig = plt.figure()
ax = fig.add_subplot(111)
t = Transformer(ax)
-show()
+plt.show()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2009-08-11 09:57:58
|
Revision: 7449
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7449&view=rev
Author: jdh2358
Date: 2009-08-11 09:57:52 +0000 (Tue, 11 Aug 2009)
Log Message:
-----------
working on a sphinx_qs tutorial
Added Paths:
-----------
trunk/py4science/examples/sphinx_qs/
trunk/py4science/examples/sphinx_qs/Makefile
trunk/py4science/examples/sphinx_qs/_build/
trunk/py4science/examples/sphinx_qs/_static/
trunk/py4science/examples/sphinx_qs/_static/basic_screenshot.png
trunk/py4science/examples/sphinx_qs/_templates/
trunk/py4science/examples/sphinx_qs/cheatsheet.rst
trunk/py4science/examples/sphinx_qs/conf.py
trunk/py4science/examples/sphinx_qs/getting_started.rst
trunk/py4science/examples/sphinx_qs/index.rst
Added: trunk/py4science/examples/sphinx_qs/Makefile
===================================================================
--- trunk/py4science/examples/sphinx_qs/Makefile (rev 0)
+++ trunk/py4science/examples/sphinx_qs/Makefile 2009-08-11 09:57:52 UTC (rev 7449)
@@ -0,0 +1,88 @@
+# Makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line.
+SPHINXOPTS =
+SPHINXBUILD = sphinx-build
+PAPER =
+
+# Internal variables.
+PAPEROPT_a4 = -D latex_paper_size=a4
+PAPEROPT_letter = -D latex_paper_size=letter
+ALLSPHINXOPTS = -d _build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
+
+.PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest
+
+help:
+ @echo "Please use \`make <target>' where <target> is one of"
+ @echo " html to make standalone HTML files"
+ @echo " dirhtml to make HTML files named index.html in directories"
+ @echo " pickle to make pickle files"
+ @echo " json to make JSON files"
+ @echo " htmlhelp to make HTML files and a HTML help project"
+ @echo " qthelp to make HTML files and a qthelp project"
+ @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
+ @echo " changes to make an overview of all changed/added/deprecated items"
+ @echo " linkcheck to check all external links for integrity"
+ @echo " doctest to run all doctests embedded in the documentation (if enabled)"
+
+clean:
+ -rm -rf _build/*
+
+html:
+ $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) _build/html
+ @echo
+ @echo "Build finished. The HTML pages are in _build/html."
+
+dirhtml:
+ $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) _build/dirhtml
+ @echo
+ @echo "Build finished. The HTML pages are in _build/dirhtml."
+
+pickle:
+ $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) _build/pickle
+ @echo
+ @echo "Build finished; now you can process the pickle files."
+
+json:
+ $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) _build/json
+ @echo
+ @echo "Build finished; now you can process the JSON files."
+
+htmlhelp:
+ $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) _build/htmlhelp
+ @echo
+ @echo "Build finished; now you can run HTML Help Workshop with the" \
+ ".hhp project file in _build/htmlhelp."
+
+qthelp:
+ $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) _build/qthelp
+ @echo
+ @echo "Build finished; now you can run "qcollectiongenerator" with the" \
+ ".qhcp project file in _build/qthelp, like this:"
+ @echo "# qcollectiongenerator _build/qthelp/py4sci.qhcp"
+ @echo "To view the help file:"
+ @echo "# assistant -collectionFile _build/qthelp/py4sci.qhc"
+
+latex:
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex
+ @echo
+ @echo "Build finished; the LaTeX files are in _build/latex."
+ @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
+ "run these through (pdf)latex."
+
+changes:
+ $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) _build/changes
+ @echo
+ @echo "The overview file is in _build/changes."
+
+linkcheck:
+ $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) _build/linkcheck
+ @echo
+ @echo "Link check complete; look for any errors in the above output " \
+ "or in _build/linkcheck/output.txt."
+
+doctest:
+ $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) _build/doctest
+ @echo "Testing of doctests in the sources finished, look at the " \
+ "results in _build/doctest/output.txt."
Added: trunk/py4science/examples/sphinx_qs/_static/basic_screenshot.png
===================================================================
(Binary files differ)
Property changes on: trunk/py4science/examples/sphinx_qs/_static/basic_screenshot.png
___________________________________________________________________
Added: svn:mime-type
+ application/octet-stream
Added: trunk/py4science/examples/sphinx_qs/cheatsheet.rst
===================================================================
--- trunk/py4science/examples/sphinx_qs/cheatsheet.rst (rev 0)
+++ trunk/py4science/examples/sphinx_qs/cheatsheet.rst 2009-08-11 09:57:52 UTC (rev 7449)
@@ -0,0 +1,38 @@
+.. _sphinx_helpers:
+
+
+******************
+Sphinx Cheat Sheet
+******************
+
+Cheat sheet on how to make this site and install these extensions and
+other goodies. You can see a literal version of this file below in
+:ref:`sphinx-literal`.
+
+.. _installing-docdir:
+Installing your doc directory
+=============================
+
+You may already have sphinx `sphinx <http://sphinx.pocoo.org/>`_
+installed -- you can check by doing::
+
+ python -c 'import sphinx'
+
+If that fails grab the latest version of and install it with::
+
+ > sudo easy_install sphinx
+
+Now you are ready to build a template for your docs, using
+sphinx-quickstart::
+
+ > sphinx-quickstart
+
+accepting most of the defaults. I choose "py4sci" as the name of my project
+
+We can test the installation by changing into the project directory,
+and typing `make html`::
+
+ cd py4sci
+ make html
+
+
Added: trunk/py4science/examples/sphinx_qs/conf.py
===================================================================
--- trunk/py4science/examples/sphinx_qs/conf.py (rev 0)
+++ trunk/py4science/examples/sphinx_qs/conf.py 2009-08-11 09:57:52 UTC (rev 7449)
@@ -0,0 +1,194 @@
+# -*- coding: utf-8 -*-
+#
+# py4sci documentation build configuration file, created by
+# sphinx-quickstart on Tue Aug 11 04:33:46 2009.
+#
+# This file is execfile()d with the current directory set to its containing dir.
+#
+# Note that not all possible configuration values are present in this
+# autogenerated file.
+#
+# All configuration values have a default; values that are commented out
+# serve to show the default.
+
+import sys, os
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+#sys.path.append(os.path.abspath('.'))
+
+# -- General configuration -----------------------------------------------------
+
+# Add any Sphinx extension module names here, as strings. They can be extensions
+# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+extensions = ['sphinx.ext.autodoc']
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix of source filenames.
+source_suffix = '.rst'
+
+# The encoding of source files.
+#source_encoding = 'utf-8'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General information about the project.
+project = u'py4sci'
+copyright = u'2009, jdh'
+
+# The version info for the project you're documenting, acts as replacement for
+# |version| and |release|, also used in various other places throughout the
+# built documents.
+#
+# The short X.Y version.
+version = '0.1'
+# The full version, including alpha/beta/rc tags.
+release = '0.1'
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#language = None
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+#today_fmt = '%B %d, %Y'
+
+# List of documents that shouldn't be included in the build.
+#unused_docs = []
+
+# List of directories, relative to source directory, that shouldn't be searched
+# for source files.
+exclude_trees = ['_build']
+
+# The reST default role (used for this markup: `text`) to use for all documents.
+#default_role = None
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+#add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+#show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'sphinx'
+
+# A list of ignored prefixes for module index sorting.
+#modindex_common_prefix = []
+
+
+# -- Options for HTML output ---------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages. Major themes that come with
+# Sphinx are currently 'default' and 'sphinxdoc'.
+html_theme = 'default'
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further. For a list of options available for each theme, see the
+# documentation.
+#html_theme_options = {}
+
+# Add any paths that contain custom themes here, relative to this directory.
+#html_theme_path = []
+
+# The name for this set of Sphinx documents. If None, it defaults to
+# "<project> v<release> documentation".
+#html_title = None
+
+# A shorter title for the navigation bar. Default is the same as html_title.
+#html_short_title = None
+
+# The name of an image file (relative to this directory) to place at the top
+# of the sidebar.
+#html_logo = None
+
+# The name of an image file (within the static path) to use as favicon of the
+# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
+# pixels large.
+#html_favicon = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+#html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+#html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+#html_use_modindex = True
+
+# If false, no index is generated.
+#html_use_index = True
+
+# If true, the index is split into individual pages for each letter.
+#html_split_index = False
+
+# If true, links to the reST sources are added to the pages.
+#html_show_sourcelink = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a <link> tag referring to it. The value of this option must be the
+# base URL from which the finished HTML is served.
+#html_use_opensearch = ''
+
+# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
+#html_file_suffix = ''
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'py4scidoc'
+
+
+# -- Options for LaTeX output --------------------------------------------------
+
+# The paper size ('letter' or 'a4').
+#latex_paper_size = 'letter'
+
+# The font size ('10pt', '11pt' or '12pt').
+#latex_font_size = '10pt'
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title, author, documentclass [howto/manual]).
+latex_documents = [
+ ('index', 'py4sci.tex', u'py4sci Documentation',
+ u'jdh', 'manual'),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+#latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+#latex_use_parts = False
+
+# Additional stuff for the LaTeX preamble.
+#latex_preamble = ''
+
+# Documents to append as an appendix to all manuals.
+#latex_appendices = []
+
+# If false, no module index is generated.
+#latex_use_modindex = True
Added: trunk/py4science/examples/sphinx_qs/getting_started.rst
===================================================================
--- trunk/py4science/examples/sphinx_qs/getting_started.rst (rev 0)
+++ trunk/py4science/examples/sphinx_qs/getting_started.rst 2009-08-11 09:57:52 UTC (rev 7449)
@@ -0,0 +1,46 @@
+.. _sphinx_helpers:
+
+
+******************
+Sphinx Cheat Sheet
+******************
+
+Cheat sheet on how to make this site and install these extensions and
+other goodies. You can see a literal version of this file below in
+:ref:`sphinx-literal`.
+
+.. _installing-docdir:
+Installing your doc directory
+=============================
+
+You may already have sphinx `sphinx <http://sphinx.pocoo.org/>`_
+installed -- you can check by doing::
+
+ python -c 'import sphinx'
+
+If that fails grab the latest version of and install it with::
+
+ > sudo easy_install sphinx
+
+Now you are ready to build a template for your docs, using
+sphinx-quickstart::
+
+ > sphinx-quickstart
+
+accepting most of the defaults. I choose "py4sci" as the name of my
+project. cd into your new directory and check the contents::
+
+ home:~/tmp/py4sci> ls
+ Makefile _static conf.py
+ _build _templates index.rst
+
+The index.rst is the master ReST for your project, but before adding
+anything, let's see if we can build some html::
+
+ make html
+
+If you now point your browser to :file:`_build/html/index.html`, you
+should see a basic spinx site.
+
+.. image:: _static/basic_screenshot.png
+
Added: trunk/py4science/examples/sphinx_qs/index.rst
===================================================================
--- trunk/py4science/examples/sphinx_qs/index.rst (rev 0)
+++ trunk/py4science/examples/sphinx_qs/index.rst 2009-08-11 09:57:52 UTC (rev 7449)
@@ -0,0 +1,21 @@
+.. py4sci documentation master file, created by
+ sphinx-quickstart on Tue Aug 11 04:33:46 2009.
+ You can adapt this file completely to your liking, but it should at least
+ contain the root `toctree` directive.
+
+Welcome to py4sci's documentation!
+==================================
+
+Contents:
+
+.. toctree::
+ :maxdepth: 2
+
+ getting_started.rst
+Indices and tables
+==================
+
+* :ref:`genindex`
+* :ref:`modindex`
+* :ref:`search`
+
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2009-12-05 17:47:34
|
Revision: 8007
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8007&view=rev
Author: jdh2358
Date: 2009-12-05 17:47:26 +0000 (Sat, 05 Dec 2009)
Log Message:
-----------
add izhikevich neuron ODE example
Modified Paths:
--------------
trunk/py4science/examples/lotka_volterra.py
Added Paths:
-----------
trunk/py4science/examples/izhikevich_neurons.py
Added: trunk/py4science/examples/izhikevich_neurons.py
===================================================================
--- trunk/py4science/examples/izhikevich_neurons.py (rev 0)
+++ trunk/py4science/examples/izhikevich_neurons.py 2009-12-05 17:47:26 UTC (rev 8007)
@@ -0,0 +1,165 @@
+import numpy as np
+import matplotlib.pyplot as plt
+from matplotlib.cbook import iterable
+
+def rk4step(derivs, y0, t, dt):
+
+ dt2 = dt/2.0
+
+ k1 = np.asarray(derivs(y0, t))
+ k2 = np.asarray(derivs(y0 + dt2*k1, t+dt2))
+ k3 = np.asarray(derivs(y0 + dt2*k2, t+dt2))
+ k4 = np.asarray(derivs(y0 + dt*k3, t+dt))
+ return y0 + dt/6.0*(k1 + 2*k2 + 2*k3 + k4)
+
+class Izhikevich:
+ def __init__(self, a, b, c, d):
+ self.a = a
+ self.b = b
+ self.c = c
+ self.d = d
+ self.I = 0
+ self.indI = 0
+
+ def __call__(self, state, t):
+ v, u = state
+ if hasattr(self.I, 'shape'):
+ if len(self.I.shape)==2:
+ I = self.I[:,self.indI]
+ else:
+ I = self.I[self.indI]
+ else:
+ I = self.I
+
+
+ dv = 0.04*v**2 + 5*v + 140 -u + I
+ du = self.a*(self.b*v-u)
+ return dv, du
+
+ def reset_if_action_potential(self, state):
+ v, u = state
+ spiked = v>=30.0
+
+ if iterable(spiked):
+ ind = np.nonzero(spiked)
+ v = np.where(spiked, self.c, v)
+ u = np.where(spiked, u + self.d, u)
+ else:
+ ind = None
+ if spiked:
+ v = self.c
+ u += self.d
+ self.indI += 1
+ return ind, v, u
+
+
+def integrate_single(times, abcd, V0, I):
+
+ model = Izhikevich(*abcd)
+
+
+ state = np.array( [V0,0], float)
+ if not iterable(I):
+ I = I*np.ones(times.shape, float)
+
+
+ model.I = I
+ volts = np.zeros(times.shape, float)
+ volts[0] = state[0]
+ for i in range(1, len(times)):
+
+ dt = times[i] - times[i-1]
+ state = rk4step(model, state, times[i], dt)
+ ind, v, u = model.reset_if_action_potential(state)
+ state[0] = v
+ state[1] = u
+ volts[i] = state[0]
+
+ return volts
+
+regular_spiking = 0.02, 0.2, -65, 8
+chattering = 0.02, 0.2, -50, 2
+fast_spiking = 0.1, 0.2, -65, 2
+intrinsically_bursting = 0.02, 0.2, -55, 4
+thalamocortical = 0.02, 0.25, -65, 0.05
+
+lines = []
+texts = []
+labels = []
+
+times = np.arange(0.0, 500.0, 0.1)
+V0 = -65
+I = np.where(times>=100, 10, 0)
+offset = 150
+#ax = plt.subplot(111)
+ax = plt.axes([0.125, .11, 0.725, 0.79], axisbg='w')
+
+num = 0
+v = integrate_single(times, regular_spiking, V0, I)
+l = ax.plot(times/1000.0, v+num*offset, 'k')
+ax.text(0.51, v[0]+num*offset+20, 'RS', fontsize=15)
+lines.extend(l)
+num += 1
+
+v = integrate_single(times, chattering, V0, I)
+l = ax.plot(times/1000.0, v+num*offset, 'k')
+ax.text(0.51, v[0]+num*offset+20, 'CH', fontsize=15)
+lines.extend(l)
+num += 1
+
+v = integrate_single(times, fast_spiking, V0, I)
+l = ax.plot(times/1000.0, v+num*offset, 'k')
+ax.text(0.51, v[0]+num*offset+20, 'FS', fontsize=15)
+lines.extend(l)
+
+num += 1
+
+v = integrate_single(times, intrinsically_bursting, V0, I)
+l = ax.plot(times/1000.0, v+num*offset, 'k')
+ax.text(0.51, v[0]+num*offset+20, 'IB', fontsize=15)
+lines.extend(l)
+num += 1
+
+
+ax.axis([0, 0.5, -100, 900])
+ax.set_yticklabels([])
+ax.set_xlabel('time (s)')
+ax.grid(False)
+
+
+ax = plt.axes([0.25, 0.7, 0.175, 0.175], axisbg='w')
+ax.set_xticks([0.02, 0.1])
+ax.set_yticks([0.2, 0.25])
+ax.plot([0.02, 0.1], [0.2, 0.2], 'o',
+ markerfacecolor='k', markeredgecolor='k', markersize=4)
+texts.append( ax.text(0.01, 0.18, 'RS, IB, CH') )
+texts.append( ax.text(0.1, 0.18, 'FS') )
+
+ax.grid(False)
+
+ax.axis([0, 0.15, 0.15, 0.3])
+labels.append(ax.set_xlabel('parameter a'))
+labels.append(ax.set_ylabel('parameter b'))
+
+ax = plt.axes([0.6, 0.7, 0.175, 0.175], axisbg='w')
+ax.set_xticks([-65, -55, -50])
+ax.set_yticks([2, 4, 8])
+ax.plot([-65, -50, -55, -65], [2, 2, 4, 8], 'o',
+ markerfacecolor='k', markeredgecolor='k', markersize=4)
+
+texts.append( ax.text(-64, 2.5, 'FS') )
+texts.append( ax.text(-49, 2.5, 'CH') )
+texts.append( ax.text(-54, 4.5, 'IB') )
+texts.append( ax.text(-64, 8.5, 'RS') )
+
+for text in texts:
+ text.set_fontsize(10)
+
+labels.append(ax.set_xlabel('parameter c'))
+labels.append(ax.set_ylabel('parameter d'))
+
+ax.axis([-70, -40, 0.05, 10])
+ax.grid(False)
+#plt.savefig('figures/four_neurons.eps')
+
+plt.show()
Modified: trunk/py4science/examples/lotka_volterra.py
===================================================================
--- trunk/py4science/examples/lotka_volterra.py 2009-12-03 20:51:21 UTC (rev 8006)
+++ trunk/py4science/examples/lotka_volterra.py 2009-12-05 17:47:26 UTC (rev 8007)
@@ -22,14 +22,14 @@
def derivs(state, t):
"""
- Return the derivatives of r and f, stored in the *state* vector::
+ Return the derivatives of R and F, stored in the *state* vector::
- state = [r, f]
+ state = [R, F]
- The return data should be [dr, df] which are the derivatives of r
- and f at position state and time *t*
+ The return data should be [dR, dF] which are the derivatives of R
+ and F at position state and time *t*
"""
- r, f = state # and foxes #@
+ R, F = state # and foxes #@
deltar = dr(r, f) # in rabbits #@
deltaf = df(r, f) # in foxes #@
return deltar, deltaf #@
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|