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

NAG AD Library Introduction
Example description
    Program s01ba_a1w_fe

!     S01BA_A1W_F Example Program Text
!     Mark 29.2 Release. NAG Copyright 2023.

!     .. Use Statements ..
      Use iso_c_binding, Only: c_ptr
      Use nagad_library, Only: nagad_a1w_get_derivative,                       &
                               nagad_a1w_inc_derivative,                       &
                               nagad_a1w_ir_create => x10za_a1w_f,             &
                               nagad_a1w_ir_interpret_adjoint,                 &
                               nagad_a1w_ir_register_variable,                 &
                               nagad_a1w_ir_remove, nagad_a1w_ir_zero_adjoints &
                               , nagad_a1w_w_rtype, s01ba_a1w_f, x10aa_a1w_f,  &
                               x10ab_a1w_f, Assignment (=)
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Type (c_ptr)                     :: ad_handle
      Type (nagad_a1w_w_rtype)         :: x, y
      Real (Kind=nag_wp)               :: dydx, xr
      Integer                          :: i, ifail, ifail2, n
!     .. Local Arrays ..
      Type (nagad_a1w_w_rtype), Allocatable :: xv(:)
!     .. Executable Statements ..
      Write (nout,*) 'S01BA_A1W_F Example Program Results'

      Call nagad_a1w_ir_create

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

      Allocate (xv(n))

!     Read x values from data file

      Do i = 1, n
        Read (nin,*) xr
        xv(i) = xr
      End Do

      Write (nout,*)
      Write (nout,*) '       x       y=ln(1+x)     dy/dx'

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

      Do i = 1, n

        x = xv(i)
!       Register variables to differentiate w.r.t.
        Call nagad_a1w_ir_register_variable(x)

        ifail = -1
        Call s01ba_a1w_f(ad_handle,x,y,ifail)

        Call nagad_a1w_ir_zero_adjoints
        Call nagad_a1w_inc_derivative(y,1.0_nag_wp)
        Call nagad_a1w_ir_interpret_adjoint(ifail2)

!       Get derivatives
        dydx = nagad_a1w_get_derivative(x)

        If (ifail<0) Then
          Write (nout,99999) x%value, 'fail = ', ifail
        Else
          Write (nout,99998) x%value, y%value, dydx
        End If
      End Do
99999 Format (1X,1P,E12.4,1X,A12,I0)
99998 Format (1X,1P,3E12.4)

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

    End Program s01ba_a1w_fe