Using Fortran in Python: f2py

2021-12-27
#Fortran #Python

1. Usage

  1. Open the jupyter notebook:
jupyter notebook
  1. The basic information is:
In[1]: import os, sys

In[2]: %config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
import scipy.fftpack as sf
import scipy.linalg as sl
import numpy as np
  1. Create the fortran file euclidian_norm.f90:
In[3]: %%file euclidian_norm.f90
subroutine euclidian_norm (a, b, c)
  real(8), intent(in) :: a, b
  real(8), intent(out) :: c 
  c = sqrt (a*a+b*b) 
end subroutine euclidian_norm
  1. Build extension module with f2py program:
In[4]: !{sys.executable} -m numpy.f2py --quiet -c euclidian_norm.f90 -m vect

A vect.so file will be obtained.

  1. Use the extension module in Python:
In[5]: import vect
c = vect.euclidian_norm(3,4)
c
Out[5]: 5.0
  1. The basic information of vect.euclidian_norm is:
In[6]: print(vect.euclidian_norm.__doc__)

c = euclidian_norm(a,b)

Wrapper for ``euclidian_norm``.

Parameters
----------
a : input float
b : input float

Returns
-------
c : float

2. Reference