Skip to content

Nicholaswogan/Differentia

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

36 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Differentia

Differentia 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.

Examples

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 $f(x) = \sin(x)\exp(x)x^2 + 1$ at $x = 2$.

program main
  use differentia, 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 differentia
    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

Building

mkdir build
cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
cmake --build .
# run test
./test/test_differentia

Limitations

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.

The name "Differentia"

The 17th-century mathematician Leibniz developed the common $dx$ notation in calculus, indicating a infinitesimal change in $x$. The $d$ in $dx$ is derived from the Latin word "differentia" meaning difference.