/* nag_glopt_bnd_mcs_solve (e05jbc) Example Program.
 *
 * NAGPRODCODE Version.
 *
 * Copyright 2016 Numerical Algorithms Group.
 *
 * Mark 26, 2016.
 */
#include <stdio.h>
#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nage05.h>

#ifdef __cplusplus
extern "C"
{
#endif
  static void NAG_CALL objfun(Integer n, const double x[], double *f,
                              Integer nstate, Nag_Comm *comm,
                              Integer *inform);
  static void NAG_CALL monit(Integer n, Integer ncall, const double xbest[],
                             const Integer icount[], Integer sdlist,
                             const double list[], const Integer numpts[],
                             const Integer initpt[], Integer nbaskt,
                             const double xbaskt[], const double boxl[],
                             const double boxu[], Integer nstate,
                             Nag_Comm *comm, Integer *inform);
  static void NAG_CALL output_current_box(const double boxl[],
                                          const double boxu[]);
#ifdef __cplusplus
}
#endif

int main(void)
{
  /* Scalars */
  double obj;
  Integer exit_status = 0, i, n = 2, plot, sdlist;
  Nag_BoundType boundenum;
  Nag_MCSInitMethod initmethodenum;
  /* Arrays */
  static double ruser[2] = { -1.0, -1.0 };
  char bound[16], initmethod[18];
  double *bl = 0, *bu = 0, *list = 0, *x = 0;
  Integer *initpt = 0, *numpts = 0;
  Integer iuser[1];
  /* Nag Types */
  Nag_E05State state;
  NagError fail;
  Nag_Comm comm;

  INIT_FAIL(fail);

  printf("nag_glopt_bnd_mcs_solve (e05jbc) Example Program Results\n");

  /* For communication with user-supplied functions: */
  comm.iuser = iuser;
  comm.user = ruser;

  /* Skip heading in data file */
  scanf("%*[^\n] ");
  /* Read sdlist from data file */
  scanf("%" NAG_IFMT "%*[^\n] ", &sdlist);

  if (n <= 0 || sdlist <= 0)
    goto END;

  if (!(bl = NAG_ALLOC(n, double)) ||
      !(bu = NAG_ALLOC(n, double)) ||
      !(list = NAG_ALLOC(n * sdlist, double)) ||
      !(x = NAG_ALLOC(n, double)) ||
      !(initpt = NAG_ALLOC(n, Integer)) || !(numpts = NAG_ALLOC(n, Integer)))
  {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  /* Read in bound (and bl and bu if necessary) */
  scanf("%15s%*[^\n] ", bound);

  /* nag_enum_name_to_value (x04nac).
   * Converts NAG enum member name to value
   */
  boundenum = (Nag_BoundType) nag_enum_name_to_value(bound);

  if (boundenum == Nag_Bounds)
    /* Read in the whole of each bound */
  {
    for (i = 0; i < n; ++i)
      scanf("%lf", &bl[i]);
    scanf("%*[^\n] ");

    for (i = 0; i < n; ++i)
      scanf("%lf", &bu[i]);
    scanf("%*[^\n] ");
  }
  else if (boundenum == Nag_BoundsEqual)
    /* Bounds are uniform: read in only the first entry of each */
  {
    scanf("%lf%*[^\n] ", &bl[0]);
    scanf("%lf%*[^\n] ", &bu[0]);
  }

  /* Read in initmethod */
  scanf("%17s%*[^\n] ", initmethod);

  /* nag_enum_name_to_value (x04nac).
   * Converts NAG enum member name to value
   */
  initmethodenum = (Nag_MCSInitMethod) nag_enum_name_to_value(initmethod);

  /* Read in plot. Its value determines whether monit displays
   * information on the current search box
   */
  scanf("%" NAG_IFMT "%*[^\n] ", &plot);

  /* Communicate plot through to monit */
  iuser[0] = plot;

  /* Call nag_glopt_bnd_mcs_init (e05jac) to initialize
   * nag_glopt_bnd_mcs_solve (e05jbc). */
  /* Its first argument is a legacy argument and has no significance. */
  nag_glopt_bnd_mcs_init(0, &state, &fail);

  if (fail.code != NE_NOERROR) {
    printf("Initialization of nag_glopt_bnd_mcs_solve (e05jbc) failed.\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }

  /* Solve the problem. */
  /* nag_glopt_bnd_mcs_solve (e05jbc).
   * Global optimization by multilevel coordinate search, simple bounds.
   */
  nag_glopt_bnd_mcs_solve(n, objfun, boundenum, initmethodenum, bl, bu,
                          sdlist, list, numpts, initpt, monit, x, &obj,
                          &state, &comm, &fail);

  if (fail.code != NE_NOERROR) {
    printf("Error message from nag_glopt_bnd_mcs_solve (e05jbc).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }

  printf("Final objective value = %11.5f\n", obj);
  printf("Global optimum x = ");
  for (i = 0; i < n; ++i)
    printf("%9.5f", x[i]);
  printf("\n");

END:
  NAG_FREE(bl);
  NAG_FREE(bu);
  NAG_FREE(list);
  NAG_FREE(x);
  NAG_FREE(initpt);
  NAG_FREE(numpts);

  return exit_status;
}

static void NAG_CALL objfun(Integer n, const double x[], double *f,
                            Integer nstate, Nag_Comm *comm, Integer *inform)
{
  /* Routine to evaluate objective function */

  if (comm->user[0] == -1.0) {
    printf("(User-supplied callback objfun, first invocation.)\n");
    comm->user[0] = 0.0;
  }

  /* This is a two-dimensional objective function.
   * As an example of using the inform mechanism,
   * terminate if any other problem size is supplied.
   */
  if (n != 2) {
    *inform = -1;
    return;
  }

  *inform = 0;

  if (*inform >= 0)
    /* Here we're prepared to evaluate objfun at the current x */
  {
    if (nstate == 1)
      /* This is the first call to objfun */
    {
      printf("\n(objfun was just called for the first time)\n");
    }

    *f = (3.0 * pow((1.0 - x[0]), 2) * exp(-pow(x[0], 2) - pow((x[1] + 1), 2))
          - (10.0 * (x[0] / 5.0 - pow(x[0], 3) - pow(x[1], 5)) *
             exp(-pow(x[0], 2) - pow(x[1], 2)))
          - 1.0 / 3.0 * exp(-pow((x[0] + 1.0), 2) - pow(x[1], 2))
           );
  }
}

static void NAG_CALL monit(Integer n, Integer ncall, const double xbest[],
                           const Integer icount[], Integer sdlist,
                           const double list[], const Integer numpts[],
                           const Integer initpt[], Integer nbaskt,
                           const double xbaskt[], const double boxl[],
                           const double boxu[], Integer nstate,
                           Nag_Comm *comm, Integer *inform)
{
  /* Scalars */
  Integer i, j;
  Integer plot;

#define LIST(I, J) list[(I-1)*sdlist + (J-1)]
#define XBASKT(I, J) xbaskt[(I-1)*nbaskt + (J-1)]

  if (comm->user[1] == -1.0) {
    printf("(User-supplied callback monit, first invocation.)\n");
    comm->user[1] = 0.0;
  }

  *inform = 0;

  if (*inform >= 0)
    /* We are going to allow the iterations to continue */
  {
    /* Extract plot from the communication structure */
    plot = comm->iuser[0];

    if (nstate == 0 || nstate == 1)
      /* When nstate == 1, monit is called for the first time.
       * When nstate == 0, monit is called for the first AND last time.
       * Display a welcome message */
    {
      printf("\n*** Begin monitoring information ***\n\n");

      printf("Values controlling initial splitting of a box:\n");
      for (i = 1; i <= n; ++i) {
        printf("**\n");
        printf("In dimension %5" NAG_IFMT "\n", i);
        printf("Extent of initialization list in this dimension ="
               "%5" NAG_IFMT "\n", numpts[i - 1]);
        printf("Initialization points in this dimension:\n");
        printf("LIST(i, 1:numpts[i - 1]) =");
        for (j = 1; j <= numpts[i - 1]; ++j)
          printf("%9.5f", LIST(i, j));
        printf("\n");
        printf("Initial point in this dimension: LIST(i,%5" NAG_IFMT ")\n",
               initpt[i - 1]);
      }

      if (plot != 0 && n == 2)
        printf("<Begin displaying search boxes>\n\n");
    }

    if (plot != 0 && n == 2) {
      /* Display the coordinates of the edges of the current search box */
      output_current_box(boxl, boxu);
    }

    if (nstate <= 0)
      /* monit is called for the last time */
    {
      if (plot != 0 && n == 2)
        printf("<End displaying search boxes>\n\n");
      printf("Total sub-boxes = %5" NAG_IFMT "\n", icount[0]);
      printf("Total function evaluations (rounded to nearest 10) = "
             "%5" NAG_IFMT "\n", 10*((ncall+5)/10));
      printf("Total function evaluations used in local search (rounded\n"
             "  to nearest 10) = %5" NAG_IFMT "\n", 10*((icount[1]+5)/10));
      printf("Total points used in local search = %5" NAG_IFMT "\n",
             icount[2]);
      printf("Total sweeps through levels = %5" NAG_IFMT "\n", icount[3]);
      printf("Total splits by init. list = %5" NAG_IFMT "\n", icount[4]);
      printf("Lowest level with nonsplit boxes = %5" NAG_IFMT "\n",
             icount[5]);
      printf("Number of candidate minima in the 'shopping basket'"
             " = %5" NAG_IFMT "\n", nbaskt);
      printf("Shopping basket:\n");

      for (i = 1; i <= n; ++i) {
        printf("xbaskt(%3" NAG_IFMT ",:) =", i);
        for (j = 1; j <= nbaskt; ++j)
          printf("%9.5f", XBASKT(i, j));
        printf("\n");
      }

      printf("Best point:\n");
      printf("xbest =");
      for (i = 0; i < n; ++i)
        printf("%9.5f", xbest[i]);
      printf("\n");

      printf("\n*** End monitoring information ***\n\n");
    }
  }
}

static void NAG_CALL output_current_box(const double boxl[],
                                        const double boxu[])
{
  printf("%20.15f %20.15f\n", boxl[0], boxl[1]);
  printf("%20.15f %20.15f\n\n", boxl[0], boxu[1]);
  printf("%20.15f %20.15f\n", boxl[0], boxl[1]);
  printf("%20.15f %20.15f\n\n", boxu[0], boxl[1]);
  printf("%20.15f %20.15f\n", boxl[0], boxu[1]);
  printf("%20.15f %20.15f\n\n", boxu[0], boxu[1]);
  printf("%20.15f %20.15f\n", boxu[0], boxl[1]);
  printf("%20.15f %20.15f\n\n", boxu[0], boxu[1]);
}