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

NAG AD Library Introduction
Example description
    Program g02aa_t1w_fe

!     G02AA_T1W_F Example Program Text
!     Mark 28.6 Release. NAG Copyright 2022.

!     .. Use Statements ..
      Use iso_c_binding, Only: c_ptr
      Use nagad_library, Only: g02aa_t1w_f, nagad_t1w_w_rtype, x10aa_t1w_f,    &
                               x10ab_t1w_f, Assignment (=)
      Use nag_library, Only: nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Type (c_ptr)                     :: ad_handle
      Type (nagad_t1w_w_rtype)         :: errtol, nrmgrd
      Real (Kind=nag_wp)               :: dx
      Integer                          :: feval, i, ifail, iter, j, k, l, ldg, &
                                          ldx, maxit, maxits, n
!     .. Local Arrays ..
      Type (nagad_t1w_w_rtype), Allocatable :: g(:,:), g_in(:,:), x(:,:)
      Real (Kind=nag_wp), Allocatable  :: dxdg(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G02AA_T1W_F Example Program Results'
      Write (nout,*)
      Flush (nout)

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

!     Read in the problem size
      Read (nin,*) n

      ldg = n
      ldx = n
      Allocate (g(ldg,n),x(ldx,n),g_in(ldg,n),dxdg(n,n))

      g_in(1:n,1:n) = 0.0_nag_wp
!     Read in the matrix G
      Read (nin,*)(g_in(i,1:n)%value,i=1,n)


      ifail = 0
      Call x10aa_t1w_f(ad_handle,ifail)
!     Use the defaults for ERRTOL, MAXITS and MAXIT
      errtol = 0.0E0_nag_wp
      maxits = 0
      maxit = 0

      g = g_in

outer: Do i = 1, n
        Do j = 1, n
          g(i,j)%tangent = 1.0_nag_wp

!         Calculate nearest correlation matrix
          x(1:n,1:n) = 0.0_nag_wp
          ifail = 0
          Call g02aa_t1w_f(ad_handle,g,ldg,n,errtol,maxits,maxit,x,ldx,iter,   &
            feval,nrmgrd,ifail)

          If (i==1 .And. j==1) Then
!              Display results
            ifail = 0
            Call x04caf('General',' ',n,n,x%value,ldx,                         &
              'Nearest Correlation Matrix',ifail)
            Write (nout,*)
            Write (nout,99999) ' Number of Newton steps taken:', iter
            Write (nout,99998) ' Number of function evaluations:', feval
            Write (nout,*)
          End If

          dx = 0.0_nag_wp
          Do k = 1, n
            Do l = 1, n
              dx = dx + x(k,l)%tangent
            End Do
          End Do
          dxdg(i,j) = dx

          g = g_in

        End Do

      End Do outer

      Call x04caf('General',' ',n,n,dxdg,n,' (1,...,1)^T * dx/dg',ifail)

      Call x10ab_t1w_f(ad_handle,ifail)
99999 Format (1X,A,I11)
99998 Format (1X,A,I9)
    End Program g02aa_t1w_fe