/* bbowda - Black Box Optimization With Data Analysis
   Copyright (C) 2006-2012 Kevin Kofler <Kevin@tigcc.ticalc.org>
   Copyright (C) 2025 DAGOPT Optimization Technologies GmbH (www.dagopt.com)
                      written by Kevin Kofler <kofler@dagopt.com>

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version. A copy of the GNU General Public
   License version 3 can be found in the file gpl-3.0.txt.

   Linking bbowda statically or dynamically (directly or indirectly) with
   other modules is making a combined work based on bbowda. Thus, the terms
   and conditions of the GNU General Public License cover the whole
   combination.

   In addition, as a special exception, the copyright holder of bbowda gives
   you permission to combine the bbowda program:
   * with free software programs or libraries that are released under the
     GNU Library or Lesser General Public License (LGPL), either version 2
     of the License, or (at your option) any later version,
   * with free software programs or libraries that are released under the
     IBM Common Public License (CPL), either version 1.0 of the License, or
     (at your option) any later version,
   * with free software programs or libraries that are released under the
     eclipse.org Eclipse Public License (EPL), either version 1.0 of the
     License, or (at your option) any later version,
   * with free software programs or libraries that are released under the
     CeCILL-C Free Software License Agreement, either version 1 of the License,
     or (at your option) any later version,
   * with code included in the standard release of MUMPS under the old MUMPS
     Conditions of Use as reproduced in licenses.txt (or modified versions
     of such code, with unchanged license; variants of the license where only
     the list of contributors and/or the list of suggested citations changed
     shall be considered the same license) and
   * if you qualify for a free of charge license of DONLP2, with code
     included in the standard release of DONLP2 under the DONLP2 Conditions
     of Use as reproduced in licenses.txt (or modified versions of such code,
     with unchanged license).
   (For avoidance of doubt, this implies that it is permitted, e.g., to combine
   the bbowda program with current versions of Ipopt released under the EPL
   version 2.0, because 2.0 is >= 1.0. Its dependency MUMPS is released under
   the CeCILL-C version 1, which is also listed above.)

   You may copy and distribute such a system following the terms of the GNU
   GPL for bbowda and the licenses of the other code concerned, provided that
   you include the source code of that other code when and as the GNU GPL
   requires distribution of source code.

   Note that people who make modified versions of bbowda are not obligated
   to grant this special exception for their modified versions; it is their
   choice whether to do so. The GNU General Public License gives permission
   to release a modified version without this exception; this exception also
   makes it possible to release a modified version which carries forward
   this exception.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#include "eqconst.h"
#include <lp_lib.h>
#include "eval.h"
#include "xmalloc.h"
#include <stdio.h>
#include <stdlib.h>

struct eqc_estimates {
  struct estimate_constraints estimatec;
  size_t *n_estimated_constraint;
  unsigned char *is_overestimator;
};

struct eqc_estimates * alloc_eqc_estimates(void) {
  struct eqc_estimates *eqc = xmalloc(sizeof(struct eqc_estimates));
  eqc->estimatec.num_estimate_constraints=0;
  eqc->estimatec.estimate_constraint_coeffs_p=NULL;
  eqc->n_estimated_constraint=NULL;
  eqc->is_overestimator=NULL;
  return eqc;
}

static void eqconst_optimize_lp(struct eqc_estimates *eqc,
                                const struct bbowda_problem *problem,
                                struct eval_points *evalpts, const double *X,
                                const int over, const size_t constraint_no)
{
  lprec *lp;
  REAL row[DIMX+DIMZ+2]; /* must be 1 more then number of columns ! */
  /* (Sigh. I can understand DONLP2 using 1-based indexing, being ported from
     Fortran, but this makes just no sense. Index 0 is not used at all.) */
  memset(row, 0, sizeof(row));

  /* create a new LP model */
  lp=make_lp(0,1+DIMX+DIMZ);
  if (!lp) {
    fprintf(stderr, "make_lp failed\n");
    exit(1);
  }

  /* For the underestimate, we want to maximize to get the best (closest) one.
     For the overestimate, we want to minimize to get the best (closest) one. */
  if (!over) set_maxim(lp);

  /* bounds: upper defaults to +Inf, which is OK, lower defaults to 0, we need -Inf */
  size_t i;
  REAL infinite=get_infinite(lp); /* lp_solve uses a fake infinity */
  for (i=1; i<=(size_t)(1+DIMX+DIMZ); i++) {
    set_lowbo(lp,i,-infinite);
  }

  /* objective function
     coefficient of qi: sum phi_i(xj) for all j */
  size_t j;
  row[1]=evalpts->numcurrpts; /* constant term */
  for (j=0; j<evalpts->numcurrpts; j++) {
    REAL *p=row+2;
    double *x=currpts(evalpts)[j];
    size_t k,l;
    for (k=0; k<(size_t)DIMX; k++) { /* linear terms */
      *(p++)+=x[k];
    }
    for (k=0; k<(size_t)DIMX; k++) { /* quadratic/bilinear terms */
      for (l=0; l<=k; l++) {
        *(p++)+=(x[k]*x[l]);
      }
    }
  }
  if (!set_obj_fn(lp,row)) {
    fprintf(stderr, "set_obj_fn failed\n");
    exit(1);
  }

  /* constraints
     coefficient of qi in constraint j: phi_i(xj) */
  for (j=0; j<evalpts->numcurrpts; j++) {
    REAL *p=row+1;
    double *x=currpts(evalpts)[j];
    size_t k,l;
    *(p++)=1.; /* constant term */
    for (k=0; k<(size_t)DIMX; k++) { /* linear terms */
      *(p++)=x[k];
    }
    for (k=0; k<(size_t)DIMX; k++) { /* quadratic/bilinear terms */
      for (l=0; l<=k; l++) {
        *(p++)=(x[k]*x[l]);
      }
    }
    if (!add_constraint(lp,row,(X && x==X)?EQ:(over?GE:LE),x[DIMX+DIMY+constraint_no])) {
      fprintf(stderr, "add_constraint failed\n");
      exit(1);
    }
  }

  /* solve the problem */
  set_verbose(lp,IMPORTANT);
  int ret=solve(lp);
  if (ret<0) {
    fprintf(stderr, "lp_solve failed\n");
    exit(1);
  }
  if (ret)
    printf("lp_solve returned non-zero retval %d\n",ret);
  else {
    /* save the result */
    get_variables(lp,row);
    size_t j=eqc->estimatec.num_estimate_constraints++,i;
    eqc->estimatec.estimate_constraint_coeffs_p=xrealloc(eqc->estimatec.estimate_constraint_coeffs_p,
      eqc->estimatec.num_estimate_constraints*((size_t)(1+DIMX+DIMZ))*sizeof(double));
    eqc->n_estimated_constraint=xrealloc(eqc->n_estimated_constraint,
                                         eqc->estimatec.num_estimate_constraints*sizeof(size_t));
    eqc->n_estimated_constraint[j]=constraint_no;
    eqc->is_overestimator=xrealloc(eqc->is_overestimator,eqc->estimatec.num_estimate_constraints);
    eqc->is_overestimator[j]=over;
    REAL *p=row;
    double *q=estimate_constraint_coeffs(&eqc->estimatec)[j];
    /* transform constraints to >=0 form */
    if (over) { /* overestimator >= 0 */
      for (i=0; i<(size_t)(1+DIMX+DIMZ); i++) *(q++)=*(p++);
    } else { /* underestimator <= 0 */
      for (i=0; i<(size_t)(1+DIMX+DIMZ); i++) *(q++)=-*(p++);
    }
  }

  /* clean up */
  delete_lp(lp);
}

static void eqconst_optimize_lps(struct eqc_estimates *eqc,
                                 const struct bbowda_problem *problem,
                                 struct eval_points *evalpts, const double *X,
                                 const int over)
{
  size_t i;
  for (i=0; i<(size_t)DIMY_EQ; i++) {
    eqconst_optimize_lp(eqc,problem,evalpts,X,over,i);
  }
}

/* compute global over-/underestimates of equality constraints around a new
   point, or the first estimate if X is NULL */
void compute_global_eq_cst_estimates_around(struct eqc_estimates *eqc,
  const struct bbowda_problem *problem, struct eval_points *evalpts,
  const double *X)
{
  if (X) {
    /* fix previous estimates for the new point */
    size_t j,k,l;
    for (j=0; j<eqc->estimatec.num_estimate_constraints; j++) {
      /* evaluate quadratic polynomial */
      double *p=estimate_constraint_coeffs(&eqc->estimatec)[j], *q=p;
      double z=*(p++); /* constant term */
      for (k=0; k<(size_t)DIMX; k++) { /* linear terms */
        z+=*(p++) * X[k];
      }
      for (k=0; k<(size_t)DIMX; k++) { /* quadratic/bilinear terms */
        for (l=0; l<=k; l++) {
          z+=*(p++) * (X[k]*X[l]);
        }
      }
      double zactual=X[DIMX+DIMY+eqc->n_estimated_constraint[j]];
      /* check if the constraint is violated */
      if (eqc->is_overestimator[j]) {
        /* should be an overestimator */
        if (z<zactual) { /* oops */
          *q+=zactual-z; /* fix it */
        }
      } else {
        /* -z should be an underestimator */
        if (-z>zactual) { /* oops */
          *q-=zactual+z; /* fix it */
        }
      }
    }
  }

  eqconst_optimize_lps(eqc,problem,evalpts,X,0); /* compute underestimate */
  eqconst_optimize_lps(eqc,problem,evalpts,X,1); /* compute overestimate */
}

const struct estimate_constraints * eqc_get_estimatec(
  struct eqc_estimates *eqc)
{
  return &eqc->estimatec;
}

void free_eqc_estimates(struct eqc_estimates *eqc)
{
  free(eqc->estimatec.estimate_constraint_coeffs_p);
  free(eqc->n_estimated_constraint);
  free(eqc->is_overestimator);
  free(eqc);
}
