|
From: <fer...@us...> - 2008-10-19 07:11:05
|
Revision: 6265
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6265&view=rev
Author: fer_perez
Date: 2008-10-19 07:10:58 +0000 (Sun, 19 Oct 2008)
Log Message:
-----------
Complete making workbook be pure-tex, self-contained (no more links to
the top-level book dir).
Added Paths:
-----------
trunk/py4science/workbook/examples/
trunk/py4science/workbook/examples/ip_embed-short.py
trunk/py4science/workbook/examples/ip_embed.py
trunk/py4science/workbook/examples/ip_expensive_init.py
trunk/py4science/workbook/examples/ip_simple.py
trunk/py4science/workbook/examples/ip_simple2.py
trunk/py4science/workbook/examples/mpl_agg_oo.py
trunk/py4science/workbook/examples/mpl_pylab.py
trunk/py4science/workbook/examples/mpl_subplot_demo.py
trunk/py4science/workbook/examples/wrap_f2py_setup.py
trunk/py4science/workbook/examples/wrap_weave.py
trunk/py4science/workbook/snippets/
trunk/py4science/workbook/snippets/load_binary.ipy
trunk/py4science/workbook/snippets/load_data.ipy
trunk/py4science/workbook/snippets/mpl_get.ipy
trunk/py4science/workbook/snippets/mpl_plot_line.ipy
trunk/py4science/workbook/snippets/mpl_set.ipy
trunk/py4science/workbook/snippets/mpl_text_set.ipy
trunk/py4science/workbook/snippets/wrap_sub_sig.f
trunk/py4science/workbook/snippets/wrap_sub_sig_f2py.f
Added: trunk/py4science/workbook/examples/ip_embed-short.py
===================================================================
--- trunk/py4science/workbook/examples/ip_embed-short.py (rev 0)
+++ trunk/py4science/workbook/examples/ip_embed-short.py 2008-10-19 07:10:58 UTC (rev 6265)
@@ -0,0 +1,51 @@
+"""Quick code snippets for embedding IPython into other programs.
+
+See example-embed.py for full details, this file has the bare minimum code for
+cut and paste use once you understand how to use the system."""
+
+#---------------------------------------------------------------------------
+# This code loads IPython but modifies a few things if it detects it's running
+# embedded in another IPython session (helps avoid confusion)
+
+try:
+ __IPYTHON__
+except NameError:
+ argv = ['']
+ banner = exit_msg = ''
+else:
+ # Command-line options for IPython (a list like sys.argv)
+ argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:']
+ banner = '*** Nested interpreter ***'
+ exit_msg = '*** Back in main IPython ***'
+
+# First import the embeddable shell class
+from IPython.Shell import IPShellEmbed
+# Now create the IPython shell instance. Put ipshell() anywhere in your code
+# where you want it to open.
+ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg)
+
+#---------------------------------------------------------------------------
+# This code will load an embeddable IPython shell always with no changes for
+# nested embededings.
+
+from IPython.Shell import IPShellEmbed
+ipshell = IPShellEmbed()
+# Now ipshell() will open IPython anywhere in the code.
+
+#---------------------------------------------------------------------------
+# This code loads an embeddable shell only if NOT running inside
+# IPython. Inside IPython, the embeddable shell variable ipshell is just a
+# dummy function.
+
+try:
+ __IPYTHON__
+except NameError:
+ from IPython.Shell import IPShellEmbed
+ ipshell = IPShellEmbed()
+ # Now ipshell() will open IPython anywhere in the code
+else:
+ # Define a dummy ipshell() so the same code doesn't crash inside an
+ # interactive IPython
+ def ipshell(): pass
+
+#******************* End of file <example-embed-short.py> ********************
Added: trunk/py4science/workbook/examples/ip_embed.py
===================================================================
--- trunk/py4science/workbook/examples/ip_embed.py (rev 0)
+++ trunk/py4science/workbook/examples/ip_embed.py 2008-10-19 07:10:58 UTC (rev 6265)
@@ -0,0 +1,127 @@
+#!/usr/bin/env python
+
+"""An example of how to embed an IPython shell into a running program.
+
+Please see the documentation in the IPython.Shell module for more details.
+
+The accompanying file example-embed-short.py has quick code fragments for
+embedding which you can cut and paste in your code once you understand how
+things work.
+
+The code in this file is deliberately extra-verbose, meant for learning."""
+
+# The basics to get you going:
+
+# IPython sets the __IPYTHON__ variable so you can know if you have nested
+# copies running.
+
+# Try running this code both at the command line and from inside IPython (with
+# %run example-embed.py)
+try:
+ __IPYTHON__
+except NameError:
+ nested = 0
+ args = ['']
+else:
+ print "Running nested copies of IPython."
+ print "The prompts for the nested copy have been modified"
+ nested = 1
+ # what the embedded instance will see as sys.argv:
+ args = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:','-nosep']
+
+# First import the embeddable shell class
+from IPython.Shell import IPShellEmbed
+
+# Now create an instance of the embeddable shell. The first argument is a
+# string with options exactly as you would type them if you were starting
+# IPython at the system command line. Any parameters you want to define for
+# configuration can thus be specified here.
+ipshell = IPShellEmbed(args,
+ banner = 'Dropping into IPython',
+ exit_msg = 'Leaving Interpreter, back to program.')
+
+# Make a second instance, you can have as many as you want.
+if nested:
+ args[1] = 'In2<\\#>'
+else:
+ args = ['-pi1','In2<\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:','-nosep']
+ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.')
+
+print '\nHello. This is printed from the main controller program.\n'
+
+# You can then call ipshell() anywhere you need it (with an optional
+# message):
+ipshell('***Called from top level. '
+ 'Hit Ctrl-D to exit interpreter and continue program.')
+
+print '\nBack in caller program, moving along...\n'
+
+#---------------------------------------------------------------------------
+# More details:
+
+# IPShellEmbed instances don't print the standard system banner and
+# messages. The IPython banner (which actually may contain initialization
+# messages) is available as <instance>.IP.BANNER in case you want it.
+
+# IPShellEmbed instances print the following information everytime they
+# start:
+
+# - A global startup banner.
+
+# - A call-specific header string, which you can use to indicate where in the
+# execution flow the shell is starting.
+
+# They also print an exit message every time they exit.
+
+# Both the startup banner and the exit message default to None, and can be set
+# either at the instance constructor or at any other time with the
+# set_banner() and set_exit_msg() methods.
+
+# The shell instance can be also put in 'dummy' mode globally or on a per-call
+# basis. This gives you fine control for debugging without having to change
+# code all over the place.
+
+# The code below illustrates all this.
+
+
+# This is how the global banner and exit_msg can be reset at any point
+ipshell.set_banner('Entering interpreter - New Banner')
+ipshell.set_exit_msg('Leaving interpreter - New exit_msg')
+
+def foo(m):
+ s = 'spam'
+ ipshell('***In foo(). Try @whos, or print s or m:')
+ print 'foo says m = ',m
+
+def bar(n):
+ s = 'eggs'
+ ipshell('***In bar(). Try @whos, or print s or n:')
+ print 'bar says n = ',n
+
+# Some calls to the above functions which will trigger IPython:
+print 'Main program calling foo("eggs")\n'
+foo('eggs')
+
+# The shell can be put in 'dummy' mode where calls to it silently return. This
+# allows you, for example, to globally turn off debugging for a program with a
+# single call.
+ipshell.set_dummy_mode(1)
+print '\nTrying to call IPython which is now "dummy":'
+ipshell()
+print 'Nothing happened...'
+# The global 'dummy' mode can still be overridden for a single call
+print '\nOverriding dummy mode manually:'
+ipshell(dummy=0)
+
+# Reactivate the IPython shell
+ipshell.set_dummy_mode(0)
+
+print 'You can even have multiple embedded instances:'
+ipshell2()
+
+print '\nMain program calling bar("spam")\n'
+bar('spam')
+
+print 'Main program finished. Bye!'
+
+#********************** End of file <example-embed.py> ***********************
Property changes on: trunk/py4science/workbook/examples/ip_embed.py
___________________________________________________________________
Added: svn:executable
+ *
Added: trunk/py4science/workbook/examples/ip_expensive_init.py
===================================================================
--- trunk/py4science/workbook/examples/ip_expensive_init.py (rev 0)
+++ trunk/py4science/workbook/examples/ip_expensive_init.py 2008-10-19 07:10:58 UTC (rev 6265)
@@ -0,0 +1,21 @@
+"""Example script with an expensive initialization.
+
+Meant to be used via ipython's %run -i, though it can run standalone."""
+
+# Imagine that bigobject is actually something whose creation is an expensive
+# process, though here we are just going to make it a list of numbers for
+# demonstration's sake. The trick is to trap a test for the existence of this
+# name in a try/except block. If the object exists, we don't recreate it, if
+# it doesn't exist yet (such as the first time the code is run in any given
+# session), we make it.
+
+try:
+ bigobject
+ print "We found bigobject! No need to initialize it."
+except NameError:
+ print "bigobject not found, performing expensive initialization..."
+ bigobject = range(1000)
+
+# And now you can move on with working on bigobject:
+total = sum(bigobject)
+print 'total is:',total
Added: trunk/py4science/workbook/examples/ip_simple.py
===================================================================
--- trunk/py4science/workbook/examples/ip_simple.py (rev 0)
+++ trunk/py4science/workbook/examples/ip_simple.py 2008-10-19 07:10:58 UTC (rev 6265)
@@ -0,0 +1,4 @@
+import sys
+print 'sys.argv is:',sys.argv
+print '__name__ is:',__name__
+x = 1
Added: trunk/py4science/workbook/examples/ip_simple2.py
===================================================================
--- trunk/py4science/workbook/examples/ip_simple2.py (rev 0)
+++ trunk/py4science/workbook/examples/ip_simple2.py 2008-10-19 07:10:58 UTC (rev 6265)
@@ -0,0 +1,3 @@
+"""This simple file prints a variable which is NOT defined here.
+It should be run via IPython's %run with the -i option."""
+print 'x is:',x
Added: trunk/py4science/workbook/examples/mpl_agg_oo.py
===================================================================
--- trunk/py4science/workbook/examples/mpl_agg_oo.py (rev 0)
+++ trunk/py4science/workbook/examples/mpl_agg_oo.py 2008-10-19 07:10:58 UTC (rev 6265)
@@ -0,0 +1,26 @@
+"""
+A pure object oriented example using the agg backend
+"""
+# import the matplotlib backend you want to use and the Figure class
+from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
+from matplotlib.figure import Figure
+
+# the figure is the center of the action, and the canvas is a backend
+# dependent container to hold the figure and make backend specific calls
+fig = Figure()
+canvas = FigureCanvas(fig)
+
+# you can add multiple subplots and axes
+ax = fig.add_subplot(111)
+
+# the simplest plot!
+ax.plot([1,2,3])
+
+# you can decorate your plot with text and grids
+ax.set_title('hi mom')
+ax.grid(True)
+ax.set_xlabel('time')
+ax.set_ylabel('volts')
+
+# and save it to hardcopy
+fig.savefig('../fig/mpl_one_two_three.png')
Added: trunk/py4science/workbook/examples/mpl_pylab.py
===================================================================
--- trunk/py4science/workbook/examples/mpl_pylab.py (rev 0)
+++ trunk/py4science/workbook/examples/mpl_pylab.py 2008-10-19 07:10:58 UTC (rev 6265)
@@ -0,0 +1,8 @@
+from pylab import *
+plot([1,2,3])
+title('hi mom')
+grid(True)
+xlabel('time')
+ylabel('volts')
+savefig('../fig/mpl_one_two_three.png')
+show()
Added: trunk/py4science/workbook/examples/mpl_subplot_demo.py
===================================================================
--- trunk/py4science/workbook/examples/mpl_subplot_demo.py (rev 0)
+++ trunk/py4science/workbook/examples/mpl_subplot_demo.py 2008-10-19 07:10:58 UTC (rev 6265)
@@ -0,0 +1,28 @@
+from pylab import *
+
+def f(t):
+ s1 = cos(2*pi*t)
+ e1 = exp(-t)
+ return multiply(s1,e1)
+
+t1 = arange(0.0, 5.0, 0.1)
+t2 = arange(0.0, 5.0, 0.02)
+t3 = arange(0.0, 2.0, 0.01)
+
+# create and upper subplot and make it current
+subplot(211)
+l1, l2 = plot(t1, f(t1), 'bo', t2, f(t2), 'k--')
+set(l1, markerfacecolor='g')
+grid(True)
+title('A tale of 2 subplots')
+ylabel('Damped oscillation')
+
+# create a lower subplot and make it current
+subplot(212)
+plot(t3, cos(2*pi*t3), 'r.')
+grid(True)
+xlabel('time (s)')
+ylabel('Undamped')
+savefig('../fig/mpl_subplot_demo')
+show()
+
Added: trunk/py4science/workbook/examples/wrap_f2py_setup.py
===================================================================
--- trunk/py4science/workbook/examples/wrap_f2py_setup.py (rev 0)
+++ trunk/py4science/workbook/examples/wrap_f2py_setup.py 2008-10-19 07:10:58 UTC (rev 6265)
@@ -0,0 +1,74 @@
+#!/usr/bin/env python
+"""Setup script for F2PY-processed, Fortran based extension modules.
+
+A typical call is:
+
+% ./setup.py install --home=~/usr
+
+This will build and install the generated modules in ~/usr/lib/python.
+
+If called with no args, the script defaults to the above call form (it
+automatically adds the 'install --home=~/usr' options)."""
+
+# Global variables for this extension:
+name = "mwadap_tools" # name of the generated python extension (.so)
+description = "F2PY-wrapped MultiWavelet Tree Toolbox"
+author = "Fast Algorithms Group - CU Boulder"
+author_email = "fp...@co..."
+
+# Necessary sources, _including_ the .pyf interface file
+sources = """
+binary_decomp.f90 binexpandx.f90 bitsequence.f90 constructwv.f90
+display_matrix.f90 findkeypos.f90 findlevel.f90 findnodx.f90 gauleg.f90
+gauleg2.f90 gauleg3.f90 ihpsort.f90 invert_f2cmatrix.f90 keysequence2d.f90
+level_of_nsi.f90 matmult.f90 plegnv.f90 plegvec.f90 r2norm.f90 xykeys.f90
+
+mwadap_tools.pyf""".split()
+
+# Additional libraries required by our extension module (these will be linked
+# in with -l):
+libraries = ['m']
+
+# Set to true (1) to turn on Fortran/C API debugging (very verbose)
+debug_capi = 0
+
+#***************************************************************************
+# Do not modify the code below unless you know what you are doing.
+
+# Required modules
+import sys,os
+from os.path import expanduser,expandvars
+from scipy_distutils.core import setup,Extension
+
+expand_sh = lambda path: expanduser(expandvars(path))
+
+# Additional directories for libraries (besides the compiler's defaults)
+fc_vendor = os.environ.get('FC_VENDOR','Gnu').lower()
+library_dirs = ["~/usr/lib/"+fc_vendor]
+
+# Modify default arguments (if none are supplied) to install in ~/usr
+if len(sys.argv)==1:
+ default_args = 'install --home=~/usr'
+ print '*** Adding default arguments to setup:',default_args
+ sys.argv += default_args.split() # it must be a list
+
+# Additional options specific to f2py:
+f2py_options = []
+if debug_capi:
+ f2py_options.append('--debug-capi')
+
+# Define the extension module(s)
+extension = Extension(name = name,
+ sources = sources,
+ libraries = libraries,
+ library_dirs = map(expand_sh,library_dirs),
+ f2py_options = f2py_options,
+ )
+
+# Call the actual building/installation routine, in usual distutils form.
+setup(name = name,
+ description = description,
+ author = author,
+ author_email = author_email,
+ ext_modules = [extension],
+ )
Property changes on: trunk/py4science/workbook/examples/wrap_f2py_setup.py
___________________________________________________________________
Added: svn:executable
+ *
Added: trunk/py4science/workbook/examples/wrap_weave.py
===================================================================
--- trunk/py4science/workbook/examples/wrap_weave.py (rev 0)
+++ trunk/py4science/workbook/examples/wrap_weave.py 2008-10-19 07:10:58 UTC (rev 6265)
@@ -0,0 +1,475 @@
+#!/usr/bin/env python
+"""Simple examples of weave use.
+
+Code meant to be used for learning/testing, not production.
+
+Fernando Perez <fp...@co...>
+March 2002, updated 2003."""
+
+from weave import inline,converters
+from Numeric import *
+
+#-----------------------------------------------------------------------------
+def simple_print(input):
+ """Simple print test.
+
+ Since there's a hard-coded printf %i in here, it will only work for numerical
+ inputs (ints). """
+
+ # note in the printf that newlines must be passed as \\n:
+ code = '''
+ std::cout << "Printing from C++ (using std::cout) : "<<input<<std::endl;
+ printf("And using C syntax (printf) : %i\\n",input);
+ '''
+ inline(code,['input'],
+ verbose=2) # see inline docstring for details
+
+def py_print(input):
+ "Trivial printer, for timing."
+ print "Input:",input
+
+def c_print(input):
+ "Trivial printer, for timing."
+ code = """printf("Input: %i \\n",input);"""
+ inline(code,['input'])
+
+def cpp_print(input):
+ "Trivial printer, for timing."
+ code = """std::cout << "Input: " << input << std::endl;"""
+ inline(code,['input'])
+
+#-----------------------------------------------------------------------------
+# Returning a scalar quantity computed from a Numeric array.
+def trace(mat):
+ """Return the trace of a matrix.
+ """
+ nrow,ncol = mat.shape
+ code = \
+"""
+double tr=0.0;
+
+for(int i=0;i<nrow;++i)
+ tr += mat(i,i);
+return_val = tr;
+"""
+ return inline(code,['mat','nrow','ncol'],
+ type_converters = converters.blitz)
+
+#-----------------------------------------------------------------------------
+# WRONG CODE: trace() version which modifies in-place a python scalar
+# variable. Note that this doesn't work, similarly to how in-place changes in
+# python only work for mutable objects. Below is an example that does work.
+def trace2(mat):
+ """Return the trace of a matrix. WRONG CODE.
+ """
+ nrow,ncol = mat.shape
+ tr = 0.0
+ code = \
+"""
+for(int i=0;i<nrow;++i)
+ tr += mat(i,i);
+"""
+ inline(code,['mat','nrow','ncol','tr'],
+ type_converters = converters.blitz)
+ return tr
+
+#-----------------------------------------------------------------------------
+# Operating in-place in an existing Numeric array. Contrary to trying to modify
+# in-place a scalar, this works correctly.
+def in_place_mult(num,mat):
+ """In-place multiplication of a matrix by a scalar.
+ """
+ nrow,ncol = mat.shape
+ code = \
+"""
+for(int i=0;i<nrow;++i)
+ for(int j=0;j<ncol;++j)
+ mat(i,j) *= num;
+
+"""
+ inline(code,['num','mat','nrow','ncol'],
+ type_converters = converters.blitz)
+
+#-----------------------------------------------------------------------------
+# Pure Python version for checking.
+def cross_product(a,b):
+ """Cross product of two 3-d vectors.
+ """
+ cross = [0]*3
+ cross[0] = a[1]*b[2]-a[2]*b[1]
+ cross[1] = a[2]*b[0]-a[0]*b[2]
+ cross[2] = a[0]*b[1]-a[1]*b[0]
+ return array(cross)
+
+#-----------------------------------------------------------------------------
+# Here we return a list from the C code. This is probably *much* slower than
+# the python version, it's meant as an illustration and not as production
+# code.
+def cross_productC(a,b):
+ """Cross product of two 3-d vectors.
+ """
+ # py::tuple or py::list both work equally well in this case.
+ code = \
+"""
+py::tuple cross(3);
+
+cross[0] = a(1)*b(2)-a(2)*b(1);
+cross[1] = a(2)*b(0)-a(0)*b(2);
+cross[2] = a(0)*b(1)-a(1)*b(0);
+return_val = cross;
+"""
+ return array(inline(code,['a','b'],
+ type_converters = converters.blitz))
+
+#-----------------------------------------------------------------------------
+# C version which accesses a pre-allocated NumPy vector. Note: when using
+# blitz, index access is done with (,,), not [][][]. In fact, [] indexing
+# fails silently. See this and the next version for a comparison.
+def cross_productC2(a,b):
+ """Cross product of two 3-d vectors.
+ """
+
+ cross = zeros(3,a.typecode())
+ code = \
+"""
+cross(0) = a(1)*b(2)-a(2)*b(1);
+cross(1) = a(2)*b(0)-a(0)*b(2);
+cross(2) = a(0)*b(1)-a(1)*b(0);
+"""
+ inline(code,['a','b','cross'],
+ type_converters = converters.blitz)
+ return cross
+
+#-----------------------------------------------------------------------------
+# Just like the previous case, but now we don't use the blitz converters.
+# Weave automagically does the type conversions for us.
+def cross_productC3(a,b):
+ """Cross product of two 3-d vectors.
+ """
+
+ cross = zeros(3,a.typecode())
+ code = \
+"""
+cross[0] = a[1]*b[2]-a[2]*b[1];
+cross[1] = a[2]*b[0]-a[0]*b[2];
+cross[2] = a[0]*b[1]-a[1]*b[0];
+"""
+ inline(code,['a','b','cross'])
+
+ return cross
+
+#-----------------------------------------------------------------------------
+def dot_product(a,b):
+ """Dot product of two vectors.
+
+ Implemented in a funny (ridiculous) way to use support_code.
+
+ I want to see if we can call another function from inside our own
+ code. This would give us a crude way to implement better modularity by
+ having global constants which include the raw code for whatever C
+ functions we need to call in various places. These can then be included
+ via support_code.
+
+ The overhead is that the support code gets compiled in *every* dynamically
+ generated module, but I'm not sure that's a big deal since the big
+ compilation overhead seems to come from all the fancy C++ templating and
+ whatnot.
+
+ Later: ask Eric if there's a cleaner way to do this."""
+
+ N = len(a)
+ support = \
+"""
+double mult(double x,double y) {
+ return x*y;
+}
+"""
+ code = \
+"""
+double sum = 0.0;
+for (int i=0;i<N;++i) {
+ sum += mult(a(i),b(i));
+}
+return_val = sum;
+"""
+ return inline(code,['a','b','N'],
+ type_converters = converters.blitz,
+ support_code = support,
+ libraries = ['m'],
+ )
+
+#-----------------------------------------------------------------------------
+def sumC(x):
+ """Return the sum of the elements of a 1-d array.
+
+ An example of how weave accesses a Numeric array without blitz. """
+
+ num_types = {Float:'double',
+ Float32:'float'}
+ x_type = num_types[x.typecode()]
+
+ code = """
+ double result=0.0;
+ double element;
+
+ for (int i = 0; i < Nx[0]; i++){
+
+ // Note the type of the pointer below is computed in python
+ //element = *(%s *)(x->data+i*x->strides[0]);
+
+ // Weave's magic does the above for us:
+ element = x[i];
+
+ result += element;
+ std::cout << "Element " << i << " = " << element << "\\n";
+ }
+ std::cout << "size x " << Nx[0] << "\\n";
+
+ return_val = result;
+ """ % x_type;
+
+ return inline(code,['x'],verbose=0)
+
+#-----------------------------------------------------------------------------
+def Cglobals(arr):
+ """How to pass data from function to function via globals.
+
+ This allows the kind of 'over the head' parameter passing via globals
+ which is ugly but necessary for using things like generic integrators in
+ Numerical Recipes with aditional parameters. """
+
+ support = \
+"""
+// Declare globals here
+
+/* These blitz guys must be accessed via pointers to avoid a costly copy.
+Note that now the type is hardwired in. All python polymorphism is gone. I
+should look into whether this can be fixed by properly using blitz templating.
+*/
+blitz::Array<int, 1> *G_arr_pt;
+
+// The global M will be visible in the "code" segment
+int M = 99;
+
+void aprint(int N) {
+ std::cout << "In aprint()\\n";
+ for (int i=0;i<N;++i)
+ std::cout << "arr[" << i << "]=" << (*G_arr_pt)(i) << " ";
+ std::cout << std::endl;
+}
+
+"""
+ code = \
+"""
+// Get the passed array reference so the data becomes global
+G_arr_pt = &arr;
+
+std::cout << "global M=" << M << std::endl;
+std::cout << "local N=" << N << std::endl;
+
+
+std::cout << "First, print using the blitz internal printer:\\n";
+std::cout << "all arr\\n";
+std::cout << arr << std::endl;
+
+std::cout << "all G_arr\\n";
+std::cout << *G_arr_pt << std::endl;
+
+std::cout << "now by loop\\n";
+
+for (int i=0;i<N;++i)
+ std::cout << "arr[" << i << "]=" << arr(i) << " ";
+std::cout << std::endl;
+
+
+std::cout << "Now calling aprint\\n";
+
+aprint(N);
+"""
+ N = len(arr)
+ return inline(code,['arr','N'],
+ type_converters = converters.blitz,
+ support_code = support,
+ libraries = ['m'],
+ verbose = 0,
+ )
+
+
+#-----------------------------------------------------------------------------
+# Two trivial examples using the C math library follow.
+def powC(x,n):
+ """powC(x,n) -> x**n. Implemented using the C pow() function.
+ """
+ support = \
+"""
+#include <math.h>
+"""
+ code = \
+"""
+return_val = pow(x,n);
+"""
+ return inline(code,['x','n'],
+ type_converters = converters.blitz,
+ support_code = support,
+ libraries = ['m'],
+ )
+
+# Some callback examples
+def foo(x,y):
+ print "In Python's foo:"
+ print 'x',x
+ print 'y',y
+ return x
+
+def cfoo(x,y):
+ code = """
+ printf("Attemtping to call back foo() from C...\\n");
+ py::tuple foo_args(2);
+ py::object z; // This will hold the return value of foo()
+ foo_args[0] = x;
+ foo_args[1] = y;
+ z = foo.call(foo_args);
+ printf("Exiting C code.\\n");
+ return_val = z;
+ """
+ return inline(code,"foo x y".split() )
+
+x=99
+y="Hello"
+
+print "Pure python..."
+z=foo(x,y)
+print "foo returned:",z
+print "\nVia weave..."
+z=cfoo(x,y)
+print "cfoo returned:",z
+
+# Complex numbers
+def complex_test():
+ a = zeros((4,4),Complex)
+ a[0,0] = 1+2j
+ a[1,1] = 2+3.5j
+ print 'Before\n',a
+ code = \
+"""
+std::complex<double> i(0, 1);
+std::cout << a(1,1) << std::endl;
+a(2,2) = 3.0+4.5*i;
+//a(2,2).imag = 4.5;
+"""
+ inline(code,['a'],type_converters = converters.blitz)
+ print 'After\n',a
+
+complex_test()
+
+#-----------------------------------------------------------------------------
+def sinC(x):
+ """sinC(x) -> sin(x). Implemented using the C sin() function.
+ """
+ support = \
+"""
+#include <math.h>
+"""
+ code = \
+"""
+return_val = sin(x);
+"""
+ return inline(code,['x'],
+ type_converters = converters.blitz,
+ support_code = support,
+ libraries = ['m'],
+ )
+
+def in_place_multNum(num,mat):
+ mat *= num
+
+
+from weave import inline
+class bunch: pass
+
+def oaccess():
+ x=bunch()
+
+ x.a = 1
+
+ code = """ // BROKEN!
+ // Try to emulate Python's: print 'x.a',x.a
+ std::cout << "x.a " << x.a << std::endl;
+ """
+ inline(code,['x'])
+
+main2 = oaccess
+
+
+def ttest():
+ nrun = 10
+ size = 6000
+ mat = ones((size,size),'d')
+ num = 5.6
+ tNum = time_test(nrun,in_place_multNum,*(num,mat))
+ print 'time Num',tNum
+ tC = time_test(nrun,in_place_mult,*(num,mat))
+ print 'time C',tC
+
+def main():
+ print 'Printing comparisons:'
+ print '\nPassing an int - what the C was coded for:'
+ simple_print(42)
+ print '\nNow passing a float. C++ is fine (cout<< takes care of things) but C fails:'
+ simple_print(42.1)
+ print '\nAnd a string. Again, C++ is ok and C fails:'
+ simple_print('Hello World!')
+
+ A = zeros((3,3),'d')
+
+ A[0,0],A[1,1],A[2,2] = 1,2.5,3.3
+
+ print '\nMatrix A:\n',A
+ print 'Trace by two methods. Second fails, see code for details.'
+ print '\ntr(A)=',trace(A)
+ print '\ntr(A)=',trace2(A)
+
+ a = 5.6
+ print '\nMultiplying A in place by %s:' % a
+ in_place_mult(a,A)
+ print A
+
+ # now some simple operations with 3-vectors.
+ a = array([4.3,1.5,5.6])
+ b = array([0.8,2.9,3.8])
+
+ print '\nPython and C versions follow. Results should be identical:'
+ print 'a =',a
+ print 'b =',b
+
+ print '\nsum(a_i) =',sum(a)
+ print 'sum(a_i) =',sumC(a)
+
+ print '\na.b =',dot(a,b)
+ print 'a.b =',dot_product(a,b)
+
+ print '\na x b =',cross_product(a,b)
+ print 'a x b =',cross_productC(a,b)
+
+ print '\nIn-place versions.'
+ print 'a x b =',cross_productC2(a,b)
+ print 'a x b =',cross_productC3(a,b)
+
+ print '\nSimple functions using the C math library:'
+ import math
+ x = 3.5
+ n = 4
+ theta = math.pi/4.
+ print '\nx**'+str(n)+'=',x**n
+ print 'x**'+str(n)+'=',powC(x,n)
+ print '\nsin('+str(theta)+')=',math.sin(theta)
+ print 'sin('+str(theta)+')=',sinC(theta)
+
+ print '\nGlobal variables and explicitly typed blitz arrays.'
+ x = array([4,5,6])
+ print 'x is a Numeric array:\nx=',x
+ print 'Now using weave:'
+ Cglobals (x)
+
+if __name__ == '__main__':
+ main()
Property changes on: trunk/py4science/workbook/examples/wrap_weave.py
___________________________________________________________________
Added: svn:executable
+ *
Added: trunk/py4science/workbook/snippets/load_binary.ipy
===================================================================
--- trunk/py4science/workbook/snippets/load_binary.ipy (rev 0)
+++ trunk/py4science/workbook/snippets/load_binary.ipy 2008-10-19 07:10:58 UTC (rev 6265)
@@ -0,0 +1,13 @@
+# open a file as "read binary" and read it into a string
+In [1]: s = file('data/images/r1025.ima', 'rb').read()
+# the string is length 256*256*2 = 131072
+In [2]: len(s)
+Out[2]: 131072
+# the data are 2 byte / 16 bit integers
+# fromstring converts them to array
+In [3]: im = nx.fromstring(s, nx.Int16)
+# reshape the array to 256x256
+In [4]: im.shape = 256,256
+# and plot it with matplotlib's imshow function
+In [5]: imshow(im)
+Out[5]: <matplotlib.image.AxesImage instance at 0xb659230c>
Added: trunk/py4science/workbook/snippets/load_data.ipy
===================================================================
--- trunk/py4science/workbook/snippets/load_data.ipy (rev 0)
+++ trunk/py4science/workbook/snippets/load_data.ipy 2008-10-19 07:10:58 UTC (rev 6265)
@@ -0,0 +1,9 @@
+In [1]: X = load('data/ascii_data.dat') # X is an array
+In [2]: t = X[:,0] # extract the first column
+In [3]: v = X[:,1] # extract the second column
+In [4]: len(t)
+Out[4]: 20
+In [5]: len(v)
+Out[5]: 20
+In [6]: plot(t,v) # plot the data
+Out[6]: [<matplotlib.lines.Line2D instance at 0xb65921ac>]
Added: trunk/py4science/workbook/snippets/mpl_get.ipy
===================================================================
--- trunk/py4science/workbook/snippets/mpl_get.ipy (rev 0)
+++ trunk/py4science/workbook/snippets/mpl_get.ipy 2008-10-19 07:10:58 UTC (rev 6265)
@@ -0,0 +1,20 @@
+In [29]: get(lines)
+ alpha = 1.0
+ antialiased or aa = True
+ clip_on = True
+ color or c = blue
+ figure = <matplotlib.figure.Figure instance at 0xb40e1cec>
+ label =
+ linestyle or ls = None
+ linewidth or lw = 0.5
+ marker = o
+ markeredgecolor or mec = black
+ markeredgewidth or mew = 0.5
+ markerfacecolor or mfc = blue
+ markersize or ms = 6.0
+ transform = <Affine object at 0x8683c6c>
+ visible = True
+ xdata = [ 0.16952688 0.59729624 0.16829208 0.51311375 0.7227286 0.45925692]...
+ ydata = [ 0.86459035 0.25595992 0.01905832 0.24303582 0.74993261 0.28751132]...
+ zorder = 2
+
Added: trunk/py4science/workbook/snippets/mpl_plot_line.ipy
===================================================================
--- trunk/py4science/workbook/snippets/mpl_plot_line.ipy (rev 0)
+++ trunk/py4science/workbook/snippets/mpl_plot_line.ipy 2008-10-19 07:10:58 UTC (rev 6265)
@@ -0,0 +1,9 @@
+In [2]: x = rand(20); y = rand(20)
+
+In [3]: lines = plot(x,y,'o')
+
+In [4]: type(lines) # plot always returns a list
+Out[4]: <type 'list'>
+
+In [5]: len(lines) # even if it is length 1
+Out[5]: 1
Added: trunk/py4science/workbook/snippets/mpl_set.ipy
===================================================================
--- trunk/py4science/workbook/snippets/mpl_set.ipy (rev 0)
+++ trunk/py4science/workbook/snippets/mpl_set.ipy 2008-10-19 07:10:58 UTC (rev 6265)
@@ -0,0 +1,27 @@
+In [37]: set(lines)
+ alpha: float
+ antialiased or aa: [True | False]
+ clip_box: a matplotlib.transform.Bbox instance
+ clip_on: [True | False]
+ color or c: any matplotlib color - see help(colors)
+ dashes: sequence of on/off ink in points
+ data: (array xdata, array ydata)
+ data_clipping: [True | False]
+ figure: a matplotlib.figure.Figure instance
+ label: any string
+ linestyle or ls: [ '-' | '--' | '-.' | ':' | 'steps' | 'None' ]
+ linewidth or lw: float value in points
+ lod: [True | False]
+ marker: [ '+' | ',' | '.' | '1' | '2' | '3' | '4' | '<' | '>' | 'D' | 'H' | '^' | '_' | 'd' | 'h' | 'o' | 'p' | 's' | 'v' | 'x' | '|' ]
+ markeredgecolor or mec: any matplotlib color - see help(colors)
+ markeredgewidth or mew: float value in points
+ markerfacecolor or mfc: any matplotlib color - see help(colors)
+ markersize or ms: float
+ transform: a matplotlib.transform transformation instance
+ visible: [True | False]
+ xclip: (xmin, xmax)
+ xdata: array
+ yclip: (ymin, ymax)
+ ydata: array
+ zorder: any number
+
Added: trunk/py4science/workbook/snippets/mpl_text_set.ipy
===================================================================
--- trunk/py4science/workbook/snippets/mpl_text_set.ipy (rev 0)
+++ trunk/py4science/workbook/snippets/mpl_text_set.ipy 2008-10-19 07:10:58 UTC (rev 6265)
@@ -0,0 +1,30 @@
+In [8]: t = xlabel('time (s)')
+
+In [9]: set(t)
+ alpha: float
+ backgroundcolor: any matplotlib color - see help(colors)
+ bbox: rectangle prop dict plus key 'pad' which is a pad in points
+ clip_box: a matplotlib.transform.Bbox instance
+ clip_on: [True | False]
+ color: any matplotlib color - see help(colors)
+ family: [ 'serif' | 'sans-serif' | 'cursive' | 'fantasy' | 'monospace' ]
+ figure: a matplotlib.figure.Figure instance
+ fontproperties: a matplotlib.font_manager.FontProperties instance
+ horizontalalignment or ha: [ 'center' | 'right' | 'left' ]
+ label: any string
+ lod: [True | False]
+ multialignment: ['left' | 'right' | 'center' ]
+ name or fontname: string eg, ['Sans' | 'Courier' | 'Helvetica' ...]
+ position: (x,y)
+ rotation: [ angle in degrees 'vertical' | 'horizontal'
+ size or fontsize: [ size in points | relative size eg 'smaller', 'x-large' ] style or fontstyle: [ 'normal' | 'italic' | 'oblique']
+ text: string
+ transform: a matplotlib.transform transformation instance
+ variant: [ 'normal' | 'small-caps' ]
+ verticalalignment or va: [ 'center' | 'top' | 'bottom' ]
+ visible: [True | False]
+ weight or fontweight: [ 'normal' | 'bold' | 'heavy' | 'light' | 'ultrabold' | 'ultralight']
+ x: float
+ y: float
+ zorder: any number
+
Added: trunk/py4science/workbook/snippets/wrap_sub_sig.f
===================================================================
--- trunk/py4science/workbook/snippets/wrap_sub_sig.f (rev 0)
+++ trunk/py4science/workbook/snippets/wrap_sub_sig.f 2008-10-19 07:10:58 UTC (rev 6265)
@@ -0,0 +1,5 @@
+ subroutine phipol(j,mm,nodes,wei,nn,x,phi,wrk)
+
+ implicit real *8 (a-h, o-z)
+ real *8 nodes(*),wei(*),x(*),wrk(*),phi(*)
+ real *8 sum, one, two, half
Added: trunk/py4science/workbook/snippets/wrap_sub_sig_f2py.f
===================================================================
--- trunk/py4science/workbook/snippets/wrap_sub_sig_f2py.f (rev 0)
+++ trunk/py4science/workbook/snippets/wrap_sub_sig_f2py.f 2008-10-19 07:10:58 UTC (rev 6265)
@@ -0,0 +1,25 @@
+ subroutine phipol(j,mm,nodes,wei,nn,x,phi,wrk)
+c
+c Lines with Cf2py in them are directives for f2py to generate a better
+c python interface. These must come _before_ the Fortran variable
+c declarations so we can control the dimension of the arrays in Python.
+c
+c Inputs:
+Cf2py integer check(0<=j && j<mm),depend(mm) :: j
+Cf2py real *8 dimension(mm),intent(in) :: nodes
+Cf2py real *8 dimension(mm),intent(in) :: wei
+Cf2py real *8 dimension(nn),intent(in) :: x
+c
+c Outputs:
+Cf2py real *8 dimension(nn),intent(out),depend(nn) :: phi
+c
+c Hidden args:
+c - scratch areas can be auto-generated by python
+Cf2py real *8 dimension(2*mm+2),intent(hide,cache),depend(mm) :: wrk
+c - array sizes can be auto-determined
+Cf2py integer intent(hide),depend(x):: nn=len(x)
+Cf2py integer intent(hide),depend(nodes) :: mm = len(nodes)
+c
+ implicit real *8 (a-h, o-z)
+ real *8 nodes(*),wei(*),x(*),wrk(*),phi(*)
+ real *8 sum, one, two, half
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|