ForwardDiff allows for the computation of derivatives, gradients and Jacobians of Fortran subroutines or functions using forward mode automatic differentiation (AD). To create this package I borrowed code, syntax and inspiration from DNAD, ForwardDiff.jl, and a lecture series by Chris Rackauckas.
For a comprehensive set of examples see the tests in the test
directory. In particular, test/fypp_example.fypp
shows how to use the fypp preprocessor to write more general, differentiable code.
Below is a simple demo that computes the derivative of the scalar function
program main
use forwarddiff, only: wp, derivative
implicit none
call example()
contains
subroutine example()
real(wp) :: x, f, dfdx
x = 2.0_wp
call derivative(fcn, x, f, dfdx)
print*,'x = ',x
print*,'f = ',f
print*,'df/dx = ',dfdx
end subroutine
function fcn(x) result(f)
use forwarddiff
type(dual), intent(in) :: x
type(dual) :: f
f = sin(x)*exp(x)*x**2.0_wp + 1.0_wp
end function
end program
Output:
x = 2.0000000000000000
f = 27.875398789713000
df/dx = 41.451068296868563
mkdir build
cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
cmake --build .
# run test
./test/test_forwarddiff
This package has the following limitations:
-
The package is not compatible with all Fortran intrinsic functions. If you identify an intrinsic that should be added, please submit a pull request.
-
The
jacobian
routine can only compute square Jacobians.