/* nag_opt_check_deriv (e04hcc) Example Program.
 *
 * Copyright 2014 Numerical Algorithms Group.
 *
 * Mark 2, 1991.
 * Mark 7 revised, 2001.
 * Mark 8 revised, 2004.
 *
 */

#include <nag.h>
#include <stdio.h>
#include <nag_stdlib.h>
#include <nage04.h>

#ifdef __cplusplus
extern "C" {
#endif
static void NAG_CALL objfun(Integer n, const double x[], double *f, double g[],
                            Nag_Comm *comm);
#ifdef __cplusplus
}
#endif

#define NMAX 4

int main(void)
{
  Integer  exit_status = 0, i, n;
  NagError fail;
  double   *g = 0, objf, *x = 0;
  Nag_Comm comm;

  INIT_FAIL(fail);

  printf("nag_opt_check_deriv (e04hcc) Example Program Results\n");

  n = NMAX;
  if (n >= 1)
    {
      if (!(x = NAG_ALLOC(n, double)) ||
          !(g = NAG_ALLOC(n, double)))
        {
          printf("Allocation failure\n");
          exit_status = -1;
          goto END;
        }
    }
  else
    {
      printf("Invalid n.\n");
      exit_status = 1;
      return exit_status;
    }
  x[0] = 1.46;
  x[1] = -0.82;
  x[2] = 0.57;
  x[3] = 1.21;

  printf("\nThe test point is:\n");
  for (i = 0; i < n; ++i)
    printf(" %8.4f", x[i]);
  printf("\n");

  /* Call derivative checker */
  /* nag_opt_check_deriv (e04hcc).
   * Derivative checker for use with nag_opt_bounds_deriv
   * (e04kbc)
   */
  nag_opt_check_deriv(n, objfun, x, &objf, g, &comm, &fail);
  if (fail.code != NE_NOERROR)
    {
      printf("Error from nag_opt_check_deriv (e04hcc).\n%s\n",
             fail.message);
      exit_status = 1;
      goto END;
    }

  printf("\nFirst derivatives are consistent with function values.\n\n");
  printf("At the test point, objfun gives the function value %13.4e\n",
         objf);
  printf("and the 1st derivatives\n\n");
  for (i = 0; i < n; ++i)
    printf("  %12.3e ", g[i]);
  printf("\n");
 END:
  NAG_FREE(x);
  NAG_FREE(g);
  return exit_status;
}

static void NAG_CALL objfun(Integer n, const double x[], double *objf,
                            double g[], Nag_Comm *comm)
{
  /* objfun evaluates the objective function and its derivatives. */

  double x1, x2, x3, x4;
  double tmp, tmp1, tmp2, tmp3, tmp4;

  x1 = x[0];
  x2 = x[1];
  x3 = x[2];
  x4 = x[3];

  /* Supply a single function value */
  tmp1 = x1 + 10.0*x2;
  tmp2 = x3 - x4;
  tmp3 = x2 - 2.0*x3, tmp3 *= tmp3;
  tmp4 = x1 - x4, tmp4 *= tmp4;
  *objf = tmp1*tmp1 + 5.0*tmp2*tmp2 + tmp3*tmp3 + 10.0*tmp4*tmp4;

  if (comm->flag != 0)
    {
      /* Calculate the derivatives */
      tmp = x1 - x4;
      g[0] = 2.0*(x1 + 10.0*x2) + 40.0*tmp*tmp*tmp;
      tmp = x2 - 2.0*x3;
      g[1] = 20.0*(x1 + 10.0*x2) + 4.0*tmp*tmp*tmp;
      tmp = x2 - 2.0*x3;
      g[2] = 10.0*(x3 - x4) - 8.0*tmp*tmp*tmp;
      tmp = x1 - x4;
      g[3] = 10.0*(x4 - x3) - 40.0*tmp*tmp*tmp;
    }
} /* objfun */