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

NAG AD Library Introduction
Example description
    Program s15ab_a1w_fe

!     S15AB_A1W_F Example Program Text
!     Mark 30.0 Release. NAG Copyright 2024.

!     .. Use Statements ..
      Use iso_c_binding, Only: c_ptr
      Use nagad_library, Only: nagad_a1w_get_derivative,                       &
                               nagad_a1w_inc_derivative,                       &
                               nagad_a1w_ir_interpret_adjoint_sparse,          &
                               nagad_a1w_ir_register_variable,                 &
                               nagad_a1w_ir_remove, nagad_a1w_ir_zero_adjoints &
                               , nagad_a1w_w_rtype, s15ab_a1w_f, x10aa_a1w_f,  &
                               x10ab_a1w_f, x10za_a1w_f, Assignment (=)
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Type (c_ptr)                     :: ad_handle
      Type (nagad_a1w_w_rtype)         :: p, x
      Real (Kind=nag_wp)               :: dpdx
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'S15AB_A1W_F Example Program Results'

      Call x10za_a1w_f

      x = -1._nag_wp

      Write (nout,*)
      Write (nout,*) '       x         P(x)       dP/dx      Exact P'''

!     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(x)

      ifail = 0
      Call s15ab_a1w_f(ad_handle,x,p,ifail)

      Call nagad_a1w_ir_zero_adjoints
      Call nagad_a1w_inc_derivative(p,1.0_nag_wp)
      ifail = 0
      Call nagad_a1w_ir_interpret_adjoint_sparse(ifail)

!     Get derivatives
      dpdx = nagad_a1w_get_derivative(x)

      Write (nout,99999) x%value, p%value, dpdx, exact_dpdx(x%value)

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

99999 Format (1X,1P,4E12.3)
    Contains
      Function exact_dpdx(x_val)
!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: exact_dpdx
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x_val
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp, sqrt
!       .. Executable Statements ..
        exact_dpdx = 1._nag_wp/(sqrt(2._nag_wp*x01aaf(x_val)))*                &
          exp(-x_val**2/2._nag_wp)
        Return
      End Function exact_dpdx
    End Program s15ab_a1w_fe