Return to Computer Vision Notebooks

Basics [F2PY]



Basic functions and operations using F2PY, NumPy and Python.

0. Installation


F2PY is a native Fortran to Python interface generator from NumPy. Thus, the Installation command for anaconda and pip:

$ conda install numpy

or

$ pip install numpy

1. Compilation


A Fortran source file can have the name of the module. For example, given the source file examples_f2py.f90 with a simple function which returns a string in bytes.

function hello_f2py() result(output)
    character(len=12) :: output
    output = "Hello, F2PY!"
end function hello_f2py

The following step is the compilation, which is done by running the command:

$ f2py -m examples_f2py -c examples_f2py.f90

2. Performance


The following example, we will try to approximate the value $\large\pi$ with the idea of $\\tan^{-1}1=\frac{\pi}{4}$ using the power series of arctan, defined by:

$$\large 4 \sum_{n=0}^{N}\frac{(-1)^n}{2n+1} \approx \pi $$

where $N$ tends to the infinity.

In the same Fortran source file examples_f2py.f90, lets include the function and adapt it to be compiled.

function pi_f2py(N_) result(pi)
    integer :: N_, n
    real    :: pi
    pi = 0
    do n=0,N_
        pi = pi + (-1)**n/real(2*n + 1)
    end do
    pi = 4*pi
end function pi_f2py

p.s.: compile it again by running the command:

$ f2py -m examples_f2py -c examples_f2py.f90

3. Inline fortran source


Build inline fortran commands and compile with numpy.f2py.