A short guide on using f2py to call Fortran subroutines from Python
Python is a scripting language, while Numpy and Matplotlib are Python modules (or libraries) for scientific computing and plotting respectively. This is not a guide specificly on using these libraries — although, they are great, and you should try them out in more detail.
f2py is a command line utility that is included with Numpy that converts files containing Fortran subroutines or modules into Python modules. This allows you to code your numerical routines in Fortran, while allowing Python scripts to “drive” the main program for plotting, etc. You can find more detail about
f2py by reading its User guide and reference manual.
Reading text image data from a file and thresholding it in Fortran
As an example, we will
- Read a square image stored in a file as text data into Python as a double precision matrix.
- Pass the image to a Fortran subroutine that thresholds the values of the matrix.
- Return the image back to the Python script and plot the results.
Writing the Fortran routine
Let’s assume we have a file, my_lib.f90, containing one or more Fortran subroutines that looks like the following:
This subroutine has 3 special comments that start with
- The first tells
f2pythat the variables
thresholdare required inputs when called from Python.
- The second tells
f2pythat the variable
nis defined implicitly through the
imageargument when called from Python, and its value is the size of the first dimension of
- The third tells
f2pythat the variable,
output, does not need to be provided as an argument when called from Python, and the variable is in fact returned by the function when called from Python. If multiple variables are returned, they are returned as a Python Tuple.
Compiling the Fortran file to a Python module
From the command line where the file is present, run
A new file is produced,
my_lib.so, which can be imported into Python.
Testing the routine from a Python script
And run it from the command line:
If successful, you should see both the original and thresholded image displayed as well as a the line “Hello from the Fortran subroutine!” printed.