Tuesday, August 16, 2016

F2PY: Interfacing Fortran and Python

Python is notoriously slow with loops. One of the many ways to speed things up is to incorporate subroutines written in C or Fortran into Python.

F2PY is a program that enables us to just that: "provide a connection between Python and Fortran languages." It lets us wrap Fortran code (you'll need a compiler like gfortran) for use in Python.

You can thus salvage legacy Fortran 77 code, or write "new" Fortran 90 code. The latter is much easier to incorporate.

Basic Steps:

1. Write a subroutine file in Fortran 90. Use "intent" modifier to express interface. Avoid allocatable arrays.
2. Use f2py to generate a python interface/signature file ("pyf" file) and a module that can be imported by python. You may have to edit the signature file sometimes.
3. Compile the python module.

Some resources:

1. Robert Johansson has a very nice set of iPython notebooks for Scientific Computing with python. The first part of the lecture "Lecture-6A-Fortran-and-C.ipynb" provides a gentle introduction to F2PY. If you don't have jupyter/iPython notebooks installed on your computer, a PDF of the entire set of notebooks is also available on his github site.

2. A nice example is available here.

3. The official site also provides a cheat-sheet for three different ways to wrap things.

4. Another nice introduction, that goes on to talk about stuff beyond the basic.

I plan on demonstrating this on a practical example shortly.

No comments:

Post a Comment