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

NAG AD Library Introduction
Example description
    Program g01ec_a1w_fe

!     G01EC_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: g01ec_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_ir_zero_adjoints &
                               , nagad_a1w_w_rtype, 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)         :: df, p, x
      Real (Kind=nag_wp)               :: dfr, dpdf, dpdx, xr
      Integer                          :: i, ifail, n
      Character (1)                    :: tail
!     .. Local Arrays ..
      Type (nagad_a1w_w_rtype), Allocatable :: dfv(:), xv(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01EC_A1W_F Example Program Results'

!     Create AD tape
      Call nagad_a1w_ir_create

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

      Allocate (xv(n),dfv(n))

!     Read x values from data file

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

      tail = 'L'
      Write (nout,*)
      Write (nout,*) 'Left tail significance levels and derivatives'
      Write (nout,*)
      Write (nout,*) '   x            df           p            dp/dx' //      &
        '       dp/ddf'

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

      Do i = 1, n

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

        ifail = 0
        Call g01ec_a1w_f(ad_handle,tail,x,df,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)
        dpdf = nagad_a1w_get_derivative(df)

        Write (nout,99999) x%value, p%value, df%value, dpdx, dpdf
      End Do
99999 Format (1X,1P,5E13.4)

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

    End Program g01ec_a1w_fe