Commit 276d027e authored by celinedurniak's avatar celinedurniak
Browse files

Added example using f2py

parent 8b340d47
...@@ -4,4 +4,8 @@ This project aims to benchmark different schemes of Python-Fortran bindings ...@@ -4,4 +4,8 @@ This project aims to benchmark different schemes of Python-Fortran bindings
## TestForpy ## TestForpy
This folder tests [forpy](https://ylikx.github.io/forpy/index.html). This folder tests [forpy](https://ylikx.github.io/forpy/index.html).
The scripts have been tested on Ubuntu18.04 with gfortran. The scripts have been tested on Ubuntu18.04 with gfortran.
\ No newline at end of file
## TestF2py
This folder tests [f2py](https://docs.scipy.org/doc/numpy/f2py/).
The scripts have been tested on MacOS High Sierra and Ubuntu18.04 with gfortran
my_lib:
f2py -c -m my_lib my_lib.f90
main: my_lib*.so
python main.py
This folder contains an example to use Fortran features in Python with `f2py` (which is available from `numpy`).
This example was taken from https://notmatthancock.github.io/2017/02/10/calling-fortran-from-python.html
It has be tested on MacOS High Sierra and Ubuntu 18.04 with gfortran.
To run the scripts, please refer to the `Makefile`.
# Example from https://notmatthancock.github.io/2017/02/10/calling-fortran-from-python.html
import numpy as np
import matplotlib.pyplot as plt
import my_lib as ml
# Read matrix from text file as double precision matrix.
I = plt.imread('image0.png')
# Threshold value.
t = 0.3
# Call the fortran routine.
T = ml.threshold_image(image=I, threshold=t)
# Plot the images.
fig, axes = plt.subplots(1, 2)
axes[0].imshow(I, cmap=plt.cm.gray)
axes[0].axis('off'); axes[0].set_title('Original')
axes[1].imshow(T, cmap=plt.cm.gray)
axes[1].axis('off'); axes[1].set_title('Thresholded at %.2f' % t)
plt.tight_layout()
plt.show()
! Example from https://notmatthancock.github.io/2017/02/10/calling-fortran-from-python.html
subroutine threshold_image(image, n, threshold, output)
! Inputs: image, n, threshold.
! Output: output
! output(i,j) is 1 if image(i,j) > threshold and 0 otherwise.
integer n
real(8) threshold
real(8), dimension(n,n) :: image, output
!f2py intent(in) :: image, threshold
!f2py intent(hide), depend(image) :: n = shape(image, 0)
!f2py intent(out) output
write(*,*) "Hello from the Fortran subroutine!"
! Loop through columns and rows and threshold the image.
do j=1,n
do i=1,n
if (image(i,j) > threshold) then
output(i,j) = 1.0
else
output(i,j) = 0.0
end if
end do
end do
end subroutine
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment