NAG Library Manual, Mark 27.2
Interfaces:  FL   CL   CPP   AD 

NAG AD Library Introduction
Example description
    Program d01ga_a1w_fe

!     D01GA_A1W_F Example Program Text
!     Mark 27.2 Release. NAG Copyright 2021.

!     .. Use Statements ..
      Use iso_c_binding, Only: c_ptr
      Use nagad_library, Only: d01ga_a1w_f, nagad_a1w_get_derivative,          &
                               nagad_a1w_inc_derivative,                       &
                               nagad_a1w_ir_create => x10za_a1w_f,             &
                               nagad_a1w_ir_interpret_adjoint_sparse,          &
                               nagad_a1w_ir_register_variable,                 &
                               nagad_a1w_ir_remove, nagad_a1w_w_rtype,         &
                               x10aa_a1w_f, x10ab_a1w_f, Assignment (=),       &
                               Operator (/), Operator (+), Operator (*)
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Type (nagad_a1w_w_rtype)         :: a, ans, er
      Type (c_ptr)                     :: ad_handle
      Real (Kind=nag_wp)               :: ar, da, xr
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Type (nagad_a1w_w_rtype), Allocatable :: x(:), y(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..

      Write (nout,*) 'D01GA_A1W_F Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n
      Read (nin,*) ar

      a = ar
      Allocate (x(n),y(n))

!     Create AD tape
      Call nagad_a1w_ir_create

!     Create AD configuration data object
      ifail = 0
      Call x10aa_a1w_f(ad_handle,ifail)

!     Register variables to differentiate w.r.t.
      Call nagad_a1w_ir_register_variable(a)

      Do i = 1, n
        xr = real(i-1,kind=nag_wp)/real(n-1,kind=nag_wp)
        x(i) = xr
        y(i) = 4.0_nag_wp/(1.0_nag_wp+a*a*xr*xr)
      End Do

!     Call the AD routine
      ifail = 0
      Call d01ga_a1w_f(ad_handle,x,y,n,ans,er,ifail)

      Write (nout,*)
      Write (nout,99999) ' Solution, ans =', ans%value
      Write (nout,*)

      Call nagad_a1w_inc_derivative(ans,1.0E0_nag_wp)
      Call nagad_a1w_ir_interpret_adjoint_sparse(ifail)

      Write (nout,*) ' Derivatives calculated: First order adjoints'
      Write (nout,*) ' Computational mode    : algorithmic'

!     Get derivatives
      da = nagad_a1w_get_derivative(a)

      Write (nout,*) ' Derivatives of solution w.r.t a:'
      Write (nout,*)
      Write (nout,99998) '     d(ans)/da  = ', da
99999 Format (1X,A,1X,F12.5)
99998 Format (1X,A,E13.5)

!     Remove computational data object and tape
      ifail = 0
      Call x10ab_a1w_f(ad_handle,ifail)
      Call nagad_a1w_ir_remove

    End Program d01ga_a1w_fe