User guide
NumPy User Guide, Release 1.9.0
interface simply by placing the INTENT(OUT) :: C comment line in the source code. The only difference is that N
would be an optional input that would default to the length of A.
A filtering example
For comparison with the other methods to be discussed. Here is another example of a function that filters a two-
dimensional array of double precision floating-point numbers using a fixed averaging filter. The advantage of using
Fortran to index into multi-dimensional arrays should be clear from this example.
SUBROUTINE DFILTER2D(A,B,M,N)
C
DOUBLE PRECISION A(M,N)
DOUBLE PRECISION B(M,N)
INTEGER N, M
CF2PY INTENT(OUT) :: B
CF2PY INTENT(HIDE) :: N
CF2PY INTENT(HIDE) :: M
DO 20 I = 2,M-1
DO 40 J=2,N-1
B(I,J) = A(I,J) +
$ (A(I-1,J)+A(I+1,J) +
$ A(I,J-1)+A(I,J+1) )
*
0.5D0 +
$ (A(I-1,J-1) + A(I-1,J+1) +
$ A(I+1,J-1) + A(I+1,J+1))
*
0.25D0
40 CONTINUE
20 CONTINUE
END
This code can be compiled and linked into an extension module named filter using:
f2py -c -m filter filter.f
This will produce an extension module named filter.so in the current directory with a method named dfilter2d that
returns a filtered version of the input.
Calling f2py from Python
The f2py program is written in Python and can be run from inside your module. This provides a facility that is
somewhat similar to the use of weave.ext_tools described below. An example of the final interface executed using
Python code is:
import numpy.f2py as f2py
fid = open(’add.f’)
source = fid.read()
fid.close()
f2py.compile(source, modulename=’add’)
import add
The source string can be any valid Fortran code. If you want to save the extension-module source code then a suitable
file-name can be provided by the source_fn keyword to the compile function.
Automatic extension module generation
If you want to distribute your f2py extension module, then you only need to include the .pyf file and the Fortran code.
The distutils extensions in NumPy allow you to define an extension module entirely in terms of this interface file. A
5.2. Using Python as glue 65