Python API generators
f2py
Python wrapper generator that is part of NumPy
Main limitations:
Doesn't support derived types
f90wrap
Fortran to Python interface generator that extends f2yp with derived type support.
Rohit Goswami changed 4 years agoView mode Like Bookmark
ctypes
The ctypes library is part of the Python standard libary and provides convenient access to C compatible data types and loading of shared libraries. C datatypes like c_int, c_double, c_long etc. are supported and libraries are loaded with CDLL. A simple example on the use of ctypes was given in the Introduction.
Working with NumPy arrays
The most convenient way to work with arrays is through numpy.ctypeslib.
In particular, it includes the functions as_array, which converts a C array to a NumPy ndarray, and as_ctypes, which converts an ndarray to a C array.
Here is an example passing a NumPy array to a Fortran subroutine that sums the column values:
from ctypes import CDLL, byref, c_int
import numpy as np
Some introduction
The end goal is to be able to make our code installable with package managers such as conda or pip without the end user having to worry about compiling code, setting up paths for shared libraries etc.
f2py
Packaging Fortran code with f2py is embarrasingly easy thanks to numpy.distutils. We can tell setuptools to build Fortran source files by using the numpy.distutils drop-in replacements for the regular Extension and setup.
Let's start with our function that does addition.
! file: add.f90
Authors: Kjell Jorner, ...
In recent years, Python has taken over as the most commonly used language in applied science.
Although Python itself as a scripting language is quite slow, it often serves as a glue between computationally demanding procedures written in compiled languages such as Fortran or C.
Prime examples of this approch are the NumPy and SciPy packages that power applications such as machine learning via scikit-learn and quantum chemistry via PySCF.
There are a number of reasons why you would want to interface Python and Fortran, such as:
Making your Fortran application available within the Python eco-system
Speeding up slow parts of a Python code
The reason why Fortran can be called from Python is the C interoperability features that were added with Fortran 2003 and expanded later. By writing our code to be interoperable with C, we can call procedures, module variables and derived types from C code. Many other programming languages, such as Python, then gain access to our Fortran code, as they are able to call C code.
C interoperable code
The two most important parts of making your Fortran code C interoperable are:
Using the bind(c) attribute
Using C interoperable types
bind(c) is built in, while the C interoperable types are available through the intrinsic module iso_c_binding that needs to be imported.
We have seen one basic example of this in the Introduction:
Kjell Jorner changed 4 years agoView mode Like Bookmark