Forpy allows you to use Python features in Fortran (“embedding Python in Fortran”)
It provides datastructures such as list, dict, tuple and interoperability of arrays using numpy. With forpy you can even import Python modules in Fortran. Simply use your own or third-party Python modules for tasks that you don’t want to do in Fortran. For example: plot with matplotlib or use scientific functions from scipy.
Forpy also works to other way around: You can write Python modules entirely in Fortran (extending Python with Fortran - “Fortran in Python”).
Link: forpy - use Python from Fortran
The following example shows some advanced usage of forpy. The matplotlib
Python module is imported and the matplotlib’s plot
command is used to create a simple graph.
! Matplotlib example
! Author: Elias Rabel
! License: MIT
!
! A C preprocessor macro to simplify error handling
#define errcheck if(ierror/=0) then;call err_print;stop;endif
program matplotlib_example
use forpy_mod
implicit none
integer :: ierror, ii
real, parameter :: PI = 3.1415927
integer, parameter :: NPOINTS = 200
real :: x(NPOINTS)
real :: y(NPOINTS)
do ii = 1, NPOINTS
x(ii) = ((ii-1) * 2. * PI)/(NPOINTS-1)
y(ii) = sin(x(ii))
enddo
ierror = forpy_initialize()
! forpy_initialize returns NO_NUMPY_ERROR if numpy could not be imported
! You could still use forpy without the array features, but here we need them.
if (ierror == NO_NUMPY_ERROR) then
write(*,*) "This example needs numpy..."
stop
endif
errcheck
call simple_plot(x, y)
call forpy_finalize
CONTAINS
subroutine simple_plot(x, y)
real, intent(in) :: x(:)
real, intent(in) :: y(:)
integer ierror
type(module_py) :: plt
type(tuple) :: args
type(ndarray) :: x_arr, y_arr
ierror = import_py(plt, "matplotlib.pyplot")
! You can also test for certain exceptions
if (ierror /= 0) then
if (exception_matches(ImportError)) then
write(*,*) "This example needs matplotlib..."
stop
else
call err_print
stop
endif
endif
ierror = ndarray_create(x_arr, x)
errcheck
ierror = ndarray_create(y_arr, y)
errcheck
ierror = tuple_create(args, 2)
errcheck
ierror = args%setitem(0, x_arr)
errcheck
ierror = args%setitem(1, y_arr)
errcheck
ierror = call_py_noret(plt, "plot", args)
errcheck
ierror = call_py_noret(plt, "show")
errcheck
call x_arr%destroy
call y_arr%destroy
call args%destroy
call plt%destroy
end subroutine
end program