Fortran (from Formula Translation System) is a mature programming language mostly used for scientific computing. It was developed in the 1950s with newer versions emerging such as Fortran 77, Fortran 90, Fortran 95, Fortran 2003, and Fortran 2008 (refer to http://en.wikipedia.org/wiki/Fortran). Each version added features and new programming paradigms. We will need a Fortran compiler for this example. The gfortran compiler is a GNU Fortran compiler, which can be downloaded from http://gcc.gnu.org/wiki/GFortranBinaries.
The NumPy f2py
module serves as an interface between Fortran and Python. If a Fortran compiler is present, we can create a shared library from Fortran code using this module. We will write a Fortran subroutine that is intended to sum rain amount values as given in the previous examples. Define the subroutine and store it in a Python string. After that, we can call the f2py.compile()
function to produce a shared library from the Fortran code. The end product is in the fort_src.py
file in this book's code bundle:
from numpy import f2py fsource = ''' subroutine sumarray(A, N) REAL, DIMENSION(N) :: A INTEGER :: N RES = 0.1 * SUM(A, MASK = A .GT. 0) RES2 = -0.025 * SUM(A, MASK = A .LT. 0) print*, RES + RES2 end ''' f2py.compile(fsource,modulename='fort_sum',verbose=0)
Call the subroutine as given in the fort_demo.py
file in this book's code bundle:
import fort_sum import numpy as np rain = np.load('rain.npy') fort_sum.sumarray(rain, len(rain)) rain = .1 * rain rain[rain < 0] = .025 print "Numpy", rain.sum()
The results of Fortran and NumPy agree as expected (we can ignore the last two digits printed by the Fortran subroutine):
85291.5547 Numpy 85291.55
3.136.17.12